@payos-inc/payos-react 1.0.40 → 1.0.41

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.
@@ -18,7 +18,7 @@ import*as fn from"react";import{Slot as Ei}from"@radix-ui/react-slot";import{cva
18
18
  w-5 h-5 rounded-full border-2 flex items-center justify-center
19
19
  transition-colors
20
20
  ${n===i.id?"border-[#1A1F71] dark:border-blue-400 black:border-blue-400":"border-gray-300 dark:border-slate-600 black:border-[#262626]"}
21
- `,children:n===i.id&&Se("div",{className:"w-2.5 h-2.5 rounded-full bg-[#1A1F71] dark:bg-blue-400 black:bg-blue-400"})})}),Se("input",{type:"radio",name:"verification-method",value:i.id,checked:n===i.id,onChange:()=>s(i.id),className:"sr-only"}),Se("span",{className:"text-sm font-medium text-slate-900 dark:text-white black:text-white",children:d(i.type,i.maskedValue)})]},i.id))}),Se("div",{className:"p-4 pt-2",children:Se(re,{onClick:o,className:"w-full",disabled:!n||r,isLoading:r,loadingText:"Sending code...",children:"Confirm"})})]}),a&&Se("div",{className:"text-center",children:Se("button",{type:"button",onClick:a,className:"text-sm text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline disabled:opacity-50",children:"Go back"})})]})};Fa.displayName="VisaMethodView";import*as sa from"react";import{jsx as Oe,jsxs as za}from"react/jsx-runtime";var Ts="#1A1F71",Wa=({methodDescription:e,otp:t,onOtpChange:a,onVerify:r,onBack:n,onResend:s,onVerifyAnotherWay:o,isLoading:d=!1,error:i,canRetry:m=!0})=>{let g=sa.useRef(!1);sa.useEffect(()=>{t.length<6&&(g.current=!1)},[t]);let p=c=>{c.preventDefault(),t.length===6&&m&&!d&&(g.current=!0,r())};sa.useEffect(()=>{t.length===6&&!d&&m&&!g.current&&(g.current=!0,r())},[t,d,r,m]);let b=!m;return za("form",{onSubmit:p,className:"space-y-6",children:[Oe("div",{className:"flex items-center justify-center py-6",children:Oe("img",{src:Oa,alt:"Visa",className:"h-8 dark:brightness-0 dark:invert black:brightness-0 black:invert",style:{objectFit:"contain"}})}),za("div",{className:"text-center px-4 space-y-1",children:[za("p",{className:"text-sm text-gray-600 dark:text-slate-300 black:text-gray-300",children:["Enter the code sent to ",e,"."]}),s&&!b&&Oe("button",{type:"button",onClick:s,disabled:d,className:"text-sm font-semibold text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline disabled:opacity-50",children:"Resend code"})]}),za(ne,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] rounded-2xl p-6 space-y-6",children:[Oe("div",{className:d||b?"opacity-50 pointer-events-none":"",children:Oe(Ft,{value:t,onChange:a,length:6,variant:"underline",accentColor:typeof document<"u"&&document.documentElement.classList.contains("dark")?"#60a5fa":Ts})}),i&&Oe("p",{className:"text-sm text-red-600 dark:text-red-400 black:text-red-400 text-center",children:i}),Oe(re,{type:"submit",className:"w-full",disabled:t.length!==6||d||b,isLoading:d,loadingText:"Verifying...",children:"Verify"}),b&&o&&Oe("div",{className:"text-center",children:Oe("button",{type:"button",onClick:o,className:"text-sm text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline",children:"Verify another way"})})]}),Oe("div",{className:"text-center",children:Oe("button",{type:"button",onClick:n,className:"text-sm text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline disabled:opacity-50",children:"Go back"})})]})};Wa.displayName="VisaOtpView";import{AlertCircle as Bs}from"lucide-react";import{useMemo as As}from"react";import{Fingerprint as Ms,Smile as Vs,User as Us,Lock as $n}from"lucide-react";function Hn(){return As(()=>{if(typeof navigator>"u")return{text:"Enable Secure Access",icon:$n,type:"generic"};let e=navigator.userAgent.toLowerCase();return/iphone|ipad/.test(e)?{text:"Enable Passkey",icon:Vs,type:"faceId"}:/macintosh|mac os/.test(e)?{text:"Enable Passkey",icon:Ms,type:"touchId"}:/windows/.test(e)?{text:"Enable Passkey",icon:Us,type:"windowsHello"}:{text:"Enable Passkey",icon:$n,type:"generic"}},[])}import{jsx as _e,jsxs as Ht}from"react/jsx-runtime";var $a=({card:e,cardNetwork:t,onCreatePasskey:a,onSkip:r,onBack:n,isLoading:s=!1,error:o,showSkip:d=!1})=>{let i=Hn(),m=i.icon;return Ht("div",{className:"space-y-4 flex flex-col justify-center min-h-full",children:[Ht(ne,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] rounded-2xl p-6 space-y-6",children:[e.cardArtUrl&&_e("div",{className:"flex justify-center",children:_e(ra,{cardArtUrl:e.cardArtUrl,network:t,last4:e.last4})}),Ht("div",{className:"text-center space-y-2",children:[_e("h2",{className:"text-xl font-bold text-slate-900 dark:text-white black:text-white",children:"Turn on One-Touch Buying"}),Ht("p",{className:"text-sm text-gray-500 dark:text-slate-400 black:text-gray-400",children:["Secure your card ending in ",e.last4," for your AI Agent"]})]}),o&&Ht("div",{className:"flex items-center gap-2 p-3 bg-red-50 dark:bg-red-900/20 black:bg-red-900/20 border border-red-200 dark:border-red-700 black:border-red-700 rounded-lg",children:[_e(Bs,{className:"w-4 h-4 text-red-500 flex-shrink-0"}),_e("p",{className:"text-sm text-red-700 dark:text-red-300 black:text-red-300",children:o})]}),Ht(re,{onClick:a,className:"w-full",disabled:s,isLoading:s,loadingText:"Verifying...",children:[_e(m,{className:"w-5 h-5 mr-2"}),i.text]}),d&&r&&_e("button",{type:"button",onClick:r,disabled:s,className:"w-full text-sm text-gray-500 dark:text-slate-400 black:text-gray-400 hover:underline disabled:opacity-50",children:"Skip for now"}),_e("p",{className:"text-xs text-gray-400 dark:text-slate-500 black:text-gray-500 text-center",children:"This grants the agent permission for this specific transaction."})]}),_e("div",{id:"visa-auth-container",className:"w-full max-w-md mx-auto rounded-2xl overflow-hidden empty:hidden"}),n&&_e("div",{className:"text-center px-4 mt-4",children:_e("button",{type:"button",onClick:n,disabled:s,className:"text-sm text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline disabled:opacity-50",children:"Back to checkout"})})]})};$a.displayName="AgentRegistrationView";import{useEffect as Qr,useCallback as sr,useState as We,useRef as Xr,useMemo as El}from"react";import{useState as Fe,useEffect as Vr,useCallback as se,useRef as ja}from"react";var j=class extends Error{constructor(t,a,r){super(t),this.name="ApiError",this.status=a,this.details=r}};function Gn(e,t){if(!e)return"";if(e.startsWith("+")){let r=e.replace(/\D/g,"");if(r.length>=4&&r.length<=15)return`+${r}`}let a=e.replace(/\D/g,"");if(t){let r=Ce.find(n=>n.code===t);if(r){let n=r.dial.replace(/\D/g,""),s=Ot(a,r),o=`+${n}${s}`;if(s.length>0&&o.length<=16)return o}}return a.length===10?`+1${a}`:a.length===11&&a.startsWith("1")?`+${a}`:a.length===0||a.length>15?"":`+${a}`}function Ha(e){return{id:e.id||e.cardId,brand:e.brand?.toLowerCase()||"unknown",last4:e.last4,expiryMonth:e.expMonth?.toString()||e.expiryMonth||"",expiryYear:e.expYear?.toString()||e.expiryYear||"",cardholderName:e.cardholderName,isDefault:e.isDefault||!1,network:e.brand?.toLowerCase()||"visa",passkeyEnrolled:e.passkeyEnrolled||!1,cardArtUrl:e.cardArt||e.artwork||e.cardArtUrl,issuerName:e.issuerName,provider:e.provider}}async function ie(e,t,a,r={}){let n=`${e}${t}`,s={"Content-Type":"application/json",Authorization:`Bearer ${a}`,"ngrok-skip-browser-warning":"true"};try{let o=await fetch(n,{...r,headers:{...s,...r.headers}}),d=o.headers.get("content-type"),i;if(d&&d.includes("application/json"))i=await o.json();else{let m=await o.text();try{i=JSON.parse(m)}catch{throw m.includes("<!DOCTYPE")||m.includes("<html")?new j("Received HTML instead of JSON. Ngrok bypass header may not be working.",o.status,"HTML response received"):new j("Invalid JSON response from server",o.status,m.substring(0,200))}}if(!o.ok)throw new j(i.message||"An error occurred",o.status);return i}catch(o){throw o instanceof j?o:new j(o instanceof Error?o.message:"Network error",0)}}async function Ar(e,t,a,r){let n=Gn(a,r),s=await ie(e,"/api/otp/payos-link/generate",t,{method:"POST",body:JSON.stringify({phone:n,channel:"sms"})});if(s.error||!s.data)throw new j(s.message||"Failed to send verification code",400);return s.data.reference}async function Kn(e,t,a,r){let n=await ie(e,"/api/otp/payos-link/verify",t,{method:"POST",body:JSON.stringify({reference:a,code:r})});if(n.error||!n.data)throw new j(n.message||"Invalid verification code",400);return n.data}async function Os(e,t,a){let r=await ie(e,`/api/otp/payos-link/status/${a}`,t,{method:"GET"});if(r.error||!r.data)throw new j(r.message||"Failed to get verification status",400);return r.data}async function Yn(e,t,a,r,n){try{let s=await Os(e,t,a),o=new Date(s.createdAt),d=Date.now()-o.getTime(),i=30*1e3;if(d<i&&s.status==="pending"){let g=Math.ceil((i-d)/1e3);return{reference:a,waitTimeRemaining:g}}return{reference:await Ar(e,t,r,n)}}catch(s){throw s}}async function Zn(e,t,a,r,n){let s=Gn(a,n),o=await ie(e,"/api/wallet-users/process-verified-wallet-user",t,{method:"POST",body:JSON.stringify({phone:s,verificationId:r})});if(o.error||!o.data)throw new j(o.message||"Failed to process wallet user",400);let d=(o.data.savedCards||[]).map(Ha);return{...o.data,savedCards:d}}async function Ga(e,t,a){let r=await ie(e,`/api/wallet-users/${a}/cards`,t,{method:"GET"});if(r.error)throw new j(r.message||"Failed to get wallet user cards",400);return(r.data||[]).map(Ha)}async function qn(e,t,a){let r=await ie(e,`/api/wallet-users/${a}/cards?include=stripe_link`,t,{method:"GET"});if(r.error)throw new j(r.message||"Failed to get wallet user cards",400);return{cards:(r.data||[]).map(Ha),linkSyncStatus:r.linkSyncStatus??null}}function Gt(e,t){return`/api/wallet-users/${e}/link${t}`}function _s(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`idem-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}async function jn(e,t,a){let r=await ie(e,Gt(a,"/auth/status"),t,{method:"GET"});if(r.error)throw new j(r.message||"Failed to get Link auth status",400);return r.data}async function Jn(e,t,a,r){let n=await ie(e,Gt(a,"/auth/initiate"),t,{method:"POST",body:JSON.stringify(r||{})});if(n.error)throw new j(n.message||"Failed to initiate Link auth",400);return n.data}async function Qn(e,t,a){let r=await ie(e,Gt(a,"/auth/poll"),t,{method:"GET"});if(r.error)throw new j(r.message||"Failed to poll Link auth",400);return r.data}async function Xn(e,t,a){let r=await ie(e,Gt(a,"/auth/logout"),t,{method:"POST"});if(r.error)throw new j(r.message||"Failed to revoke Link",400);return r.data}async function eo(e,t,a,r,n){let s=n?.idempotencyKey||_s(),o=await ie(e,Gt(a,"/spend/create"),t,{method:"POST",headers:{"Idempotency-Key":s},body:JSON.stringify(r)});if(o.error)throw new j(o.message||"Failed to create Link spend request",400);return o.data}async function to(e,t,a,r){let n=await ie(e,Gt(a,`/spend/${r}/poll`),t,{method:"POST"});if(n.error)throw new j(n.message||"Failed to poll Link spend",400);return n.data}async function Ka(e,t){let a=await ie(e,"/web/sessions/current",t,{method:"GET"});if(a.error||!a.data)throw new j(a.message||"Failed to get session",400);return a.data}async function ao(e,t){let a=await ie(e,"/web/sessions/current/start",t,{method:"PATCH"});if(a.error||!a.data)throw new j(a.message||"Failed to start session",400);return a.data}async function Ya(e,t){let a=await ie(e,"/web/sessions/current/complete",t,{method:"POST"});if(a.error||!a.data)throw new j(a.message||"Failed to complete session",400);return a.data}async function ro(e,t){let a=await ie(e,"/web/sessions/current/abandon",t,{method:"POST"});if(a.error||!a.data)throw new j(a.message||"Failed to abandon session",400);return a.data}async function Dt(e,t,a){let r=await ie(e,"/web/sessions/current/payment-intent",t,{method:"PATCH",body:JSON.stringify(a)});if(r.error||!r.data)throw new j(r.message||"Failed to update payment intent",400);return r.data}async function no(e,t,a){let r=`${e}/api/payment-credentials/generate`,n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"ngrok-skip-browser-warning":"true"},body:JSON.stringify({paymentIntentId:a})}),s=n.headers.get("content-type"),o;if(s&&s.includes("application/json"))o=await n.json();else{let d=await n.text();try{o=JSON.parse(d)}catch{throw new j("Invalid response from credential generation",n.status,d.substring(0,200))}}if(!n.ok)throw new j(o.message||"Failed to generate credentials",n.status,o.data?.status);return{status:o.data?.status||"success",message:o.message,retrievalToken:o.data?.retrievalToken,approvalId:o.data?.approvalId}}async function oo(e,t,a,r){let n=await ie(e,`/api/wallet-users/${a}/cards/${r}/default`,t,{method:"PUT"});if(n.error)throw new j(n.message||"Failed to set default card",400);return Ha(n.data||{id:r,isDefault:!0})}async function io(e,t,a,r){let n=await ie(e,`/api/wallet-users/${a}/cards/${r}`,t,{method:"DELETE"});if(n.error)throw new j(n.message||"Failed to delete card",400);return{success:!0}}async function so(e,t,a,r){let n=new URLSearchParams({deviceId:a});r&&n.set("walletUserId",r);let s=await ie(e,`/web/device-trust?${n}`,t,{method:"GET"});return s.error?{isTrusted:!1}:{isTrusted:s.data?.isTrusted??!1,expiresAt:s.data?.expiresAt,walletUserId:s.data?.walletUserId}}async function lo(e,t,a,r){return(await ie(e,"/web/device-trust",t,{method:"POST",body:JSON.stringify({deviceId:a,walletUserId:r})})).error?{success:!1}:{success:!0}}var co="payos_device_id",Fs="payos_device_created";function zs(){let e=[];e.push(`${screen.width}x${screen.height}`),e.push(`${screen.colorDepth}`),e.push(Intl.DateTimeFormat().resolvedOptions().timeZone),e.push(navigator.language),e.push(navigator.platform),e.push(navigator.userAgent),e.push(String(navigator.hardwareConcurrency||0));let t=navigator;e.push(String(t.deviceMemory||0));let a=e.join("|");return Ws(a)}function Ws(e){let t=2166136261;for(let a=0;a<e.length;a++)t^=e.charCodeAt(a),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function po(){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Mr(){try{let e=localStorage.getItem(co);if(e)return e;let t=zs(),a=po().substring(0,8),r=`${t}-${a}`;return localStorage.setItem(co,r),localStorage.setItem(Fs,new Date().toISOString()),r}catch{return po()}}function Za(e,t,a){let r,n;t&&(r=e.find(o=>o.id===t)),!r&&a&&(r=e.find(o=>o.id===a)),r||(r=e.find(o=>o.isDefault)||e[0],n=r?.id);let s=t&&r?.id===t?t:void 0;return{selectedCard:r,cardToSync:s}}function qa(e){return!!e?.payments?.some(t=>t.credentialStatus==="active"||t.credentialStatus==="retrieved")}function Ur(e,t){let{apiBaseUrl:a,exitOnCardAdd:r=!1,skipCredentialGeneration:n=!1,cardId:s,skipToAuth:o=!1,preferMethodList:d=!1}=t,[i,m]=Fe(null),[g,p]=Fe("LOADING"),[b,c]=Fe(!0),[y,h]=Fe(null),[v,u]=Fe(null),[f,l]=Fe("checkout"),[x,L]=Fe(""),[w,V]=Fe("initial"),[D,N]=Fe(null),[C,T]=Fe(null),[A,B]=Fe(null),k=ja(!0),M=ja(e),K=ja(!1),O=ja();Vr(()=>{M.current!==e&&(K.current=!1,u(null)),M.current=e},[e]);let _=se((R,S)=>{let{session:P,paymentIntent:E}=R,ee=E?{id:E.id,type:E.type,currency:E.currency,organizationId:E.organizationId,status:E.status,totalAmount:E.totalAmount,totalSubtotal:E.totalSubtotal??E.totalAmount,totalTax:E.totalTax,totalShipping:E.totalShipping,payments:E.payments.map(Y=>({id:Y.id,merchantName:Y.merchantName,merchantUrl:Y.merchantUrl,amount:Y.amount,subtotal:Y.subtotal||Y.amount,tax:Y.tax,shipping:Y.shipping,description:Y.description,quantity:Y.quantity,credentialStatus:Y.credentialStatus,status:Y.status,createdAt:Y.createdAt,updatedAt:Y.updatedAt})),intentType:E.intentType||"standard",walletUserId:E.walletUserId,selectedCardId:E.selectedCardId,requireHitl:E.requireHitl??!1,hitlAttemptCount:E.hitlAttemptCount??0,hitlApproved:E.hitlApproved??!1,networkAuthRequired:E.networkAuthRequired??!1,networkAuthCompleted:E.networkAuthCompleted??!1,authValid:E.authValid??!1,credentialType:E.credentialType||"pci_vault_token",createdAt:E.createdAt,updatedAt:E.updatedAt,facilitationFee:void 0}:S?.paymentIntent||void 0,U=R.sessionType==="wallet_onboard"||R.sessionType==="wallet_onboard_agentic";if(!ee&&!U)throw new Error("No payment intent available");let G="initialized";return P.status==="complete"?G="completed":P.status==="expired"?G="expired":P.status==="abandoned"?G="abandoned":S?.deviceVerified&&(G="verified"),{id:P.id,status:G,sessionType:R.sessionType||void 0,organizationId:P.organizationId,paymentIntent:ee,linkToken:M.current,walletUser:S?.walletUser,savedCards:S?.savedCards||[],selectedCard:S?.selectedCard,deviceVerified:S?.deviceVerified||!1,verificationMethod:"phone",verificationReference:D||"",verificationPhone:C||"",validCardBrandAcceptance:R.validCardBrandAcceptance??S?.validCardBrandAcceptance,expiresAt:P.expiresAt,createdAt:P.createdAt,updatedAt:P.updatedAt}},[D,C]),Q=se(R=>{if(!R)return"LOADING";switch(R.status){case"initialized":return R.deviceVerified?"PAYMENT":"IDENTITY";case"otp_pending":return"OTP_VERIFY";case"verified":case"payment_pending":return"PAYMENT";case"completed":return"SUCCESS";case"expired":return"EXPIRED";case"abandoned":return"ERROR";default:return"IDENTITY"}},[]);Vr(()=>(k.current=!0,K.current?void 0:((async()=>{K.current=!0,c(!0),h(null);try{let S=await Ka(a,e),P=S.sessionType==="wallet_onboard"||S.sessionType==="wallet_onboard_agentic",E=S.paymentIntent?.status;if(!P&&E&&["approved","credentials_ready","completed","awaiting_payment"].includes(E)){k.current&&(h({code:"PAYMENT_INTENT_ALREADY_PROCESSED",message:E==="completed"?"This payment has already been completed.":E==="awaiting_payment"?"This payment is already in progress.":"This payment has already been approved. Use the credentials API to retrieve or regenerate.",sessionId:S.session.id}),p("ERROR"));return}await ao(a,e);let U=_(S),G=S.walletUserId;if(S.identityPreVerified&&G){try{U.deviceVerified=!0,U.status="verified",U.walletUser={id:G};let vt=await Ga(a,e,G);if(U.savedCards=vt||[],O.current=vt?.find(ce=>ce.isDefault)?.id,!P&&U.savedCards.length>0){let{selectedCard:ce,cardToSync:$e}=Za(U.savedCards,s,S.paymentIntent?.selectedCardId);if(U.selectedCard=ce,$e)try{await Dt(a,e,{selectedCardId:$e})}catch{}}}catch{}if(U.walletUser){k.current&&(m(U),p(Q(U)));return}}let Y=S.paymentIntent?.walletUserId;if(Y)try{let vt=Mr();if((await so(a,e,vt,Y)).isTrusted){U.deviceVerified=!0,U.status="verified";let $e=await Ga(a,e,Y);if(U.walletUser={id:Y},U.savedCards=$e||[],O.current=$e?.find(Ut=>Ut.isDefault)?.id,!P&&U.savedCards.length>0){let{selectedCard:Ut,cardToSync:Ct}=Za(U.savedCards,s,S.paymentIntent?.selectedCardId);if(U.selectedCard=Ut,Ct)try{await Dt(a,e,{selectedCardId:Ct})}catch{}}}}catch{}k.current&&(m(U),p(Q(U)))}catch(S){if(k.current){let P=S,E=P.status===410||P.message?.toLowerCase().includes("expired");h({code:E?"SESSION_EXPIRED":"LOAD_FAILED",message:P.message||"Failed to load session",sessionId:e}),p(E?"EXPIRED":"ERROR")}}finally{k.current&&c(!1)}})(),()=>{k.current=!1})),[e,Q,_,a]);let X=i?.sessionType==="wallet_onboard"||i?.sessionType==="wallet_onboard_agentic",F=!X&&(i?.paymentIntent?.type==="pay_on_behalf"||i?.paymentIntent?.type==="agent_to_agent"||i?.paymentIntent?.type==="agentic_multi"),de=!!i?.selectedCard,Le=(i?.savedCards?.length??0)>0;Vr(()=>{g==="PAYMENT"&&l(X?"add":o&&de?"checkout":d?"methods":de?"checkout":Le?"methods":"add")},[g,X,o,d,de,Le]);let bt=se(()=>{l("methods")},[]),Xe=se(()=>{l("add")},[]),et=se(()=>{l(de?"checkout":Le?"methods":"add")},[de,Le]),tt=se(()=>{p("IDENTITY")},[]),ht=se(async R=>{if(!i||!R.phone)return!1;c(!0);try{let S=await Ar(a,M.current,R.phone,R.countryCode);return k.current&&(N(S),T(R.phone),B(R.countryCode||null),m(P=>P?{...P,status:"otp_pending",verificationReference:S,verificationPhone:R.phone}:null),p("OTP_VERIFY")),!0}catch(S){let P=S;return k.current&&h({code:"VERIFICATION_FAILED",message:P.message||"Failed to send verification",sessionId:i.id}),!1}finally{k.current&&c(!1)}},[i,a]),at=se(async R=>{if(!i||!D||!C)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session or verification context"}};c(!0);try{let S=await Kn(a,M.current,D,R),P=await Zn(a,M.current,S.phone,S.reference,A||void 0);if(k.current){let E,ee;if(!(i.sessionType==="wallet_onboard"||i.sessionType==="wallet_onboard_agentic")&&P.savedCards.length>0){let G=Za(P.savedCards,s,i.paymentIntent?.selectedCardId);if(E=G.selectedCard,ee=G.cardToSync,ee)try{await Dt(a,M.current,{selectedCardId:ee})}catch{}}m(G=>G?{...G,status:"verified",deviceVerified:!0,walletUser:{id:P.walletUserId,phone:S.phone},savedCards:P.savedCards,selectedCard:E,...G.paymentIntent&&{paymentIntent:{...G.paymentIntent,walletUserId:P.walletUserId,...ee&&{selectedCardId:ee}}}}:null),p("PAYMENT"),O.current=P.savedCards?.find(G=>G.isDefault)?.id;try{let G=Mr();await lo(a,M.current,G,P.walletUserId)}catch{}}return{success:!0,walletUserId:P.walletUserId}}catch(S){return{success:!1,error:{code:"INVALID_OTP",message:S.message||"Invalid verification code"}}}finally{k.current&&c(!1)}},[i,D,C,A,a]),yt=se(async()=>{if(!i||!D||!C)return!1;c(!0);try{let R=await Yn(a,M.current,D,C,A||void 0);return R.waitTimeRemaining?!1:(k.current&&R.reference!==D&&N(R.reference),!0)}catch{return!1}finally{k.current&&c(!1)}},[i,D,C,A,a]),rt=se(async R=>{if(!i)return!1;c(!0);try{i.paymentIntent&&await Dt(a,M.current,{selectedCardId:R});let S=i.savedCards.find(P=>P.id===R);return k.current&&(m(P=>P?{...P,selectedCard:S,...P.paymentIntent&&{paymentIntent:{...P.paymentIntent,selectedCardId:R}}}:null),l("checkout")),!0}catch(S){let P=S;if(k.current){let E=P.message?.includes("spending limit")?"ISSUER_LIMIT_EXCEEDED":"CARD_SELECT_FAILED";h({code:E,message:P.message||"Failed to select card",sessionId:i.id})}return!1}finally{k.current&&c(!1)}},[i,a]),nt=se(async R=>{if(!i)return{success:!1};c(!0);try{let S={id:R.cardId,brand:R.brand?.toLowerCase()||"unknown",last4:R.last4,expiryMonth:R.expiryMonth||R.expMonth?.toString()||"",expiryYear:R.expiryYear||R.expYear?.toString()||"",cardholderName:R.cardholderName,isDefault:!1,network:R.network?.toLowerCase()||"visa",cardArtUrl:R.cardArtUrl};if(i.paymentIntent&&await Dt(a,M.current,{selectedCardId:S.id}),k.current){if(m(U=>U?{...U,savedCards:[...U.savedCards,S],selectedCard:S,...U.paymentIntent&&{paymentIntent:{...U.paymentIntent,selectedCardId:S.id}}}:null),i.sessionType==="wallet_onboard"||i.sessionType==="wallet_onboard_agentic"){if(i.walletUser?.id)try{let U=await Ga(a,M.current,i.walletUser.id),G=U.find(Y=>Y.id===S.id)||S;m(Y=>Y?{...Y,savedCards:U,selectedCard:G}:null)}catch{}if(r){p("PROCESSING");try{return await Ya(a,M.current),k.current&&(m(U=>U?{...U,status:"completed"}:null),p("SUCCESS")),{success:!0,card:S}}catch(U){let G=U;return k.current&&(h({code:"PAYMENT_FAILED",message:G.message||"Failed to complete session",sessionId:i.id}),p("PAYMENT"),l("methods")),{success:!1}}}return l("methods"),{success:!0,card:S}}let E=i.paymentIntent?.type;E==="pay_on_behalf"||E==="agent_to_agent"||E==="agentic_multi"?(V("initial"),p("AGENT_REGISTRATION")):l("checkout")}return{success:!0,card:S}}catch(S){let P=S;return k.current&&h({code:"CARD_ADD_FAILED",message:P.message||"Failed to add card",sessionId:i.id}),{success:!1}}finally{k.current&&c(!1)}},[i,a,r]),xt=se(async R=>{if(!i||!i.walletUser?.id)return!1;c(!0);try{if(await io(a,M.current,i.walletUser.id,R),k.current){let S=i.savedCards.filter(E=>E.id!==R),P=i.selectedCard?.id===R;m(E=>E?{...E,savedCards:S,selectedCard:P?void 0:E.selectedCard,...E.paymentIntent&&{paymentIntent:{...E.paymentIntent,selectedCardId:P?void 0:E.paymentIntent.selectedCardId}}}:null),S.length===0&&l("add")}return!0}catch(S){let P=S;return k.current&&h({code:"CARD_DELETE_FAILED",message:P.message||"Failed to delete card",sessionId:i.id}),!1}finally{k.current&&c(!1)}},[i,a]),z=se(async()=>{if(i)try{i.paymentIntent&&await Dt(a,M.current,{selectedCardId:void 0}),k.current&&m(R=>R?{...R,selectedCard:void 0,...R.paymentIntent&&{paymentIntent:{...R.paymentIntent,selectedCardId:void 0}}}:null)}catch{}},[i,a]),be=se(()=>{V("initial"),p("PAYMENT"),l("checkout")},[]),me=se(()=>{V("initial"),p("PAYMENT"),l("checkout")},[]),oe=se(async R=>{if(!i||!i.walletUser?.id)return!1;m(S=>S?{...S,savedCards:S.savedCards.map(P=>({...P,isDefault:P.id===R}))}:null);try{return await oo(a,M.current,i.walletUser.id,R),O.current=R,!0}catch(S){let P=O.current;k.current&&P&&m(ee=>ee?{...ee,savedCards:ee.savedCards.map(U=>({...U,isDefault:U.id===P}))}:null);let E=S;return k.current&&h({code:"CARD_SELECT_FAILED",message:E.message||"Failed to set default card",sessionId:i.id}),!1}},[i,a]),Mt=se(async()=>{if(!i)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session"}};u(null),p("PROCESSING"),c(!0);try{await Ya(a,M.current);let R={success:!0,walletUserId:i.walletUser?.id};return k.current&&(u(R),m(S=>S?{...S,status:"completed"}:null),p("SUCCESS")),R}catch(R){let P={success:!1,error:{code:"PAYMENT_FAILED",message:R.message||"Failed to complete session"}};return k.current&&(h({code:P.error.code,message:P.error.message,sessionId:i.id}),p("PAYMENT"),l("methods")),P}finally{k.current&&c(!1)}},[i,a]),kt=se(async R=>{if(!i)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session"}};u(null),p("PROCESSING"),c(!0);try{let S=!X&&F&&R?.passkeyAuthenticated&&i.paymentIntent&&!n,P=!1;S&&(await no(a,M.current,i.paymentIntent.id),P=!0),await Ya(a,M.current);let E=i.paymentIntent;if(S)try{let G=await Ka(a,M.current),Y=_(G,i);Y.paymentIntent&&(E=Y.paymentIntent)}catch{}let ee=qa(E)||P,U={success:!0,walletUserId:i.walletUser?.id,paymentIntentId:i.paymentIntent?.id,credentialGenerated:ee};return k.current&&(u(U),m(G=>G?{...G,status:"completed",paymentIntent:E}:null),p("SUCCESS")),U}catch(S){let P=S,ee={success:!1,error:{code:P.message?.includes("credential")||P.message?.includes("generate")?"CREDENTIAL_GENERATION_FAILED":"PAYMENT_FAILED",message:P.message||"Payment failed"}};return k.current&&(h({code:ee.error.code,message:ee.error.message,sessionId:i.id}),p("PAYMENT")),ee}finally{k.current&&c(!1)}},[i,F,X,a,n,_]),ot=se(async()=>{if(i)try{await ro(a,M.current)}catch{}},[i,a]),Vt=se(()=>{h(null)},[]),wt=se(async()=>{if(i){c(!0);try{let R=await Ka(a,M.current),S=_(R,i);k.current&&(m(S),p(Q(S)))}catch(R){let S=R;k.current&&h({code:"LOAD_FAILED",message:S.message||"Failed to refresh session",sessionId:i.id})}finally{k.current&&c(!1)}}},[i,Q,_,a]);return{session:i,setSession:m,phase:g,loading:b,error:y,completionResult:v,isAgentMode:F,isSetupMode:X??!1,hasSelectedCard:de,hasSavedCards:Le,paymentView:f,cvc:x,setCvc:L,showMethodList:bt,showAddCard:Xe,returnToCheckout:et,submitIdentity:ht,goBackToIdentity:tt,submitOTP:at,resendCode:yt,selectPaymentCard:rt,addPaymentCard:nt,deletePaymentCard:xt,clearCard:z,registrationSubPhase:w,setRegistrationSubPhase:V,skipRegistration:be,completeAgentRegistration:me,setPhase:p,setPaymentView:l,setDefaultCard:oe,completeSetup:Mt,complete:kt,abandon:ot,clearError:Vt,refresh:wt}}import{useRef as mo,useState as go,useEffect as $s,useCallback as Ge}from"react";import{PayOSPasskey as Hs}from"@payos-inc/payos-passkey-js";var Ja={enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,isLoading:!1,error:null,canRetry:!0,attemptsRemaining:void 0};function uo(e){let t=mo(null),[a,r]=go(!1),[n,s]=go(Ja),o=mo(!0);$s(()=>{if(!e.sessionSecret){r(!1);return}if(t.current){o.current=!0,a||r(!0);return}o.current=!0;try{t.current=new Hs(e.sessionSecret,{sandbox:e.sandbox,debug:e.debug,visaContainerId:e.visaContainerId,apiBaseUrl:e.apiBaseUrl}),r(!0)}catch(u){console.error("[usePasskeySDK] Failed to initialize SDK:",u),s(f=>({...f,error:u?.message||"Failed to initialize passkey SDK"})),r(!1)}return()=>{o.current=!1,setTimeout(()=>{!o.current&&t.current&&(t.current.cleanup(),t.current=null,r(!1))},100)}},[e]);let d=Ge(async u=>{if(!t.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};s(f=>({...f,isLoading:!0,error:null}));try{let f=await t.current.register(u);if(f.requiresStepUp){let l=(f.stepUpMethods||[]).map((x,L)=>({id:String(L),type:x.type?.toLowerCase()==="email"?"email":"sms",maskedValue:x.maskedValue||x.value||`Method ${L+1}`}));s(x=>({...x,isLoading:!1,enrollmentId:f.enrollmentId||null,stepUpMethods:l}))}else s(l=>({...l,isLoading:!1}));return f}catch(f){let l=f?.message||"Registration failed";return s(x=>({...x,isLoading:!1,error:l})),{success:!1,message:l,error:{code:"REGISTRATION_ERROR",message:l}}}},[]),i=Ge(async u=>{if(!t.current||!n.enrollmentId)return{success:!1};s(f=>({...f,isLoading:!0,error:null}));try{let f=await t.current.submitStepUpMethod(n.enrollmentId,u),l=n.stepUpMethods[u];return s(x=>({...x,isLoading:!1,selectedMethodDescription:l?.maskedValue||null})),f}catch(f){let l=f?.message||"Failed to send OTP";return s(x=>({...x,isLoading:!1,error:l})),{success:!1}}},[n.enrollmentId,n.stepUpMethods]),m=Ge(async u=>{if(!t.current||!n.enrollmentId)return{success:!1,message:"No enrollment in progress",error:{code:"NO_ENROLLMENT",message:"No active enrollment"}};s(f=>({...f,isLoading:!0,error:null}));try{let f=await t.current.validateStepUpOTP(n.enrollmentId,u);return f.success?s(l=>({...l,isLoading:!1,canRetry:!0,attemptsRemaining:void 0})):s(l=>({...l,isLoading:!1,error:f.message||"OTP validation failed",canRetry:f.canRetry??!0,attemptsRemaining:f.attemptsRemaining})),f}catch(f){let l=f?.message||"OTP validation failed";return s(x=>({...x,isLoading:!1,error:l})),{success:!1,message:l,error:{code:"OTP_ERROR",message:l}}}},[n.enrollmentId]),g=Ge(async u=>{if(!t.current||!n.enrollmentId)return{success:!1,message:"No enrollment in progress",error:{code:"NO_ENROLLMENT",message:"No active enrollment"}};s(f=>({...f,isLoading:!0,error:null}));try{let f=await t.current.completeVisaRegistration(n.enrollmentId,u);return s(l=>({...l,isLoading:!1,enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,error:f.success?null:f.message||"Registration failed"})),f}catch(f){let l=f?.message||"Registration failed";return s(x=>({...x,isLoading:!1,enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,error:l})),{success:!1,message:l,error:{code:"REGISTRATION_ERROR",message:l}}}},[n.enrollmentId]),p=Ge(async(u,f)=>{if(!t.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};s(l=>({...l,isLoading:!0,error:null}));try{let l=await t.current.authenticateForVicEnrollment(u,f);return s(x=>({...x,isLoading:!1})),l}catch(l){let x=l?.message||"VIC authentication failed";return s(L=>({...L,isLoading:!1,error:x})),{success:!1,message:x,error:{code:"VIC_AUTH_ERROR",message:x}}}},[]),b=Ge(async(u,f)=>{if(!t.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};s(l=>({...l,isLoading:!0,error:null}));try{let l=await t.current.authenticate(u,f);return s(x=>({...x,isLoading:!1})),l}catch(l){let x=l?.message||"Authentication failed";return s(L=>({...L,isLoading:!1,error:x})),{success:!1,message:x,error:{code:"AUTH_ERROR",message:x}}}},[]),c=Ge(()=>{s(u=>({...u,error:null}))},[]),y=Ge(()=>{s(Ja)},[]),h=Ge(()=>{t.current?.removeVisaIframeOnly(),s(Ja)},[]),v=Ge(()=>{t.current?.cleanup(),s(Ja)},[]);return{sdk:t.current,isReady:a,state:n,startRegistration:d,selectStepUpMethod:i,submitVisaOtp:m,completeVisaRegistration:g,authenticateForVicEnrollment:p,authenticate:b,clearError:c,resetState:y,removeVisaIframe:h,cleanup:v}}import{useCallback as Pe,useEffect as Fr,useRef as zr,useState as Kt}from"react";var Qa={},Gs=()=>{let a=Math.max(0,(window.screenX||0)+(window.outerWidth-400)/2),r=Math.max(0,(window.screenY||0)+(window.outerHeight-600)/2);return`width=400,height=600,left=${a},top=${r},toolbar=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes`},Ks={connect:"payos-link-connect",approval:"payos-link-approve"};function Xa(e,t){let a=Qa[e];if(a&&!a.closed)try{return a.location.href=t,a.focus(),a}catch{}let r=window.open("about:blank",Ks[e],Gs());if(r)try{r.location.href=t}catch{r.location.replace(t)}return Qa[e]=r,r}function we(e){let t=Qa[e];try{t&&!t.closed&&(t.close(),setTimeout(()=>{try{t&&!t.closed&&(t.blur(),window.focus())}catch{}},100))}catch{}Qa[e]=null}function er(){we("connect"),we("approval")}import{useCallback as Ys,useEffect as Zs,useRef as qs,useState as Br}from"react";function Or(e){let{baseUrl:t,token:a,walletUserId:r,enabled:n=!0}=e,[s,o]=Br(null),[d,i]=Br(!1),[m,g]=Br(null),p=qs(!1),b=Ys(async()=>{if(!(!n||!r)){i(!0),g(null);try{let c=await jn(t,a,r);p.current||o(c)}catch(c){p.current||g(c instanceof Error?c:new Error(String(c)))}finally{p.current||i(!1)}}},[t,a,r,n]);return Zs(()=>(p.current=!1,b(),()=>{p.current=!0}),[b]),{status:s,loading:d,error:m,refresh:b}}import{useEffect as js,useRef as Js}from"react";var Qs=new Set(["approved","denied","expired","error","revoked"]);function fo(e){let{baseUrl:t,token:a,walletUserId:r,enabled:n,intervalMs:s=1500,onApproved:o,onDenied:d,onExpired:i,onError:m,onTick:g}=e,p=Js({onApproved:o,onDenied:d,onExpired:i,onError:m,onTick:g});p.current={onApproved:o,onDenied:d,onExpired:i,onError:m,onTick:g},js(()=>{if(!n||!r)return;let b=!1,c=null,y=async()=>{if(!b){try{let h=await Qn(t,a,r);if(b)return;if(p.current.onTick?.(h),Qs.has(h.status)){h.status==="approved"?p.current.onApproved?.():h.status==="denied"?p.current.onDenied?.(h.error):h.status==="expired"?p.current.onExpired?.(h.error):p.current.onError?.(h.error);return}}catch(h){if(b)return;p.current.onError?.(h instanceof Error?h.message:String(h));return}c=setTimeout(y,s)}};return c=setTimeout(y,s),()=>{b=!0,c&&clearTimeout(c)}},[t,a,r,n,s])}import{useCallback as Xs,useEffect as el,useRef as tl,useState as tr}from"react";function _r(e){let{baseUrl:t,token:a,walletUserId:r,enabled:n=!0}=e,[s,o]=tr([]),[d,i]=tr(null),[m,g]=tr(!1),[p,b]=tr(null),c=tl(!1),y=Xs(async()=>{if(!(!n||!r)){g(!0),b(null);try{let u=await qn(t,a,r);if(c.current)return;o(u.cards),i(u.linkSyncStatus)}catch(u){c.current||b(u instanceof Error?u:new Error(String(u)))}finally{c.current||g(!1)}}},[t,a,r,n]);el(()=>(c.current=!1,y(),()=>{c.current=!0}),[y]);let h=s.filter(u=>u.provider==="stripe_link"),v=s.filter(u=>u.provider!=="stripe_link");return{cards:s,linkCards:h,payosCards:v,linkSyncStatus:d,loading:m,error:p,refresh:y}}import{useEffect as al,useRef as rl}from"react";var nl=new Set(["consumed","denied","expired","failed"]);function bo(e){let{baseUrl:t,token:a,walletUserId:r,spendRowId:n,enabled:s,intervalMs:o=1500,onApproved:d,onDenied:i,onExpired:m,onFailed:g,onConsumed:p,onTick:b}=e,c=rl({onApproved:d,onDenied:i,onExpired:m,onFailed:g,onConsumed:p,onTick:b});c.current={onApproved:d,onDenied:i,onExpired:m,onFailed:g,onConsumed:p,onTick:b},al(()=>{if(!s||!r||!n)return;let y=!1,h=null,v=!1,u=async()=>{if(!y){try{let f=await to(t,a,r,n);if(y)return;if(c.current.onTick?.(f),f.status==="approved"&&!v&&(v=!0,c.current.onApproved?.()),nl.has(f.status)){f.status==="consumed"?c.current.onConsumed?.():f.status==="denied"?c.current.onDenied?.(f.error):f.status==="expired"?c.current.onExpired?.(f.error):c.current.onFailed?.(f.error);return}}catch(f){if(y)return;c.current.onFailed?.(f instanceof Error?f.message:String(f));return}h=setTimeout(u,o)}};return h=setTimeout(u,o),()=>{y=!0,h&&clearTimeout(h)}},[t,a,r,n,s,o])}var ho=async()=>{};function ol(e){return e instanceof Error?e.message:String(e)}function Et(e){let{baseUrl:t,token:a,walletUserId:r,organizationId:n,enabled:s=!0,testMode:o,spendContext:d,onSpendApproved:i}=e,m=zr(i);Fr(()=>{m.current=i},[i]);let[g,p]=Kt("idle"),[b,c]=Kt(null),[y,h]=Kt(null),[v,u]=Kt(null),[f,l]=Kt(null),[x,L]=Kt(null),{status:w,loading:V,error:D,refresh:N}=Or({baseUrl:t,token:a,walletUserId:r,enabled:s}),C=s&&!!r&&w?.authenticated===!0,{cards:T,linkCards:A,payosCards:B,linkSyncStatus:k,loading:M,error:K,refresh:O}=_r({baseUrl:t,token:a,walletUserId:r,enabled:C}),_=zr(!1),Q=Pe(()=>{er(),_.current=!1,c(null),h(null),u(null),l(null),L(null),p("idle")},[]);fo({baseUrl:t,token:a,walletUserId:r,enabled:s&&g==="connect",onApproved:()=>{we("connect"),c(null),p("loading"),_.current=!0,N()},onDenied:z=>{we("connect"),c(null),l(z||"Authorization denied"),p("denied")},onExpired:z=>{we("connect"),c(null),l(z||"Authorization expired"),p("denied")},onError:z=>{we("connect"),c(null),l(z||"Authorization error"),p("denied")}}),Fr(()=>{if(!_.current||g!=="loading"||!w?.authenticated)return;_.current=!1;let z=!1,be=()=>{z||(z=!0,p(oe=>oe==="loading"?"checkout":oe))},me=setTimeout(be,8e3);return O().finally(()=>{clearTimeout(me),be()}),()=>{z=!0,clearTimeout(me)}},[w?.authenticated,g,O]);let X=Pe(async(z=y)=>{L(null);try{await m.current?.(z)}catch(be){L(ol(be))}},[y]);bo({baseUrl:t,token:a,walletUserId:r,spendRowId:y?.id||null,enabled:s&&!!y&&g==="checkout",onApproved:()=>{let z=y?{...y,approvalUrl:null,status:"approved"}:null;we("approval"),h(z),X(z)},onConsumed:()=>{we("approval"),p("success")},onDenied:z=>{we("approval"),l(z||"Spend approval denied"),p("denied")},onExpired:z=>{we("approval"),l(z||"Spend approval expired"),p("denied")},onFailed:z=>{we("approval"),l(z||"Spend approval failed"),p("denied")}});let F=Pe(async()=>{if(!r)return;l(null),p("connect");let z;try{z=await Jn(t,a,r,{organizationId:n})}catch(be){l(be instanceof Error?be.message:String(be)),p("denied");return}if(z.alreadyAuthenticated){c(null),p("loading"),_.current=!0,await N();return}c({passphrase:z.passphrase||z.userCode,verificationUrl:z.verificationUrl,verificationUrlComplete:z.verificationUrlComplete,expiresAt:Date.now()+z.expiresIn*1e3}),Xa("connect",z.verificationUrlComplete||z.verificationUrl)},[t,a,r,n]),de=Pe(()=>{we("connect"),c(null),p("idle")},[]),Le=Pe(async z=>{if(!r)return;l(null),L(null);let be={...z,...o?{test:!0}:{},...d&&!z.context?{context:d}:{}},me;try{me=await eo(t,a,r,be)}catch(oe){L(oe instanceof Error?oe.message:String(oe));return}h(me),me.approvalUrl&&Xa("approval",me.approvalUrl)},[t,a,r,o,d]),bt=Pe(()=>{y?.approvalUrl&&Xa("approval",y.approvalUrl)},[y?.approvalUrl]),Xe=Pe(()=>{we("approval"),h(null),u(null),p("idle")},[]),et=Pe(async()=>{y?.status==="approved"&&await X()},[y?.status,X]),tt=Pe(async()=>{let z=!!y;if(l(null),L(null),z){we("approval"),h(null),p("checkout");return}await F()},[y,F]),ht=Pe(async()=>{if(r){try{await Xn(t,a,r)}catch{}er(),c(null),h(null),u(null),p("idle"),await N()}},[t,a,r,N]),at=Pe(()=>p("manage"),[]),yt=Pe(()=>p("idle"),[]),rt=Pe(()=>{p("checkout"),O()},[O]),nt=Pe(()=>{h(null),p("idle")},[]),xt=zr(!1);return Fr(()=>()=>{xt.current=!0,er()},[]),{phase:g,authStatus:w,authLoading:V,authError:D,linkCards:A,payosCards:B,allCards:T,linkSyncStatus:k,methodsLoading:M,methodsError:K,selectedLinkMethodId:v,setSelectedLinkMethodId:u,spendError:x,clearSpendError:()=>L(null),currentSpend:y,deviceAuthContext:b,deniedReason:f,startLinkConnect:F,cancelLinkConnect:de,approveLinkSpend:Le,reopenLinkSpendApproval:bt,cancelLinkSpend:Xe,retryApprovedSpend:et,retryDenied:tt,signOutLink:ht,goToManage:at,goToCheckout:rt,exitManage:yt,exitSuccess:nt,reset:Q,refreshAuth:N??ho,refreshMethods:O??ho}}function yo(e,t){return t||(e==="sandbox"?"https://sandbox.api.payos.ai":"https://api.payos.ai")}import{createPortal as il}from"react-dom";import{X as sl}from"lucide-react";import{Fragment as ar,jsx as ve,jsxs as Je}from"react/jsx-runtime";function xo({open:e,layout:t,title:a,totalAmount:r,orderItems:n,subtotal:s,shipping:o,tax:d,agentFee:i,isAgentMode:m,isSetupMode:g,secondsRemaining:p,paymentView:b,hideHeader:c,confirmDialog:y,onClose:h,children:v}){return t==="inline"?Je(ar,{children:[y,ve("div",{className:"payos-scope payos-inline-sheet",children:v})]}):t==="embedded"?Je(ar,{children:[y,Je("div",{className:"payos-scope payos-embedded-sheet fixed inset-0 flex flex-col bg-white dark:bg-slate-900 black:bg-black",style:{paddingTop:"env(safe-area-inset-top)",paddingLeft:"env(safe-area-inset-left)",paddingRight:"env(safe-area-inset-right)"},children:[!c&&Je("div",{className:"flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-slate-800 black:border-[#1a1a1a]",children:[ve("h2",{className:"text-base font-semibold text-gray-900 dark:text-white black:text-white truncate",children:a}),r&&ve("span",{className:"text-base font-bold text-gray-900 dark:text-white black:text-white ml-2",children:r})]}),ve("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-4",style:{overscrollBehavior:"contain",...b!=="add"&&{maskImage:"linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)",WebkitMaskImage:"linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"}},children:v}),ve("div",{className:"px-4 pt-3",style:{paddingBottom:"calc(env(safe-area-inset-bottom) + 12px)"},children:ve(Ve,{})})]})]}):t==="modal"?il(Je(ar,{children:[y,ve("div",{className:"fixed inset-0 bg-black/40 dark:bg-black/50 black:bg-black/60 z-[9998] animate-in fade-in duration-200",onClick:h,"aria-hidden":"true"}),ve("div",{className:"payos-scope fixed inset-0 z-[9999] flex items-center justify-center p-4",role:"dialog","aria-modal":"true",children:Je("div",{className:"relative w-full max-w-md h-[700px] max-h-[90vh] bg-white dark:bg-slate-900 black:bg-black rounded-2xl shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 fade-in duration-200",children:[Je("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-slate-800 black:border-[#1a1a1a]",children:[ve("h2",{className:"text-lg font-bold text-gray-900 dark:text-white black:text-white",children:a}),Je("div",{className:"flex items-center gap-2",children:[r&&ve("span",{className:"text-lg font-bold text-gray-900 dark:text-white black:text-white",children:r}),ve("button",{onClick:h,className:"p-2 rounded-full hover:bg-gray-100 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a] transition-colors","aria-label":"Close",children:ve(sl,{className:"w-5 h-5 text-gray-600 dark:text-slate-400 black:text-gray-400"})})]})]}),ve("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{overscrollBehavior:"contain",...b!=="add"&&{maskImage:"linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)",WebkitMaskImage:"linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"}},children:v}),ve(Ve,{className:"px-6 py-4"})]})})]}),document.body):Je(ar,{children:[y,ve(Ra,{open:e,onClose:h,title:a,amount:r,orderItems:n,subtotal:s,shipping:o,tax:d,orderAgentFee:i,mode:g?"standard":m?"agent":"standard",secondsRemaining:p,disableContentMask:b==="add",children:v})]})}import ko from"react";import{jsx as Wr,jsxs as ll}from"react/jsx-runtime";function Ke({className:e="h-11",markTone:t="green",wordmarkTone:a="auto"}){let r=t==="black"?"#000000":"#00D66F",n=t==="black"?"#ffffff":"#011e0f";return ll("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 72 24",className:`${e} ${a==="black"?"text-black":a==="white"?"text-white":"text-black dark:text-white black:text-white"}`,"aria-hidden":"true",children:[Wr("path",{d:"M36.12 3.67683c0-1.12801.9504-2.04481 2.0688-2.04481 1.1184 0 2.0688.9216 2.0688 2.04481 0 1.1232-.9168 2.0688-2.0688 2.0688-1.152 0-2.0688-.9168-2.0688-2.0688ZM29.9808 1.92001h3.6V22.08h-3.6V1.92001ZM40.008 7.68001h-3.6288V22.08h3.6288V7.68001ZM66.096 14.3904c2.7312-1.68 4.5888-4.1808 5.3232-6.71516h-3.6288c-.9456 2.41916-3.1152 4.23836-5.5008 5.01116V1.91523h-3.6288V22.0752h3.6288V16.08c2.7696.6912 4.9584 3.0864 5.7072 5.9952h3.6528c-.5568-3.0528-2.6448-5.9088-5.5536-7.6848ZM46.44 9.29283c.9504-1.2624 2.8032-1.99681 4.3056-1.99681 2.8032 0 5.1216 2.04961 5.1264 5.14558v9.6336h-3.6288v-8.832c0-1.272-.5664-2.7408-2.4048-2.7408-2.16 0-3.4032 1.9152-3.4032 4.1568v7.4256h-3.6288V7.68962H46.44v1.60321Z",fill:"currentColor"}),Wr("path",{d:"M12 24c6.6274 0 12-5.3726 12-12 0-6.62743-5.3726-12-12-12C5.37259 0 0 5.37257 0 12c0 6.6274 5.37259 12 12 12Z",fill:r}),Wr("path",{d:"M11.4479 4.80005H7.74707c.72 3.0096 2.82243 5.58235 5.45283 7.19995-2.6352 1.6176-4.73283 4.1904-5.45283 7.2h3.70083c.9168-2.784 3.456-5.2032 6.576-5.6976v-3.0095c-3.1248-.4896-5.664-2.90885-6.576-5.69285Z",fill:n})]})}import{jsx as pe,jsxs as ze}from"react/jsx-runtime";function la({passphrase:e,popupBlocked:t=!1,onReopen:a,onCancel:r}){return ze("div",{className:"flex flex-col items-center justify-center min-h-full p-6 space-y-5",children:[ze("div",{className:"text-center space-y-3",children:[ze("h2",{className:"text-3xl sm:text-5xl font-bold text-slate-900 dark:text-white black:text-white tracking-tight flex items-center justify-center gap-2 sm:gap-3 whitespace-nowrap",children:[pe("span",{children:"Connect to"}),pe(Ke,{className:"h-7 sm:h-11"})]}),ze("p",{className:"text-sm text-gray-500 dark:text-slate-400 black:text-gray-400",children:["We opened a window to ",pe("span",{className:"font-mono",children:"app.link.com"}),". Sign in there to continue."]})]}),ze("div",{className:"w-full max-w-sm rounded-xl border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] p-4 bg-white dark:bg-slate-900 black:bg-black text-center space-y-2",children:[pe("p",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-slate-500 black:text-gray-500",children:"Confirm this code matches what Link shows you"}),e?pe("div",{className:"inline-flex items-center gap-1 text-sm font-mono font-semibold text-slate-900 dark:text-white black:text-white flex-wrap justify-center",children:e.split("-").map((n,s,o)=>ze(ko.Fragment,{children:[pe("span",{className:"px-2 py-1 bg-gray-100 dark:bg-slate-800 black:bg-[#151515] rounded",children:n}),s<o.length-1&&pe("span",{className:"text-gray-400 dark:text-slate-500 black:text-gray-500 font-semibold",children:"-"})]},s))}):pe("div",{className:"inline-flex items-center gap-1 flex-wrap justify-center",children:[0,1,2,3].map(n=>ze(ko.Fragment,{children:[pe("span",{className:"px-2 py-1 rounded bg-gray-200 dark:bg-slate-800 black:bg-[#151515] animate-pulse w-16 h-6"}),n<3&&pe("span",{className:"text-gray-300 dark:text-slate-600 black:text-gray-700 font-semibold",children:"-"})]},n))})]}),ze("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:[pe("style",{children:"@keyframes payosLinkDot { 0%, 80%, 100% { transform: scale(0.55); opacity: 0.35; } 40% { transform: scale(1); opacity: 1; } }"}),ze("span",{className:"inline-flex gap-1",children:[pe("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 dark:bg-slate-500 black:bg-gray-500",style:{animation:"payosLinkDot 1.2s ease-in-out infinite both",animationDelay:"0s"}}),pe("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 dark:bg-slate-500 black:bg-gray-500",style:{animation:"payosLinkDot 1.2s ease-in-out infinite both",animationDelay:"0.16s"}}),pe("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 dark:bg-slate-500 black:bg-gray-500",style:{animation:"payosLinkDot 1.2s ease-in-out infinite both",animationDelay:"0.32s"}})]}),"Waiting for approval"]}),pe("div",{className:"w-full max-w-sm space-y-2",children:t?ze("div",{className:"p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 black:bg-amber-900/20 text-amber-800 dark:text-amber-300 black:text-amber-300 border border-amber-200 dark:border-amber-800/60 black:border-amber-800/60 text-xs space-y-2",children:[pe("p",{children:"Popup was blocked by your browser. Click to open:"}),pe("button",{type:"button",onClick:a,className:"block w-full h-9 rounded bg-[#00D66F] hover:bg-[#00C264] text-black font-medium",children:"Open sign-in popup"})]}):ze("p",{className:"text-xs text-center text-gray-500 dark:text-slate-400 black:text-gray-400",children:["Didn't see a popup?"," ",pe("button",{type:"button",onClick:a,className:"underline font-medium hover:text-gray-900 dark:hover:text-white black:hover:text-white",children:"Try again"})]})}),pe("button",{type:"button",onClick:r,className:"w-full max-w-sm h-10 rounded-lg text-gray-500 dark:text-slate-400 black:text-gray-400 font-medium text-sm hover:bg-gray-100 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a]",children:"Cancel"})]})}import{jsx as rr,jsxs as wo}from"react/jsx-runtime";function Qe({message:e="Loading your Link wallet\u2026"}){return wo("div",{className:"flex flex-col items-center justify-center min-h-full p-6 space-y-4",children:[wo("div",{className:"flex space-x-1.5",children:[rr("span",{className:"w-2 h-2 rounded-full bg-slate-900 dark:bg-white black:bg-white animate-bounce [animation-delay:-0.3s]"}),rr("span",{className:"w-2 h-2 rounded-full bg-slate-900 dark:bg-white black:bg-white animate-bounce [animation-delay:-0.15s]"}),rr("span",{className:"w-2 h-2 rounded-full bg-slate-900 dark:bg-white black:bg-white animate-bounce"})]}),rr("p",{className:"text-sm text-gray-500 dark:text-slate-400 black:text-gray-400",children:e})]})}import{useEffect as vo,useState as Co}from"react";import{AlertCircle as dl,Loader2 as cl,X as pl}from"lucide-react";import{Fragment as Po,jsx as $,jsxs as ae}from"react/jsx-runtime";function ml(e){let t=(e||"").toLowerCase();return t.includes("reaches the limit")||t.includes("rate limit")?{heading:"Too many pending Link payments",body:"Please wait a few minutes for older approvals to expire or complete, then try again."}:t.includes("idempotency")?{heading:"Duplicate payment request",body:"This payment has already been submitted. Refresh and try again."}:t.includes("expired")&&t.includes("token")?{heading:"Link session expired",body:"Your sign-in to Link timed out. Re-connect to continue."}:t.includes("payment_methods.agentic")||t.includes("not authorized")?{heading:"Card not authorized for agentic payments",body:"Open your Link wallet and authorize this card for agentic spending, then try again."}:t.includes("consumer limits")?{heading:"Stripe couldn't check your limits",body:"Stripe Link hit an error evaluating your spending limits. Wait a moment and try again, or use a smaller amount."}:t.includes("500")||t.includes("something went wrong")?{heading:"Stripe is having trouble",body:"Stripe Link returned an unexpected error. Wait a moment and try again."}:{heading:"Couldn't authorize this payment",body:e}}function gl(e){let t=(e||"").toLowerCase();return t==="visa"||t==="mastercard"||t==="amex"||t==="discover"?t:"unknown"}function ul(e){return e?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():"Card"}function So({method:e}){let t=e.expiryMonth&&e.expiryYear?`${String(e.expiryMonth).padStart(2,"0")}/${String(e.expiryYear).slice(-2)}`:"";return ae("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[$("div",{className:"w-12 bg-white dark:bg-slate-900 black:bg-black border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] overflow-hidden flex items-center justify-center flex-shrink-0",style:{aspectRatio:"1.586",borderRadius:"3px"},children:$(dt,{brand:gl(e.brand)})}),ae("div",{className:"flex-1 min-w-0 text-left",children:[ae("div",{className:"text-sm font-medium text-slate-900 dark:text-white black:text-white truncate",children:[ul(e.brand)," \u2022\u2022\u2022\u2022 ",e.last4||"\u2022\u2022\u2022\u2022"]}),t&&ae("div",{className:"text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:["Expires ",t]})]})]})}function $r({methods:e,selectedMethodId:t,onSelectMethod:a,onContinue:r,onCancel:n,continueLabel:s="Continue",onOpenLinkWallet:o,onReopenApproval:d,subState:i,approvalExpiresAt:m,errorMessage:g,onDismissError:p}){let b=i==="awaiting",c=i==="creating",y=i==="completing",[h,v]=Co(Date.now());vo(()=>{if(!b||!m)return;v(Date.now());let D=setInterval(()=>v(Date.now()),1e3);return()=>clearInterval(D)},[b,m]);let u=m?Math.max(0,Math.floor((m-h)/1e3)):null,f=u!=null?Math.floor(u/60):0,l=u!=null?String(u%60).padStart(2,"0"):"00",[x,L]=Co(!1),w=e.find(D=>D.id===t)||e[0]||null,V=!b&&!c&&!y&&e.length>0;return vo(()=>{!t&&e.length>0&&a(e[0].id)},[t,e,a]),ae("div",{className:"flex flex-col min-h-full p-5 relative",children:[g&&!b&&!y&&(()=>{let{heading:D,body:N}=ml(g);return $("div",{role:"alert",className:"absolute top-3 left-3 right-3 z-10 rounded-2xl bg-white dark:bg-slate-900 black:bg-black ring-1 ring-rose-200/70 dark:ring-rose-900/40 black:ring-rose-900/40 shadow-[0_8px_24px_-12px_rgba(244,63,94,0.35)] overflow-hidden animate-in slide-in-from-top-2 fade-in duration-200",children:ae("div",{className:"flex items-start gap-3 px-4 pt-3.5 pb-3",children:[$("div",{className:"flex-shrink-0 mt-0.5 w-7 h-7 rounded-full bg-rose-50 dark:bg-rose-950/40 black:bg-rose-950/40 flex items-center justify-center ring-1 ring-rose-100 dark:ring-rose-900/40 black:ring-rose-900/40",children:$(dl,{className:"w-4 h-4 text-rose-600 dark:text-rose-400 black:text-rose-400"})}),ae("div",{className:"min-w-0 flex-1",children:[$("p",{className:"text-[13px] font-semibold text-slate-900 dark:text-white black:text-white leading-snug",children:D}),$("p",{className:"text-[12px] text-slate-600 dark:text-slate-400 black:text-gray-400 mt-0.5 leading-relaxed break-words",children:N}),$("div",{className:"mt-2.5 flex flex-wrap items-center gap-2",children:$("a",{href:"mailto:support@payos.ai",className:"inline-flex items-center px-2.5 py-1 rounded-md border border-slate-200 dark:border-slate-700 black:border-[#1f1f1f] bg-white dark:bg-slate-900 black:bg-black text-slate-700 dark:text-slate-200 black:text-gray-200 text-[11px] font-medium hover:bg-slate-50 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a]",children:"Contact support"})})]}),p&&$("button",{type:"button","aria-label":"Dismiss",onClick:p,className:"flex-shrink-0 -mr-1 -mt-1 p-1.5 rounded-md text-slate-400 dark:text-slate-500 black:text-gray-500 hover:text-slate-700 dark:hover:text-slate-200 black:hover:text-gray-200 hover:bg-slate-100 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a] transition-colors",children:$(pl,{className:"w-3.5 h-3.5"})})]})})})(),ae("div",{className:"flex-1 flex flex-col justify-center space-y-4 py-12",children:[ae("div",{className:"text-center space-y-3",children:[ae("h2",{className:"text-5xl font-bold text-slate-900 dark:text-white black:text-white tracking-tight flex items-center justify-center gap-3",children:[$("span",{children:"Pay with"}),$(Ke,{})]}),$("p",{className:"text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:b?ae(Po,{children:["Approve this payment in the Link window at ",$("span",{className:"font-mono",children:"app.link.com"}),"."]}):y?"Finishing your payment securely.":"Approve this payment in Link to complete your purchase."})]}),b&&u!=null&&u>0&&$("div",{className:"flex justify-center",children:ae("span",{className:"inline-flex items-center text-sm font-medium text-gray-600 dark:text-slate-300 black:text-gray-300 px-3 py-1.5 rounded-full border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] bg-white dark:bg-slate-900 black:bg-black",children:["Expires in ",f,":",l]})}),y&&ae("div",{role:"status","aria-live":"polite",className:"pt-4 flex flex-col items-center justify-center gap-3 text-center",children:[$(cl,{className:"w-9 h-9 animate-spin text-slate-900 dark:text-white black:text-white"}),ae("div",{className:"space-y-1",children:[$("p",{className:"text-sm font-semibold text-slate-900 dark:text-white black:text-white",children:"Generating credentials"}),$("p",{className:"text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:"This usually takes a moment."})]})]}),!b&&!y&&ae("div",{className:"space-y-1",children:[ae("p",{className:"text-[10px] uppercase tracking-wider font-semibold text-gray-500 dark:text-slate-400 black:text-gray-400 px-1",children:["Link wallet",o&&ae(Po,{children:[" (",$("button",{type:"button",onClick:o,className:"uppercase tracking-wider font-semibold text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline",children:"manage"}),")"]})]}),ae("div",{className:"relative",children:[ae("button",{type:"button",onClick:()=>V&&L(D=>!D),disabled:!V&&e.length===0,className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl border bg-white dark:bg-slate-900 black:bg-black transition-colors ${V?"border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] hover:border-gray-400 dark:hover:border-slate-500 black:hover:border-[#333333] cursor-pointer":"border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] cursor-default"}`,children:[w?$(So,{method:w}):$("span",{className:"text-sm text-gray-400 dark:text-slate-500 black:text-gray-500",children:"No Link card available"}),V&&$("svg",{className:`w-4 h-4 text-gray-400 dark:text-slate-500 black:text-gray-500 transition-transform ${x?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:$("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),x&&V&&$("div",{className:"absolute left-0 right-0 mt-2 rounded-xl border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] bg-white dark:bg-slate-900 black:bg-black shadow-xl ring-1 ring-black/5 dark:ring-white/5 black:ring-white/10 z-10 overflow-hidden max-h-72 overflow-y-auto animate-in fade-in slide-in-from-top-1 duration-150",children:e.map((D,N)=>{let C=D.id===w?.id;return ae("button",{type:"button",onClick:()=>{a(D.id),L(!1)},className:`w-full flex items-center gap-3 px-4 py-3 transition-colors ${N>0?"border-t border-gray-100 dark:border-slate-800 black:border-[#1f1f1f]":""} ${C?"bg-[#00D66F]/10 hover:bg-[#00D66F]/15":"hover:bg-gray-50 dark:hover:bg-slate-800/60 black:hover:bg-[#0a0a0a] active:bg-gray-100 dark:active:bg-slate-800 black:active:bg-[#151515]"}`,children:[$(So,{method:D}),C&&$("svg",{className:"w-4 h-4 text-[#007f3f] dark:text-[#00D66F] black:text-[#00D66F] flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:$("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})]},D.id)})})]})]}),!y&&$("div",{className:b?"":"pt-4",children:ae("div",{className:"space-y-3",children:[!b&&$("button",{type:"button",onClick:r,disabled:!t||c||e.length===0,className:"w-full h-11 rounded-lg bg-[#00D66F] hover:bg-[#00C264] disabled:opacity-50 text-black font-semibold text-sm",children:c?"Preparing approval...":s}),b&&ae("div",{className:"space-y-2",children:[ae("button",{type:"button",disabled:!0,className:"w-full h-11 rounded-lg bg-[#00D66F] disabled:opacity-50 text-black font-semibold text-sm flex items-center justify-center gap-2",children:[$("style",{children:"@keyframes payosLinkApproval { 0%, 80%, 100% { transform: scale(0.55); opacity: 0.35; } 40% { transform: scale(1); opacity: 1; } }"}),ae("span",{className:"inline-flex gap-1",children:[$("span",{className:"w-1.5 h-1.5 rounded-full bg-black",style:{animation:"payosLinkApproval 1.2s ease-in-out infinite both",animationDelay:"0s"}}),$("span",{className:"w-1.5 h-1.5 rounded-full bg-black",style:{animation:"payosLinkApproval 1.2s ease-in-out infinite both",animationDelay:"0.16s"}}),$("span",{className:"w-1.5 h-1.5 rounded-full bg-black",style:{animation:"payosLinkApproval 1.2s ease-in-out infinite both",animationDelay:"0.32s"}})]}),"Awaiting approval"]}),d&&ae("p",{className:"text-center text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:["Don't see the popup?"," ",$("button",{type:"button",onClick:d,className:"font-semibold text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline",children:"Try again"})]})]}),$("div",{className:"flex items-center justify-center text-xs",children:$("button",{type:"button",onClick:n,className:"text-gray-500 dark:text-slate-400 black:text-gray-400 underline hover:text-gray-900 dark:hover:text-white black:hover:text-white",children:"Cancel"})})]})})]})]})}import{X as fl,Clock as bl}from"lucide-react";import{jsx as It,jsxs as Hr}from"react/jsx-runtime";var hl={denied:{heading:"Approval denied",body:"You declined this payment in Link."},expired:{heading:"Approval expired",body:"The approval window timed out. Tap Try again to send a new request."},cancelled:{heading:"Sign-in cancelled",body:"The Link window closed before approval. Tap Try again to reopen it."}};function yl(e){let t=(e||"").toLowerCase();return t.includes("expir")?"expired":t.includes("cancel")?"cancelled":"denied"}function da({reason:e,onRetry:t,onDismiss:a}){let r=yl(e),{heading:n,body:s}=hl[r],o=r==="expired";return Hr("div",{className:"flex flex-col items-center justify-center min-h-full p-6 space-y-5 text-center",children:[It("div",{className:`w-16 h-16 rounded-full flex items-center justify-center ${o?"bg-amber-100 dark:bg-amber-900/30 black:bg-amber-900/30":"bg-red-100 dark:bg-red-900/30 black:bg-red-900/30"}`,children:o?It(bl,{className:"h-9 w-9 text-amber-600 dark:text-amber-400 black:text-amber-400",strokeWidth:2.5}):It(fl,{className:"h-9 w-9 text-red-600 dark:text-red-400 black:text-red-400",strokeWidth:3})}),Hr("div",{className:"space-y-1",children:[It("h2",{className:"text-xl font-bold text-slate-900 dark:text-white black:text-white tracking-tight",children:n}),It("p",{className:"text-sm text-gray-500 dark:text-slate-400 black:text-gray-400",children:s})]}),Hr("div",{className:"flex flex-col gap-2 w-full max-w-sm",children:[t&&It("button",{type:"button",onClick:t,className:"w-full h-11 rounded-lg bg-[#00D66F] hover:bg-[#00C264] text-black font-semibold text-sm",children:"Try again"}),a&&It("button",{type:"button",onClick:a,className:"w-full h-10 rounded-lg text-gray-500 dark:text-slate-400 black:text-gray-400 font-medium text-sm hover:bg-gray-100 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a]",children:"Use a different method"})]})]})}import{jsx as Yt,jsxs as Lo}from"react/jsx-runtime";function ca({message:e="Successfully approved"}){return Lo("div",{className:"flex flex-col items-center justify-center min-h-full p-6 space-y-5 text-center",children:[Yt("style",{children:`
21
+ `,children:n===i.id&&Se("div",{className:"w-2.5 h-2.5 rounded-full bg-[#1A1F71] dark:bg-blue-400 black:bg-blue-400"})})}),Se("input",{type:"radio",name:"verification-method",value:i.id,checked:n===i.id,onChange:()=>s(i.id),className:"sr-only"}),Se("span",{className:"text-sm font-medium text-slate-900 dark:text-white black:text-white",children:d(i.type,i.maskedValue)})]},i.id))}),Se("div",{className:"p-4 pt-2",children:Se(re,{onClick:o,className:"w-full",disabled:!n||r,isLoading:r,loadingText:"Sending code...",children:"Confirm"})})]}),a&&Se("div",{className:"text-center",children:Se("button",{type:"button",onClick:a,className:"text-sm text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline disabled:opacity-50",children:"Go back"})})]})};Fa.displayName="VisaMethodView";import*as sa from"react";import{jsx as Oe,jsxs as za}from"react/jsx-runtime";var Ts="#1A1F71",Wa=({methodDescription:e,otp:t,onOtpChange:a,onVerify:r,onBack:n,onResend:s,onVerifyAnotherWay:o,isLoading:d=!1,error:i,canRetry:m=!0})=>{let g=sa.useRef(!1);sa.useEffect(()=>{t.length<6&&(g.current=!1)},[t]);let p=c=>{c.preventDefault(),t.length===6&&m&&!d&&(g.current=!0,r())};sa.useEffect(()=>{t.length===6&&!d&&m&&!g.current&&(g.current=!0,r())},[t,d,r,m]);let b=!m;return za("form",{onSubmit:p,className:"space-y-6",children:[Oe("div",{className:"flex items-center justify-center py-6",children:Oe("img",{src:Oa,alt:"Visa",className:"h-8 dark:brightness-0 dark:invert black:brightness-0 black:invert",style:{objectFit:"contain"}})}),za("div",{className:"text-center px-4 space-y-1",children:[za("p",{className:"text-sm text-gray-600 dark:text-slate-300 black:text-gray-300",children:["Enter the code sent to ",e,"."]}),s&&!b&&Oe("button",{type:"button",onClick:s,disabled:d,className:"text-sm font-semibold text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline disabled:opacity-50",children:"Resend code"})]}),za(ne,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] rounded-2xl p-6 space-y-6",children:[Oe("div",{className:d||b?"opacity-50 pointer-events-none":"",children:Oe(Ft,{value:t,onChange:a,length:6,variant:"underline",accentColor:typeof document<"u"&&document.documentElement.classList.contains("dark")?"#60a5fa":Ts})}),i&&Oe("p",{className:"text-sm text-red-600 dark:text-red-400 black:text-red-400 text-center",children:i}),Oe(re,{type:"submit",className:"w-full",disabled:t.length!==6||d||b,isLoading:d,loadingText:"Verifying...",children:"Verify"}),b&&o&&Oe("div",{className:"text-center",children:Oe("button",{type:"button",onClick:o,className:"text-sm text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline",children:"Verify another way"})})]}),Oe("div",{className:"text-center",children:Oe("button",{type:"button",onClick:n,className:"text-sm text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline disabled:opacity-50",children:"Go back"})})]})};Wa.displayName="VisaOtpView";import{AlertCircle as Bs}from"lucide-react";import{useMemo as As}from"react";import{Fingerprint as Ms,Smile as Vs,User as Us,Lock as $n}from"lucide-react";function Hn(){return As(()=>{if(typeof navigator>"u")return{text:"Enable Secure Access",icon:$n,type:"generic"};let e=navigator.userAgent.toLowerCase();return/iphone|ipad/.test(e)?{text:"Enable Passkey",icon:Vs,type:"faceId"}:/macintosh|mac os/.test(e)?{text:"Enable Passkey",icon:Ms,type:"touchId"}:/windows/.test(e)?{text:"Enable Passkey",icon:Us,type:"windowsHello"}:{text:"Enable Passkey",icon:$n,type:"generic"}},[])}import{jsx as _e,jsxs as Ht}from"react/jsx-runtime";var $a=({card:e,cardNetwork:t,onCreatePasskey:a,onSkip:r,onBack:n,isLoading:s=!1,error:o,showSkip:d=!1})=>{let i=Hn(),m=i.icon;return Ht("div",{className:"space-y-4 flex flex-col justify-center min-h-full",children:[Ht(ne,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] rounded-2xl p-6 space-y-6",children:[e.cardArtUrl&&_e("div",{className:"flex justify-center",children:_e(ra,{cardArtUrl:e.cardArtUrl,network:t,last4:e.last4})}),Ht("div",{className:"text-center space-y-2",children:[_e("h2",{className:"text-xl font-bold text-slate-900 dark:text-white black:text-white",children:"Turn on One-Touch Buying"}),Ht("p",{className:"text-sm text-gray-500 dark:text-slate-400 black:text-gray-400",children:["Secure your card ending in ",e.last4," for your AI Agent"]})]}),o&&Ht("div",{className:"flex items-center gap-2 p-3 bg-red-50 dark:bg-red-900/20 black:bg-red-900/20 border border-red-200 dark:border-red-700 black:border-red-700 rounded-lg",children:[_e(Bs,{className:"w-4 h-4 text-red-500 flex-shrink-0"}),_e("p",{className:"text-sm text-red-700 dark:text-red-300 black:text-red-300",children:o})]}),Ht(re,{onClick:a,className:"w-full",disabled:s,isLoading:s,loadingText:"Verifying...",children:[_e(m,{className:"w-5 h-5 mr-2"}),i.text]}),d&&r&&_e("button",{type:"button",onClick:r,disabled:s,className:"w-full text-sm text-gray-500 dark:text-slate-400 black:text-gray-400 hover:underline disabled:opacity-50",children:"Skip for now"}),_e("p",{className:"text-xs text-gray-400 dark:text-slate-500 black:text-gray-500 text-center",children:"This grants the agent permission for this specific transaction."})]}),_e("div",{id:"visa-auth-container",className:"w-full max-w-md mx-auto rounded-2xl overflow-hidden empty:hidden"}),n&&_e("div",{className:"text-center px-4 mt-4",children:_e("button",{type:"button",onClick:n,disabled:s,className:"text-sm text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline disabled:opacity-50",children:"Back to checkout"})})]})};$a.displayName="AgentRegistrationView";import{useEffect as Qr,useCallback as sr,useState as We,useRef as Xr,useMemo as El}from"react";import{useState as Fe,useEffect as Vr,useCallback as se,useRef as ja}from"react";var j=class extends Error{constructor(t,a,r){super(t),this.name="ApiError",this.status=a,this.details=r}};function Gn(e,t){if(!e)return"";if(e.startsWith("+")){let r=e.replace(/\D/g,"");if(r.length>=4&&r.length<=15)return`+${r}`}let a=e.replace(/\D/g,"");if(t){let r=Ce.find(n=>n.code===t);if(r){let n=r.dial.replace(/\D/g,""),s=Ot(a,r),o=`+${n}${s}`;if(s.length>0&&o.length<=16)return o}}return a.length===10?`+1${a}`:a.length===11&&a.startsWith("1")?`+${a}`:a.length===0||a.length>15?"":`+${a}`}function Ha(e){return{id:e.id||e.cardId,brand:e.brand?.toLowerCase()||"unknown",last4:e.last4,expiryMonth:e.expMonth?.toString()||e.expiryMonth||"",expiryYear:e.expYear?.toString()||e.expiryYear||"",cardholderName:e.cardholderName,isDefault:e.isDefault||!1,network:e.brand?.toLowerCase()||"visa",passkeyEnrolled:e.passkeyEnrolled||!1,cardArtUrl:e.cardArt||e.artwork||e.cardArtUrl,issuerName:e.issuerName,cardProductName:e.cardProductName,passkeyExpected:e.passkeyExpected,provider:e.provider}}async function ie(e,t,a,r={}){let n=`${e}${t}`,s={"Content-Type":"application/json",Authorization:`Bearer ${a}`,"ngrok-skip-browser-warning":"true"};try{let o=await fetch(n,{...r,headers:{...s,...r.headers}}),d=o.headers.get("content-type"),i;if(d&&d.includes("application/json"))i=await o.json();else{let m=await o.text();try{i=JSON.parse(m)}catch{throw m.includes("<!DOCTYPE")||m.includes("<html")?new j("Received HTML instead of JSON. Ngrok bypass header may not be working.",o.status,"HTML response received"):new j("Invalid JSON response from server",o.status,m.substring(0,200))}}if(!o.ok)throw new j(i.message||"An error occurred",o.status);return i}catch(o){throw o instanceof j?o:new j(o instanceof Error?o.message:"Network error",0)}}async function Ar(e,t,a,r){let n=Gn(a,r),s=await ie(e,"/api/otp/payos-link/generate",t,{method:"POST",body:JSON.stringify({phone:n,channel:"sms"})});if(s.error||!s.data)throw new j(s.message||"Failed to send verification code",400);return s.data.reference}async function Kn(e,t,a,r){let n=await ie(e,"/api/otp/payos-link/verify",t,{method:"POST",body:JSON.stringify({reference:a,code:r})});if(n.error||!n.data)throw new j(n.message||"Invalid verification code",400);return n.data}async function Os(e,t,a){let r=await ie(e,`/api/otp/payos-link/status/${a}`,t,{method:"GET"});if(r.error||!r.data)throw new j(r.message||"Failed to get verification status",400);return r.data}async function Yn(e,t,a,r,n){try{let s=await Os(e,t,a),o=new Date(s.createdAt),d=Date.now()-o.getTime(),i=30*1e3;if(d<i&&s.status==="pending"){let g=Math.ceil((i-d)/1e3);return{reference:a,waitTimeRemaining:g}}return{reference:await Ar(e,t,r,n)}}catch(s){throw s}}async function Zn(e,t,a,r,n){let s=Gn(a,n),o=await ie(e,"/api/wallet-users/process-verified-wallet-user",t,{method:"POST",body:JSON.stringify({phone:s,verificationId:r})});if(o.error||!o.data)throw new j(o.message||"Failed to process wallet user",400);let d=(o.data.savedCards||[]).map(Ha);return{...o.data,savedCards:d}}async function Ga(e,t,a){let r=await ie(e,`/api/wallet-users/${a}/cards`,t,{method:"GET"});if(r.error)throw new j(r.message||"Failed to get wallet user cards",400);return(r.data||[]).map(Ha)}async function qn(e,t,a){let r=await ie(e,`/api/wallet-users/${a}/cards?include=stripe_link`,t,{method:"GET"});if(r.error)throw new j(r.message||"Failed to get wallet user cards",400);return{cards:(r.data||[]).map(Ha),linkSyncStatus:r.linkSyncStatus??null}}function Gt(e,t){return`/api/wallet-users/${e}/link${t}`}function _s(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`idem-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}async function jn(e,t,a){let r=await ie(e,Gt(a,"/auth/status"),t,{method:"GET"});if(r.error)throw new j(r.message||"Failed to get Link auth status",400);return r.data}async function Jn(e,t,a,r){let n=await ie(e,Gt(a,"/auth/initiate"),t,{method:"POST",body:JSON.stringify(r||{})});if(n.error)throw new j(n.message||"Failed to initiate Link auth",400);return n.data}async function Qn(e,t,a){let r=await ie(e,Gt(a,"/auth/poll"),t,{method:"GET"});if(r.error)throw new j(r.message||"Failed to poll Link auth",400);return r.data}async function Xn(e,t,a){let r=await ie(e,Gt(a,"/auth/logout"),t,{method:"POST"});if(r.error)throw new j(r.message||"Failed to revoke Link",400);return r.data}async function eo(e,t,a,r,n){let s=n?.idempotencyKey||_s(),o=await ie(e,Gt(a,"/spend/create"),t,{method:"POST",headers:{"Idempotency-Key":s},body:JSON.stringify(r)});if(o.error)throw new j(o.message||"Failed to create Link spend request",400);return o.data}async function to(e,t,a,r){let n=await ie(e,Gt(a,`/spend/${r}/poll`),t,{method:"POST"});if(n.error)throw new j(n.message||"Failed to poll Link spend",400);return n.data}async function Ka(e,t){let a=await ie(e,"/web/sessions/current",t,{method:"GET"});if(a.error||!a.data)throw new j(a.message||"Failed to get session",400);return a.data}async function ao(e,t){let a=await ie(e,"/web/sessions/current/start",t,{method:"PATCH"});if(a.error||!a.data)throw new j(a.message||"Failed to start session",400);return a.data}async function Ya(e,t){let a=await ie(e,"/web/sessions/current/complete",t,{method:"POST"});if(a.error||!a.data)throw new j(a.message||"Failed to complete session",400);return a.data}async function ro(e,t){let a=await ie(e,"/web/sessions/current/abandon",t,{method:"POST"});if(a.error||!a.data)throw new j(a.message||"Failed to abandon session",400);return a.data}async function Dt(e,t,a){let r=await ie(e,"/web/sessions/current/payment-intent",t,{method:"PATCH",body:JSON.stringify(a)});if(r.error||!r.data)throw new j(r.message||"Failed to update payment intent",400);return r.data}async function no(e,t,a){let r=`${e}/api/payment-credentials/generate`,n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"ngrok-skip-browser-warning":"true"},body:JSON.stringify({paymentIntentId:a})}),s=n.headers.get("content-type"),o;if(s&&s.includes("application/json"))o=await n.json();else{let d=await n.text();try{o=JSON.parse(d)}catch{throw new j("Invalid response from credential generation",n.status,d.substring(0,200))}}if(!n.ok)throw new j(o.message||"Failed to generate credentials",n.status,o.data?.status);return{status:o.data?.status||"success",message:o.message,retrievalToken:o.data?.retrievalToken,approvalId:o.data?.approvalId}}async function oo(e,t,a,r){let n=await ie(e,`/api/wallet-users/${a}/cards/${r}/default`,t,{method:"PUT"});if(n.error)throw new j(n.message||"Failed to set default card",400);return Ha(n.data||{id:r,isDefault:!0})}async function io(e,t,a,r){let n=await ie(e,`/api/wallet-users/${a}/cards/${r}`,t,{method:"DELETE"});if(n.error)throw new j(n.message||"Failed to delete card",400);return{success:!0}}async function so(e,t,a,r){let n=new URLSearchParams({deviceId:a});r&&n.set("walletUserId",r);let s=await ie(e,`/web/device-trust?${n}`,t,{method:"GET"});return s.error?{isTrusted:!1}:{isTrusted:s.data?.isTrusted??!1,expiresAt:s.data?.expiresAt,walletUserId:s.data?.walletUserId}}async function lo(e,t,a,r){return(await ie(e,"/web/device-trust",t,{method:"POST",body:JSON.stringify({deviceId:a,walletUserId:r})})).error?{success:!1}:{success:!0}}var co="payos_device_id",Fs="payos_device_created";function zs(){let e=[];e.push(`${screen.width}x${screen.height}`),e.push(`${screen.colorDepth}`),e.push(Intl.DateTimeFormat().resolvedOptions().timeZone),e.push(navigator.language),e.push(navigator.platform),e.push(navigator.userAgent),e.push(String(navigator.hardwareConcurrency||0));let t=navigator;e.push(String(t.deviceMemory||0));let a=e.join("|");return Ws(a)}function Ws(e){let t=2166136261;for(let a=0;a<e.length;a++)t^=e.charCodeAt(a),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function po(){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Mr(){try{let e=localStorage.getItem(co);if(e)return e;let t=zs(),a=po().substring(0,8),r=`${t}-${a}`;return localStorage.setItem(co,r),localStorage.setItem(Fs,new Date().toISOString()),r}catch{return po()}}function Za(e,t,a){let r,n;t&&(r=e.find(o=>o.id===t)),!r&&a&&(r=e.find(o=>o.id===a)),r||(r=e.find(o=>o.isDefault)||e[0],n=r?.id);let s=t&&r?.id===t?t:void 0;return{selectedCard:r,cardToSync:s}}function qa(e){return!!e?.payments?.some(t=>t.credentialStatus==="active"||t.credentialStatus==="retrieved")}function Ur(e,t){let{apiBaseUrl:a,exitOnCardAdd:r=!1,skipCredentialGeneration:n=!1,cardId:s,skipToAuth:o=!1,preferMethodList:d=!1}=t,[i,m]=Fe(null),[g,p]=Fe("LOADING"),[b,c]=Fe(!0),[y,h]=Fe(null),[v,u]=Fe(null),[f,l]=Fe("checkout"),[x,L]=Fe(""),[w,V]=Fe("initial"),[D,N]=Fe(null),[C,T]=Fe(null),[A,B]=Fe(null),k=ja(!0),M=ja(e),K=ja(!1),O=ja();Vr(()=>{M.current!==e&&(K.current=!1,u(null)),M.current=e},[e]);let _=se((R,S)=>{let{session:P,paymentIntent:E}=R,ee=E?{id:E.id,type:E.type,currency:E.currency,organizationId:E.organizationId,status:E.status,totalAmount:E.totalAmount,totalSubtotal:E.totalSubtotal??E.totalAmount,totalTax:E.totalTax,totalShipping:E.totalShipping,payments:E.payments.map(Y=>({id:Y.id,merchantName:Y.merchantName,merchantUrl:Y.merchantUrl,amount:Y.amount,subtotal:Y.subtotal||Y.amount,tax:Y.tax,shipping:Y.shipping,description:Y.description,quantity:Y.quantity,credentialStatus:Y.credentialStatus,status:Y.status,createdAt:Y.createdAt,updatedAt:Y.updatedAt})),intentType:E.intentType||"standard",walletUserId:E.walletUserId,selectedCardId:E.selectedCardId,requireHitl:E.requireHitl??!1,hitlAttemptCount:E.hitlAttemptCount??0,hitlApproved:E.hitlApproved??!1,networkAuthRequired:E.networkAuthRequired??!1,networkAuthCompleted:E.networkAuthCompleted??!1,authValid:E.authValid??!1,credentialType:E.credentialType||"pci_vault_token",createdAt:E.createdAt,updatedAt:E.updatedAt,facilitationFee:void 0}:S?.paymentIntent||void 0,U=R.sessionType==="wallet_onboard"||R.sessionType==="wallet_onboard_agentic";if(!ee&&!U)throw new Error("No payment intent available");let G="initialized";return P.status==="complete"?G="completed":P.status==="expired"?G="expired":P.status==="abandoned"?G="abandoned":S?.deviceVerified&&(G="verified"),{id:P.id,status:G,sessionType:R.sessionType||void 0,organizationId:P.organizationId,paymentIntent:ee,linkToken:M.current,walletUser:S?.walletUser,savedCards:S?.savedCards||[],selectedCard:S?.selectedCard,deviceVerified:S?.deviceVerified||!1,verificationMethod:"phone",verificationReference:D||"",verificationPhone:C||"",validCardBrandAcceptance:R.validCardBrandAcceptance??S?.validCardBrandAcceptance,expiresAt:P.expiresAt,createdAt:P.createdAt,updatedAt:P.updatedAt}},[D,C]),Q=se(R=>{if(!R)return"LOADING";switch(R.status){case"initialized":return R.deviceVerified?"PAYMENT":"IDENTITY";case"otp_pending":return"OTP_VERIFY";case"verified":case"payment_pending":return"PAYMENT";case"completed":return"SUCCESS";case"expired":return"EXPIRED";case"abandoned":return"ERROR";default:return"IDENTITY"}},[]);Vr(()=>(k.current=!0,K.current?void 0:((async()=>{K.current=!0,c(!0),h(null);try{let S=await Ka(a,e),P=S.sessionType==="wallet_onboard"||S.sessionType==="wallet_onboard_agentic",E=S.paymentIntent?.status;if(!P&&E&&["approved","credentials_ready","completed","awaiting_payment"].includes(E)){k.current&&(h({code:"PAYMENT_INTENT_ALREADY_PROCESSED",message:E==="completed"?"This payment has already been completed.":E==="awaiting_payment"?"This payment is already in progress.":"This payment has already been approved. Use the credentials API to retrieve or regenerate.",sessionId:S.session.id}),p("ERROR"));return}await ao(a,e);let U=_(S),G=S.walletUserId;if(S.identityPreVerified&&G){try{U.deviceVerified=!0,U.status="verified",U.walletUser={id:G};let vt=await Ga(a,e,G);if(U.savedCards=vt||[],O.current=vt?.find(ce=>ce.isDefault)?.id,!P&&U.savedCards.length>0){let{selectedCard:ce,cardToSync:$e}=Za(U.savedCards,s,S.paymentIntent?.selectedCardId);if(U.selectedCard=ce,$e)try{await Dt(a,e,{selectedCardId:$e})}catch{}}}catch{}if(U.walletUser){k.current&&(m(U),p(Q(U)));return}}let Y=S.paymentIntent?.walletUserId;if(Y)try{let vt=Mr();if((await so(a,e,vt,Y)).isTrusted){U.deviceVerified=!0,U.status="verified";let $e=await Ga(a,e,Y);if(U.walletUser={id:Y},U.savedCards=$e||[],O.current=$e?.find(Ut=>Ut.isDefault)?.id,!P&&U.savedCards.length>0){let{selectedCard:Ut,cardToSync:Ct}=Za(U.savedCards,s,S.paymentIntent?.selectedCardId);if(U.selectedCard=Ut,Ct)try{await Dt(a,e,{selectedCardId:Ct})}catch{}}}}catch{}k.current&&(m(U),p(Q(U)))}catch(S){if(k.current){let P=S,E=P.status===410||P.message?.toLowerCase().includes("expired");h({code:E?"SESSION_EXPIRED":"LOAD_FAILED",message:P.message||"Failed to load session",sessionId:e}),p(E?"EXPIRED":"ERROR")}}finally{k.current&&c(!1)}})(),()=>{k.current=!1})),[e,Q,_,a]);let X=i?.sessionType==="wallet_onboard"||i?.sessionType==="wallet_onboard_agentic",F=!X&&(i?.paymentIntent?.type==="pay_on_behalf"||i?.paymentIntent?.type==="agent_to_agent"||i?.paymentIntent?.type==="agentic_multi"),de=!!i?.selectedCard,Le=(i?.savedCards?.length??0)>0;Vr(()=>{g==="PAYMENT"&&l(X?"add":o&&de?"checkout":d?"methods":de?"checkout":Le?"methods":"add")},[g,X,o,d,de,Le]);let bt=se(()=>{l("methods")},[]),Xe=se(()=>{l("add")},[]),et=se(()=>{l(de?"checkout":Le?"methods":"add")},[de,Le]),tt=se(()=>{p("IDENTITY")},[]),ht=se(async R=>{if(!i||!R.phone)return!1;c(!0);try{let S=await Ar(a,M.current,R.phone,R.countryCode);return k.current&&(N(S),T(R.phone),B(R.countryCode||null),m(P=>P?{...P,status:"otp_pending",verificationReference:S,verificationPhone:R.phone}:null),p("OTP_VERIFY")),!0}catch(S){let P=S;return k.current&&h({code:"VERIFICATION_FAILED",message:P.message||"Failed to send verification",sessionId:i.id}),!1}finally{k.current&&c(!1)}},[i,a]),at=se(async R=>{if(!i||!D||!C)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session or verification context"}};c(!0);try{let S=await Kn(a,M.current,D,R),P=await Zn(a,M.current,S.phone,S.reference,A||void 0);if(k.current){let E,ee;if(!(i.sessionType==="wallet_onboard"||i.sessionType==="wallet_onboard_agentic")&&P.savedCards.length>0){let G=Za(P.savedCards,s,i.paymentIntent?.selectedCardId);if(E=G.selectedCard,ee=G.cardToSync,ee)try{await Dt(a,M.current,{selectedCardId:ee})}catch{}}m(G=>G?{...G,status:"verified",deviceVerified:!0,walletUser:{id:P.walletUserId,phone:S.phone},savedCards:P.savedCards,selectedCard:E,...G.paymentIntent&&{paymentIntent:{...G.paymentIntent,walletUserId:P.walletUserId,...ee&&{selectedCardId:ee}}}}:null),p("PAYMENT"),O.current=P.savedCards?.find(G=>G.isDefault)?.id;try{let G=Mr();await lo(a,M.current,G,P.walletUserId)}catch{}}return{success:!0,walletUserId:P.walletUserId}}catch(S){return{success:!1,error:{code:"INVALID_OTP",message:S.message||"Invalid verification code"}}}finally{k.current&&c(!1)}},[i,D,C,A,a]),yt=se(async()=>{if(!i||!D||!C)return!1;c(!0);try{let R=await Yn(a,M.current,D,C,A||void 0);return R.waitTimeRemaining?!1:(k.current&&R.reference!==D&&N(R.reference),!0)}catch{return!1}finally{k.current&&c(!1)}},[i,D,C,A,a]),rt=se(async R=>{if(!i)return!1;c(!0);try{i.paymentIntent&&await Dt(a,M.current,{selectedCardId:R});let S=i.savedCards.find(P=>P.id===R);return k.current&&(m(P=>P?{...P,selectedCard:S,...P.paymentIntent&&{paymentIntent:{...P.paymentIntent,selectedCardId:R}}}:null),l("checkout")),!0}catch(S){let P=S;if(k.current){let E=P.message?.includes("spending limit")?"ISSUER_LIMIT_EXCEEDED":"CARD_SELECT_FAILED";h({code:E,message:P.message||"Failed to select card",sessionId:i.id})}return!1}finally{k.current&&c(!1)}},[i,a]),nt=se(async R=>{if(!i)return{success:!1};c(!0);try{let S={id:R.cardId,brand:R.brand?.toLowerCase()||"unknown",last4:R.last4,expiryMonth:R.expiryMonth||R.expMonth?.toString()||"",expiryYear:R.expiryYear||R.expYear?.toString()||"",cardholderName:R.cardholderName,isDefault:!1,network:R.network?.toLowerCase()||"visa",cardArtUrl:R.cardArtUrl};if(i.paymentIntent&&await Dt(a,M.current,{selectedCardId:S.id}),k.current){if(m(U=>U?{...U,savedCards:[...U.savedCards,S],selectedCard:S,...U.paymentIntent&&{paymentIntent:{...U.paymentIntent,selectedCardId:S.id}}}:null),i.sessionType==="wallet_onboard"||i.sessionType==="wallet_onboard_agentic"){if(i.walletUser?.id)try{let U=await Ga(a,M.current,i.walletUser.id),G=U.find(Y=>Y.id===S.id)||S;m(Y=>Y?{...Y,savedCards:U,selectedCard:G}:null)}catch{}if(r){p("PROCESSING");try{return await Ya(a,M.current),k.current&&(m(U=>U?{...U,status:"completed"}:null),p("SUCCESS")),{success:!0,card:S}}catch(U){let G=U;return k.current&&(h({code:"PAYMENT_FAILED",message:G.message||"Failed to complete session",sessionId:i.id}),p("PAYMENT"),l("methods")),{success:!1}}}return l("methods"),{success:!0,card:S}}let E=i.paymentIntent?.type;E==="pay_on_behalf"||E==="agent_to_agent"||E==="agentic_multi"?(V("initial"),p("AGENT_REGISTRATION")):l("checkout")}return{success:!0,card:S}}catch(S){let P=S;return k.current&&h({code:"CARD_ADD_FAILED",message:P.message||"Failed to add card",sessionId:i.id}),{success:!1}}finally{k.current&&c(!1)}},[i,a,r]),xt=se(async R=>{if(!i||!i.walletUser?.id)return!1;c(!0);try{if(await io(a,M.current,i.walletUser.id,R),k.current){let S=i.savedCards.filter(E=>E.id!==R),P=i.selectedCard?.id===R;m(E=>E?{...E,savedCards:S,selectedCard:P?void 0:E.selectedCard,...E.paymentIntent&&{paymentIntent:{...E.paymentIntent,selectedCardId:P?void 0:E.paymentIntent.selectedCardId}}}:null),S.length===0&&l("add")}return!0}catch(S){let P=S;return k.current&&h({code:"CARD_DELETE_FAILED",message:P.message||"Failed to delete card",sessionId:i.id}),!1}finally{k.current&&c(!1)}},[i,a]),z=se(async()=>{if(i)try{i.paymentIntent&&await Dt(a,M.current,{selectedCardId:void 0}),k.current&&m(R=>R?{...R,selectedCard:void 0,...R.paymentIntent&&{paymentIntent:{...R.paymentIntent,selectedCardId:void 0}}}:null)}catch{}},[i,a]),be=se(()=>{V("initial"),p("PAYMENT"),l("checkout")},[]),me=se(()=>{V("initial"),p("PAYMENT"),l("checkout")},[]),oe=se(async R=>{if(!i||!i.walletUser?.id)return!1;m(S=>S?{...S,savedCards:S.savedCards.map(P=>({...P,isDefault:P.id===R}))}:null);try{return await oo(a,M.current,i.walletUser.id,R),O.current=R,!0}catch(S){let P=O.current;k.current&&P&&m(ee=>ee?{...ee,savedCards:ee.savedCards.map(U=>({...U,isDefault:U.id===P}))}:null);let E=S;return k.current&&h({code:"CARD_SELECT_FAILED",message:E.message||"Failed to set default card",sessionId:i.id}),!1}},[i,a]),Mt=se(async()=>{if(!i)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session"}};u(null),p("PROCESSING"),c(!0);try{await Ya(a,M.current);let R={success:!0,walletUserId:i.walletUser?.id};return k.current&&(u(R),m(S=>S?{...S,status:"completed"}:null),p("SUCCESS")),R}catch(R){let P={success:!1,error:{code:"PAYMENT_FAILED",message:R.message||"Failed to complete session"}};return k.current&&(h({code:P.error.code,message:P.error.message,sessionId:i.id}),p("PAYMENT"),l("methods")),P}finally{k.current&&c(!1)}},[i,a]),kt=se(async R=>{if(!i)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session"}};u(null),p("PROCESSING"),c(!0);try{let S=!X&&F&&R?.passkeyAuthenticated&&i.paymentIntent&&!n,P=!1;S&&(await no(a,M.current,i.paymentIntent.id),P=!0),await Ya(a,M.current);let E=i.paymentIntent;if(S)try{let G=await Ka(a,M.current),Y=_(G,i);Y.paymentIntent&&(E=Y.paymentIntent)}catch{}let ee=qa(E)||P,U={success:!0,walletUserId:i.walletUser?.id,paymentIntentId:i.paymentIntent?.id,credentialGenerated:ee};return k.current&&(u(U),m(G=>G?{...G,status:"completed",paymentIntent:E}:null),p("SUCCESS")),U}catch(S){let P=S,ee={success:!1,error:{code:P.message?.includes("credential")||P.message?.includes("generate")?"CREDENTIAL_GENERATION_FAILED":"PAYMENT_FAILED",message:P.message||"Payment failed"}};return k.current&&(h({code:ee.error.code,message:ee.error.message,sessionId:i.id}),p("PAYMENT")),ee}finally{k.current&&c(!1)}},[i,F,X,a,n,_]),ot=se(async()=>{if(i)try{await ro(a,M.current)}catch{}},[i,a]),Vt=se(()=>{h(null)},[]),wt=se(async()=>{if(i){c(!0);try{let R=await Ka(a,M.current),S=_(R,i);k.current&&(m(S),p(Q(S)))}catch(R){let S=R;k.current&&h({code:"LOAD_FAILED",message:S.message||"Failed to refresh session",sessionId:i.id})}finally{k.current&&c(!1)}}},[i,Q,_,a]);return{session:i,setSession:m,phase:g,loading:b,error:y,completionResult:v,isAgentMode:F,isSetupMode:X??!1,hasSelectedCard:de,hasSavedCards:Le,paymentView:f,cvc:x,setCvc:L,showMethodList:bt,showAddCard:Xe,returnToCheckout:et,submitIdentity:ht,goBackToIdentity:tt,submitOTP:at,resendCode:yt,selectPaymentCard:rt,addPaymentCard:nt,deletePaymentCard:xt,clearCard:z,registrationSubPhase:w,setRegistrationSubPhase:V,skipRegistration:be,completeAgentRegistration:me,setPhase:p,setPaymentView:l,setDefaultCard:oe,completeSetup:Mt,complete:kt,abandon:ot,clearError:Vt,refresh:wt}}import{useRef as mo,useState as go,useEffect as $s,useCallback as Ge}from"react";import{PayOSPasskey as Hs}from"@payos-inc/payos-passkey-js";var Ja={enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,isLoading:!1,error:null,canRetry:!0,attemptsRemaining:void 0};function uo(e){let t=mo(null),[a,r]=go(!1),[n,s]=go(Ja),o=mo(!0);$s(()=>{if(!e.sessionSecret){r(!1);return}if(t.current){o.current=!0,a||r(!0);return}o.current=!0;try{t.current=new Hs(e.sessionSecret,{sandbox:e.sandbox,debug:e.debug,visaContainerId:e.visaContainerId,apiBaseUrl:e.apiBaseUrl}),r(!0)}catch(u){console.error("[usePasskeySDK] Failed to initialize SDK:",u),s(f=>({...f,error:u?.message||"Failed to initialize passkey SDK"})),r(!1)}return()=>{o.current=!1,setTimeout(()=>{!o.current&&t.current&&(t.current.cleanup(),t.current=null,r(!1))},100)}},[e]);let d=Ge(async u=>{if(!t.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};s(f=>({...f,isLoading:!0,error:null}));try{let f=await t.current.register(u);if(f.requiresStepUp){let l=(f.stepUpMethods||[]).map((x,L)=>({id:String(L),type:x.type?.toLowerCase()==="email"?"email":"sms",maskedValue:x.maskedValue||x.value||`Method ${L+1}`}));s(x=>({...x,isLoading:!1,enrollmentId:f.enrollmentId||null,stepUpMethods:l}))}else s(l=>({...l,isLoading:!1}));return f}catch(f){let l=f?.message||"Registration failed";return s(x=>({...x,isLoading:!1,error:l})),{success:!1,message:l,error:{code:"REGISTRATION_ERROR",message:l}}}},[]),i=Ge(async u=>{if(!t.current||!n.enrollmentId)return{success:!1};s(f=>({...f,isLoading:!0,error:null}));try{let f=await t.current.submitStepUpMethod(n.enrollmentId,u),l=n.stepUpMethods[u];return s(x=>({...x,isLoading:!1,selectedMethodDescription:l?.maskedValue||null})),f}catch(f){let l=f?.message||"Failed to send OTP";return s(x=>({...x,isLoading:!1,error:l})),{success:!1}}},[n.enrollmentId,n.stepUpMethods]),m=Ge(async u=>{if(!t.current||!n.enrollmentId)return{success:!1,message:"No enrollment in progress",error:{code:"NO_ENROLLMENT",message:"No active enrollment"}};s(f=>({...f,isLoading:!0,error:null}));try{let f=await t.current.validateStepUpOTP(n.enrollmentId,u);return f.success?s(l=>({...l,isLoading:!1,canRetry:!0,attemptsRemaining:void 0})):s(l=>({...l,isLoading:!1,error:f.message||"OTP validation failed",canRetry:f.canRetry??!0,attemptsRemaining:f.attemptsRemaining})),f}catch(f){let l=f?.message||"OTP validation failed";return s(x=>({...x,isLoading:!1,error:l})),{success:!1,message:l,error:{code:"OTP_ERROR",message:l}}}},[n.enrollmentId]),g=Ge(async u=>{if(!t.current||!n.enrollmentId)return{success:!1,message:"No enrollment in progress",error:{code:"NO_ENROLLMENT",message:"No active enrollment"}};s(f=>({...f,isLoading:!0,error:null}));try{let f=await t.current.completeVisaRegistration(n.enrollmentId,u);return s(l=>({...l,isLoading:!1,enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,error:f.success?null:f.message||"Registration failed"})),f}catch(f){let l=f?.message||"Registration failed";return s(x=>({...x,isLoading:!1,enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,error:l})),{success:!1,message:l,error:{code:"REGISTRATION_ERROR",message:l}}}},[n.enrollmentId]),p=Ge(async(u,f)=>{if(!t.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};s(l=>({...l,isLoading:!0,error:null}));try{let l=await t.current.authenticateForVicEnrollment(u,f);return s(x=>({...x,isLoading:!1})),l}catch(l){let x=l?.message||"VIC authentication failed";return s(L=>({...L,isLoading:!1,error:x})),{success:!1,message:x,error:{code:"VIC_AUTH_ERROR",message:x}}}},[]),b=Ge(async(u,f)=>{if(!t.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};s(l=>({...l,isLoading:!0,error:null}));try{let l=await t.current.authenticate(u,f);return s(x=>({...x,isLoading:!1})),l}catch(l){let x=l?.message||"Authentication failed";return s(L=>({...L,isLoading:!1,error:x})),{success:!1,message:x,error:{code:"AUTH_ERROR",message:x}}}},[]),c=Ge(()=>{s(u=>({...u,error:null}))},[]),y=Ge(()=>{s(Ja)},[]),h=Ge(()=>{t.current?.removeVisaIframeOnly(),s(Ja)},[]),v=Ge(()=>{t.current?.cleanup(),s(Ja)},[]);return{sdk:t.current,isReady:a,state:n,startRegistration:d,selectStepUpMethod:i,submitVisaOtp:m,completeVisaRegistration:g,authenticateForVicEnrollment:p,authenticate:b,clearError:c,resetState:y,removeVisaIframe:h,cleanup:v}}import{useCallback as Pe,useEffect as Fr,useRef as zr,useState as Kt}from"react";var Qa={},Gs=()=>{let a=Math.max(0,(window.screenX||0)+(window.outerWidth-400)/2),r=Math.max(0,(window.screenY||0)+(window.outerHeight-600)/2);return`width=400,height=600,left=${a},top=${r},toolbar=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes`},Ks={connect:"payos-link-connect",approval:"payos-link-approve"};function Xa(e,t){let a=Qa[e];if(a&&!a.closed)try{return a.location.href=t,a.focus(),a}catch{}let r=window.open("about:blank",Ks[e],Gs());if(r)try{r.location.href=t}catch{r.location.replace(t)}return Qa[e]=r,r}function we(e){let t=Qa[e];try{t&&!t.closed&&(t.close(),setTimeout(()=>{try{t&&!t.closed&&(t.blur(),window.focus())}catch{}},100))}catch{}Qa[e]=null}function er(){we("connect"),we("approval")}import{useCallback as Ys,useEffect as Zs,useRef as qs,useState as Br}from"react";function Or(e){let{baseUrl:t,token:a,walletUserId:r,enabled:n=!0}=e,[s,o]=Br(null),[d,i]=Br(!1),[m,g]=Br(null),p=qs(!1),b=Ys(async()=>{if(!(!n||!r)){i(!0),g(null);try{let c=await jn(t,a,r);p.current||o(c)}catch(c){p.current||g(c instanceof Error?c:new Error(String(c)))}finally{p.current||i(!1)}}},[t,a,r,n]);return Zs(()=>(p.current=!1,b(),()=>{p.current=!0}),[b]),{status:s,loading:d,error:m,refresh:b}}import{useEffect as js,useRef as Js}from"react";var Qs=new Set(["approved","denied","expired","error","revoked"]);function fo(e){let{baseUrl:t,token:a,walletUserId:r,enabled:n,intervalMs:s=1500,onApproved:o,onDenied:d,onExpired:i,onError:m,onTick:g}=e,p=Js({onApproved:o,onDenied:d,onExpired:i,onError:m,onTick:g});p.current={onApproved:o,onDenied:d,onExpired:i,onError:m,onTick:g},js(()=>{if(!n||!r)return;let b=!1,c=null,y=async()=>{if(!b){try{let h=await Qn(t,a,r);if(b)return;if(p.current.onTick?.(h),Qs.has(h.status)){h.status==="approved"?p.current.onApproved?.():h.status==="denied"?p.current.onDenied?.(h.error):h.status==="expired"?p.current.onExpired?.(h.error):p.current.onError?.(h.error);return}}catch(h){if(b)return;p.current.onError?.(h instanceof Error?h.message:String(h));return}c=setTimeout(y,s)}};return c=setTimeout(y,s),()=>{b=!0,c&&clearTimeout(c)}},[t,a,r,n,s])}import{useCallback as Xs,useEffect as el,useRef as tl,useState as tr}from"react";function _r(e){let{baseUrl:t,token:a,walletUserId:r,enabled:n=!0}=e,[s,o]=tr([]),[d,i]=tr(null),[m,g]=tr(!1),[p,b]=tr(null),c=tl(!1),y=Xs(async()=>{if(!(!n||!r)){g(!0),b(null);try{let u=await qn(t,a,r);if(c.current)return;o(u.cards),i(u.linkSyncStatus)}catch(u){c.current||b(u instanceof Error?u:new Error(String(u)))}finally{c.current||g(!1)}}},[t,a,r,n]);el(()=>(c.current=!1,y(),()=>{c.current=!0}),[y]);let h=s.filter(u=>u.provider==="stripe_link"),v=s.filter(u=>u.provider!=="stripe_link");return{cards:s,linkCards:h,payosCards:v,linkSyncStatus:d,loading:m,error:p,refresh:y}}import{useEffect as al,useRef as rl}from"react";var nl=new Set(["consumed","denied","expired","failed"]);function bo(e){let{baseUrl:t,token:a,walletUserId:r,spendRowId:n,enabled:s,intervalMs:o=1500,onApproved:d,onDenied:i,onExpired:m,onFailed:g,onConsumed:p,onTick:b}=e,c=rl({onApproved:d,onDenied:i,onExpired:m,onFailed:g,onConsumed:p,onTick:b});c.current={onApproved:d,onDenied:i,onExpired:m,onFailed:g,onConsumed:p,onTick:b},al(()=>{if(!s||!r||!n)return;let y=!1,h=null,v=!1,u=async()=>{if(!y){try{let f=await to(t,a,r,n);if(y)return;if(c.current.onTick?.(f),f.status==="approved"&&!v&&(v=!0,c.current.onApproved?.()),nl.has(f.status)){f.status==="consumed"?c.current.onConsumed?.():f.status==="denied"?c.current.onDenied?.(f.error):f.status==="expired"?c.current.onExpired?.(f.error):c.current.onFailed?.(f.error);return}}catch(f){if(y)return;c.current.onFailed?.(f instanceof Error?f.message:String(f));return}h=setTimeout(u,o)}};return h=setTimeout(u,o),()=>{y=!0,h&&clearTimeout(h)}},[t,a,r,n,s,o])}var ho=async()=>{};function ol(e){return e instanceof Error?e.message:String(e)}function Et(e){let{baseUrl:t,token:a,walletUserId:r,organizationId:n,enabled:s=!0,testMode:o,spendContext:d,onSpendApproved:i}=e,m=zr(i);Fr(()=>{m.current=i},[i]);let[g,p]=Kt("idle"),[b,c]=Kt(null),[y,h]=Kt(null),[v,u]=Kt(null),[f,l]=Kt(null),[x,L]=Kt(null),{status:w,loading:V,error:D,refresh:N}=Or({baseUrl:t,token:a,walletUserId:r,enabled:s}),C=s&&!!r&&w?.authenticated===!0,{cards:T,linkCards:A,payosCards:B,linkSyncStatus:k,loading:M,error:K,refresh:O}=_r({baseUrl:t,token:a,walletUserId:r,enabled:C}),_=zr(!1),Q=Pe(()=>{er(),_.current=!1,c(null),h(null),u(null),l(null),L(null),p("idle")},[]);fo({baseUrl:t,token:a,walletUserId:r,enabled:s&&g==="connect",onApproved:()=>{we("connect"),c(null),p("loading"),_.current=!0,N()},onDenied:z=>{we("connect"),c(null),l(z||"Authorization denied"),p("denied")},onExpired:z=>{we("connect"),c(null),l(z||"Authorization expired"),p("denied")},onError:z=>{we("connect"),c(null),l(z||"Authorization error"),p("denied")}}),Fr(()=>{if(!_.current||g!=="loading"||!w?.authenticated)return;_.current=!1;let z=!1,be=()=>{z||(z=!0,p(oe=>oe==="loading"?"checkout":oe))},me=setTimeout(be,8e3);return O().finally(()=>{clearTimeout(me),be()}),()=>{z=!0,clearTimeout(me)}},[w?.authenticated,g,O]);let X=Pe(async(z=y)=>{L(null);try{await m.current?.(z)}catch(be){L(ol(be))}},[y]);bo({baseUrl:t,token:a,walletUserId:r,spendRowId:y?.id||null,enabled:s&&!!y&&g==="checkout",onApproved:()=>{let z=y?{...y,approvalUrl:null,status:"approved"}:null;we("approval"),h(z),X(z)},onConsumed:()=>{we("approval"),p("success")},onDenied:z=>{we("approval"),l(z||"Spend approval denied"),p("denied")},onExpired:z=>{we("approval"),l(z||"Spend approval expired"),p("denied")},onFailed:z=>{we("approval"),l(z||"Spend approval failed"),p("denied")}});let F=Pe(async()=>{if(!r)return;l(null),p("connect");let z;try{z=await Jn(t,a,r,{organizationId:n})}catch(be){l(be instanceof Error?be.message:String(be)),p("denied");return}if(z.alreadyAuthenticated){c(null),p("loading"),_.current=!0,await N();return}c({passphrase:z.passphrase||z.userCode,verificationUrl:z.verificationUrl,verificationUrlComplete:z.verificationUrlComplete,expiresAt:Date.now()+z.expiresIn*1e3}),Xa("connect",z.verificationUrlComplete||z.verificationUrl)},[t,a,r,n]),de=Pe(()=>{we("connect"),c(null),p("idle")},[]),Le=Pe(async z=>{if(!r)return;l(null),L(null);let be={...z,...o?{test:!0}:{},...d&&!z.context?{context:d}:{}},me;try{me=await eo(t,a,r,be)}catch(oe){L(oe instanceof Error?oe.message:String(oe));return}h(me),me.approvalUrl&&Xa("approval",me.approvalUrl)},[t,a,r,o,d]),bt=Pe(()=>{y?.approvalUrl&&Xa("approval",y.approvalUrl)},[y?.approvalUrl]),Xe=Pe(()=>{we("approval"),h(null),u(null),p("idle")},[]),et=Pe(async()=>{y?.status==="approved"&&await X()},[y?.status,X]),tt=Pe(async()=>{let z=!!y;if(l(null),L(null),z){we("approval"),h(null),p("checkout");return}await F()},[y,F]),ht=Pe(async()=>{if(r){try{await Xn(t,a,r)}catch{}er(),c(null),h(null),u(null),p("idle"),await N()}},[t,a,r,N]),at=Pe(()=>p("manage"),[]),yt=Pe(()=>p("idle"),[]),rt=Pe(()=>{p("checkout"),O()},[O]),nt=Pe(()=>{h(null),p("idle")},[]),xt=zr(!1);return Fr(()=>()=>{xt.current=!0,er()},[]),{phase:g,authStatus:w,authLoading:V,authError:D,linkCards:A,payosCards:B,allCards:T,linkSyncStatus:k,methodsLoading:M,methodsError:K,selectedLinkMethodId:v,setSelectedLinkMethodId:u,spendError:x,clearSpendError:()=>L(null),currentSpend:y,deviceAuthContext:b,deniedReason:f,startLinkConnect:F,cancelLinkConnect:de,approveLinkSpend:Le,reopenLinkSpendApproval:bt,cancelLinkSpend:Xe,retryApprovedSpend:et,retryDenied:tt,signOutLink:ht,goToManage:at,goToCheckout:rt,exitManage:yt,exitSuccess:nt,reset:Q,refreshAuth:N??ho,refreshMethods:O??ho}}function yo(e,t){return t||(e==="sandbox"?"https://sandbox.api.payos.ai":"https://api.payos.ai")}import{createPortal as il}from"react-dom";import{X as sl}from"lucide-react";import{Fragment as ar,jsx as ve,jsxs as Je}from"react/jsx-runtime";function xo({open:e,layout:t,title:a,totalAmount:r,orderItems:n,subtotal:s,shipping:o,tax:d,agentFee:i,isAgentMode:m,isSetupMode:g,secondsRemaining:p,paymentView:b,hideHeader:c,confirmDialog:y,onClose:h,children:v}){return t==="inline"?Je(ar,{children:[y,ve("div",{className:"payos-scope payos-inline-sheet",children:v})]}):t==="embedded"?Je(ar,{children:[y,Je("div",{className:"payos-scope payos-embedded-sheet fixed inset-0 flex flex-col bg-white dark:bg-slate-900 black:bg-black",style:{paddingTop:"env(safe-area-inset-top)",paddingLeft:"env(safe-area-inset-left)",paddingRight:"env(safe-area-inset-right)"},children:[!c&&Je("div",{className:"flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-slate-800 black:border-[#1a1a1a]",children:[ve("h2",{className:"text-base font-semibold text-gray-900 dark:text-white black:text-white truncate",children:a}),r&&ve("span",{className:"text-base font-bold text-gray-900 dark:text-white black:text-white ml-2",children:r})]}),ve("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-4",style:{overscrollBehavior:"contain",...b!=="add"&&{maskImage:"linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)",WebkitMaskImage:"linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"}},children:v}),ve("div",{className:"px-4 pt-3",style:{paddingBottom:"calc(env(safe-area-inset-bottom) + 12px)"},children:ve(Ve,{})})]})]}):t==="modal"?il(Je(ar,{children:[y,ve("div",{className:"fixed inset-0 bg-black/40 dark:bg-black/50 black:bg-black/60 z-[9998] animate-in fade-in duration-200",onClick:h,"aria-hidden":"true"}),ve("div",{className:"payos-scope fixed inset-0 z-[9999] flex items-center justify-center p-4",role:"dialog","aria-modal":"true",children:Je("div",{className:"relative w-full max-w-md h-[700px] max-h-[90vh] bg-white dark:bg-slate-900 black:bg-black rounded-2xl shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 fade-in duration-200",children:[Je("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-slate-800 black:border-[#1a1a1a]",children:[ve("h2",{className:"text-lg font-bold text-gray-900 dark:text-white black:text-white",children:a}),Je("div",{className:"flex items-center gap-2",children:[r&&ve("span",{className:"text-lg font-bold text-gray-900 dark:text-white black:text-white",children:r}),ve("button",{onClick:h,className:"p-2 rounded-full hover:bg-gray-100 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a] transition-colors","aria-label":"Close",children:ve(sl,{className:"w-5 h-5 text-gray-600 dark:text-slate-400 black:text-gray-400"})})]})]}),ve("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{overscrollBehavior:"contain",...b!=="add"&&{maskImage:"linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)",WebkitMaskImage:"linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"}},children:v}),ve(Ve,{className:"px-6 py-4"})]})})]}),document.body):Je(ar,{children:[y,ve(Ra,{open:e,onClose:h,title:a,amount:r,orderItems:n,subtotal:s,shipping:o,tax:d,orderAgentFee:i,mode:g?"standard":m?"agent":"standard",secondsRemaining:p,disableContentMask:b==="add",children:v})]})}import ko from"react";import{jsx as Wr,jsxs as ll}from"react/jsx-runtime";function Ke({className:e="h-11",markTone:t="green",wordmarkTone:a="auto"}){let r=t==="black"?"#000000":"#00D66F",n=t==="black"?"#ffffff":"#011e0f";return ll("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 72 24",className:`${e} ${a==="black"?"text-black":a==="white"?"text-white":"text-black dark:text-white black:text-white"}`,"aria-hidden":"true",children:[Wr("path",{d:"M36.12 3.67683c0-1.12801.9504-2.04481 2.0688-2.04481 1.1184 0 2.0688.9216 2.0688 2.04481 0 1.1232-.9168 2.0688-2.0688 2.0688-1.152 0-2.0688-.9168-2.0688-2.0688ZM29.9808 1.92001h3.6V22.08h-3.6V1.92001ZM40.008 7.68001h-3.6288V22.08h3.6288V7.68001ZM66.096 14.3904c2.7312-1.68 4.5888-4.1808 5.3232-6.71516h-3.6288c-.9456 2.41916-3.1152 4.23836-5.5008 5.01116V1.91523h-3.6288V22.0752h3.6288V16.08c2.7696.6912 4.9584 3.0864 5.7072 5.9952h3.6528c-.5568-3.0528-2.6448-5.9088-5.5536-7.6848ZM46.44 9.29283c.9504-1.2624 2.8032-1.99681 4.3056-1.99681 2.8032 0 5.1216 2.04961 5.1264 5.14558v9.6336h-3.6288v-8.832c0-1.272-.5664-2.7408-2.4048-2.7408-2.16 0-3.4032 1.9152-3.4032 4.1568v7.4256h-3.6288V7.68962H46.44v1.60321Z",fill:"currentColor"}),Wr("path",{d:"M12 24c6.6274 0 12-5.3726 12-12 0-6.62743-5.3726-12-12-12C5.37259 0 0 5.37257 0 12c0 6.6274 5.37259 12 12 12Z",fill:r}),Wr("path",{d:"M11.4479 4.80005H7.74707c.72 3.0096 2.82243 5.58235 5.45283 7.19995-2.6352 1.6176-4.73283 4.1904-5.45283 7.2h3.70083c.9168-2.784 3.456-5.2032 6.576-5.6976v-3.0095c-3.1248-.4896-5.664-2.90885-6.576-5.69285Z",fill:n})]})}import{jsx as pe,jsxs as ze}from"react/jsx-runtime";function la({passphrase:e,popupBlocked:t=!1,onReopen:a,onCancel:r}){return ze("div",{className:"flex flex-col items-center justify-center min-h-full p-6 space-y-5",children:[ze("div",{className:"text-center space-y-3",children:[ze("h2",{className:"text-3xl sm:text-5xl font-bold text-slate-900 dark:text-white black:text-white tracking-tight flex items-center justify-center gap-2 sm:gap-3 whitespace-nowrap",children:[pe("span",{children:"Connect to"}),pe(Ke,{className:"h-7 sm:h-11"})]}),ze("p",{className:"text-sm text-gray-500 dark:text-slate-400 black:text-gray-400",children:["We opened a window to ",pe("span",{className:"font-mono",children:"app.link.com"}),". Sign in there to continue."]})]}),ze("div",{className:"w-full max-w-sm rounded-xl border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] p-4 bg-white dark:bg-slate-900 black:bg-black text-center space-y-2",children:[pe("p",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-slate-500 black:text-gray-500",children:"Confirm this code matches what Link shows you"}),e?pe("div",{className:"inline-flex items-center gap-1 text-sm font-mono font-semibold text-slate-900 dark:text-white black:text-white flex-wrap justify-center",children:e.split("-").map((n,s,o)=>ze(ko.Fragment,{children:[pe("span",{className:"px-2 py-1 bg-gray-100 dark:bg-slate-800 black:bg-[#151515] rounded",children:n}),s<o.length-1&&pe("span",{className:"text-gray-400 dark:text-slate-500 black:text-gray-500 font-semibold",children:"-"})]},s))}):pe("div",{className:"inline-flex items-center gap-1 flex-wrap justify-center",children:[0,1,2,3].map(n=>ze(ko.Fragment,{children:[pe("span",{className:"px-2 py-1 rounded bg-gray-200 dark:bg-slate-800 black:bg-[#151515] animate-pulse w-16 h-6"}),n<3&&pe("span",{className:"text-gray-300 dark:text-slate-600 black:text-gray-700 font-semibold",children:"-"})]},n))})]}),ze("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:[pe("style",{children:"@keyframes payosLinkDot { 0%, 80%, 100% { transform: scale(0.55); opacity: 0.35; } 40% { transform: scale(1); opacity: 1; } }"}),ze("span",{className:"inline-flex gap-1",children:[pe("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 dark:bg-slate-500 black:bg-gray-500",style:{animation:"payosLinkDot 1.2s ease-in-out infinite both",animationDelay:"0s"}}),pe("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 dark:bg-slate-500 black:bg-gray-500",style:{animation:"payosLinkDot 1.2s ease-in-out infinite both",animationDelay:"0.16s"}}),pe("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 dark:bg-slate-500 black:bg-gray-500",style:{animation:"payosLinkDot 1.2s ease-in-out infinite both",animationDelay:"0.32s"}})]}),"Waiting for approval"]}),pe("div",{className:"w-full max-w-sm space-y-2",children:t?ze("div",{className:"p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 black:bg-amber-900/20 text-amber-800 dark:text-amber-300 black:text-amber-300 border border-amber-200 dark:border-amber-800/60 black:border-amber-800/60 text-xs space-y-2",children:[pe("p",{children:"Popup was blocked by your browser. Click to open:"}),pe("button",{type:"button",onClick:a,className:"block w-full h-9 rounded bg-[#00D66F] hover:bg-[#00C264] text-black font-medium",children:"Open sign-in popup"})]}):ze("p",{className:"text-xs text-center text-gray-500 dark:text-slate-400 black:text-gray-400",children:["Didn't see a popup?"," ",pe("button",{type:"button",onClick:a,className:"underline font-medium hover:text-gray-900 dark:hover:text-white black:hover:text-white",children:"Try again"})]})}),pe("button",{type:"button",onClick:r,className:"w-full max-w-sm h-10 rounded-lg text-gray-500 dark:text-slate-400 black:text-gray-400 font-medium text-sm hover:bg-gray-100 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a]",children:"Cancel"})]})}import{jsx as rr,jsxs as wo}from"react/jsx-runtime";function Qe({message:e="Loading your Link wallet\u2026"}){return wo("div",{className:"flex flex-col items-center justify-center min-h-full p-6 space-y-4",children:[wo("div",{className:"flex space-x-1.5",children:[rr("span",{className:"w-2 h-2 rounded-full bg-slate-900 dark:bg-white black:bg-white animate-bounce [animation-delay:-0.3s]"}),rr("span",{className:"w-2 h-2 rounded-full bg-slate-900 dark:bg-white black:bg-white animate-bounce [animation-delay:-0.15s]"}),rr("span",{className:"w-2 h-2 rounded-full bg-slate-900 dark:bg-white black:bg-white animate-bounce"})]}),rr("p",{className:"text-sm text-gray-500 dark:text-slate-400 black:text-gray-400",children:e})]})}import{useEffect as vo,useState as Co}from"react";import{AlertCircle as dl,Loader2 as cl,X as pl}from"lucide-react";import{Fragment as Po,jsx as $,jsxs as ae}from"react/jsx-runtime";function ml(e){let t=(e||"").toLowerCase();return t.includes("reaches the limit")||t.includes("rate limit")?{heading:"Too many pending Link payments",body:"Please wait a few minutes for older approvals to expire or complete, then try again."}:t.includes("idempotency")?{heading:"Duplicate payment request",body:"This payment has already been submitted. Refresh and try again."}:t.includes("expired")&&t.includes("token")?{heading:"Link session expired",body:"Your sign-in to Link timed out. Re-connect to continue."}:t.includes("payment_methods.agentic")||t.includes("not authorized")?{heading:"Card not authorized for agentic payments",body:"Open your Link wallet and authorize this card for agentic spending, then try again."}:t.includes("consumer limits")?{heading:"Stripe couldn't check your limits",body:"Stripe Link hit an error evaluating your spending limits. Wait a moment and try again, or use a smaller amount."}:t.includes("500")||t.includes("something went wrong")?{heading:"Stripe is having trouble",body:"Stripe Link returned an unexpected error. Wait a moment and try again."}:{heading:"Couldn't authorize this payment",body:e}}function gl(e){let t=(e||"").toLowerCase();return t==="visa"||t==="mastercard"||t==="amex"||t==="discover"?t:"unknown"}function ul(e){return e?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():"Card"}function So({method:e}){let t=e.expiryMonth&&e.expiryYear?`${String(e.expiryMonth).padStart(2,"0")}/${String(e.expiryYear).slice(-2)}`:"";return ae("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[$("div",{className:"w-12 bg-white dark:bg-slate-900 black:bg-black border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] overflow-hidden flex items-center justify-center flex-shrink-0",style:{aspectRatio:"1.586",borderRadius:"3px"},children:$(dt,{brand:gl(e.brand)})}),ae("div",{className:"flex-1 min-w-0 text-left",children:[ae("div",{className:"text-sm font-medium text-slate-900 dark:text-white black:text-white truncate",children:[ul(e.brand)," \u2022\u2022\u2022\u2022 ",e.last4||"\u2022\u2022\u2022\u2022"]}),t&&ae("div",{className:"text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:["Expires ",t]})]})]})}function $r({methods:e,selectedMethodId:t,onSelectMethod:a,onContinue:r,onCancel:n,continueLabel:s="Continue",onOpenLinkWallet:o,onReopenApproval:d,subState:i,approvalExpiresAt:m,errorMessage:g,onDismissError:p}){let b=i==="awaiting",c=i==="creating",y=i==="completing",[h,v]=Co(Date.now());vo(()=>{if(!b||!m)return;v(Date.now());let D=setInterval(()=>v(Date.now()),1e3);return()=>clearInterval(D)},[b,m]);let u=m?Math.max(0,Math.floor((m-h)/1e3)):null,f=u!=null?Math.floor(u/60):0,l=u!=null?String(u%60).padStart(2,"0"):"00",[x,L]=Co(!1),w=e.find(D=>D.id===t)||e[0]||null,V=!b&&!c&&!y&&e.length>0;return vo(()=>{!t&&e.length>0&&a(e[0].id)},[t,e,a]),ae("div",{className:"flex flex-col min-h-full p-5 relative",children:[g&&!b&&!y&&(()=>{let{heading:D,body:N}=ml(g);return $("div",{role:"alert",className:"absolute top-3 left-3 right-3 z-10 rounded-2xl bg-white dark:bg-slate-900 black:bg-black ring-1 ring-rose-200/70 dark:ring-rose-900/40 black:ring-rose-900/40 shadow-[0_8px_24px_-12px_rgba(244,63,94,0.35)] overflow-hidden animate-in slide-in-from-top-2 fade-in duration-200",children:ae("div",{className:"flex items-start gap-3 px-4 pt-3.5 pb-3",children:[$("div",{className:"flex-shrink-0 mt-0.5 w-7 h-7 rounded-full bg-rose-50 dark:bg-rose-950/40 black:bg-rose-950/40 flex items-center justify-center ring-1 ring-rose-100 dark:ring-rose-900/40 black:ring-rose-900/40",children:$(dl,{className:"w-4 h-4 text-rose-600 dark:text-rose-400 black:text-rose-400"})}),ae("div",{className:"min-w-0 flex-1",children:[$("p",{className:"text-[13px] font-semibold text-slate-900 dark:text-white black:text-white leading-snug",children:D}),$("p",{className:"text-[12px] text-slate-600 dark:text-slate-400 black:text-gray-400 mt-0.5 leading-relaxed break-words",children:N}),$("div",{className:"mt-2.5 flex flex-wrap items-center gap-2",children:$("a",{href:"mailto:support@payos.ai",className:"inline-flex items-center px-2.5 py-1 rounded-md border border-slate-200 dark:border-slate-700 black:border-[#1f1f1f] bg-white dark:bg-slate-900 black:bg-black text-slate-700 dark:text-slate-200 black:text-gray-200 text-[11px] font-medium hover:bg-slate-50 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a]",children:"Contact support"})})]}),p&&$("button",{type:"button","aria-label":"Dismiss",onClick:p,className:"flex-shrink-0 -mr-1 -mt-1 p-1.5 rounded-md text-slate-400 dark:text-slate-500 black:text-gray-500 hover:text-slate-700 dark:hover:text-slate-200 black:hover:text-gray-200 hover:bg-slate-100 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a] transition-colors",children:$(pl,{className:"w-3.5 h-3.5"})})]})})})(),ae("div",{className:"flex-1 flex flex-col justify-center space-y-4 py-12",children:[ae("div",{className:"text-center space-y-3",children:[ae("h2",{className:"text-5xl font-bold text-slate-900 dark:text-white black:text-white tracking-tight flex items-center justify-center gap-3",children:[$("span",{children:"Pay with"}),$(Ke,{})]}),$("p",{className:"text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:b?ae(Po,{children:["Approve this payment in the Link window at ",$("span",{className:"font-mono",children:"app.link.com"}),"."]}):y?"Finishing your payment securely.":"Approve this payment in Link to complete your purchase."})]}),b&&u!=null&&u>0&&$("div",{className:"flex justify-center",children:ae("span",{className:"inline-flex items-center text-sm font-medium text-gray-600 dark:text-slate-300 black:text-gray-300 px-3 py-1.5 rounded-full border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] bg-white dark:bg-slate-900 black:bg-black",children:["Expires in ",f,":",l]})}),y&&ae("div",{role:"status","aria-live":"polite",className:"pt-4 flex flex-col items-center justify-center gap-3 text-center",children:[$(cl,{className:"w-9 h-9 animate-spin text-slate-900 dark:text-white black:text-white"}),ae("div",{className:"space-y-1",children:[$("p",{className:"text-sm font-semibold text-slate-900 dark:text-white black:text-white",children:"Generating credentials"}),$("p",{className:"text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:"This usually takes a moment."})]})]}),!b&&!y&&ae("div",{className:"space-y-1",children:[ae("p",{className:"text-[10px] uppercase tracking-wider font-semibold text-gray-500 dark:text-slate-400 black:text-gray-400 px-1",children:["Link wallet",o&&ae(Po,{children:[" (",$("button",{type:"button",onClick:o,className:"uppercase tracking-wider font-semibold text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline",children:"manage"}),")"]})]}),ae("div",{className:"relative",children:[ae("button",{type:"button",onClick:()=>V&&L(D=>!D),disabled:!V&&e.length===0,className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl border bg-white dark:bg-slate-900 black:bg-black transition-colors ${V?"border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] hover:border-gray-400 dark:hover:border-slate-500 black:hover:border-[#333333] cursor-pointer":"border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] cursor-default"}`,children:[w?$(So,{method:w}):$("span",{className:"text-sm text-gray-400 dark:text-slate-500 black:text-gray-500",children:"No Link card available"}),V&&$("svg",{className:`w-4 h-4 text-gray-400 dark:text-slate-500 black:text-gray-500 transition-transform ${x?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:$("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),x&&V&&$("div",{className:"absolute left-0 right-0 mt-2 rounded-xl border border-gray-200 dark:border-slate-700 black:border-[#1f1f1f] bg-white dark:bg-slate-900 black:bg-black shadow-xl ring-1 ring-black/5 dark:ring-white/5 black:ring-white/10 z-10 overflow-hidden max-h-72 overflow-y-auto animate-in fade-in slide-in-from-top-1 duration-150",children:e.map((D,N)=>{let C=D.id===w?.id;return ae("button",{type:"button",onClick:()=>{a(D.id),L(!1)},className:`w-full flex items-center gap-3 px-4 py-3 transition-colors ${N>0?"border-t border-gray-100 dark:border-slate-800 black:border-[#1f1f1f]":""} ${C?"bg-[#00D66F]/10 hover:bg-[#00D66F]/15":"hover:bg-gray-50 dark:hover:bg-slate-800/60 black:hover:bg-[#0a0a0a] active:bg-gray-100 dark:active:bg-slate-800 black:active:bg-[#151515]"}`,children:[$(So,{method:D}),C&&$("svg",{className:"w-4 h-4 text-[#007f3f] dark:text-[#00D66F] black:text-[#00D66F] flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:$("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})]},D.id)})})]})]}),!y&&$("div",{className:b?"":"pt-4",children:ae("div",{className:"space-y-3",children:[!b&&$("button",{type:"button",onClick:r,disabled:!t||c||e.length===0,className:"w-full h-11 rounded-lg bg-[#00D66F] hover:bg-[#00C264] disabled:opacity-50 text-black font-semibold text-sm",children:c?"Preparing approval...":s}),b&&ae("div",{className:"space-y-2",children:[ae("button",{type:"button",disabled:!0,className:"w-full h-11 rounded-lg bg-[#00D66F] disabled:opacity-50 text-black font-semibold text-sm flex items-center justify-center gap-2",children:[$("style",{children:"@keyframes payosLinkApproval { 0%, 80%, 100% { transform: scale(0.55); opacity: 0.35; } 40% { transform: scale(1); opacity: 1; } }"}),ae("span",{className:"inline-flex gap-1",children:[$("span",{className:"w-1.5 h-1.5 rounded-full bg-black",style:{animation:"payosLinkApproval 1.2s ease-in-out infinite both",animationDelay:"0s"}}),$("span",{className:"w-1.5 h-1.5 rounded-full bg-black",style:{animation:"payosLinkApproval 1.2s ease-in-out infinite both",animationDelay:"0.16s"}}),$("span",{className:"w-1.5 h-1.5 rounded-full bg-black",style:{animation:"payosLinkApproval 1.2s ease-in-out infinite both",animationDelay:"0.32s"}})]}),"Awaiting approval"]}),d&&ae("p",{className:"text-center text-xs text-gray-500 dark:text-slate-400 black:text-gray-400",children:["Don't see the popup?"," ",$("button",{type:"button",onClick:d,className:"font-semibold text-blue-600 dark:text-blue-400 black:text-blue-400 hover:underline",children:"Try again"})]})]}),$("div",{className:"flex items-center justify-center text-xs",children:$("button",{type:"button",onClick:n,className:"text-gray-500 dark:text-slate-400 black:text-gray-400 underline hover:text-gray-900 dark:hover:text-white black:hover:text-white",children:"Cancel"})})]})})]})]})}import{X as fl,Clock as bl}from"lucide-react";import{jsx as It,jsxs as Hr}from"react/jsx-runtime";var hl={denied:{heading:"Approval denied",body:"You declined this payment in Link."},expired:{heading:"Approval expired",body:"The approval window timed out. Tap Try again to send a new request."},cancelled:{heading:"Sign-in cancelled",body:"The Link window closed before approval. Tap Try again to reopen it."}};function yl(e){let t=(e||"").toLowerCase();return t.includes("expir")?"expired":t.includes("cancel")?"cancelled":"denied"}function da({reason:e,onRetry:t,onDismiss:a}){let r=yl(e),{heading:n,body:s}=hl[r],o=r==="expired";return Hr("div",{className:"flex flex-col items-center justify-center min-h-full p-6 space-y-5 text-center",children:[It("div",{className:`w-16 h-16 rounded-full flex items-center justify-center ${o?"bg-amber-100 dark:bg-amber-900/30 black:bg-amber-900/30":"bg-red-100 dark:bg-red-900/30 black:bg-red-900/30"}`,children:o?It(bl,{className:"h-9 w-9 text-amber-600 dark:text-amber-400 black:text-amber-400",strokeWidth:2.5}):It(fl,{className:"h-9 w-9 text-red-600 dark:text-red-400 black:text-red-400",strokeWidth:3})}),Hr("div",{className:"space-y-1",children:[It("h2",{className:"text-xl font-bold text-slate-900 dark:text-white black:text-white tracking-tight",children:n}),It("p",{className:"text-sm text-gray-500 dark:text-slate-400 black:text-gray-400",children:s})]}),Hr("div",{className:"flex flex-col gap-2 w-full max-w-sm",children:[t&&It("button",{type:"button",onClick:t,className:"w-full h-11 rounded-lg bg-[#00D66F] hover:bg-[#00C264] text-black font-semibold text-sm",children:"Try again"}),a&&It("button",{type:"button",onClick:a,className:"w-full h-10 rounded-lg text-gray-500 dark:text-slate-400 black:text-gray-400 font-medium text-sm hover:bg-gray-100 dark:hover:bg-slate-800 black:hover:bg-[#0a0a0a]",children:"Use a different method"})]})]})}import{jsx as Yt,jsxs as Lo}from"react/jsx-runtime";function ca({message:e="Successfully approved"}){return Lo("div",{className:"flex flex-col items-center justify-center min-h-full p-6 space-y-5 text-center",children:[Yt("style",{children:`
22
22
  @keyframes payosLinkSuccessPop {
23
23
  0% { transform: scale(0); opacity: 0; }
24
24
  60% { transform: scale(1.15); opacity: 1; }