@payos-inc/payos-react 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/ui/button.d.ts +1 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/payos-react.esm.js +7 -7
- package/dist/payos-react.min.js +1 -1
- package/dist/services/linkTokenService.d.ts +4 -24
- package/dist/services/linkTokenService.d.ts.map +1 -1
- package/dist/services/mockSessionService.d.ts +7 -20
- package/dist/services/mockSessionService.d.ts.map +1 -1
- package/dist/types/index.d.ts +0 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/services/linkTokenService.d.ts +4 -24
- package/dist/types/services/linkTokenService.d.ts.map +1 -1
- package/dist/types/services/mockSessionService.d.ts +7 -20
- package/dist/types/services/mockSessionService.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as React from "react";
|
|
2
2
|
import { type VariantProps } from "class-variance-authority";
|
|
3
3
|
declare const buttonVariants: (props?: ({
|
|
4
|
-
variant?: "default" | "
|
|
4
|
+
variant?: "default" | "link" | "destructive" | "outline" | "secondary" | "ghost" | null | undefined;
|
|
5
5
|
size?: "default" | "sm" | "lg" | "icon" | null | undefined;
|
|
6
6
|
} & import("class-variance-authority/dist/types").ClassProp) | undefined) => string;
|
|
7
7
|
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
|
package/dist/index.d.ts
CHANGED
|
@@ -38,6 +38,4 @@ export { useVisualViewport, useVisualViewportStyle } from './hooks/useVisualView
|
|
|
38
38
|
export type { PaymentView, CheckoutPhase, SavedCard, CardData, CardBrand } from './types';
|
|
39
39
|
export type { SessionStatus, PaymentIntentType, MultiPaymentIntent, PaymentIntentStatus, WalletUser, SavedCard as SessionSavedCard, CardNetwork, CheckoutSession, SessionError, SessionErrorCode, VerificationInitResult, VerificationResult, CompletionResult, PaymentSheetResult, PaymentSheetError, } from './types/session';
|
|
40
40
|
export { cn } from './lib/utils';
|
|
41
|
-
export { createTestSessionWithRealIntent } from './services/mockSessionService';
|
|
42
|
-
export type { CreatePaymentIntentRequest } from './services/apiService';
|
|
43
41
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,eAAe,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC7G,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAGtD,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAC/D,YAAY,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAG7D,OAAO,EAAE,YAAY,EAAE,MAAM,uCAAuC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAC3E,OAAO,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAC;AAG3D,OAAO,EAAE,YAAY,EAAE,MAAM,uCAAuC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AAGnE,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,YAAY,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,MAAM,yCAAyC,CAAC;AACzE,YAAY,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AAC3G,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,YAAY,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,gDAAgD,CAAC;AACvF,YAAY,EAAE,0BAA0B,EAAE,MAAM,gDAAgD,CAAC;AAGjG,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAC/D,YAAY,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAGzE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,YAAY,EAAE,gBAAgB,EAAE,YAAY,EAAE,WAAW,IAAI,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC5G,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAGtF,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAG1F,YAAY,EACV,aAAa,EACb,iBAAiB,EACjB,kBAAkB,EAClB,mBAAmB,EACnB,UAAU,EACV,SAAS,IAAI,gBAAgB,EAC7B,WAAW,EACX,eAAe,EACf,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,EACtB,kBAAkB,EAClB,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,eAAe,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC7G,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAGtD,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAC/D,YAAY,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAG7D,OAAO,EAAE,YAAY,EAAE,MAAM,uCAAuC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAC3E,OAAO,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAC;AAG3D,OAAO,EAAE,YAAY,EAAE,MAAM,uCAAuC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AAGnE,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,YAAY,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,MAAM,yCAAyC,CAAC;AACzE,YAAY,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AAC3G,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,YAAY,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,gDAAgD,CAAC;AACvF,YAAY,EAAE,0BAA0B,EAAE,MAAM,gDAAgD,CAAC;AAGjG,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAC/D,YAAY,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAGzE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,YAAY,EAAE,gBAAgB,EAAE,YAAY,EAAE,WAAW,IAAI,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC5G,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAGtF,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAG1F,YAAY,EACV,aAAa,EACb,iBAAiB,EACjB,kBAAkB,EAClB,mBAAmB,EACnB,UAAU,EACV,SAAS,IAAI,gBAAgB,EAC7B,WAAW,EACX,eAAe,EACf,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,EACtB,kBAAkB,EAClB,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC"}
|
package/dist/payos-react.esm.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import*as Pr from"react";import{Slot as Ya}from"@radix-ui/react-slot";import{cva as Ga}from"class-variance-authority";import{Loader2 as Wa}from"lucide-react";import{clsx as $a}from"clsx";import{twMerge as Ha}from"tailwind-merge";function R(...e){return Ha($a(e))}import{Fragment as qa,jsx as jt,jsxs as ja}from"react/jsx-runtime";var Ka=Ga("inline-flex items-center justify-center whitespace-nowrap rounded-xl text-base font-semibold ring-offset-white dark:ring-offset-slate-950 transition-all duration-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-950 dark:focus-visible:ring-slate-300 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:bg-slate-900/20 disabled:text-slate-900/50 active:scale-[0.98]",{variants:{variant:{default:"bg-primary text-white hover:opacity-90 shadow-lg",destructive:"bg-red-500 text-white hover:bg-red-600 shadow-sm dark:bg-red-900 dark:hover:bg-red-800",outline:"border border-gray-300 dark:border-slate-600 bg-white dark:bg-slate-800 hover:bg-gray-50 dark:hover:bg-slate-700 hover:border-gray-400 dark:hover:border-slate-500",secondary:"bg-gray-100 dark:bg-slate-700 text-gray-900 dark:text-white hover:bg-gray-200 dark:hover:bg-slate-600",ghost:"hover:bg-gray-100 dark:hover:bg-slate-800 hover:text-gray-900 dark:hover:text-white",link:"text-blue-600 dark:text-blue-400 underline-offset-4 hover:underline"},size:{default:"h-12 px-4 py-3",sm:"h-9 px-3 text-sm",lg:"h-14 px-6 py-4 text-lg",icon:"h-12 w-12"}},defaultVariants:{variant:"default",size:"default"}}),M=Pr.forwardRef(({className:e,variant:r,size:t,asChild:a=!1,isLoading:n,loadingText:i,children:o,disabled:p,...l},f)=>jt(a?Ya:"button",{className:R(Ka({variant:r,size:t,className:e})),ref:f,disabled:p||n,"aria-busy":n,...l,children:n?ja(qa,{children:[jt(Wa,{className:"mr-2 h-4 w-4 animate-spin"}),jt("span",{children:i||(typeof o=="string"?"Loading...":o)})]}):o}));M.displayName="Button";import*as Nr from"react";import{jsx as Ja}from"react/jsx-runtime";var Ir=Nr.forwardRef(({className:e,type:r,...t},a)=>Ja("input",{type:r,className:R("flex h-11 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-base text-gray-900 placeholder:text-gray-400 focus:border-black focus:outline-none focus:ring-2 focus:ring-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:text-gray-400 transition-colors","-webkit-appearance-none appearance-none",e),ref:a,...t}));Ir.displayName="Input";import*as Se from"react";import{cva as Xa}from"class-variance-authority";import{jsx as De}from"react/jsx-runtime";var Za=Xa("rounded-xl overflow-hidden mb-4",{variants:{variant:{default:"bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 shadow-sm",flat:"bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700",transparent:"bg-transparent border-none shadow-none"}},defaultVariants:{variant:"default"}}),O=Se.forwardRef(({className:e,variant:r,...t},a)=>De("div",{ref:a,className:R(Za({variant:r}),e),...t}));O.displayName="Card";var Rr=Se.forwardRef(({className:e,...r},t)=>De("div",{ref:t,className:R("flex flex-col space-y-1.5 p-4",e),...r}));Rr.displayName="CardHeader";var Er=Se.forwardRef(({className:e,...r},t)=>De("h3",{ref:t,className:R("text-lg font-semibold leading-none tracking-tight text-gray-900 dark:text-white",e),...r}));Er.displayName="CardTitle";var Tr=Se.forwardRef(({className:e,...r},t)=>De("p",{ref:t,className:R("text-sm text-gray-500 dark:text-slate-400",e),...r}));Tr.displayName="CardDescription";var Ar=Se.forwardRef(({className:e,...r},t)=>De("div",{ref:t,className:R("p-4 pt-0",e),...r}));Ar.displayName="CardContent";var Or=Se.forwardRef(({className:e,...r},t)=>De("div",{ref:t,className:R("flex items-center p-4 pt-0",e),...r}));Or.displayName="CardFooter";import*as _r from"react";import*as Jt from"@radix-ui/react-label";import{cva as Qa}from"class-variance-authority";import{jsx as tn}from"react/jsx-runtime";var en=Qa("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-gray-700"),Dr=_r.forwardRef(({className:e,...r},t)=>tn(Jt.Root,{ref:t,className:R(en(),e),...r}));Dr.displayName=Jt.Root.displayName;import*as Mr from"react";import*as Xt from"@radix-ui/react-separator";import{jsx as rn}from"react/jsx-runtime";var Vr=Mr.forwardRef(({className:e,orientation:r="horizontal",decorative:t=!0,...a},n)=>rn(Xt.Root,{ref:n,decorative:t,orientation:r,className:R("shrink-0 bg-gray-200",r==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...a}));Vr.displayName=Xt.Root.displayName;import*as Ur from"react";import{useState as an,useRef as nn,useEffect as on}from"react";import{Lock as sn,ChevronDown as dn}from"lucide-react";import{jsx as le,jsxs as it}from"react/jsx-runtime";var Zt=[{code:"US",name:"United States",dial:"+1",flag:"\u{1F1FA}\u{1F1F8}"},{code:"CA",name:"Canada",dial:"+1",flag:"\u{1F1E8}\u{1F1E6}"},{code:"GB",name:"United Kingdom",dial:"+44",flag:"\u{1F1EC}\u{1F1E7}"},{code:"AU",name:"Australia",dial:"+61",flag:"\u{1F1E6}\u{1F1FA}"},{code:"DE",name:"Germany",dial:"+49",flag:"\u{1F1E9}\u{1F1EA}"},{code:"FR",name:"France",dial:"+33",flag:"\u{1F1EB}\u{1F1F7}"},{code:"ES",name:"Spain",dial:"+34",flag:"\u{1F1EA}\u{1F1F8}"},{code:"IT",name:"Italy",dial:"+39",flag:"\u{1F1EE}\u{1F1F9}"},{code:"NL",name:"Netherlands",dial:"+31",flag:"\u{1F1F3}\u{1F1F1}"},{code:"MX",name:"Mexico",dial:"+52",flag:"\u{1F1F2}\u{1F1FD}"},{code:"BR",name:"Brazil",dial:"+55",flag:"\u{1F1E7}\u{1F1F7}"},{code:"IN",name:"India",dial:"+91",flag:"\u{1F1EE}\u{1F1F3}"},{code:"JP",name:"Japan",dial:"+81",flag:"\u{1F1EF}\u{1F1F5}"},{code:"KR",name:"South Korea",dial:"+82",flag:"\u{1F1F0}\u{1F1F7}"},{code:"SG",name:"Singapore",dial:"+65",flag:"\u{1F1F8}\u{1F1EC}"}];function dt(e,r="US"){let t=e.replace(/\D/g,"");if(r==="US"||r==="CA"){let a=t.startsWith("1")&&t.length>10?t.slice(1):t;return a.length===0?"":a.length<=3?`(${a}`:a.length<=6?`(${a.slice(0,3)}) ${a.slice(3)}`:`(${a.slice(0,3)}) ${a.slice(3,6)}-${a.slice(6,10)}`}return t}var lt=Ur.forwardRef(({className:e,value:r,onChange:t,countryCode:a="US",onCountryChange:n,...i},o)=>{let[p,l]=an(!1),f=nn(null),m=Zt.find(d=>d.code===a)||Zt[0],N=dt(r||"",a);on(()=>{if(!p)return;let d=g=>{f.current&&!f.current.contains(g.target)&&l(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[p]);let b=d=>{if(t){let g=dt(d.target.value,a);t(g)}},s=d=>{n?.(d),l(!1),d!==a&&t&&t("")},c=a==="US"||a==="CA"?"(555) 000-0000":"Phone number";return it("div",{className:"relative",ref:f,children:[it("div",{className:R("flex items-center h-14 bg-white dark:bg-slate-800 border border-gray-300 dark:border-slate-600 rounded-xl overflow-hidden transition-all duration-150","focus-within:ring-2 focus-within:ring-slate-900 focus-within:ring-offset-0",e),children:[it("button",{type:"button",onClick:()=>l(!p),className:"flex items-center gap-1.5 px-3 h-full bg-gray-50 dark:bg-slate-900 border-r border-gray-200 dark:border-slate-700 cursor-pointer hover:bg-gray-100 dark:hover:bg-slate-800 transition-colors","aria-label":"Select country code","aria-expanded":p,children:[le("span",{className:"text-xl",children:m.flag}),le("span",{className:"text-sm font-medium text-gray-700 dark:text-slate-300",children:m.dial}),le(dn,{className:R("w-3.5 h-3.5 text-gray-400 transition-transform",p&&"rotate-180")})]}),le("input",{ref:o,type:"tel",inputMode:"tel",autoComplete:"tel",value:N,onChange:b,className:R("flex-1 h-full px-3 border-0 outline-none","text-lg font-normal tracking-wide text-gray-900 dark:text-white","placeholder:text-gray-400 dark:placeholder:text-slate-500 placeholder:font-light","bg-transparent"),placeholder:c,...i}),le("div",{className:"px-3",children:le(sn,{className:"w-4 h-4 text-gray-400 dark:text-slate-500"})})]}),p&&le("div",{className:"absolute top-full left-0 mt-1 w-64 bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-xl shadow-lg z-50 max-h-60 overflow-y-auto",children:Zt.map(d=>it("button",{type:"button",onClick:()=>s(d.code),className:R("w-full px-3 py-2.5 flex items-center gap-3 hover:bg-gray-50 dark:hover:bg-slate-700 transition-colors text-left",d.code===a&&"bg-gray-50 dark:bg-slate-700"),children:[le("span",{className:"text-xl",children:d.flag}),le("span",{className:"flex-1 text-sm text-gray-900 dark:text-white",children:d.name}),le("span",{className:"text-sm text-gray-500 dark:text-slate-400",children:d.dial})]},d.code))})]})});lt.displayName="PhoneInput";import*as be from"react";import{jsx as Lr}from"react/jsx-runtime";var Me=be.forwardRef(({value:e="",onChange:r,onComplete:t,length:a=6,className:n},i)=>{let o=be.useRef([]),[p,l]=be.useState(e.split("").slice(0,a).concat(Array(a).fill("")).slice(0,a));be.useEffect(()=>{let s=e.split("").slice(0,a).concat(Array(a).fill("")).slice(0,a);l(s)},[e,a]);let f=(s,c)=>{if(c.length>1&&(c=c.slice(-1)),!/^\d*$/.test(c))return;let d=[...p];d[s]=c,l(d);let g=d.join("");r?.(g),c&&s<a-1&&o.current[s+1]?.focus(),d.every(y=>y)&&g.length===a&&t?.(g)},m=(s,c)=>{if(c.key==="Backspace"){c.preventDefault();let d=[...p];p[s]?(d[s]="",l(d),r?.(d.join(""))):s>0&&(d[s-1]="",l(d),r?.(d.join("")),o.current[s-1]?.focus())}c.key==="ArrowLeft"&&s>0&&o.current[s-1]?.focus(),c.key==="ArrowRight"&&s<a-1&&o.current[s+1]?.focus()},N=s=>{s.preventDefault();let c=s.clipboardData.getData("text").slice(0,a).replace(/\D/g,"");if(c){let d=c.split("").concat(Array(a).fill("")).slice(0,a);l(d),r?.(c);let g=Math.min(c.length,a-1);o.current[g]?.focus(),c.length===a&&t?.(c)}},b=s=>{o.current[s]?.select()};return Lr("div",{ref:i,className:R("flex gap-2 justify-center",n),onPaste:N,children:Array.from({length:a},(s,c)=>Lr("input",{ref:d=>o.current[c]=d,type:"text",inputMode:"numeric",maxLength:1,value:p[c]||"",onChange:d=>f(c,d.target.value),onKeyDown:d=>m(c,d),onFocus:()=>b(c),className:R("w-12 h-14 text-center text-2xl font-bold","border-2 border-gray-300 dark:border-slate-600 rounded-md","bg-white dark:bg-slate-800","text-gray-900 dark:text-white","focus:ring-2 focus:ring-black dark:focus:ring-white focus:border-transparent focus:outline-none","transition-all duration-150"),"aria-label":`Digit ${c+1} of ${a}`},c))})});Me.displayName="OTPInput";import*as ce from"react";import{X as bn}from"lucide-react";function ct(e,r){let t=e.replace(/\D/g,"");return r==="US"||r==="CA"?t.length===10||t.length===11:t.length>=7&&t.length<=15}function Fr(e,r){let t=e.replace(/\D/g,"");return r==="amex"?t.length===4:t.length===3}import{jsx as Ve,jsxs as Qt}from"react/jsx-runtime";var Ue=({phone:e,onPhoneChange:r,countryCode:t="US",onCountryChange:a,onSubmit:n,isLoading:i=!1,error:o})=>{let p=m=>{m.preventDefault(),n()},l=ct(e,t);return Ve("form",{onSubmit:p,className:"space-y-4",children:Qt(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-6",children:[Qt("div",{className:"space-y-1",children:[Ve("h2",{className:"text-xl font-bold text-slate-900 dark:text-white text-center tracking-tight mx-auto",children:"Complete your purchase"}),Ve("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center mx-auto",children:"Verify your mobile number to secure this payment."})]}),Qt("div",{children:[Ve(lt,{value:e,onChange:r,countryCode:t,onCountryChange:a,onKeyDown:m=>{m.key==="Enter"&&l&&!i&&n()},autoFocus:!0}),o&&Ve("p",{className:"text-sm text-red-600 dark:text-red-400 mt-2",children:o})]}),Ve(M,{type:"submit",className:"w-full",disabled:!l||i,isLoading:i,loadingText:"Sending code...",children:"Continue"})]})})};Ue.displayName="IdentityView";import{User as ln,CheckCircle2 as cn}from"lucide-react";import{jsx as se,jsxs as er}from"react/jsx-runtime";var pt=({phone:e,onContinue:r,onSwitchAccount:t,isLoading:a=!1})=>er("form",{onSubmit:i=>{i.preventDefault(),r()},className:"space-y-4",children:[er(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-6",children:[se("h2",{className:"text-xl font-bold text-slate-900 dark:text-white text-center",children:"Welcome back!"}),er("div",{className:"w-full bg-gray-50 dark:bg-slate-800/50 border border-gray-200 dark:border-slate-700 rounded-xl p-4 flex items-center gap-3",children:[se("div",{className:"flex-shrink-0 bg-gray-100 dark:bg-slate-700 rounded-full p-1",children:se(ln,{className:"w-5 h-5 text-gray-500 dark:text-slate-400"})}),se("div",{className:"flex-1 min-w-0",children:se("p",{className:"text-lg font-semibold text-slate-900 dark:text-white truncate",children:e})}),se("div",{className:"flex-shrink-0",children:se(cn,{className:"w-5 h-5 text-green-500 dark:text-green-400"})})]}),se(M,{type:"submit",className:"w-full mt-4",disabled:a,isLoading:a,loadingText:"Sending code...",children:"Send Verification Code"}),se("p",{className:"text-xs text-gray-400 dark:text-slate-500 text-center mt-4",children:"We'll send you a verification code to confirm it's you"})]}),se("div",{className:"text-center px-4 mt-4",children:se("button",{type:"button",onClick:t,disabled:a,className:"text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",children:"Not you? Use a different number"})})]});pt.displayName="WelcomeBackView";import{ShoppingCart as pn,ChevronDown as mn}from"lucide-react";import{Fragment as un,jsx as Le,jsxs as gn}from"react/jsx-runtime";var Ye=({amount:e,label:r="Total",onClick:t,isExpanded:a=!1,showChevron:n=!1,showIcon:i=!1,className:o=""})=>{let p=!!t,l=R("border rounded-lg px-3 py-2 flex items-center gap-2 transition-colors","bg-gray-50/50 dark:bg-slate-800/50 border-gray-200 dark:border-slate-700",p&&"cursor-pointer select-none hover:bg-gray-100 dark:hover:bg-slate-700",p&&"text-slate-700 dark:text-slate-300 hover:text-black dark:hover:text-white",!p&&"bg-gray-50 dark:bg-slate-800",o),f=gn(un,{children:[i&&p&&Le(pn,{className:"w-4 h-4 text-gray-500 dark:text-slate-400"}),Le("span",{className:"text-xs font-medium text-gray-500 dark:text-slate-400",children:r}),Le("span",{className:"text-sm font-bold text-slate-900 dark:text-white",children:e}),n&&p&&Le(mn,{className:R("w-4 h-4 text-gray-400 dark:text-slate-500 transition-transform duration-200",a&&"rotate-180")})]});return p?Le("button",{type:"button",onClick:t,className:l,"aria-expanded":a,"aria-label":`${a?"Hide":"Show"} order details`,children:f}):Le("div",{className:l,children:f})};Ye.displayName="PriceTag";import{Bot as Br}from"lucide-react";import{jsx as z,jsxs as Z}from"react/jsx-runtime";var mt=({items:e,subtotal:r,shipping:t,tax:a,agentFee:n,total:i,isAgentMode:o=!1})=>z("div",{className:"bg-gray-50 dark:bg-slate-800 border-b border-gray-200 dark:border-slate-700",children:Z("div",{className:"px-6 py-4 space-y-3",children:[o&&Z("div",{className:"flex items-center gap-2 pb-2 border-b border-gray-200 dark:border-slate-700",children:[Z("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-violet-100 text-violet-700 text-xs font-medium dark:bg-violet-900/30 dark:text-violet-300",children:[z(Br,{className:"h-3 w-3"}),"Agent"]}),z("span",{className:"text-xs text-gray-600 dark:text-slate-400",children:"AI Agent Purchase"})]}),e&&e.length>0&&Z("div",{className:"space-y-2",children:[e.map((p,l)=>Z("div",{className:"flex items-start justify-between gap-2",children:[Z("div",{className:"flex-1 min-w-0",children:[z("div",{className:"text-sm text-slate-900 dark:text-white truncate",children:p.label}),p.description&&z("div",{className:"text-xs text-gray-500 dark:text-slate-400",children:p.description})]}),z("div",{className:"text-sm font-medium text-slate-900 dark:text-white whitespace-nowrap",children:p.value})]},l)),z("div",{className:"h-px bg-gray-200 dark:bg-slate-700"})]}),Z("div",{className:"space-y-2 text-sm",children:[Z("div",{className:"flex items-center justify-between",children:[z("span",{className:"text-gray-600 dark:text-slate-400",children:"Subtotal"}),z("span",{className:"font-medium text-slate-900 dark:text-white",children:r})]}),t&&Z("div",{className:"flex items-center justify-between",children:[z("span",{className:"text-gray-600 dark:text-slate-400",children:"Shipping"}),z("span",{className:"font-medium text-slate-900 dark:text-white",children:t})]}),a&&Z("div",{className:"flex items-center justify-between",children:[z("span",{className:"text-gray-600 dark:text-slate-400",children:"Tax"}),z("span",{className:"font-medium text-slate-900 dark:text-white",children:a})]}),n&&o&&Z("div",{className:"flex items-center justify-between",children:[Z("span",{className:"text-gray-600 dark:text-slate-400 flex items-center gap-1",children:["Agent Fee",z(Br,{className:"h-3 w-3 text-violet-500"})]}),z("span",{className:"font-medium text-slate-900 dark:text-white",children:n})]})]}),z("div",{className:"pt-2 border-t border-gray-200 dark:border-slate-700",children:Z("div",{className:"flex items-center justify-between",children:[z("span",{className:"text-sm font-bold text-slate-900 dark:text-white",children:"Total"}),z("span",{className:"text-lg font-bold text-slate-900 dark:text-white",children:i})]})})]})});mt.displayName="ReceiptPanel";import*as $r from"react";import{ShieldCheck as fn}from"lucide-react";import{jsx as zr,jsxs as hn}from"react/jsx-runtime";var ut=$r.forwardRef(({className:e},r)=>hn("div",{ref:r,className:R("flex items-center justify-center gap-1.5 text-xs text-gray-500 dark:text-slate-400",e),children:[zr(fn,{className:"w-3.5 h-3.5"}),zr("span",{children:"Powered by PayOS"})]}));ut.displayName="PayOSFooter";import*as Hr from"react";function tr(e,r={}){let{preventTouch:t=!1}=r;Hr.useEffect(()=>{if(!e)return;let a=document.body.style.overflow,n=document.body.style.position,i=document.body.style.top,o=document.body.style.width,p=document.body.style.touchAction,l=window.scrollY;return document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${l}px`,document.body.style.width="100%",t&&(document.body.style.touchAction="none"),()=>{document.body.style.overflow=a,document.body.style.position=n,document.body.style.top=i,document.body.style.width=o,document.body.style.touchAction=p,window.scrollTo(0,l)}},[e,t])}import*as Fe from"react";var yn=450;function gt(){let[e,r]=Fe.useState(0);return Fe.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;let t=window.visualViewport,a=()=>{let n=window.innerHeight-t.height;r(Math.max(0,n));let i=t.height;i<yn?document.documentElement.style.setProperty("--visual-viewport-height",`${window.innerHeight*.85}px`):document.documentElement.style.setProperty("--visual-viewport-height",`${i}px`)};return a(),t.addEventListener("resize",a),t.addEventListener("scroll",a),()=>{t.removeEventListener("resize",a),t.removeEventListener("scroll",a),document.documentElement.style.removeProperty("--visual-viewport-height")}},[]),e}function wn(){let e=gt();return Fe.useMemo(()=>({bottom:e>0?`${e}px`:void 0}),[e])}import{Fragment as xn,jsx as q,jsxs as ft}from"react/jsx-runtime";var ht=ce.forwardRef(({open:e=!1,onClose:r,title:t,subtitle:a,amount:n,orderItems:i,subtotal:o,shipping:p,tax:l,orderAgentFee:f,mode:m="standard",children:N,className:b,prefill:s,onPhoneSubmit:c,onContinue:d},g)=>{let[y,L]=ce.useState(s?.phone?"welcome-back":"identity"),[A,G]=ce.useState(""),[k,S]=ce.useState(!1),[K,J]=ce.useState(!1);tr(e),gt(),ce.useEffect(()=>{L(s?.phone?"welcome-back":"identity")},[s?.phone]),ce.useEffect(()=>{let H=ne=>{ne.key==="Escape"&&e&&r&&r()};return e&&document.addEventListener("keydown",H),()=>{document.removeEventListener("keydown",H)}},[e,r]);let X=async()=>{if(c){S(!0);try{await c(A)}finally{S(!1)}}},I=async()=>{if(d){S(!0);try{await d()}finally{S(!1)}}},P=()=>{L("identity"),G("")};if(!e)return null;let C=()=>N||(y==="welcome-back"&&s?.phone?q(pt,{phone:s.phone,onContinue:I,onSwitchAccount:P,isLoading:k}):q(Ue,{phone:A,onPhoneChange:G,onSubmit:X,isLoading:k}));return ft(xn,{children:[q("div",{className:"fixed inset-0 bg-black/40 dark:bg-black/60 z-[9998] animate-in fade-in duration-200",onClick:r,"aria-hidden":"true"}),ft("div",{ref:g,className:R("fixed z-[9999] flex flex-col shadow-2xl","left-0 right-0 bottom-0 w-full max-w-[480px] mx-auto","h-auto rounded-t-2xl max-h-[90vh]","animate-in slide-in-from-bottom duration-300","md:top-0 md:bottom-0 md:right-0 md:left-auto","md:w-[480px] md:max-w-none md:h-full","md:rounded-none md:border-l md:max-h-none","md:animate-in md:slide-in-from-right","bg-gray-50 dark:bg-slate-900","md:border-gray-200 md:dark:border-slate-800","overscroll-y-contain",b),style:{maxHeight:"var(--visual-viewport-height, 90vh)"},role:"dialog","aria-modal":"true","aria-labelledby":t?"drawer-title":void 0,children:[q("div",{className:"flex justify-center pt-3 pb-2 md:hidden",children:q("div",{className:"w-10 h-1 bg-gray-300 dark:bg-slate-700 rounded-full"})}),(t||a||n||r)&&ft("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-slate-800",children:[t&&q("h2",{id:"drawer-title",className:"text-lg font-bold text-gray-900 dark:text-white",children:t}),ft("div",{className:"flex items-center gap-2 ml-auto",children:[n&&i&&q(Ye,{amount:n,onClick:()=>J(!K),isExpanded:K,showChevron:!0,showIcon:!0}),n&&!i&&q(Ye,{amount:n}),!n&&a&&q("div",{className:"text-lg font-bold text-gray-900 dark:text-white",children:a}),r&&q("button",{onClick:r,className:"p-2 rounded-full hover:bg-gray-100 dark:hover:bg-slate-800 transition-colors active:scale-95","aria-label":"Close drawer",children:q(bn,{className:"w-5 h-5 text-gray-600 dark:text-slate-400"})})]})]}),K&&n&&i&&q(mt,{items:i,subtotal:o||n,shipping:p,tax:l,agentFee:f,total:n,isAgentMode:m==="agent"}),q("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-y-contain px-6 pt-6 pb-8",children:C()}),q(ut,{className:"px-6 pb-6"})]})]})});ht.displayName="PayOSDrawer";import{Check as vn}from"lucide-react";import{jsx as W,jsxs as yt}from"react/jsx-runtime";var wt=({brand:e,size:r="md",className:t=""})=>{let a=r==="sm"?"h-4":"h-5";return e==="visa"?yt("svg",{className:`${a} ${t}`,viewBox:"0 0 48 16",fill:"none",children:[W("path",{d:"M18.5 0L15.2 15.8H11.7L15 0H18.5Z",fill:"#1434CB"}),W("path",{d:"M32.5 10.3L34.2 5.4L35.3 10.3H32.5ZM36.8 15.8H40L37.1 0H34.1C33.4 0 32.8 0.4 32.5 1L27 15.8H30.8L31.6 13.5H36.3L36.8 15.8Z",fill:"#1434CB"}),W("path",{d:"M13.2 10.7L13.6 8.3L12.5 7.9C11.7 7.6 10.3 7.2 10.3 6.2C10.3 5.4 11.1 4.6 12.7 4.6C13.9 4.6 14.8 4.9 15.5 5.2L16 2.6C15.3 2.3 14.2 2 12.8 2C9.2 2 6.6 4 6.6 6.8C6.6 8.9 8.4 10 9.7 10.7C11.1 11.4 11.6 11.9 11.6 12.5C11.6 13.5 10.4 14 9.3 14C7.7 14 6.8 13.7 5.6 13.2L5.1 15.9C6 16.3 7.6 16.7 9.3 16.7C13.2 16.7 15.7 14.8 15.7 11.8C15.7 10.2 14.7 9.1 13.2 10.7Z",fill:"#1434CB"}),W("path",{d:"M26 0L22.9 11L22.7 10C21.9 7.8 19.6 5.4 17 4.2L20.1 15.8H24L29.8 0H26Z",fill:"#1434CB"}),W("path",{d:"M20.5 0H15.8L15.7 0.3C20.1 1.5 23 4.3 24.2 7.9L22.8 1.2C22.6 0.5 22 0 21.3 0H20.5Z",fill:"#FCA121"})]}):e==="mastercard"?yt("svg",{className:`${a} ${t}`,viewBox:"0 0 48 32",fill:"none",children:[W("circle",{cx:"18",cy:"16",r:"14",fill:"#EB001B"}),W("circle",{cx:"30",cy:"16",r:"14",fill:"#F79E1B"}),W("path",{d:"M24 6C26.2 7.6 27.7 10.2 28 13H20C20.3 10.2 21.8 7.6 24 6ZM24 26C21.8 24.4 20.3 21.8 20 19H28C27.7 21.8 26.2 24.4 24 26Z",fill:"#FF5F00"})]}):e==="amex"?yt("svg",{className:`${a} ${t}`,viewBox:"0 0 48 16",fill:"none",children:[W("rect",{width:"48",height:"16",rx:"2",fill:"#006FCF"}),W("path",{d:"M10 5H8L6 11H8L10 5Z",fill:"white"}),W("path",{d:"M15 5L13 8L11 5H9L12 11H14L17 5H15Z",fill:"white"}),W("path",{d:"M22 5H18V11H22C23.7 11 25 9.7 25 8C25 6.3 23.7 5 22 5Z",fill:"white"})]}):e==="discover"?yt("svg",{className:`${a} ${t}`,viewBox:"0 0 48 16",fill:"none",children:[W("rect",{width:"48",height:"16",rx:"2",fill:"#FF6000"}),W("path",{d:"M8 5H6V11H8V5Z",fill:"white"}),W("path",{d:"M14 5H10V11H14C15.7 11 17 9.7 17 8C17 6.3 15.7 5 14 5Z",fill:"white"})]}):null};import{jsx as rr,jsxs as Ge}from"react/jsx-runtime";var bt=({last4:e,brand:r,expiry:t,cardArtUrl:a,issuerName:n,selected:i=!1,onClick:o,isLast:p=!1})=>Ge("div",{onClick:o,className:`
|
|
1
|
+
import*as hr from"react";import{Slot as Aa}from"@radix-ui/react-slot";import{cva as Oa}from"class-variance-authority";import{Loader2 as Va}from"lucide-react";import{clsx as Ia}from"clsx";import{twMerge as Ta}from"tailwind-merge";function N(...e){return Ta(Ia(e))}import{Fragment as Ma,jsx as $t,jsxs as Da}from"react/jsx-runtime";var La=Oa("inline-flex items-center justify-center whitespace-nowrap rounded-xl text-base font-semibold ring-offset-white dark:ring-offset-slate-950 transition-all duration-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-950 dark:focus-visible:ring-slate-300 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:bg-slate-900/20 disabled:text-slate-900/50 active:scale-[0.98]",{variants:{variant:{default:"bg-primary text-white hover:opacity-90 shadow-lg",destructive:"bg-red-500 text-white hover:bg-red-600 shadow-sm dark:bg-red-900 dark:hover:bg-red-800",outline:"border border-gray-300 dark:border-slate-600 bg-white dark:bg-slate-800 hover:bg-gray-50 dark:hover:bg-slate-700 hover:border-gray-400 dark:hover:border-slate-500",secondary:"bg-gray-100 dark:bg-slate-700 text-gray-900 dark:text-white hover:bg-gray-200 dark:hover:bg-slate-600",ghost:"hover:bg-gray-100 dark:hover:bg-slate-800 hover:text-gray-900 dark:hover:text-white",link:"text-blue-600 dark:text-blue-400 underline-offset-4 hover:underline"},size:{default:"h-12 px-4 py-3",sm:"h-9 px-3 text-sm",lg:"h-14 px-6 py-4 text-lg",icon:"h-12 w-12"}},defaultVariants:{variant:"default",size:"default"}}),M=hr.forwardRef(({className:e,variant:r,size:t,asChild:a=!1,isLoading:o,loadingText:i,children:n,disabled:p,...l},h)=>$t(a?Aa:"button",{className:N(La({variant:r,size:t,className:e})),ref:h,disabled:p||o,"aria-busy":o,...l,children:o?Da(Ma,{children:[$t(Va,{className:"mr-2 h-4 w-4 animate-spin"}),$t("span",{children:i||(typeof n=="string"?"Loading...":n)})]}):n}));M.displayName="Button";import*as br from"react";import{jsx as Ua}from"react/jsx-runtime";var wr=br.forwardRef(({className:e,type:r,...t},a)=>Ua("input",{type:r,className:N("flex h-11 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-base text-gray-900 placeholder:text-gray-400 focus:border-black focus:outline-none focus:ring-2 focus:ring-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:text-gray-400 transition-colors","-webkit-appearance-none appearance-none",e),ref:a,...t}));wr.displayName="Input";import*as Ce from"react";import{cva as _a}from"class-variance-authority";import{jsx as Oe}from"react/jsx-runtime";var Ba=_a("rounded-xl overflow-hidden mb-4",{variants:{variant:{default:"bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 shadow-sm",flat:"bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700",transparent:"bg-transparent border-none shadow-none"}},defaultVariants:{variant:"default"}}),O=Ce.forwardRef(({className:e,variant:r,...t},a)=>Oe("div",{ref:a,className:N(Ba({variant:r}),e),...t}));O.displayName="Card";var yr=Ce.forwardRef(({className:e,...r},t)=>Oe("div",{ref:t,className:N("flex flex-col space-y-1.5 p-4",e),...r}));yr.displayName="CardHeader";var vr=Ce.forwardRef(({className:e,...r},t)=>Oe("h3",{ref:t,className:N("text-lg font-semibold leading-none tracking-tight text-gray-900 dark:text-white",e),...r}));vr.displayName="CardTitle";var xr=Ce.forwardRef(({className:e,...r},t)=>Oe("p",{ref:t,className:N("text-sm text-gray-500 dark:text-slate-400",e),...r}));xr.displayName="CardDescription";var kr=Ce.forwardRef(({className:e,...r},t)=>Oe("div",{ref:t,className:N("p-4 pt-0",e),...r}));kr.displayName="CardContent";var Cr=Ce.forwardRef(({className:e,...r},t)=>Oe("div",{ref:t,className:N("flex items-center p-4 pt-0",e),...r}));Cr.displayName="CardFooter";import*as Sr from"react";import*as Yt from"@radix-ui/react-label";import{cva as Fa}from"class-variance-authority";import{jsx as Ha}from"react/jsx-runtime";var za=Fa("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-gray-700"),Pr=Sr.forwardRef(({className:e,...r},t)=>Ha(Yt.Root,{ref:t,className:N(za(),e),...r}));Pr.displayName=Yt.Root.displayName;import*as Rr from"react";import*as Gt from"@radix-ui/react-separator";import{jsx as $a}from"react/jsx-runtime";var Nr=Rr.forwardRef(({className:e,orientation:r="horizontal",decorative:t=!0,...a},o)=>$a(Gt.Root,{ref:o,decorative:t,orientation:r,className:N("shrink-0 bg-gray-200",r==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...a}));Nr.displayName=Gt.Root.displayName;import*as Er from"react";import{useState as Ya,useRef as Ga,useEffect as Wa}from"react";import{Lock as ja,ChevronDown as Ka}from"lucide-react";import{jsx as le,jsxs as rt}from"react/jsx-runtime";var Wt=[{code:"US",name:"United States",dial:"+1",flag:"\u{1F1FA}\u{1F1F8}"},{code:"CA",name:"Canada",dial:"+1",flag:"\u{1F1E8}\u{1F1E6}"},{code:"GB",name:"United Kingdom",dial:"+44",flag:"\u{1F1EC}\u{1F1E7}"},{code:"AU",name:"Australia",dial:"+61",flag:"\u{1F1E6}\u{1F1FA}"},{code:"DE",name:"Germany",dial:"+49",flag:"\u{1F1E9}\u{1F1EA}"},{code:"FR",name:"France",dial:"+33",flag:"\u{1F1EB}\u{1F1F7}"},{code:"ES",name:"Spain",dial:"+34",flag:"\u{1F1EA}\u{1F1F8}"},{code:"IT",name:"Italy",dial:"+39",flag:"\u{1F1EE}\u{1F1F9}"},{code:"NL",name:"Netherlands",dial:"+31",flag:"\u{1F1F3}\u{1F1F1}"},{code:"MX",name:"Mexico",dial:"+52",flag:"\u{1F1F2}\u{1F1FD}"},{code:"BR",name:"Brazil",dial:"+55",flag:"\u{1F1E7}\u{1F1F7}"},{code:"IN",name:"India",dial:"+91",flag:"\u{1F1EE}\u{1F1F3}"},{code:"JP",name:"Japan",dial:"+81",flag:"\u{1F1EF}\u{1F1F5}"},{code:"KR",name:"South Korea",dial:"+82",flag:"\u{1F1F0}\u{1F1F7}"},{code:"SG",name:"Singapore",dial:"+65",flag:"\u{1F1F8}\u{1F1EC}"}];function at(e,r="US"){let t=e.replace(/\D/g,"");if(r==="US"||r==="CA"){let a=t.startsWith("1")&&t.length>10?t.slice(1):t;return a.length===0?"":a.length<=3?`(${a}`:a.length<=6?`(${a.slice(0,3)}) ${a.slice(3)}`:`(${a.slice(0,3)}) ${a.slice(3,6)}-${a.slice(6,10)}`}return t}var ot=Er.forwardRef(({className:e,value:r,onChange:t,countryCode:a="US",onCountryChange:o,...i},n)=>{let[p,l]=Ya(!1),h=Ga(null),m=Wt.find(d=>d.code===a)||Wt[0],E=at(r||"",a);Wa(()=>{if(!p)return;let d=u=>{h.current&&!h.current.contains(u.target)&&l(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[p]);let v=d=>{if(t){let u=at(d.target.value,a);t(u)}},s=d=>{o?.(d),l(!1),d!==a&&t&&t("")},c=a==="US"||a==="CA"?"(555) 000-0000":"Phone number";return rt("div",{className:"relative",ref:h,children:[rt("div",{className:N("flex items-center h-14 bg-white dark:bg-slate-800 border border-gray-300 dark:border-slate-600 rounded-xl overflow-hidden transition-all duration-150","focus-within:ring-2 focus-within:ring-slate-900 focus-within:ring-offset-0",e),children:[rt("button",{type:"button",onClick:()=>l(!p),className:"flex items-center gap-1.5 px-3 h-full bg-gray-50 dark:bg-slate-900 border-r border-gray-200 dark:border-slate-700 cursor-pointer hover:bg-gray-100 dark:hover:bg-slate-800 transition-colors","aria-label":"Select country code","aria-expanded":p,children:[le("span",{className:"text-xl",children:m.flag}),le("span",{className:"text-sm font-medium text-gray-700 dark:text-slate-300",children:m.dial}),le(Ka,{className:N("w-3.5 h-3.5 text-gray-400 transition-transform",p&&"rotate-180")})]}),le("input",{ref:n,type:"tel",inputMode:"tel",autoComplete:"tel",value:E,onChange:v,className:N("flex-1 h-full px-3 border-0 outline-none","text-lg font-normal tracking-wide text-gray-900 dark:text-white","placeholder:text-gray-400 dark:placeholder:text-slate-500 placeholder:font-light","bg-transparent"),placeholder:c,...i}),le("div",{className:"px-3",children:le(ja,{className:"w-4 h-4 text-gray-400 dark:text-slate-500"})})]}),p&&le("div",{className:"absolute top-full left-0 mt-1 w-64 bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-xl shadow-lg z-50 max-h-60 overflow-y-auto",children:Wt.map(d=>rt("button",{type:"button",onClick:()=>s(d.code),className:N("w-full px-3 py-2.5 flex items-center gap-3 hover:bg-gray-50 dark:hover:bg-slate-700 transition-colors text-left",d.code===a&&"bg-gray-50 dark:bg-slate-700"),children:[le("span",{className:"text-xl",children:d.flag}),le("span",{className:"flex-1 text-sm text-gray-900 dark:text-white",children:d.name}),le("span",{className:"text-sm text-gray-500 dark:text-slate-400",children:d.dial})]},d.code))})]})});ot.displayName="PhoneInput";import*as ye from"react";import{jsx as Ir}from"react/jsx-runtime";var Ve=ye.forwardRef(({value:e="",onChange:r,onComplete:t,length:a=6,className:o},i)=>{let n=ye.useRef([]),[p,l]=ye.useState(e.split("").slice(0,a).concat(Array(a).fill("")).slice(0,a));ye.useEffect(()=>{let s=e.split("").slice(0,a).concat(Array(a).fill("")).slice(0,a);l(s)},[e,a]);let h=(s,c)=>{if(c.length>1&&(c=c.slice(-1)),!/^\d*$/.test(c))return;let d=[...p];d[s]=c,l(d);let u=d.join("");r?.(u),c&&s<a-1&&n.current[s+1]?.focus(),d.every(w=>w)&&u.length===a&&t?.(u)},m=(s,c)=>{if(c.key==="Backspace"){c.preventDefault();let d=[...p];p[s]?(d[s]="",l(d),r?.(d.join(""))):s>0&&(d[s-1]="",l(d),r?.(d.join("")),n.current[s-1]?.focus())}c.key==="ArrowLeft"&&s>0&&n.current[s-1]?.focus(),c.key==="ArrowRight"&&s<a-1&&n.current[s+1]?.focus()},E=s=>{s.preventDefault();let c=s.clipboardData.getData("text").slice(0,a).replace(/\D/g,"");if(c){let d=c.split("").concat(Array(a).fill("")).slice(0,a);l(d),r?.(c);let u=Math.min(c.length,a-1);n.current[u]?.focus(),c.length===a&&t?.(c)}},v=s=>{n.current[s]?.select()};return Ir("div",{ref:i,className:N("flex gap-2 justify-center",o),onPaste:E,children:Array.from({length:a},(s,c)=>Ir("input",{ref:d=>n.current[c]=d,type:"text",inputMode:"numeric",maxLength:1,value:p[c]||"",onChange:d=>h(c,d.target.value),onKeyDown:d=>m(c,d),onFocus:()=>v(c),className:N("w-12 h-14 text-center text-2xl font-bold","border-2 border-gray-300 dark:border-slate-600 rounded-md","bg-white dark:bg-slate-800","text-gray-900 dark:text-white","focus:ring-2 focus:ring-black dark:focus:ring-white focus:border-transparent focus:outline-none","transition-all duration-150"),"aria-label":`Digit ${c+1} of ${a}`},c))})});Ve.displayName="OTPInput";import*as ce from"react";import{X as no}from"lucide-react";function nt(e,r){let t=e.replace(/\D/g,"");return r==="US"||r==="CA"?t.length===10||t.length===11:t.length>=7&&t.length<=15}function Tr(e,r){let t=e.replace(/\D/g,"");return r==="amex"?t.length===4:t.length===3}import{jsx as Le,jsxs as jt}from"react/jsx-runtime";var Me=({phone:e,onPhoneChange:r,countryCode:t="US",onCountryChange:a,onSubmit:o,isLoading:i=!1,error:n})=>{let p=m=>{m.preventDefault(),o()},l=nt(e,t);return Le("form",{onSubmit:p,className:"space-y-4",children:jt(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-6",children:[jt("div",{className:"space-y-1",children:[Le("h2",{className:"text-xl font-bold text-slate-900 dark:text-white text-center tracking-tight mx-auto",children:"Complete your purchase"}),Le("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center mx-auto",children:"Verify your mobile number to secure this payment."})]}),jt("div",{children:[Le(ot,{value:e,onChange:r,countryCode:t,onCountryChange:a,onKeyDown:m=>{m.key==="Enter"&&l&&!i&&o()},autoFocus:!0}),n&&Le("p",{className:"text-sm text-red-600 dark:text-red-400 mt-2",children:n})]}),Le(M,{type:"submit",className:"w-full",disabled:!l||i,isLoading:i,loadingText:"Sending code...",children:"Continue"})]})})};Me.displayName="IdentityView";import{User as qa,CheckCircle2 as Xa}from"lucide-react";import{jsx as se,jsxs as Kt}from"react/jsx-runtime";var st=({phone:e,onContinue:r,onSwitchAccount:t,isLoading:a=!1})=>Kt("form",{onSubmit:i=>{i.preventDefault(),r()},className:"space-y-4",children:[Kt(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-6",children:[se("h2",{className:"text-xl font-bold text-slate-900 dark:text-white text-center",children:"Welcome back!"}),Kt("div",{className:"w-full bg-gray-50 dark:bg-slate-800/50 border border-gray-200 dark:border-slate-700 rounded-xl p-4 flex items-center gap-3",children:[se("div",{className:"flex-shrink-0 bg-gray-100 dark:bg-slate-700 rounded-full p-1",children:se(qa,{className:"w-5 h-5 text-gray-500 dark:text-slate-400"})}),se("div",{className:"flex-1 min-w-0",children:se("p",{className:"text-lg font-semibold text-slate-900 dark:text-white truncate",children:e})}),se("div",{className:"flex-shrink-0",children:se(Xa,{className:"w-5 h-5 text-green-500 dark:text-green-400"})})]}),se(M,{type:"submit",className:"w-full mt-4",disabled:a,isLoading:a,loadingText:"Sending code...",children:"Send Verification Code"}),se("p",{className:"text-xs text-gray-400 dark:text-slate-500 text-center mt-4",children:"We'll send you a verification code to confirm it's you"})]}),se("div",{className:"text-center px-4 mt-4",children:se("button",{type:"button",onClick:t,disabled:a,className:"text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",children:"Not you? Use a different number"})})]});st.displayName="WelcomeBackView";import{ShoppingCart as Ja,ChevronDown as Za}from"lucide-react";import{Fragment as Qa,jsx as De,jsxs as eo}from"react/jsx-runtime";var ze=({amount:e,label:r="Total",onClick:t,isExpanded:a=!1,showChevron:o=!1,showIcon:i=!1,className:n=""})=>{let p=!!t,l=N("border rounded-lg px-3 py-2 flex items-center gap-2 transition-colors","bg-gray-50/50 dark:bg-slate-800/50 border-gray-200 dark:border-slate-700",p&&"cursor-pointer select-none hover:bg-gray-100 dark:hover:bg-slate-700",p&&"text-slate-700 dark:text-slate-300 hover:text-black dark:hover:text-white",!p&&"bg-gray-50 dark:bg-slate-800",n),h=eo(Qa,{children:[i&&p&&De(Ja,{className:"w-4 h-4 text-gray-500 dark:text-slate-400"}),De("span",{className:"text-xs font-medium text-gray-500 dark:text-slate-400",children:r}),De("span",{className:"text-sm font-bold text-slate-900 dark:text-white",children:e}),o&&p&&De(Za,{className:N("w-4 h-4 text-gray-400 dark:text-slate-500 transition-transform duration-200",a&&"rotate-180")})]});return p?De("button",{type:"button",onClick:t,className:l,"aria-expanded":a,"aria-label":`${a?"Hide":"Show"} order details`,children:h}):De("div",{className:l,children:h})};ze.displayName="PriceTag";import{Bot as Ar}from"lucide-react";import{jsx as z,jsxs as J}from"react/jsx-runtime";var it=({items:e,subtotal:r,shipping:t,tax:a,agentFee:o,total:i,isAgentMode:n=!1})=>z("div",{className:"bg-gray-50 dark:bg-slate-800 border-b border-gray-200 dark:border-slate-700",children:J("div",{className:"px-6 py-4 space-y-3",children:[n&&J("div",{className:"flex items-center gap-2 pb-2 border-b border-gray-200 dark:border-slate-700",children:[J("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-violet-100 text-violet-700 text-xs font-medium dark:bg-violet-900/30 dark:text-violet-300",children:[z(Ar,{className:"h-3 w-3"}),"Agent"]}),z("span",{className:"text-xs text-gray-600 dark:text-slate-400",children:"AI Agent Purchase"})]}),e&&e.length>0&&J("div",{className:"space-y-2",children:[e.map((p,l)=>J("div",{className:"flex items-start justify-between gap-2",children:[J("div",{className:"flex-1 min-w-0",children:[z("div",{className:"text-sm text-slate-900 dark:text-white truncate",children:p.label}),p.description&&z("div",{className:"text-xs text-gray-500 dark:text-slate-400",children:p.description})]}),z("div",{className:"text-sm font-medium text-slate-900 dark:text-white whitespace-nowrap",children:p.value})]},l)),z("div",{className:"h-px bg-gray-200 dark:bg-slate-700"})]}),J("div",{className:"space-y-2 text-sm",children:[J("div",{className:"flex items-center justify-between",children:[z("span",{className:"text-gray-600 dark:text-slate-400",children:"Subtotal"}),z("span",{className:"font-medium text-slate-900 dark:text-white",children:r})]}),t&&J("div",{className:"flex items-center justify-between",children:[z("span",{className:"text-gray-600 dark:text-slate-400",children:"Shipping"}),z("span",{className:"font-medium text-slate-900 dark:text-white",children:t})]}),a&&J("div",{className:"flex items-center justify-between",children:[z("span",{className:"text-gray-600 dark:text-slate-400",children:"Tax"}),z("span",{className:"font-medium text-slate-900 dark:text-white",children:a})]}),o&&n&&J("div",{className:"flex items-center justify-between",children:[J("span",{className:"text-gray-600 dark:text-slate-400 flex items-center gap-1",children:["Agent Fee",z(Ar,{className:"h-3 w-3 text-violet-500"})]}),z("span",{className:"font-medium text-slate-900 dark:text-white",children:o})]})]}),z("div",{className:"pt-2 border-t border-gray-200 dark:border-slate-700",children:J("div",{className:"flex items-center justify-between",children:[z("span",{className:"text-sm font-bold text-slate-900 dark:text-white",children:"Total"}),z("span",{className:"text-lg font-bold text-slate-900 dark:text-white",children:i})]})})]})});it.displayName="ReceiptPanel";import*as Vr from"react";import{ShieldCheck as to}from"lucide-react";import{jsx as Or,jsxs as ro}from"react/jsx-runtime";var dt=Vr.forwardRef(({className:e},r)=>ro("div",{ref:r,className:N("flex items-center justify-center gap-1.5 text-xs text-gray-500 dark:text-slate-400",e),children:[Or(to,{className:"w-3.5 h-3.5"}),Or("span",{children:"Powered by PayOS"})]}));dt.displayName="PayOSFooter";import*as Lr from"react";function qt(e,r={}){let{preventTouch:t=!1}=r;Lr.useEffect(()=>{if(!e)return;let a=document.body.style.overflow,o=document.body.style.position,i=document.body.style.top,n=document.body.style.width,p=document.body.style.touchAction,l=window.scrollY;return document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${l}px`,document.body.style.width="100%",t&&(document.body.style.touchAction="none"),()=>{document.body.style.overflow=a,document.body.style.position=o,document.body.style.top=i,document.body.style.width=n,document.body.style.touchAction=p,window.scrollTo(0,l)}},[e,t])}import*as Ue from"react";var ao=450;function lt(){let[e,r]=Ue.useState(0);return Ue.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;let t=window.visualViewport,a=()=>{let o=window.innerHeight-t.height;r(Math.max(0,o));let i=t.height;i<ao?document.documentElement.style.setProperty("--visual-viewport-height",`${window.innerHeight*.85}px`):document.documentElement.style.setProperty("--visual-viewport-height",`${i}px`)};return a(),t.addEventListener("resize",a),t.addEventListener("scroll",a),()=>{t.removeEventListener("resize",a),t.removeEventListener("scroll",a),document.documentElement.style.removeProperty("--visual-viewport-height")}},[]),e}function oo(){let e=lt();return Ue.useMemo(()=>({bottom:e>0?`${e}px`:void 0}),[e])}import{Fragment as so,jsx as K,jsxs as ct}from"react/jsx-runtime";var pt=ce.forwardRef(({open:e=!1,onClose:r,title:t,subtitle:a,amount:o,orderItems:i,subtotal:n,shipping:p,tax:l,orderAgentFee:h,mode:m="standard",children:E,className:v,prefill:s,onPhoneSubmit:c,onContinue:d},u)=>{let[w,_]=ce.useState(s?.phone?"welcome-back":"identity"),[A,G]=ce.useState(""),[k,S]=ce.useState(!1),[j,q]=ce.useState(!1);qt(e),lt(),ce.useEffect(()=>{_(s?.phone?"welcome-back":"identity")},[s?.phone]),ce.useEffect(()=>{let $=oe=>{oe.key==="Escape"&&e&&r&&r()};return e&&document.addEventListener("keydown",$),()=>{document.removeEventListener("keydown",$)}},[e,r]);let X=async()=>{if(c){S(!0);try{await c(A)}finally{S(!1)}}},R=async()=>{if(d){S(!0);try{await d()}finally{S(!1)}}},P=()=>{_("identity"),G("")};if(!e)return null;let C=()=>E||(w==="welcome-back"&&s?.phone?K(st,{phone:s.phone,onContinue:R,onSwitchAccount:P,isLoading:k}):K(Me,{phone:A,onPhoneChange:G,onSubmit:X,isLoading:k}));return ct(so,{children:[K("div",{className:"fixed inset-0 bg-black/40 dark:bg-black/60 z-[9998] animate-in fade-in duration-200",onClick:r,"aria-hidden":"true"}),ct("div",{ref:u,className:N("fixed z-[9999] flex flex-col shadow-2xl","left-0 right-0 bottom-0 w-full max-w-[480px] mx-auto","h-auto rounded-t-2xl max-h-[90vh]","animate-in slide-in-from-bottom duration-300","md:top-0 md:bottom-0 md:right-0 md:left-auto","md:w-[480px] md:max-w-none md:h-full","md:rounded-none md:border-l md:max-h-none","md:animate-in md:slide-in-from-right","bg-gray-50 dark:bg-slate-900","md:border-gray-200 md:dark:border-slate-800","overscroll-y-contain",v),style:{maxHeight:"var(--visual-viewport-height, 90vh)"},role:"dialog","aria-modal":"true","aria-labelledby":t?"drawer-title":void 0,children:[K("div",{className:"flex justify-center pt-3 pb-2 md:hidden",children:K("div",{className:"w-10 h-1 bg-gray-300 dark:bg-slate-700 rounded-full"})}),(t||a||o||r)&&ct("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-slate-800",children:[t&&K("h2",{id:"drawer-title",className:"text-lg font-bold text-gray-900 dark:text-white",children:t}),ct("div",{className:"flex items-center gap-2 ml-auto",children:[o&&i&&K(ze,{amount:o,onClick:()=>q(!j),isExpanded:j,showChevron:!0,showIcon:!0}),o&&!i&&K(ze,{amount:o}),!o&&a&&K("div",{className:"text-lg font-bold text-gray-900 dark:text-white",children:a}),r&&K("button",{onClick:r,className:"p-2 rounded-full hover:bg-gray-100 dark:hover:bg-slate-800 transition-colors active:scale-95","aria-label":"Close drawer",children:K(no,{className:"w-5 h-5 text-gray-600 dark:text-slate-400"})})]})]}),j&&o&&i&&K(it,{items:i,subtotal:n||o,shipping:p,tax:l,agentFee:h,total:o,isAgentMode:m==="agent"}),K("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-y-contain px-6 pt-6 pb-8",children:C()}),K(dt,{className:"px-6 pb-6"})]})]})});pt.displayName="PayOSDrawer";import{Check as io}from"lucide-react";import{jsx as W,jsxs as mt}from"react/jsx-runtime";var gt=({brand:e,size:r="md",className:t=""})=>{let a=r==="sm"?"h-4":"h-5";return e==="visa"?mt("svg",{className:`${a} ${t}`,viewBox:"0 0 48 16",fill:"none",children:[W("path",{d:"M18.5 0L15.2 15.8H11.7L15 0H18.5Z",fill:"#1434CB"}),W("path",{d:"M32.5 10.3L34.2 5.4L35.3 10.3H32.5ZM36.8 15.8H40L37.1 0H34.1C33.4 0 32.8 0.4 32.5 1L27 15.8H30.8L31.6 13.5H36.3L36.8 15.8Z",fill:"#1434CB"}),W("path",{d:"M13.2 10.7L13.6 8.3L12.5 7.9C11.7 7.6 10.3 7.2 10.3 6.2C10.3 5.4 11.1 4.6 12.7 4.6C13.9 4.6 14.8 4.9 15.5 5.2L16 2.6C15.3 2.3 14.2 2 12.8 2C9.2 2 6.6 4 6.6 6.8C6.6 8.9 8.4 10 9.7 10.7C11.1 11.4 11.6 11.9 11.6 12.5C11.6 13.5 10.4 14 9.3 14C7.7 14 6.8 13.7 5.6 13.2L5.1 15.9C6 16.3 7.6 16.7 9.3 16.7C13.2 16.7 15.7 14.8 15.7 11.8C15.7 10.2 14.7 9.1 13.2 10.7Z",fill:"#1434CB"}),W("path",{d:"M26 0L22.9 11L22.7 10C21.9 7.8 19.6 5.4 17 4.2L20.1 15.8H24L29.8 0H26Z",fill:"#1434CB"}),W("path",{d:"M20.5 0H15.8L15.7 0.3C20.1 1.5 23 4.3 24.2 7.9L22.8 1.2C22.6 0.5 22 0 21.3 0H20.5Z",fill:"#FCA121"})]}):e==="mastercard"?mt("svg",{className:`${a} ${t}`,viewBox:"0 0 48 32",fill:"none",children:[W("circle",{cx:"18",cy:"16",r:"14",fill:"#EB001B"}),W("circle",{cx:"30",cy:"16",r:"14",fill:"#F79E1B"}),W("path",{d:"M24 6C26.2 7.6 27.7 10.2 28 13H20C20.3 10.2 21.8 7.6 24 6ZM24 26C21.8 24.4 20.3 21.8 20 19H28C27.7 21.8 26.2 24.4 24 26Z",fill:"#FF5F00"})]}):e==="amex"?mt("svg",{className:`${a} ${t}`,viewBox:"0 0 48 16",fill:"none",children:[W("rect",{width:"48",height:"16",rx:"2",fill:"#006FCF"}),W("path",{d:"M10 5H8L6 11H8L10 5Z",fill:"white"}),W("path",{d:"M15 5L13 8L11 5H9L12 11H14L17 5H15Z",fill:"white"}),W("path",{d:"M22 5H18V11H22C23.7 11 25 9.7 25 8C25 6.3 23.7 5 22 5Z",fill:"white"})]}):e==="discover"?mt("svg",{className:`${a} ${t}`,viewBox:"0 0 48 16",fill:"none",children:[W("rect",{width:"48",height:"16",rx:"2",fill:"#FF6000"}),W("path",{d:"M8 5H6V11H8V5Z",fill:"white"}),W("path",{d:"M14 5H10V11H14C15.7 11 17 9.7 17 8C17 6.3 15.7 5 14 5Z",fill:"white"})]}):null};import{jsx as Xt,jsxs as He}from"react/jsx-runtime";var ut=({last4:e,brand:r,expiry:t,cardArtUrl:a,issuerName:o,selected:i=!1,onClick:n,isLast:p=!1})=>He("div",{onClick:n,className:`
|
|
2
2
|
w-full p-4 flex items-center justify-between bg-white
|
|
3
3
|
${p?"":"border-b border-gray-100"}
|
|
4
|
-
${
|
|
5
|
-
`,role:
|
|
4
|
+
${n?"hover:bg-gray-50 cursor-pointer active:bg-gray-100 transition-colors":""}
|
|
5
|
+
`,role:n?"button":void 0,tabIndex:n?0:void 0,children:[He("div",{className:"flex items-center gap-3",children:[a?Xt("img",{src:a,alt:`${r} card`,className:"w-10 h-6 object-cover rounded-md flex-shrink-0"}):Xt(gt,{brand:r,className:"flex-shrink-0"}),He("div",{children:[He("div",{className:"text-sm font-medium text-slate-900 dark:text-white",children:[o&&o.toLowerCase()!==r.toLowerCase()?`${o} `:"",r.charAt(0).toUpperCase()+r.slice(1)," \u2022\u2022\u2022\u2022 ",e]}),He("div",{className:"text-xs text-gray-500 dark:text-slate-400",children:["Expires ",t]})]})]}),i&&Xt(io,{className:"w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0"})]});ut.displayName="PaymentMethodRow";import{Fragment as lo,jsx as Se,jsxs as pe}from"react/jsx-runtime";var ft=({card:e,cvc:r,onCvcChange:t,onChangeClick:a,error:o,disabled:i=!1,hideSecurityCode:n=!1})=>{let p=m=>{let E=m.target.value.replace(/\D/g,""),v=e.brand==="amex"?4:3;E.length<=v&&t(E)},l=e.brand==="amex"?4:3,h=Tr(r);return pe("div",{className:"w-full bg-white border border-gray-200 dark:border-slate-700 rounded-xl overflow-hidden shadow-sm",children:[pe("div",{className:"p-4 flex items-center justify-between",children:[pe("div",{className:"flex items-center gap-3",children:[e.cardArtUrl?Se("img",{src:e.cardArtUrl,alt:`${e.brand} card`,className:"w-10 h-6 object-contain rounded flex-shrink-0"}):Se(gt,{brand:e.brand,className:"flex-shrink-0"}),pe("div",{children:[pe("div",{className:"text-sm font-medium text-slate-900 dark:text-white",children:[e.brand.charAt(0).toUpperCase()+e.brand.slice(1)," \u2022\u2022\u2022\u2022 ",e.last4]}),pe("div",{className:"text-xs text-gray-500 dark:text-slate-400",children:["Expires ",e.expiryMonth,"/",e.expiryYear]})]})]}),Se("button",{type:"button",onClick:a,disabled:i,className:"text-sm font-medium text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50 disabled:no-underline",children:"Change"})]}),!n&&pe(lo,{children:[Se("div",{className:"border-b border-gray-100 dark:border-slate-700"}),pe("div",{className:"p-4 bg-gray-50/50 dark:bg-slate-800/50",children:[pe("div",{className:"flex items-center justify-between",children:[Se("label",{htmlFor:"cvc-input",className:"text-sm font-medium text-slate-900 dark:text-white",children:"Security Code"}),Se("input",{id:"cvc-input",type:"text",inputMode:"numeric",value:r,onChange:p,disabled:i,placeholder:l===4?"1234":"123",maxLength:l,className:`
|
|
6
6
|
w-16 h-10 bg-white dark:bg-slate-900
|
|
7
7
|
border rounded text-center font-bold text-base
|
|
8
8
|
text-slate-900 dark:text-white
|
|
9
9
|
placeholder-gray-400 dark:placeholder-slate-500
|
|
10
10
|
outline-none transition-all shadow-sm
|
|
11
11
|
disabled:opacity-50 disabled:cursor-not-allowed
|
|
12
|
-
${
|
|
13
|
-
`,"aria-label":"Card security code","aria-invalid":!!n,"aria-describedby":n?"cvc-error":void 0})]}),n&&Pe("p",{id:"cvc-error",className:"text-xs text-red-600 dark:text-red-400 mt-2 text-right",children:n}),!n&&pe("p",{className:"text-xs text-gray-500 dark:text-slate-400 mt-2 text-right",children:[l,"-digit code on back of card"]})]})]})]})};xt.displayName="ActiveCardWidget";import{ChevronLeft as Cn}from"lucide-react";import{jsx as vt,jsxs as Yr}from"react/jsx-runtime";var Q=({title:e,onBack:r,action:t})=>Yr("div",{className:"flex items-center justify-between pb-4 border-b border-gray-200 dark:border-slate-700 mb-6",children:[Yr("div",{className:"flex items-center gap-3",children:[r&&vt("button",{onClick:r,className:"p-2 hover:bg-gray-100 dark:hover:bg-slate-800 rounded-lg active:scale-95 transition-all","aria-label":"Go back",children:vt(Cn,{className:"w-5 h-5 text-gray-900 dark:text-white"})}),vt("h2",{className:"text-lg font-semibold text-slate-900 dark:text-white",children:e})]}),t&&vt("div",{className:"flex-shrink-0",children:t})]});Q.displayName="ViewHeader";import*as kt from"react";import{ChevronDown as Sn,Bot as Pn}from"lucide-react";import{jsx as xe,jsxs as me}from"react/jsx-runtime";var Gr=kt.forwardRef(({total:e,items:r=[],isAgentMode:t=!1,agentFee:a,defaultExpanded:n=!1,className:i},o)=>{let[p,l]=kt.useState(n);return me(O,{ref:o,variant:"default",className:R("p-4 cursor-pointer select-none transition-all duration-200",t&&"border-indigo-100 dark:border-indigo-900 bg-indigo-50/50 dark:bg-indigo-950/30",i),onClick:()=>l(!p),children:[me("div",{className:"flex items-center justify-between",children:[me("div",{className:"flex-1",children:[me("div",{className:"flex items-center gap-2 mb-1",children:[xe("h3",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Order Total"}),t&&me("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-violet-100 text-violet-700 text-xs font-medium dark:bg-violet-900/30 dark:text-violet-300",children:[xe(Pn,{className:"h-3 w-3"}),"Agent"]})]}),t&&a&&me("p",{className:"text-xs text-indigo-700 dark:text-indigo-400",children:["Agent Fee: ",a," \u2022 Standard Processing"]})]}),me("div",{className:"flex items-center gap-3",children:[xe("span",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:e}),xe(Sn,{className:R("w-5 h-5 text-gray-500 dark:text-slate-400 transition-transform duration-200",p&&"rotate-180")})]})]}),p&&r.length>0&&xe("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-slate-700 space-y-2",children:r.map((f,m)=>me("div",{className:"flex justify-between items-start text-sm",children:[me("div",{className:"flex-1",children:[xe("span",{className:"text-gray-700 dark:text-slate-300",children:f.label}),f.description&&xe("p",{className:"text-xs text-gray-500 dark:text-slate-500 mt-0.5",children:f.description})]}),xe("span",{className:"font-medium text-gray-900 dark:text-white ml-4",children:f.value})]},m))})]})});Gr.displayName="OrderSummary";import{Fragment as ar,jsx as ie,jsxs as Ne}from"react/jsx-runtime";function Nn(e){let r=e.replace(/\D/g,"");if(r.length===11&&r.startsWith("1")){let t=r.slice(1,4),a=r.slice(4,7),n=r.slice(7,11);return`+1 (${t}) ${a}-${n}`}if(r.length===10){let t=r.slice(0,3),a=r.slice(3,6),n=r.slice(6,10);return`+1 (${t}) ${a}-${n}`}return e}var Ct=({phoneNumber:e,otp:r,onOtpChange:t,onSubmit:a,onEdit:n,onResend:i,isLoading:o=!1,isResending:p=!1,error:l,resendCooldown:f=0,retryCount:m=0,maxRetries:N=3})=>{let b=m>=N,s=f===0&&!b,c=y=>{y.preventDefault(),a()},d=y=>{t(y),setTimeout(()=>{a(y)},100)},g=Nn(e);return ie("form",{onSubmit:c,className:"space-y-4",children:Ne(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6",children:[ie("h2",{className:"text-xl font-bold text-slate-900 dark:text-white text-center mb-2",children:"Enter verification code"}),Ne("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center mb-8",children:["Sent to"," ",ie("span",{className:"font-medium text-gray-900 dark:text-white",children:g}),n&&Ne(ar,{children:[" ","\u2022"," ",ie("button",{type:"button",onClick:n,className:"text-blue-600 dark:text-blue-400 hover:underline",children:"Edit"})]})]}),Ne("div",{children:[ie(Me,{value:r,onChange:t,onComplete:d}),l&&ie("p",{className:"text-sm text-red-600 dark:text-red-400 mt-4 text-center",children:l})]}),ie(M,{type:"submit",className:"w-full mt-8",disabled:r.length!==6||o,isLoading:o,loadingText:"Verifying...",children:"Verify"}),i&&ie("div",{className:"text-center mt-4",children:ie("p",{className:"text-xs text-gray-500 dark:text-slate-400",children:b?ie("span",{className:"text-red-600 dark:text-red-400",children:"Too many attempts. Please try again later."}):p?"Sending...":f>0?Ne(ar,{children:["Resend in"," ",Ne("span",{className:"font-medium text-slate-700 dark:text-slate-300",children:[f,"s"]})]}):Ne(ar,{children:["Didn't receive a code?"," ",ie("button",{type:"button",onClick:i,disabled:!s||o,className:"font-bold text-slate-900 dark:text-white hover:underline cursor-pointer disabled:opacity-50",children:"Resend"})]})})})]})})};Ct.displayName="OTPView";import{jsx as St,jsxs as nr}from"react/jsx-runtime";var Wr=(e,r="USD")=>new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(e/100),In=e=>e==="pay_on_behalf"||e==="agent_to_agent"||e==="agentic_multi",Pt=({selectedCard:e,cvc:r,onCvcChange:t,onChangeCard:a,paymentIntent:n,total:i,isAgentMode:o,onSubmit:p,isLoading:l=!1,error:f})=>{let m=y=>{y.preventDefault(),p()},N=e.brand==="amex"?4:3,b=r.length===N,s=n?Wr(n.totalAmount+(n.facilitationFee?.amount||0),n.currency):i||"$0.00",c=n?In(n.type):o||!1,d=c?!0:b,g=c?`Authorize ${s}`:`Pay ${s}`;return nr("form",{onSubmit:m,className:"space-y-6",children:[nr("div",{className:"space-y-3",children:[St("h3",{className:"text-sm font-semibold text-slate-900 dark:text-white px-1 mt-6",children:"Payment Method"}),St(xt,{card:e,cvc:r,onCvcChange:t,onChangeClick:a,disabled:l,error:f,hideSecurityCode:c})]}),c&&n?.facilitationFee&&St("div",{className:"p-3 bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-700 rounded-lg",children:nr("p",{className:"text-sm text-purple-800 dark:text-purple-200",children:["This is an agent-assisted transaction. A ",Wr(n.facilitationFee.amount,n.facilitationFee.currency)," facilitation fee applies."]})}),St(M,{type:"submit",className:"w-full",disabled:!d||l,isLoading:l,loadingText:"Processing...",children:g})]})};Pt.displayName="CheckoutView";import*as ir from"react";import{Plus as Tn,Trash2 as An}from"lucide-react";import{Loader2 as Rn}from"lucide-react";import{Fragment as En,jsx as ve,jsxs as or}from"react/jsx-runtime";var sr=({isOpen:e,title:r,message:t,confirmText:a="Confirm",cancelText:n="Cancel",onConfirm:i,onCancel:o,isLoading:p=!1,variant:l="default"})=>e?ve("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",onClick:m=>{m.target===m.currentTarget&&!p&&o()},children:or("div",{className:"bg-white dark:bg-slate-800 rounded-xl shadow-xl max-w-sm w-full mx-4 overflow-hidden animate-in fade-in zoom-in-95 duration-200",onClick:m=>m.stopPropagation(),children:[ve("div",{className:"px-6 pt-6 pb-2",children:ve("h3",{className:"text-lg font-semibold text-slate-900 dark:text-white",children:r})}),ve("div",{className:"px-6 pb-6",children:ve("p",{className:"text-sm text-slate-600 dark:text-slate-400",children:t})}),or("div",{className:"px-6 pb-6 flex gap-3",children:[ve(M,{variant:"outline",className:"flex-1",onClick:o,disabled:p,children:n}),ve(M,{variant:l==="danger"?"destructive":"default",className:"flex-1",onClick:i,disabled:p,children:p?or(En,{children:[ve(Rn,{className:"w-4 h-4 mr-2 animate-spin"}),a]}):a})]})]})}):null;sr.displayName="ConfirmDialog";import{jsx as re,jsxs as Nt}from"react/jsx-runtime";var It=({cards:e,selectedCardId:r,onSelectCard:t,onAddNewCard:a,onBack:n,onDeleteCard:i})=>{let[o,p]=ir.useState(null),[l,f]=ir.useState(null),m=(s,c)=>{s.stopPropagation(),i&&f(c)},N=async()=>{!l||!i||(p(l),await i(l),p(null),f(null))},b=l?e.find(s=>s.id===l)?.last4:"";return Nt("div",{className:"space-y-4",children:[re(Q,{title:"Payment Methods",onBack:n}),Nt(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-xl overflow-hidden",children:[e.map(s=>Nt("div",{className:"relative flex items-center",children:[re("div",{className:"flex-1",children:re(bt,{last4:s.last4,brand:s.brand,expiry:`${s.expiryMonth}/${s.expiryYear}`,cardArtUrl:s.cardArtUrl,issuerName:s.issuerName,selected:r===s.id,onClick:()=>t(s.id),isLast:!1})}),i&&re("button",{onClick:c=>m(c,s.id),disabled:o===s.id,className:"absolute right-4 p-2 text-gray-400 hover:text-red-500 dark:text-slate-500 dark:hover:text-red-400 transition-colors disabled:opacity-50","aria-label":"Delete card",children:re(An,{className:`w-4 h-4 ${o===s.id?"animate-pulse":""}`})})]},s.id)),e.length===0&&re("div",{className:"p-4 text-center border-b border-gray-100 dark:border-slate-700",children:re("p",{className:"text-sm text-gray-500 dark:text-slate-400",children:"No saved cards yet"})}),Nt("div",{onClick:a,className:"w-full p-4 flex items-center gap-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-slate-800 active:bg-gray-100 dark:active:bg-slate-700 transition-colors",children:[re("div",{className:"w-10 h-10 rounded-lg bg-gray-100 dark:bg-slate-700 flex items-center justify-center flex-shrink-0",children:re(Tn,{className:"w-5 h-5 text-gray-600 dark:text-slate-400"})}),re("div",{className:"flex-1",children:re("div",{className:"text-sm font-medium text-slate-900 dark:text-white",children:"Add new card"})})]})]}),re(sr,{isOpen:!!l,title:"Delete Card",message:`Are you sure you want to delete the card ending in ${b}? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:N,onCancel:()=>f(null),isLoading:o===l})]})};It.displayName="MethodListView";import*as ue from"react";import{AlertCircle as On,Loader2 as _n,Check as Dn}from"lucide-react";import{useEffect as Kr,useRef as Ie,useCallback as dr,useState as Tt}from"react";var Rt="1.0.0",Et=class{constructor(r,t){this.container=null;this.iframe=null;this.messageListener=null;this.iframeOrigin=null;if(this.options={environment:"sandbox",height:"720px",...t},this.validateOptions(),typeof r=="string"){if(this.container=document.querySelector(r),!this.container)throw new Error(`Container element not found: ${r}`)}else this.container=r}mount(){if(!this.container)throw new Error("Container element not found");this.unmount(),this.iframe=document.createElement("iframe"),this.iframe.style.width="100%",this.iframe.style.height=this.options.height||"720px",this.iframe.style.border="none",this.iframe.style.borderRadius="12px",this.iframe.style.background="transparent",this.iframe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),this.iframe.allow="payment *";let r=this.buildIframeUrl();this.iframeOrigin=(()=>{try{return new URL(r).origin}catch{return console.warn("[CardElementClient] Invalid iframe URL"),null}})(),this.messageListener=this.handleMessage.bind(this),window.addEventListener("message",this.messageListener),this.options.styles&&(this.iframe.onload=()=>{setTimeout(()=>{this.sendStyles(this.options.styles)},100)}),this.iframe.src=r,this.container.appendChild(this.iframe)}unmount(){this.iframe&&this.iframe.parentNode&&(this.iframe.parentNode.removeChild(this.iframe),this.iframe=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null)}destroy(){this.unmount(),this.container=null,this.options={}}configure(r){if(!this.iframe){console.error("[CardElementClient] Cannot configure: iframe not initialized");return}let t={source:"payos-sdk",type:"configure",data:r,version:Rt},a=this.iframeOrigin||new URL(this.getBaseUrl()).origin;this.iframe.contentWindow?.postMessage(t,a)}submit(){if(!this.iframe){console.error("[CardElementClient] Cannot submit: iframe not initialized");return}let r={source:"payos-sdk",type:"submit",version:Rt},t=this.iframeOrigin||new URL(this.getBaseUrl()).origin;this.iframe.contentWindow?.postMessage(r,t)}updateStyles(r){if(!this.iframe){console.error("[CardElementClient] Cannot update styles: iframe not initialized");return}this.sendStyles(r)}sendStyles(r){if(!this.iframe)return;let t={source:"payos-sdk",type:"styles",data:r,version:Rt},a=this.iframeOrigin||new URL(this.getBaseUrl()).origin;this.iframe.contentWindow?.postMessage(t,a)}handleMessage(r){if(!this.isAllowedOrigin(r.origin))return;let{data:t}=r;if(!t||typeof t!="object"||t.source!=="payos-card")return;let a=t;switch(a.type){case"ready":this.options.onReady?.();break;case"complete":a.data&&this.options.onTokenized&&this.options.onTokenized(a.data);break;case"change":a.data&&this.options.onChange&&this.options.onChange(a.data);break;case"cancel":this.options.onCancel?.();break;case"error":if(this.options.onError){let n=new Error(a.error||"Unknown error");this.options.onError(n)}break}}isAllowedOrigin(r){return this.getAllowedOrigins().some(a=>a===r)}buildIframeUrl(){let r=this.getBaseUrl(),t=new URL(`${r}/card-element`);return t.searchParams.set("token",this.options.token),t.searchParams.set("domain",window.location.origin),t.searchParams.set("env",this.options.environment||"sandbox"),t.searchParams.set("version",Rt),t.searchParams.set("mode","iframe"),this.options.customParams&&Object.entries(this.options.customParams).forEach(([a,n])=>{t.searchParams.set(a,n)}),t.toString()}getBaseUrl(){return this.options.customBaseUrl?this.options.customBaseUrl.replace(/\/$/,""):"https://wallet-onboard.payos.ai"}getAllowedOrigins(){let r=new Set;this.iframeOrigin&&r.add(this.iframeOrigin);try{let t=this.getBaseUrl(),a=new URL(t).origin;r.add(a)}catch{}return r.add("https://wallet-onboard.payos.ai"),r.add("https://wallet-onboard-sandbox.payos.ai"),r.add("http://localhost:3000"),Array.from(r)}validateOptions(){if(!this.options.token)throw new Error("Token is required");if(this.options.environment&&!["sandbox","production"].includes(this.options.environment))throw new Error('Environment must be either "sandbox" or "production"')}};function qr(e){let r=Ie(null),t=Ie(null),[a,n]=Tt(!1),[i,o]=Tt(!1),[p,l]=Tt(!0),[f,m]=Tt(void 0),N=Ie(e.onTokenized),b=Ie(e.onReady),s=Ie(e.onError),c=Ie(e.onChange),d=Ie(e.onCancel);Kr(()=>{N.current=e.onTokenized,b.current=e.onReady,s.current=e.onError,c.current=e.onChange,d.current=e.onCancel},[e.onTokenized,e.onReady,e.onError,e.onChange,e.onCancel]),Kr(()=>{let A=r.current;if(!A||!e.token)return;n(!1),o(!1),l(!0),m(void 0);let G={token:e.token,environment:e.environment||"sandbox",styles:e.styles,height:e.height,customBaseUrl:e.customBaseUrl,customParams:e.customParams,onReady:()=>{n(!0),b.current?.()},onTokenized:S=>{N.current?.(S)},onChange:S=>{o(S.complete),l(S.empty),m(S.error),c.current?.(S)},onCancel:()=>{d.current?.()},onError:S=>{m(S.message),s.current?.(S)}},k=new Et(A,G);return k.mount(),t.current=k,()=>{k.unmount(),t.current=null}},[e.token,e.environment,e.height,e.customBaseUrl]);let g=dr(()=>{t.current?t.current.submit():console.warn("[useCardElement] Cannot submit: CardElement not initialized")},[]),y=dr(A=>{t.current?t.current.configure(A):console.warn("[useCardElement] Cannot configure: CardElement not initialized")},[]),L=dr(A=>{t.current?.updateStyles?t.current.updateStyles(A):console.warn("[useCardElement] Cannot update styles: CardElement not initialized")},[]);return{containerRef:r,isReady:a,isComplete:i,isEmpty:p,error:f,submit:g,configure:y,updateStyles:L}}import{jsx as $,jsxs as Re}from"react/jsx-runtime";var At=({linkToken:e,walletUserId:r,onSubmit:t,onBack:a,isLoading:n=!1,error:i,isFirstCard:o=!1,environment:p="sandbox",customBaseUrl:l,devApiUrl:f,shippingAddress:m})=>{let[N,b]=ue.useState(null),[s,c]=ue.useState(!1),[d,g]=ue.useState(!1),y=m&&(m.line1||m.city||m.postalCode),L=ue.useCallback(C=>{c(!1);let H={number:"",expiry:"",cvc:"",cardholderName:C.cardholderName||C.card?.cardholderName||"",brand:C.card?.brand,last4:C.card?.last4,cardArtUrl:C.card?.artwork,cardId:C.card?.id},ne={line1:C.billingAddress?.street||"",line2:C.billingAddress?.street2||"",city:C.billingAddress?.city||"",state:C.billingAddress?.state||"",zip:C.billingAddress?.postalCode||"",country:C.billingAddress?.country||"US"};t(H,ne)},[t]),A=ue.useCallback(C=>{c(!1),b(C.message)},[]),{containerRef:G,isReady:k,isComplete:S,submit:K,configure:J}=qr({token:e,environment:p,customBaseUrl:l,height:"280px",styles:{layout:{padding:"0px",gap:"4px",labelPlacement:"above",showLabels:!1},container:{padding:"16px",margin:"0"}},customParams:f?{devApi:f}:void 0,onTokenized:L,onError:A,onChange:C=>{!C.empty&&N&&b(null)}});ue.useEffect(()=>{if(k){let C={};r&&(C.walletUserId=r),y&&m&&(C.shippingAddress=m,C.useShippingAsBilling=d),Object.keys(C).length>0&&(console.log("[CardAddView] Configuring CardElement:",C),J(C))}},[k,r,y,m,d,J]);let X=C=>{C.preventDefault(),!(!S||n||s)&&(b(null),c(!0),K())},I=i||N,P=n||s;return e?Re("form",{onSubmit:X,className:"space-y-4",children:[$(Q,{title:o?"Secure Checkout":"Add Card",onBack:o?void 0:a}),y&&$("div",{className:"w-full max-w-md mx-auto px-4",children:Re("button",{type:"button",onClick:()=>g(!d),className:"flex items-center gap-3 w-full text-left py-2",children:[$("div",{className:`
|
|
12
|
+
${o?"border-red-500 dark:border-red-400":h?"border-green-500 dark:border-green-400":"border-gray-300 dark:border-slate-600 focus:border-black dark:focus:border-white"}
|
|
13
|
+
`,"aria-label":"Card security code","aria-invalid":!!o,"aria-describedby":o?"cvc-error":void 0})]}),o&&Se("p",{id:"cvc-error",className:"text-xs text-red-600 dark:text-red-400 mt-2 text-right",children:o}),!o&&pe("p",{className:"text-xs text-gray-500 dark:text-slate-400 mt-2 text-right",children:[l,"-digit code on back of card"]})]})]})]})};ft.displayName="ActiveCardWidget";import{ChevronLeft as co}from"lucide-react";import{jsx as ht,jsxs as Mr}from"react/jsx-runtime";var Z=({title:e,onBack:r,action:t})=>Mr("div",{className:"flex items-center justify-between pb-4 border-b border-gray-200 dark:border-slate-700 mb-6",children:[Mr("div",{className:"flex items-center gap-3",children:[r&&ht("button",{onClick:r,className:"p-2 hover:bg-gray-100 dark:hover:bg-slate-800 rounded-lg active:scale-95 transition-all","aria-label":"Go back",children:ht(co,{className:"w-5 h-5 text-gray-900 dark:text-white"})}),ht("h2",{className:"text-lg font-semibold text-slate-900 dark:text-white",children:e})]}),t&&ht("div",{className:"flex-shrink-0",children:t})]});Z.displayName="ViewHeader";import*as bt from"react";import{ChevronDown as po,Bot as mo}from"lucide-react";import{jsx as ve,jsxs as me}from"react/jsx-runtime";var Dr=bt.forwardRef(({total:e,items:r=[],isAgentMode:t=!1,agentFee:a,defaultExpanded:o=!1,className:i},n)=>{let[p,l]=bt.useState(o);return me(O,{ref:n,variant:"default",className:N("p-4 cursor-pointer select-none transition-all duration-200",t&&"border-indigo-100 dark:border-indigo-900 bg-indigo-50/50 dark:bg-indigo-950/30",i),onClick:()=>l(!p),children:[me("div",{className:"flex items-center justify-between",children:[me("div",{className:"flex-1",children:[me("div",{className:"flex items-center gap-2 mb-1",children:[ve("h3",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Order Total"}),t&&me("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-violet-100 text-violet-700 text-xs font-medium dark:bg-violet-900/30 dark:text-violet-300",children:[ve(mo,{className:"h-3 w-3"}),"Agent"]})]}),t&&a&&me("p",{className:"text-xs text-indigo-700 dark:text-indigo-400",children:["Agent Fee: ",a," \u2022 Standard Processing"]})]}),me("div",{className:"flex items-center gap-3",children:[ve("span",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:e}),ve(po,{className:N("w-5 h-5 text-gray-500 dark:text-slate-400 transition-transform duration-200",p&&"rotate-180")})]})]}),p&&r.length>0&&ve("div",{className:"mt-4 pt-4 border-t border-gray-200 dark:border-slate-700 space-y-2",children:r.map((h,m)=>me("div",{className:"flex justify-between items-start text-sm",children:[me("div",{className:"flex-1",children:[ve("span",{className:"text-gray-700 dark:text-slate-300",children:h.label}),h.description&&ve("p",{className:"text-xs text-gray-500 dark:text-slate-500 mt-0.5",children:h.description})]}),ve("span",{className:"font-medium text-gray-900 dark:text-white ml-4",children:h.value})]},m))})]})});Dr.displayName="OrderSummary";import{Fragment as Jt,jsx as ie,jsxs as Pe}from"react/jsx-runtime";function go(e){let r=e.replace(/\D/g,"");if(r.length===11&&r.startsWith("1")){let t=r.slice(1,4),a=r.slice(4,7),o=r.slice(7,11);return`+1 (${t}) ${a}-${o}`}if(r.length===10){let t=r.slice(0,3),a=r.slice(3,6),o=r.slice(6,10);return`+1 (${t}) ${a}-${o}`}return e}var wt=({phoneNumber:e,otp:r,onOtpChange:t,onSubmit:a,onEdit:o,onResend:i,isLoading:n=!1,isResending:p=!1,error:l,resendCooldown:h=0,retryCount:m=0,maxRetries:E=3})=>{let v=m>=E,s=h===0&&!v,c=w=>{w.preventDefault(),a()},d=w=>{t(w),setTimeout(()=>{a(w)},100)},u=go(e);return ie("form",{onSubmit:c,className:"space-y-4",children:Pe(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6",children:[ie("h2",{className:"text-xl font-bold text-slate-900 dark:text-white text-center mb-2",children:"Enter verification code"}),Pe("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center mb-8",children:["Sent to"," ",ie("span",{className:"font-medium text-gray-900 dark:text-white",children:u}),o&&Pe(Jt,{children:[" ","\u2022"," ",ie("button",{type:"button",onClick:o,className:"text-blue-600 dark:text-blue-400 hover:underline",children:"Edit"})]})]}),Pe("div",{children:[ie(Ve,{value:r,onChange:t,onComplete:d}),l&&ie("p",{className:"text-sm text-red-600 dark:text-red-400 mt-4 text-center",children:l})]}),ie(M,{type:"submit",className:"w-full mt-8",disabled:r.length!==6||n,isLoading:n,loadingText:"Verifying...",children:"Verify"}),i&&ie("div",{className:"text-center mt-4",children:ie("p",{className:"text-xs text-gray-500 dark:text-slate-400",children:v?ie("span",{className:"text-red-600 dark:text-red-400",children:"Too many attempts. Please try again later."}):p?"Sending...":h>0?Pe(Jt,{children:["Resend in"," ",Pe("span",{className:"font-medium text-slate-700 dark:text-slate-300",children:[h,"s"]})]}):Pe(Jt,{children:["Didn't receive a code?"," ",ie("button",{type:"button",onClick:i,disabled:!s||n,className:"font-bold text-slate-900 dark:text-white hover:underline cursor-pointer disabled:opacity-50",children:"Resend"})]})})})]})})};wt.displayName="OTPView";import{jsx as yt,jsxs as Zt}from"react/jsx-runtime";var Ur=(e,r="USD")=>new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(e/100),uo=e=>e==="pay_on_behalf"||e==="agent_to_agent"||e==="agentic_multi",vt=({selectedCard:e,cvc:r,onCvcChange:t,onChangeCard:a,paymentIntent:o,total:i,isAgentMode:n,onSubmit:p,isLoading:l=!1,error:h})=>{let m=w=>{w.preventDefault(),p()},E=e.brand==="amex"?4:3,v=r.length===E,s=o?Ur(o.totalAmount+(o.facilitationFee?.amount||0),o.currency):i||"$0.00",c=o?uo(o.type):n||!1,d=c?!0:v,u=c?`Authorize ${s}`:`Pay ${s}`;return Zt("form",{onSubmit:m,className:"space-y-6",children:[Zt("div",{className:"space-y-3",children:[yt("h3",{className:"text-sm font-semibold text-slate-900 dark:text-white px-1 mt-6",children:"Payment Method"}),yt(ft,{card:e,cvc:r,onCvcChange:t,onChangeClick:a,disabled:l,error:h,hideSecurityCode:c})]}),c&&o?.facilitationFee&&yt("div",{className:"p-3 bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-700 rounded-lg",children:Zt("p",{className:"text-sm text-purple-800 dark:text-purple-200",children:["This is an agent-assisted transaction. A ",Ur(o.facilitationFee.amount,o.facilitationFee.currency)," facilitation fee applies."]})}),yt(M,{type:"submit",className:"w-full",disabled:!d||l,isLoading:l,loadingText:"Processing...",children:u})]})};vt.displayName="CheckoutView";import*as tr from"react";import{Plus as bo,Trash2 as wo}from"lucide-react";import{Loader2 as fo}from"lucide-react";import{Fragment as ho,jsx as xe,jsxs as Qt}from"react/jsx-runtime";var er=({isOpen:e,title:r,message:t,confirmText:a="Confirm",cancelText:o="Cancel",onConfirm:i,onCancel:n,isLoading:p=!1,variant:l="default"})=>e?xe("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",onClick:m=>{m.target===m.currentTarget&&!p&&n()},children:Qt("div",{className:"bg-white dark:bg-slate-800 rounded-xl shadow-xl max-w-sm w-full mx-4 overflow-hidden animate-in fade-in zoom-in-95 duration-200",onClick:m=>m.stopPropagation(),children:[xe("div",{className:"px-6 pt-6 pb-2",children:xe("h3",{className:"text-lg font-semibold text-slate-900 dark:text-white",children:r})}),xe("div",{className:"px-6 pb-6",children:xe("p",{className:"text-sm text-slate-600 dark:text-slate-400",children:t})}),Qt("div",{className:"px-6 pb-6 flex gap-3",children:[xe(M,{variant:"outline",className:"flex-1",onClick:n,disabled:p,children:o}),xe(M,{variant:l==="danger"?"destructive":"default",className:"flex-1",onClick:i,disabled:p,children:p?Qt(ho,{children:[xe(fo,{className:"w-4 h-4 mr-2 animate-spin"}),a]}):a})]})]})}):null;er.displayName="ConfirmDialog";import{jsx as re,jsxs as xt}from"react/jsx-runtime";var kt=({cards:e,selectedCardId:r,onSelectCard:t,onAddNewCard:a,onBack:o,onDeleteCard:i})=>{let[n,p]=tr.useState(null),[l,h]=tr.useState(null),m=(s,c)=>{s.stopPropagation(),i&&h(c)},E=async()=>{!l||!i||(p(l),await i(l),p(null),h(null))},v=l?e.find(s=>s.id===l)?.last4:"";return xt("div",{className:"space-y-4",children:[re(Z,{title:"Payment Methods",onBack:o}),xt(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-xl overflow-hidden",children:[e.map(s=>xt("div",{className:"relative flex items-center",children:[re("div",{className:"flex-1",children:re(ut,{last4:s.last4,brand:s.brand,expiry:`${s.expiryMonth}/${s.expiryYear}`,cardArtUrl:s.cardArtUrl,issuerName:s.issuerName,selected:r===s.id,onClick:()=>t(s.id),isLast:!1})}),i&&re("button",{onClick:c=>m(c,s.id),disabled:n===s.id,className:"absolute right-4 p-2 text-gray-400 hover:text-red-500 dark:text-slate-500 dark:hover:text-red-400 transition-colors disabled:opacity-50","aria-label":"Delete card",children:re(wo,{className:`w-4 h-4 ${n===s.id?"animate-pulse":""}`})})]},s.id)),e.length===0&&re("div",{className:"p-4 text-center border-b border-gray-100 dark:border-slate-700",children:re("p",{className:"text-sm text-gray-500 dark:text-slate-400",children:"No saved cards yet"})}),xt("div",{onClick:a,className:"w-full p-4 flex items-center gap-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-slate-800 active:bg-gray-100 dark:active:bg-slate-700 transition-colors",children:[re("div",{className:"w-10 h-10 rounded-lg bg-gray-100 dark:bg-slate-700 flex items-center justify-center flex-shrink-0",children:re(bo,{className:"w-5 h-5 text-gray-600 dark:text-slate-400"})}),re("div",{className:"flex-1",children:re("div",{className:"text-sm font-medium text-slate-900 dark:text-white",children:"Add new card"})})]})]}),re(er,{isOpen:!!l,title:"Delete Card",message:`Are you sure you want to delete the card ending in ${v}? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:E,onCancel:()=>h(null),isLoading:n===l})]})};kt.displayName="MethodListView";import*as ge from"react";import{AlertCircle as yo,Loader2 as vo,Check as xo}from"lucide-react";import{useEffect as _r,useRef as Re,useCallback as rr,useState as Pt}from"react";var Ct="1.0.0",St=class{constructor(r,t){this.container=null;this.iframe=null;this.messageListener=null;this.iframeOrigin=null;if(this.options={environment:"sandbox",height:"720px",...t},this.validateOptions(),typeof r=="string"){if(this.container=document.querySelector(r),!this.container)throw new Error(`Container element not found: ${r}`)}else this.container=r}mount(){if(!this.container)throw new Error("Container element not found");this.unmount(),this.iframe=document.createElement("iframe"),this.iframe.style.width="100%",this.iframe.style.height=this.options.height||"720px",this.iframe.style.border="none",this.iframe.style.borderRadius="12px",this.iframe.style.background="transparent",this.iframe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),this.iframe.allow="payment *";let r=this.buildIframeUrl();this.iframeOrigin=(()=>{try{return new URL(r).origin}catch{return console.warn("[CardElementClient] Invalid iframe URL"),null}})(),this.messageListener=this.handleMessage.bind(this),window.addEventListener("message",this.messageListener),this.options.styles&&(this.iframe.onload=()=>{setTimeout(()=>{this.sendStyles(this.options.styles)},100)}),this.iframe.src=r,this.container.appendChild(this.iframe)}unmount(){this.iframe&&this.iframe.parentNode&&(this.iframe.parentNode.removeChild(this.iframe),this.iframe=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null)}destroy(){this.unmount(),this.container=null,this.options={}}configure(r){if(!this.iframe){console.error("[CardElementClient] Cannot configure: iframe not initialized");return}let t={source:"payos-sdk",type:"configure",data:r,version:Ct},a=this.iframeOrigin||new URL(this.getBaseUrl()).origin;this.iframe.contentWindow?.postMessage(t,a)}submit(){if(!this.iframe){console.error("[CardElementClient] Cannot submit: iframe not initialized");return}let r={source:"payos-sdk",type:"submit",version:Ct},t=this.iframeOrigin||new URL(this.getBaseUrl()).origin;this.iframe.contentWindow?.postMessage(r,t)}updateStyles(r){if(!this.iframe){console.error("[CardElementClient] Cannot update styles: iframe not initialized");return}this.sendStyles(r)}sendStyles(r){if(!this.iframe)return;let t={source:"payos-sdk",type:"styles",data:r,version:Ct},a=this.iframeOrigin||new URL(this.getBaseUrl()).origin;this.iframe.contentWindow?.postMessage(t,a)}handleMessage(r){if(!this.isAllowedOrigin(r.origin))return;let{data:t}=r;if(!t||typeof t!="object"||t.source!=="payos-card")return;let a=t;switch(a.type){case"ready":this.options.onReady?.();break;case"complete":a.data&&this.options.onTokenized&&this.options.onTokenized(a.data);break;case"change":a.data&&this.options.onChange&&this.options.onChange(a.data);break;case"cancel":this.options.onCancel?.();break;case"error":if(this.options.onError){let o=new Error(a.error||"Unknown error");this.options.onError(o)}break}}isAllowedOrigin(r){return this.getAllowedOrigins().some(a=>a===r)}buildIframeUrl(){let r=this.getBaseUrl(),t=new URL(`${r}/card-element`);return t.searchParams.set("token",this.options.token),t.searchParams.set("domain",window.location.origin),t.searchParams.set("env",this.options.environment||"sandbox"),t.searchParams.set("version",Ct),t.searchParams.set("mode","iframe"),this.options.customParams&&Object.entries(this.options.customParams).forEach(([a,o])=>{t.searchParams.set(a,o)}),t.toString()}getBaseUrl(){return this.options.customBaseUrl?this.options.customBaseUrl.replace(/\/$/,""):"https://wallet-onboard.payos.ai"}getAllowedOrigins(){let r=new Set;this.iframeOrigin&&r.add(this.iframeOrigin);try{let t=this.getBaseUrl(),a=new URL(t).origin;r.add(a)}catch{}return r.add("https://wallet-onboard.payos.ai"),r.add("https://wallet-onboard-sandbox.payos.ai"),r.add("http://localhost:3000"),Array.from(r)}validateOptions(){if(!this.options.token)throw new Error("Token is required");if(this.options.environment&&!["sandbox","production"].includes(this.options.environment))throw new Error('Environment must be either "sandbox" or "production"')}};function Br(e){let r=Re(null),t=Re(null),[a,o]=Pt(!1),[i,n]=Pt(!1),[p,l]=Pt(!0),[h,m]=Pt(void 0),E=Re(e.onTokenized),v=Re(e.onReady),s=Re(e.onError),c=Re(e.onChange),d=Re(e.onCancel);_r(()=>{E.current=e.onTokenized,v.current=e.onReady,s.current=e.onError,c.current=e.onChange,d.current=e.onCancel},[e.onTokenized,e.onReady,e.onError,e.onChange,e.onCancel]),_r(()=>{let A=r.current;if(!A||!e.token)return;o(!1),n(!1),l(!0),m(void 0);let G={token:e.token,environment:e.environment||"sandbox",styles:e.styles,height:e.height,customBaseUrl:e.customBaseUrl,customParams:e.customParams,onReady:()=>{o(!0),v.current?.()},onTokenized:S=>{E.current?.(S)},onChange:S=>{n(S.complete),l(S.empty),m(S.error),c.current?.(S)},onCancel:()=>{d.current?.()},onError:S=>{m(S.message),s.current?.(S)}},k=new St(A,G);return k.mount(),t.current=k,()=>{k.unmount(),t.current=null}},[e.token,e.environment,e.height,e.customBaseUrl]);let u=rr(()=>{t.current?t.current.submit():console.warn("[useCardElement] Cannot submit: CardElement not initialized")},[]),w=rr(A=>{t.current?t.current.configure(A):console.warn("[useCardElement] Cannot configure: CardElement not initialized")},[]),_=rr(A=>{t.current?.updateStyles?t.current.updateStyles(A):console.warn("[useCardElement] Cannot update styles: CardElement not initialized")},[]);return{containerRef:r,isReady:a,isComplete:i,isEmpty:p,error:h,submit:u,configure:w,updateStyles:_}}import{jsx as H,jsxs as Ne}from"react/jsx-runtime";var Rt=({linkToken:e,walletUserId:r,onSubmit:t,onBack:a,isLoading:o=!1,error:i,isFirstCard:n=!1,environment:p="sandbox",customBaseUrl:l,devApiUrl:h,shippingAddress:m})=>{let[E,v]=ge.useState(null),[s,c]=ge.useState(!1),[d,u]=ge.useState(!1),w=m&&(m.line1||m.city||m.postalCode),_=ge.useCallback(C=>{c(!1);let $={number:"",expiry:"",cvc:"",cardholderName:C.cardholderName||C.card?.cardholderName||"",brand:C.card?.brand,last4:C.card?.last4,cardArtUrl:C.card?.artwork,cardId:C.card?.id},oe={line1:C.billingAddress?.street||"",line2:C.billingAddress?.street2||"",city:C.billingAddress?.city||"",state:C.billingAddress?.state||"",zip:C.billingAddress?.postalCode||"",country:C.billingAddress?.country||"US"};t($,oe)},[t]),A=ge.useCallback(C=>{c(!1),v(C.message)},[]),{containerRef:G,isReady:k,isComplete:S,submit:j,configure:q}=Br({token:e,environment:p,customBaseUrl:l,height:"280px",styles:{layout:{padding:"0px",gap:"4px",labelPlacement:"above",showLabels:!1},container:{padding:"16px",margin:"0"}},customParams:h?{devApi:h}:void 0,onTokenized:_,onError:A,onChange:C=>{!C.empty&&E&&v(null)}});ge.useEffect(()=>{if(k){let C={};r&&(C.walletUserId=r),w&&m&&(C.shippingAddress=m,C.useShippingAsBilling=d),Object.keys(C).length>0&&(console.log("[CardAddView] Configuring CardElement:",C),q(C))}},[k,r,w,m,d,q]);let X=C=>{C.preventDefault(),!(!S||o||s)&&(v(null),c(!0),j())},R=i||E,P=o||s;return e?Ne("form",{onSubmit:X,className:"space-y-4",children:[H(Z,{title:n?"Secure Checkout":"Add Card",onBack:n?void 0:a}),w&&H("div",{className:"w-full max-w-md mx-auto px-4",children:Ne("button",{type:"button",onClick:()=>u(!d),className:"flex items-center gap-3 w-full text-left py-2",children:[H("div",{className:`
|
|
14
14
|
w-5 h-5 rounded border-2 flex items-center justify-center transition-colors
|
|
15
15
|
${d?"bg-slate-900 border-slate-900 dark:bg-white dark:border-white":"border-gray-300 dark:border-slate-600"}
|
|
16
|
-
`,children:d
|
|
16
|
+
`,children:d&&H(xo,{className:"w-3 h-3 text-white dark:text-slate-900"})}),H("span",{className:"text-sm text-slate-700 dark:text-slate-300",children:"Billing address same as shipping"})]})}),Ne(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl overflow-hidden",children:[Ne("div",{className:"relative",children:[!k&&Ne("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-white dark:bg-slate-900 z-10 min-h-[280px]",children:[H(vo,{className:"w-8 h-8 text-gray-400 animate-spin"}),H("p",{className:"text-sm text-gray-500 dark:text-slate-400 mt-3",children:"Loading secure form..."})]}),H("div",{ref:G,className:"min-h-[280px] w-full",style:{opacity:k?1:0}})]}),R&&H("div",{className:"px-6 pb-4",children:H("p",{className:"text-sm text-red-600 dark:text-red-400 text-center",children:R})}),H("div",{className:"px-6 pb-6",children:H(M,{type:"submit",className:"w-full",disabled:!S||P,isLoading:P,loadingText:"Saving card...",children:"Save card"})})]})]}):Ne("div",{className:"space-y-4",children:[H(Z,{title:n?"Secure Checkout":"Add Card",onBack:n?void 0:a}),H(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6",children:Ne("div",{className:"flex flex-col items-center justify-center py-8 space-y-4 text-center",children:[H(yo,{className:"w-12 h-12 text-red-500"}),H("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:"Session Error"}),H("p",{className:"text-sm text-gray-600 dark:text-slate-400",children:"Unable to initialize secure card entry. Please try again."}),a&&H(M,{variant:"outline",onClick:a,className:"mt-4",children:"Go Back"})]})})]})};Rt.displayName="CardAddView";import{CheckCircle2 as ko}from"lucide-react";import{jsx as ue,jsxs as ar}from"react/jsx-runtime";var Fr=e=>e==="pay_on_behalf"||e==="agent_to_agent"||e==="agentic_multi",Co=e=>e&&Fr(e.type)?"credential":"payment",Nt=({paymentIntent:e,completionResult:r,walletUser:t,type:a,cardNetwork:o,mode:i,onCreatePasskey:n,onDismiss:p,isLoading:l=!1,passkeyEnrolled:h=!1})=>{let m=e?Fr(e.type):i==="agent",E=e?Co(e):a||"payment",v=()=>m?"Credentials Ready!":E==="payment"?"Payment Successful":"Card Added",s=()=>m?r?.credentialId?`Credential ID: ${r.credentialId}`:"Your payment credentials have been generated and are ready for agent use.":r?.transactionId?`Transaction: ${r.transactionId}`:t?.email?`Confirmation sent to ${t.email}`:null,c=v(),d=s();return ar("div",{className:"space-y-4",children:[ue(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-8",children:ar("div",{className:"flex flex-col items-center justify-center text-center space-y-4",children:[ue("div",{className:"relative",children:ue(ko,{className:"w-16 h-16 text-green-500 dark:text-green-400 animate-in zoom-in duration-300"})}),ue("h2",{className:"text-xl font-bold text-slate-900 dark:text-white",children:c}),d&&ue("p",{className:"text-sm text-gray-600 dark:text-slate-400",children:d})]})}),!m&&o&&n&&!h&&ar(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-4",children:[ue("h3",{className:"text-lg font-bold text-slate-900 dark:text-white text-center",children:"Checkout faster next time?"}),ue("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center",children:"Create a Passkey to pay securely with FaceID/TouchID\u2014no codes needed."}),ue(M,{onClick:n,className:"w-full",disabled:l,isLoading:l,loadingText:o==="mastercard"?"Creating...":"Verifying...",children:"Create Passkey"}),ue("button",{type:"button",onClick:p,disabled:l,className:"w-full text-sm text-gray-500 dark:text-slate-400 hover:text-gray-700 dark:hover:text-slate-300 disabled:opacity-50 transition-colors",children:"No thanks"})]})]})};Nt.displayName="SuccessView";import{Mail as So,MessageSquare as Po,ChevronRight as Ro,ShieldCheck as No}from"lucide-react";import{jsx as ae,jsxs as or}from"react/jsx-runtime";var $e="#0055BB",Et=({methods:e,onSelectMethod:r,onBack:t,isLoading:a=!1})=>{let o=n=>{switch(n){case"sms":return ae(Po,{className:"w-5 h-5",style:{color:$e}});case"email":return ae(So,{className:"w-5 h-5",style:{color:$e}})}},i=(n,p)=>{switch(n){case"sms":return`Text to ${p}`;case"email":return`Email to ${p}`}};return or("div",{className:"space-y-4",children:[or("div",{className:"flex items-center justify-center gap-2 py-2",children:[ae(No,{className:"w-5 h-5",style:{color:$e}}),ae("span",{className:"text-sm font-semibold",style:{color:$e},children:"Verified by Visa"})]}),ae(Z,{title:"Verify Your Identity",onBack:t}),ae("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center px-4",children:"Your bank requires additional verification. Choose how you'd like to receive your code."}),ae(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl overflow-hidden",children:e.map((n,p)=>or("button",{onClick:()=>!a&&r(n.id),disabled:a,className:`
|
|
17
17
|
w-full px-6 py-4 flex items-center gap-3
|
|
18
18
|
hover:bg-blue-50 dark:hover:bg-slate-800/50
|
|
19
19
|
active:bg-blue-100 dark:active:bg-slate-800
|
|
20
20
|
transition-colors
|
|
21
21
|
disabled:opacity-50 disabled:cursor-not-allowed
|
|
22
22
|
${p!==0?"border-t border-gray-200 dark:border-slate-700":""}
|
|
23
|
-
`,children:[ae("div",{className:"flex-shrink-0",children:n(o.type)}),ae("div",{className:"flex-1 text-left",children:ae("p",{className:"text-sm font-medium text-slate-900 dark:text-white",children:i(o.type,o.maskedValue)})}),ae("div",{className:"flex-shrink-0",children:ae(Fn,{className:"w-5 h-5",style:{color:We}})})]},o.id))})]})};_t.displayName="VisaMethodView";import*as je from"react";import{ShieldCheck as zn}from"lucide-react";import{jsx as de,jsxs as qe}from"react/jsx-runtime";var Ke="#0055BB",Dt=({methodDescription:e,otp:r,onOtpChange:t,onVerify:a,onBack:n,onResend:i,onVerifyAnotherWay:o,isLoading:p=!1,error:l,canRetry:f=!0})=>{let m=je.useRef(!1);je.useEffect(()=>{r.length<6&&(m.current=!1)},[r]);let N=s=>{s.preventDefault(),r.length===6&&f&&!p&&(m.current=!0,a())};je.useEffect(()=>{r.length===6&&!p&&f&&!m.current&&(m.current=!0,a())},[r,p,a,f]);let b=!f;return qe("form",{onSubmit:N,className:"space-y-4",children:[qe("div",{className:"flex items-center justify-center gap-2 py-2",children:[de(zn,{className:"w-5 h-5",style:{color:Ke}}),de("span",{className:"text-sm font-semibold",style:{color:Ke},children:"Verified by Visa"})]}),de(Q,{title:"Enter Bank Code",onBack:n}),qe("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center px-4",children:["Code sent to ",e]}),qe(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-6",children:[de("div",{className:p||b?"opacity-50 pointer-events-none":"",children:de(Me,{value:r,onChange:t,length:6})}),l&&de("p",{className:"text-sm text-red-600 dark:text-red-400 text-center",children:l}),de(M,{type:"submit",className:"w-full",style:{backgroundColor:Ke},disabled:r.length!==6||p||b,isLoading:p,loadingText:"Verifying...",children:"Verify"}),b&&o&&de("div",{className:"text-center",children:de("button",{type:"button",onClick:o,className:"text-sm hover:underline",style:{color:Ke},children:"Verify another way"})}),i&&!b&&de("div",{className:"text-center mt-4",children:qe("p",{className:"text-xs text-gray-500 dark:text-slate-400",children:["Didn't receive a code?"," ",de("button",{type:"button",onClick:i,disabled:p,className:"font-bold hover:underline disabled:opacity-50",style:{color:Ke},children:"Resend"})]})})]})]})};Dt.displayName="VisaOtpView";import{Sparkles as $n,Fingerprint as Hn,AlertCircle as Yn}from"lucide-react";import{jsx as ee,jsxs as Je}from"react/jsx-runtime";var Mt=({cardNetwork:e,onCreatePasskey:r,onSkip:t,onBack:a,isLoading:n=!1,error:i,showSkip:o=!1})=>Je("div",{className:"space-y-4",children:[Je(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-4",children:[ee("div",{className:"flex justify-center",children:ee("div",{className:"w-12 h-12 bg-indigo-100 dark:bg-indigo-900/30 rounded-full flex items-center justify-center",children:ee($n,{className:"w-6 h-6 text-indigo-600 dark:text-indigo-400"})})}),ee("h2",{className:"text-xl font-bold text-slate-900 dark:text-white text-center",children:"One final step"}),ee("p",{className:"text-sm text-gray-600 dark:text-slate-400 text-center leading-relaxed",children:"To allow the AI Agent to securely purchase this item for you, you must enable biometric access."})]}),e==="visa"&&ee("div",{id:"visa-auth-container",className:"w-full max-w-md mx-auto min-h-[10px] bg-gray-50 dark:bg-slate-800 rounded-2xl overflow-hidden"}),Je(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-4",children:[i&&Je("div",{className:"flex items-center gap-2 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 rounded-lg",children:[ee(Yn,{className:"w-4 h-4 text-red-500 flex-shrink-0"}),ee("p",{className:"text-sm text-red-700 dark:text-red-300",children:i})]}),Je(M,{onClick:r,className:"w-full",disabled:n,isLoading:n,loadingText:e==="mastercard"?"Creating Passkey...":"Verifying...",children:[ee(Hn,{className:"w-5 h-5 mr-2"}),e==="visa"?"Create Visa Passkey":"Create Mastercard Passkey"]}),o&&t&&ee("button",{type:"button",onClick:t,disabled:n,className:"w-full text-sm text-gray-500 dark:text-slate-400 hover:underline disabled:opacity-50",children:"Skip for now"}),ee("p",{className:"text-xs text-gray-500 dark:text-slate-400 text-center",children:"This grants the agent permission for this specific transaction."})]}),a&&ee("div",{className:"text-center px-4 mt-4",children:ee("button",{type:"button",onClick:a,disabled:n,className:"text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",children:"Back to checkout"})})]});Mt.displayName="AgentRegistrationView";import{useEffect as Te,useCallback as fa,useState as he,useRef as Qn}from"react";import{Loader2 as eo,AlertCircle as ha}from"lucide-react";import{useState as fe,useEffect as hr,useCallback as B,useRef as yr}from"react";var U=class extends Error{constructor(t,a,n){super(t);this.name="ApiError",this.status=a,this.details=n}};function Jr(e){if(!e)return e;let r=e.startsWith("+"),t=e.replace(/\D/g,"");return r?`+${t}`:t.length===10?`+1${t}`:t.length===11&&t.startsWith("1")?`+${t}`:`+${t}`}function Xr(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}}async function j(e,r,t,a={}){let n=`${e}${r}`,i={"Content-Type":"application/json",Authorization:`Bearer ${t}`,"ngrok-skip-browser-warning":"true"};try{let o=await fetch(n,{...a,headers:{...i,...a.headers}}),p=o.headers.get("content-type"),l;if(p&&p.includes("application/json"))l=await o.json();else{let f=await o.text();try{l=JSON.parse(f)}catch{throw f.includes("<!DOCTYPE")||f.includes("<html")?new U("Received HTML instead of JSON. Ngrok bypass header may not be working.",o.status,"HTML response received"):new U("Invalid JSON response from server",o.status,f.substring(0,200))}}if(!o.ok)throw new U(l.message||"An error occurred",o.status);return l}catch(o){throw o instanceof U?o:new U(o instanceof Error?o.message:"Network error",0)}}async function Vt(e,r,t){let a=Jr(t);console.log("[ApiService] Sending OTP to:",t,"\u2192",a);let n=await j(e,"/api/otp/payos-link/generate",r,{method:"POST",body:JSON.stringify({phone:a,channel:"sms"})});if(n.error||!n.data)throw new U(n.message||"Failed to send verification code",400);return console.log("[ApiService] OTP sent, reference:",n.data.reference),n.data.reference}async function pr(e,r,t,a){console.log("[ApiService] Verifying OTP, reference:",t);let n=await j(e,"/api/otp/payos-link/verify",r,{method:"POST",body:JSON.stringify({reference:t,code:a})});if(n.error||!n.data)throw new U(n.message||"Invalid verification code",400);return console.log("[ApiService] OTP verified for phone:",n.data.phone),n.data}async function Gn(e,r,t){let a=await j(e,`/api/otp/payos-link/status/${t}`,r,{method:"GET"});if(a.error||!a.data)throw new U(a.message||"Failed to get verification status",400);return a.data}async function mr(e,r,t,a){console.log("[ApiService] Resending OTP, previous reference:",t);try{let n=await Gn(e,r,t),i=new Date(n.createdAt),o=Date.now()-i.getTime(),p=30*1e3;if(o<p&&n.status==="pending"){let f=Math.ceil((p-o)/1e3);return console.log("[ApiService] Rate limited, wait time remaining:",f),{reference:t,waitTimeRemaining:f}}return{reference:await Vt(e,r,a)}}catch(n){throw console.error("[ApiService] Failed to resend verification:",n),n}}async function ur(e,r,t,a){let n=Jr(t);console.log("[ApiService] Processing verified wallet user, phone:",t,"\u2192",n);let i=await j(e,"/api/wallet-users/process-verified-wallet-user",r,{method:"POST",body:JSON.stringify({phone:n,verificationId:a})});if(i.error||!i.data)throw new U(i.message||"Failed to process wallet user",400);let o=(i.data.savedCards||[]).map(Xr);return console.log("[ApiService] Wallet user processed:",{walletUserId:i.data.walletUserId,isNewUser:i.data.isNewUser,savedCardsCount:o.length}),{...i.data,savedCards:o}}async function Zr(e,r,t){console.log("[ApiService] Getting cards for wallet user:",t);let a=await j(e,`/api/wallet-users/${t}/cards`,r,{method:"GET"});if(a.error)throw new U(a.message||"Failed to get wallet user cards",400);return(a.data||[]).map(Xr)}async function Qr(e,r,t){console.log("[ApiService] Creating payment intent:",t);let a=await j(e,"/api/payment-intents",r,{method:"POST",body:JSON.stringify(t)});if(a.error||!a.data)throw new U(a.message||"Failed to create payment intent",400);return console.log("[ApiService] Payment intent created:",a.data.id),a.data}async function gr(e,r){console.log("[ApiService] Getting current session");let t=await j(e,"/web/sessions/current",r,{method:"GET"});if(t.error||!t.data)throw new U(t.message||"Failed to get session",400);return t.data}async function ea(e,r){console.log("[ApiService] Starting session");let t=await j(e,"/web/sessions/current/start",r,{method:"PATCH"});if(t.error||!t.data)throw new U(t.message||"Failed to start session",400);return console.log("[ApiService] Session started:",t.data.id),t.data}async function ta(e,r){console.log("[ApiService] Completing session");let t=await j(e,"/web/sessions/current/complete",r,{method:"POST"});if(t.error||!t.data)throw new U(t.message||"Failed to complete session",400);return console.log("[ApiService] Session completed:",t.data.id),t.data}async function ra(e,r){console.log("[ApiService] Abandoning session");let t=await j(e,"/web/sessions/current/abandon",r,{method:"POST"});if(t.error||!t.data)throw new U(t.message||"Failed to abandon session",400);return console.log("[ApiService] Session abandoned:",t.data.id),t.data}async function Xe(e,r,t){console.log("[ApiService] Updating session payment intent:",t);let a=await j(e,"/web/sessions/current/payment-intent",r,{method:"PATCH",body:JSON.stringify(t)});if(a.error||!a.data)throw new U(a.message||"Failed to update payment intent",400);return console.log("[ApiService] Session payment intent updated"),a.data}async function aa(e,r,t){console.log("[ApiService] Generating credentials for payment intent:",t);let a=`${e}/api/payment-credentials/generate`,n=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`,"ngrok-skip-browser-warning":"true"},body:JSON.stringify({paymentIntentId:t})}),i=n.headers.get("content-type"),o;if(i&&i.includes("application/json"))o=await n.json();else{let p=await n.text();try{o=JSON.parse(p)}catch{throw new U("Invalid response from credential generation",n.status,p.substring(0,200))}}if(!n.ok)throw new U(o.message||"Failed to generate credentials",n.status,o.data?.status);return console.log("[ApiService] Credential generation result:",o.data?.status||o.message),{status:o.data?.status||"success",message:o.message,retrievalToken:o.data?.retrievalToken,approvalId:o.data?.approvalId}}async function na(e,r,t,a){console.log("[ApiService] Deleting card:",{walletUserId:t,cardId:a});let n=await j(e,`/api/wallet-users/${t}/cards/${a}`,r,{method:"DELETE"});if(n.error)throw new U(n.message||"Failed to delete card",400);return console.log("[ApiService] Card deleted successfully"),{success:!0}}async function oa(e,r,t,a){console.log("[ApiService] Checking device trust:",{deviceId:t,walletUserId:a});let n=new URLSearchParams({deviceId:t});a&&n.set("walletUserId",a);let i=await j(e,`/web/device-trust?${n}`,r,{method:"GET"});return i.error?(console.warn("[ApiService] Device trust check failed, defaulting to untrusted"),{isTrusted:!1}):(console.log("[ApiService] Device trust result:",i.data),{isTrusted:i.data?.isTrusted??!1,expiresAt:i.data?.expiresAt,walletUserId:i.data?.walletUserId})}async function sa(e,r,t,a){return console.log("[ApiService] Registering trusted device:",{deviceId:t,walletUserId:a}),(await j(e,"/web/device-trust",r,{method:"POST",body:JSON.stringify({deviceId:t,walletUserId:a})})).error?(console.warn("[ApiService] Device trust registration failed"),{success:!1}):(console.log("[ApiService] Device registered as trusted"),{success:!0})}var ia="payos_device_id",Wn="payos_device_created";function Kn(){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 r=navigator;e.push(String(r.deviceMemory||0));let t=e.join("|");return qn(t)}function qn(e){let r=2166136261;for(let t=0;t<e.length;t++)r^=e.charCodeAt(t),r=Math.imul(r,16777619);return(r>>>0).toString(16).padStart(8,"0")}function da(){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function fr(){try{let e=localStorage.getItem(ia);if(e)return e;let r=Kn(),t=da().substring(0,8),a=`${r}-${t}`;return localStorage.setItem(ia,a),localStorage.setItem(Wn,new Date().toISOString()),a}catch{return da()}}function wr(e,r){let{apiBaseUrl:t}=r,[a,n]=fe(null),[i,o]=fe("LOADING"),[p,l]=fe(!0),[f,m]=fe(null),[N,b]=fe("checkout"),[s,c]=fe(""),[d,g]=fe("initial"),[y,L]=fe(null),[A,G]=fe(null),k=yr(!0),S=yr(e),K=yr(!1);hr(()=>{S.current!==e&&(K.current=!1),S.current=e},[e]);let J=B((v,x)=>{let{session:h,paymentIntent:u}=v,E=u?{id:u.id,type:u.type,currency:u.currency,organizationId:u.organizationId,status:u.status,totalAmount:u.totalAmount,totalSubtotal:u.totalSubtotal??u.totalAmount,totalTax:u.totalTax,totalShipping:u.totalShipping,payments:u.payments.map(V=>({id:V.id,merchantName:V.merchantName,merchantUrl:V.merchantUrl,amount:V.amount,subtotal:V.subtotal||V.amount,tax:V.tax,shipping:V.shipping,description:V.description,quantity:V.quantity,credentialStatus:V.credentialStatus,status:V.status,createdAt:V.createdAt,updatedAt:V.updatedAt})),intentType:u.intentType||"standard",walletUserId:u.walletUserId,selectedCardId:u.selectedCardId,requireHitl:u.requireHitl??!1,hitlAttemptCount:u.hitlAttemptCount??0,hitlApproved:u.hitlApproved??!1,networkAuthRequired:u.networkAuthRequired??!1,networkAuthCompleted:u.networkAuthCompleted??!1,authValid:u.authValid??!1,credentialType:u.credentialType||"pci_vault_token",createdAt:u.createdAt,updatedAt:u.updatedAt,facilitationFee:void 0}:x?.paymentIntent;if(!E)throw new Error("No payment intent available");let T="initialized";return h.status==="complete"?T="completed":h.status==="expired"?T="expired":h.status==="abandoned"?T="abandoned":x?.deviceVerified&&(T="verified"),{id:h.id,status:T,organizationId:h.organizationId,paymentIntent:E,linkToken:S.current,walletUser:x?.walletUser,savedCards:x?.savedCards||[],selectedCard:x?.selectedCard,deviceVerified:x?.deviceVerified||!1,verificationMethod:"phone",verificationReference:y||"",verificationPhone:A||"",expiresAt:h.expiresAt,createdAt:h.createdAt,updatedAt:h.updatedAt}},[y,A]),X=B(v=>{if(!v)return"LOADING";switch(v.status){case"initialized":return v.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"}},[]);hr(()=>(k.current=!0,K.current?void 0:((async()=>{K.current=!0,l(!0),m(null);try{let x=await gr(t,e),h=x.paymentIntent?.status;if(h&&["approved","credentials_ready","completed","awaiting_payment"].includes(h)){k.current&&(m({code:"PAYMENT_INTENT_ALREADY_PROCESSED",message:h==="completed"?"This payment has already been completed.":h==="awaiting_payment"?"This payment is already in progress.":"This payment has already been approved. Use the credentials API to retrieve or regenerate.",sessionId:x.session.id}),o("ERROR"));return}await ea(t,e);let E=J(x),T=x.paymentIntent?.walletUserId;if(T)try{let V=fr();if((await oa(t,e,V,T)).isTrusted){console.log("[useSession] Device is trusted, skipping OTP verification"),E.deviceVerified=!0,E.status="verified";let Gt=await Zr(t,e,T);if(E.walletUser={id:T},E.savedCards=Gt||[],E.savedCards.length>0){let nt=E.savedCards.find($e=>$e.isDefault)||E.savedCards[0];E.selectedCard=nt}}}catch{console.log("[useSession] Device trust check failed, requiring OTP")}k.current&&(n(E),o(X(E)))}catch(x){if(k.current){let h=x,u=h.status===410||h.message?.toLowerCase().includes("expired");m({code:u?"SESSION_EXPIRED":"LOAD_FAILED",message:h.message||"Failed to load session",sessionId:e}),o(u?"EXPIRED":"ERROR")}}finally{k.current&&l(!1)}})(),()=>{k.current=!1})),[e,X,J,t]);let I=a?.paymentIntent.type==="pay_on_behalf"||a?.paymentIntent.type==="agent_to_agent"||a?.paymentIntent.type==="agentic_multi",P=!!a?.selectedCard,C=(a?.savedCards?.length??0)>0;hr(()=>{i==="PAYMENT"&&b(P?"checkout":C?"methods":"add")},[i,P,C]);let H=B(()=>{b("methods")},[]),ne=B(()=>{b("add")},[]),Ft=B(()=>{b(P?"checkout":C?"methods":"add")},[P,C]),Bt=B(()=>{o("IDENTITY")},[]),ye=B(async v=>{if(!a||!v.phone)return!1;l(!0);try{let x=await Vt(t,S.current,v.phone);return k.current&&(L(x),G(v.phone),n(h=>h?{...h,status:"otp_pending",verificationReference:x,verificationPhone:v.phone}:null),o("OTP_VERIFY")),!0}catch(x){let h=x;return k.current&&m({code:"VERIFICATION_FAILED",message:h.message||"Failed to send verification",sessionId:a.id}),!1}finally{k.current&&l(!1)}},[a,t]),oe=B(async v=>{if(!a||!y||!A)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session or verification context"}};l(!0);try{let x=await pr(t,S.current,y,v),h=await ur(t,S.current,x.phone,x.reference);if(k.current){let u,E;if(a.paymentIntent.selectedCardId?u=h.savedCards.find(T=>T.id===a.paymentIntent.selectedCardId):h.savedCards.length>0&&(u=h.savedCards.find(T=>T.isDefault)||h.savedCards[0],E=u?.id),E)try{await Xe(t,S.current,{selectedCardId:E})}catch(T){console.warn("[useSession] Failed to auto-select card on backend:",T)}n(T=>T?{...T,status:"verified",deviceVerified:!0,walletUser:{id:h.walletUserId,phone:x.phone},savedCards:h.savedCards,selectedCard:u,paymentIntent:{...T.paymentIntent,walletUserId:h.walletUserId,...E&&{selectedCardId:E}}}:null),o("PAYMENT");try{let T=fr();await sa(t,S.current,T,h.walletUserId),console.log("[useSession] Device registered as trusted for 90 days")}catch(T){console.warn("[useSession] Failed to register device trust:",T)}}return{success:!0,walletUserId:h.walletUserId}}catch(x){let u={success:!1,error:{code:"INVALID_OTP",message:x.message||"Invalid verification code"}};return k.current&&m({code:u.error.code,message:u.error.message,sessionId:a.id}),u}finally{k.current&&l(!1)}},[a,y,A,t]),et=B(async()=>{if(!a||!y||!A)return!1;l(!0);try{let v=await mr(t,S.current,y,A);return v.waitTimeRemaining?!1:(k.current&&v.reference!==y&&L(v.reference),!0)}catch{return!1}finally{k.current&&l(!1)}},[a,y,A,t]),zt=B(async v=>{if(!a)return!1;l(!0);try{await Xe(t,S.current,{selectedCardId:v});let x=a.savedCards.find(h=>h.id===v);return k.current&&(n(h=>h?{...h,selectedCard:x,paymentIntent:{...h.paymentIntent,selectedCardId:v}}:null),b("checkout")),!0}catch(x){let h=x;return k.current&&m({code:"CARD_SELECT_FAILED",message:h.message||"Failed to select card",sessionId:a.id}),!1}finally{k.current&&l(!1)}},[a,t]),$t=B(async v=>{if(!a)return{success:!1};l(!0);try{let x={id:v.cardId,brand:v.brand?.toLowerCase()||"unknown",last4:v.last4,expiryMonth:v.expiryMonth||"",expiryYear:v.expiryYear||"",cardholderName:v.cardholderName,isDefault:!1,network:v.network?.toLowerCase()||"visa",cardArtUrl:v.cardArtUrl};if(await Xe(t,S.current,{selectedCardId:x.id}),k.current){n(E=>E?{...E,savedCards:[...E.savedCards,x],selectedCard:x,paymentIntent:{...E.paymentIntent,selectedCardId:x.id}}:null);let h=a.paymentIntent.type;h==="pay_on_behalf"||h==="agent_to_agent"||h==="agentic_multi"?(g("initial"),o("AGENT_REGISTRATION")):b("checkout")}return{success:!0,card:x}}catch(x){let h=x;return k.current&&m({code:"CARD_ADD_FAILED",message:h.message||"Failed to add card",sessionId:a.id}),{success:!1}}finally{k.current&&l(!1)}},[a,t]),ze=B(async v=>{if(!a||!a.walletUser?.id)return console.warn("[useSession] Cannot delete card: no wallet user"),!1;l(!0);try{if(await na(t,S.current,a.walletUser.id,v),k.current){let x=a.savedCards.filter(u=>u.id!==v),h=a.selectedCard?.id===v;n(u=>u?{...u,savedCards:x,selectedCard:h?void 0:u.selectedCard,paymentIntent:{...u.paymentIntent,selectedCardId:h?void 0:u.paymentIntent.selectedCardId}}:null),x.length===0&&b("add")}return!0}catch(x){let h=x;return k.current&&m({code:"CARD_DELETE_FAILED",message:h.message||"Failed to delete card",sessionId:a.id}),!1}finally{k.current&&l(!1)}},[a,t]),tt=B(async()=>{if(a)try{await Xe(t,S.current,{selectedCardId:void 0}),k.current&&n(v=>v?{...v,selectedCard:void 0,paymentIntent:{...v.paymentIntent,selectedCardId:void 0}}:null)}catch{}},[a,t]),Ht=B(()=>{g("initial"),o("PAYMENT"),b("checkout")},[]),_=B(()=>{g("initial"),o("PAYMENT"),b("checkout")},[]),we=B(async v=>{if(!a)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session"}};o("PROCESSING"),l(!0);try{return I&&v?.passkeyAuthenticated&&(console.log("[useSession] Generating credentials for agent mode passkey authentication"),await aa(t,S.current,a.paymentIntent.id),console.log("[useSession] Credentials generated successfully")),await ta(t,S.current),k.current&&(n(x=>x?{...x,status:"completed"}:null),o("SUCCESS")),{success:!0,walletUserId:a.walletUser?.id,paymentIntentId:a.paymentIntent.id,credentialGenerated:I&&v?.passkeyAuthenticated}}catch(x){let h=x,E={success:!1,error:{code:h.message?.includes("credential")||h.message?.includes("generate")?"CREDENTIAL_GENERATION_FAILED":"PAYMENT_FAILED",message:h.message||"Payment failed"}};return k.current&&(m({code:E.error.code,message:E.error.message,sessionId:a.id}),o("PAYMENT")),E}finally{k.current&&l(!1)}},[a,I,t]),rt=B(async()=>{if(a)try{await ra(t,S.current)}catch{}},[a,t]),Oe=B(()=>{m(null)},[]),Yt=B(async()=>{if(a){l(!0);try{let v=await gr(t,S.current),x=J(v,a);k.current&&(n(x),o(X(x)))}catch(v){let x=v;k.current&&m({code:"LOAD_FAILED",message:x.message||"Failed to refresh session",sessionId:a.id})}finally{k.current&&l(!1)}}},[a,X,J,t]);return{session:a,phase:i,loading:p,error:f,isAgentMode:I,hasSelectedCard:P,hasSavedCards:C,paymentView:N,cvc:s,setCvc:c,showMethodList:H,showAddCard:ne,returnToCheckout:Ft,submitIdentity:ye,goBackToIdentity:Bt,submitOTP:oe,resendCode:et,selectPaymentCard:zt,addPaymentCard:$t,deletePaymentCard:ze,clearCard:tt,registrationSubPhase:d,setRegistrationSubPhase:g,skipRegistration:Ht,completeAgentRegistration:_,setPhase:o,setPaymentView:b,complete:we,abandon:rt,clearError:Oe,refresh:Yt}}import{useRef as jn,useState as la,useEffect as Jn,useCallback as ke}from"react";import{PayOSPasskey as Xn}from"@payos-inc/payos-passkey-js";var br={enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,isLoading:!1,error:null,canRetry:!0,attemptsRemaining:void 0};function ca(e){let r=jn(null),[t,a]=la(!1),[n,i]=la(br);Jn(()=>{if(!e.sessionSecret){a(!1);return}try{r.current=new Xn(e.sessionSecret,{sandbox:e.sandbox,debug:e.debug,visaContainerId:e.visaContainerId,apiBaseUrl:e.apiBaseUrl}),a(!0)}catch(c){console.error("[usePasskeySDK] Failed to initialize SDK:",c),i(d=>({...d,error:c?.message||"Failed to initialize passkey SDK"})),a(!1)}return()=>{r.current?.cleanup(),r.current=null,a(!1)}},[e.sessionSecret,e.sandbox,e.debug,e.visaContainerId,e.apiBaseUrl]);let o=ke(async c=>{if(!r.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};i(d=>({...d,isLoading:!0,error:null}));try{let d=await r.current.register(c);if(d.requiresStepUp){let g=(d.stepUpMethods||[]).map((y,L)=>({id:String(L),type:y.type?.toLowerCase()==="email"?"email":"sms",maskedValue:y.maskedValue||y.value||`Method ${L+1}`}));i(y=>({...y,isLoading:!1,enrollmentId:d.enrollmentId||null,stepUpMethods:g}))}else i(g=>({...g,isLoading:!1}));return d}catch(d){let g=d?.message||"Registration failed";return i(y=>({...y,isLoading:!1,error:g})),{success:!1,message:g,error:{code:"REGISTRATION_ERROR",message:g}}}},[]),p=ke(async c=>{if(!r.current||!n.enrollmentId)return{success:!1};i(d=>({...d,isLoading:!0,error:null}));try{let d=await r.current.submitStepUpMethod(n.enrollmentId,c),g=n.stepUpMethods[c];return i(y=>({...y,isLoading:!1,selectedMethodDescription:g?.maskedValue||null})),d}catch(d){let g=d?.message||"Failed to send OTP";return i(y=>({...y,isLoading:!1,error:g})),{success:!1}}},[n.enrollmentId,n.stepUpMethods]),l=ke(async c=>{if(!r.current||!n.enrollmentId)return{success:!1,message:"No enrollment in progress",error:{code:"NO_ENROLLMENT",message:"No active enrollment"}};i(d=>({...d,isLoading:!0,error:null}));try{let d=await r.current.validateStepUpOTP(n.enrollmentId,c);return d.success?i(g=>({...g,isLoading:!1,canRetry:!0,attemptsRemaining:void 0})):i(g=>({...g,isLoading:!1,error:d.message||"OTP validation failed",canRetry:d.canRetry??!0,attemptsRemaining:d.attemptsRemaining})),d}catch(d){let g=d?.message||"OTP validation failed";return i(y=>({...y,isLoading:!1,error:g})),{success:!1,message:g,error:{code:"OTP_ERROR",message:g}}}},[n.enrollmentId]),f=ke(async c=>{if(!r.current||!n.enrollmentId)return{success:!1,message:"No enrollment in progress",error:{code:"NO_ENROLLMENT",message:"No active enrollment"}};i(d=>({...d,isLoading:!0,error:null}));try{let d=await r.current.completeVisaRegistration(n.enrollmentId,c);return i(g=>({...g,isLoading:!1,enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,error:d.success?null:d.message||"Registration failed"})),d}catch(d){let g=d?.message||"Registration failed";return i(y=>({...y,isLoading:!1,enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,error:g})),{success:!1,message:g,error:{code:"REGISTRATION_ERROR",message:g}}}},[n.enrollmentId]),m=ke(async(c,d)=>{if(!r.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};i(g=>({...g,isLoading:!0,error:null}));try{let g=await r.current.authenticate(c,d);return i(y=>({...y,isLoading:!1})),g}catch(g){let y=g?.message||"Authentication failed";return i(L=>({...L,isLoading:!1,error:y})),{success:!1,message:y,error:{code:"AUTH_ERROR",message:y}}}},[]),N=ke(()=>{i(c=>({...c,error:null}))},[]),b=ke(()=>{i(br)},[]),s=ke(()=>{r.current?.cleanup(),i(br)},[]);return{sdk:r.current,isReady:t,state:n,startRegistration:o,selectStepUpMethod:p,submitVisaOtp:l,completeVisaRegistration:f,authenticate:m,clearError:N,resetState:b,cleanup:s}}import{jsx as xr,jsxs as Zn}from"react/jsx-runtime";var vr=({onCancel:e})=>Zn("div",{className:"space-y-4",children:[xr(Q,{title:"Complete Passkey Setup",onBack:e}),xr("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center px-4",children:"Follow the instructions below to create your passkey"}),xr("div",{id:"visa-auth-container",className:"w-full max-w-sm mx-auto min-h-[300px] bg-gray-50 dark:bg-slate-800 rounded-2xl overflow-hidden"})]});vr.displayName="VisaIframeView";function Ee(e,r="USD"){let t=e/100;return new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(t)}function pa(e,r){return r||(e==="sandbox"?"https://sandbox.api.payos.ai":"https://api.payos.ai")}var ma={apiBaseUrl:"https://eudiometrical-superscientifically-roselle.ngrok-free.dev",orgId:"org_9f9a90da05fa4db0916e9b2effefdba8",apiKey:"sk_test_760d15ae78084a449e550157535de125a183dd39b6a947baa50e65f84abd7ba1"};async function ua(){console.log("[LinkTokenService] Fetching link token from API...");let e=await fetch(`${ma.apiBaseUrl}/api/auth/payos-link/tokens/link`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":ma.apiKey,"ngrok-skip-browser-warning":"true"},body:JSON.stringify({domain:typeof window<"u"?window.location.origin:"http://localhost:3000"})});if(!e.ok){let t=await e.text();throw console.error("[LinkTokenService] Failed to fetch link token:",e.status,t),new Error(`Failed to fetch link token: ${e.status}`)}let r=await e.json();return console.log("[LinkTokenService] Link token fetched successfully, expires:",r.data.expiresAt),{token:r.data.token,expiresAt:r.data.expiresAt}}var ga={customBaseUrl:"https://purple-grass-0eb0a1b1e.1.azurestaticapps.net",environment:"sandbox"};import{jsx as D,jsxs as Ut}from"react/jsx-runtime";var to=({sessionSecret:e,open:r,onClose:t,onSuccess:a,onError:n,onCancel:i,title:o,environment:p="sandbox",developmentApiUrl:l,cardElementApiUrl:f,cardElementUrl:m,debug:N=!1})=>{let b=pa(p,l),{session:s,phase:c,loading:d,error:g,isAgentMode:y,hasSelectedCard:L,hasSavedCards:A,paymentView:G,cvc:k,setCvc:S,showMethodList:K,showAddCard:J,returnToCheckout:X,submitIdentity:I,goBackToIdentity:P,submitOTP:C,resendCode:H,selectPaymentCard:ne,addPaymentCard:Ft,deletePaymentCard:Bt,registrationSubPhase:ye,setRegistrationSubPhase:oe,skipRegistration:et,completeAgentRegistration:zt,setPhase:$t,complete:ze,abandon:tt,clearError:Ht}=wr(e,{apiBaseUrl:b}),_=ca({sessionSecret:e,sandbox:p==="sandbox",debug:N,apiBaseUrl:b,visaContainerId:"visa-auth-container"}),[we,rt]=he(""),[Oe,Yt]=he("US"),[v,x]=he(""),[h,u]=he(null),[E,T]=he(!1),[V,at]=he(0),[Gt,nt]=he(0),[$e,_e]=he(""),[Wt,Sr]=he(null),Kt=Qn(!1);Te(()=>{g&&n(g)},[g,n]),Te(()=>{if(c==="SUCCESS"&&s){let w=setTimeout(()=>{a({success:!0,sessionId:s.id,paymentIntent:s.paymentIntent,walletUserId:s.walletUser?.id,paymentIntentId:s.paymentIntent.id,credentialGenerated:y})},3e3);return()=>clearTimeout(w)}},[c,s,a,y]),Te(()=>{if(s?.walletUser?.phone&&!we){let w=dt(s.walletUser.phone,Oe);rt(w)}},[s?.walletUser?.phone,we,Oe]),Te(()=>{if(V<=0)return;let w=setTimeout(()=>at(F=>F-1),1e3);return()=>clearTimeout(w)},[V]),Te(()=>{c==="IDENTITY"&&(at(0),nt(0),x(""))},[c]),Te(()=>{u(null),_.clearError()},[ye]),Te(()=>{if(ye==="visa_iframe"&&Wt&&!Kt.current){Kt.current=!0;let w=setTimeout(async()=>{try{let F=await _.completeVisaRegistration(Wt);Sr(null),F.success?et():(u(F.message||"Registration failed"),oe("initial"))}finally{Kt.current=!1}},100);return()=>clearTimeout(w)}},[ye,Wt]);let He=fa(()=>{c!=="PROCESSING"&&(tt(),i?.(),t())},[c,tt,i,t]),Sa=async()=>{if(u(null),!ct(we,Oe)){u("Please enter a valid phone number");return}await I({phone:we})&&x("")},Pa=async w=>{let F=w||v;u(null),console.log("[PaymentSheet] Submitting OTP:",{otpCode:F,length:F.length});let Y=await C(F);console.log("[PaymentSheet] OTP result:",Y),!Y.success&&Y.error&&(nt(st=>st+1),u(Y.error.message))},Na=fa(async()=>{u(null),x(""),T(!0),at(30);try{await H()}finally{T(!1)}},[H]),Ia=async w=>{await ne(w)},Ra=async(w,F)=>{(await Ft({cardId:w.cardId||`card_${Date.now()}`,last4:w.last4||"",brand:w.brand||"unknown",network:w.brand||"unknown",cardholderName:w.cardholderName,cardArtUrl:w.cardArtUrl})).success||u("Failed to add card. Please try again.")},Ea=async()=>{if(!s?.selectedCard){u("Please select a card");return}if(u(null),!y){let w=await ze();!w.success&&w.error&&u(w.error.message);return}try{let w=await _.authenticate(s.paymentIntent.id,s.paymentIntent.payments?.[0]?.id);if(w.success){let Y=await ze({passkeyAuthenticated:!0});!Y.success&&Y.error&&u(Y.error.message);return}if(w.requiresRegistration||w.error?.code==="NOT_ENROLLED"||w.error?.code==="DEVICE_NOT_REGISTERED"||w.message?.toLowerCase().includes("not enrolled")||w.message?.toLowerCase().includes("no enrollment")){let Y=await _.startRegistration(s.selectedCard.id);if(Y.requiresStepUp&&Y.network==="visa"){$t("AGENT_REGISTRATION"),oe("visa_method_select");return}if(Y.success){let st=await _.authenticate(s.paymentIntent.id,s.paymentIntent.payments?.[0]?.id);if(st.success){let qt=await ze({passkeyAuthenticated:!0});!qt.success&&qt.error&&u(qt.error.message)}else u(st.message||"Authentication failed after registration");return}u(Y.message||"Registration failed");return}u(w.message||"Authentication failed")}catch(w){let F=w instanceof Error?w.message:"Passkey authentication failed";u(F)}},Ta=async()=>{if(!s?.selectedCard?.id)return;u(null);let w=await _.startRegistration(s.selectedCard.id);w.requiresStepUp&&w.network==="visa"?oe("visa_method_select"):w.success?zt():u(w.message||"Registration failed")},Aa=async w=>{u(null);let F=parseInt(w,10);(await _.selectStepUpMethod(F)).success?(_e(""),oe("visa_otp_entry")):u("Failed to send verification code")},Oa=async()=>{if(!$e)return;u(null);let w=await _.submitVisaOtp($e);w.success&&w.registrationContext?(_e(""),Sr(w.registrationContext),oe("visa_iframe")):w.success||(_e(""),u(w.message||"Invalid verification code"))},_a=()=>{u(null),_.resetState(),et()},Da=s?.paymentIntent.payments.map(w=>({label:w.description||w.merchantName,value:Ee(w.subtotal,s.paymentIntent.currency),quantity:w.quantity})),Ma=s?.paymentIntent.totalSubtotal?Ee(s.paymentIntent.totalSubtotal,s.paymentIntent.currency):void 0,Va=s?.paymentIntent.totalTax?Ee(s.paymentIntent.totalTax,s.paymentIntent.currency):void 0,Ua=s?.paymentIntent.totalShipping?Ee(s.paymentIntent.totalShipping,s.paymentIntent.currency):void 0,La=s?.paymentIntent.facilitationFee?Ee(s.paymentIntent.facilitationFee.amount,s.paymentIntent.currency):void 0,Fa=s?Ee(s.paymentIntent.totalAmount+(s.paymentIntent.facilitationFee?.amount||0),s.paymentIntent.currency):void 0,Ba=()=>{if(c==="PAYMENT"){if(G==="methods")return"Payment Methods";if(G==="add")return A?"Add Card":"Secure Checkout"}return c==="AGENT_REGISTRATION"?"Authorization Required":o||"Checkout"},ot=h||g?.message,za=()=>{if(c==="LOADING")return Ut("div",{className:"flex flex-col items-center justify-center py-12 space-y-4",children:[D(eo,{className:"w-12 h-12 text-gray-400 animate-spin"}),D("p",{className:"text-gray-600 dark:text-slate-400",children:"Loading checkout..."})]});if(c==="ERROR")return Ut("div",{className:"flex flex-col items-center justify-center py-12 space-y-4 text-center",children:[D(ha,{className:"w-16 h-16 text-red-500"}),D("h3",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"Something went wrong"}),D("p",{className:"text-sm text-gray-600 dark:text-slate-400",children:g?.message||"Unable to load checkout session"}),D("button",{onClick:He,className:"mt-4 px-6 py-2 bg-gray-900 text-white rounded-lg hover:bg-gray-800 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-100",children:"Close"})]});if(c==="EXPIRED")return Ut("div",{className:"flex flex-col items-center justify-center py-12 space-y-4 text-center",children:[D(ha,{className:"w-16 h-16 text-amber-500"}),D("h3",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"Session Expired"}),D("p",{className:"text-sm text-gray-600 dark:text-slate-400",children:"This checkout session has expired. Please start a new checkout."}),D("button",{onClick:He,className:"mt-4 px-6 py-2 bg-gray-900 text-white rounded-lg hover:bg-gray-800 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-100",children:"Close"})]});if(c==="IDENTITY")return D(Ue,{phone:we,onPhoneChange:w=>{rt(w),u(null),Ht()},countryCode:Oe,onCountryChange:Yt,onSubmit:Sa,isLoading:d,error:ot||void 0});if(c==="OTP_VERIFY")return D(Ct,{phoneNumber:we,otp:v,onOtpChange:x,onSubmit:Pa,onEdit:P,onResend:Na,isLoading:d,isResending:E,error:ot||void 0,resendCooldown:V,retryCount:Gt,maxRetries:3});if(c==="AGENT_REGISTRATION"&&s){let w=s.selectedCard?.network||"visa";return ye==="visa_method_select"?D(_t,{methods:_.state.stepUpMethods.map((F,Y)=>({id:String(Y),type:F.type,maskedValue:F.maskedValue})),onSelectMethod:Aa,onBack:()=>oe("initial"),isLoading:_.state.isLoading}):ye==="visa_otp_entry"?D(Dt,{methodDescription:_.state.selectedMethodDescription||"your phone",otp:$e,onOtpChange:F=>{_e(F),h&&u(null),_.state.error&&_.clearError()},onVerify:Oa,onBack:()=>oe("visa_method_select"),onResend:async()=>{_e(""),u(null),_.clearError()},onVerifyAnotherWay:()=>{_e(""),u(null),_.clearError(),_.resetState(),oe("visa_method_select")},isLoading:_.state.isLoading,error:h||_.state.error||void 0,canRetry:_.state.canRetry}):ye==="visa_iframe"?D(vr,{onCancel:()=>oe("initial")}):D(Mt,{cardNetwork:w,onCreatePasskey:Ta,onSkip:h?_a:void 0,onBack:X,isLoading:_.state.isLoading,error:h||void 0,showSkip:!!h,paymentIntent:s.paymentIntent,merchantName:s.paymentIntent.payments[0]?.merchantName||"Merchant"})}if(c==="PAYMENT"&&s){if(G==="checkout"&&L&&s.selectedCard){let w=d||_.state.isLoading;return D(Pt,{selectedCard:s.selectedCard,cvc:k,onCvcChange:S,onChangeCard:K,paymentIntent:s.paymentIntent,onSubmit:Ea,isLoading:w,error:ot||void 0})}if(G==="methods")return D(It,{cards:s.savedCards||[],selectedCardId:s.selectedCard?.id||null,onSelectCard:Ia,onAddNewCard:J,onBack:L?X:He,onDeleteCard:Bt});if(G==="add")return D(At,{linkToken:s.linkToken,walletUserId:s.paymentIntent.walletUserId,onSubmit:Ra,onBack:A?K:void 0,isLoading:d,error:ot||void 0,isFirstCard:!A,customBaseUrl:m||ga.customBaseUrl,environment:p,devApiUrl:f})}return c==="PROCESSING"?Ut("div",{className:"flex flex-col items-center justify-center py-12 space-y-4",children:[D("div",{className:"w-16 h-16 border-4 border-gray-200 dark:border-slate-700 border-t-black dark:border-t-white rounded-full animate-spin"}),D("p",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:y?"Generating Credentials...":"Processing Payment..."}),D("p",{className:"text-sm text-gray-600 dark:text-slate-400",children:"Please wait while we process your request"})]}):c==="SUCCESS"&&s?D(Ot,{paymentIntent:s.paymentIntent,walletUser:s.walletUser,cardNetwork:s.selectedCard?.network,onDismiss:He,passkeyEnrolled:s.selectedCard?.passkeyEnrolled}):null};return r?D(ht,{open:r,onClose:He,title:Ba(),amount:Fa,orderItems:Da,subtotal:Ma,shipping:Ua,tax:Va,orderAgentFee:La,mode:y?"agent":"standard",children:za()}):null};import{useState as Lt,useCallback as te}from"react";var kr=e=>new Promise(r=>setTimeout(r,e)),ya=async e=>{console.log("[Mock] Sending OTP to:",e),await kr(800),console.log("[Mock] OTP sent successfully")},wa=async e=>{console.log("[Mock] Verifying OTP:",e),await kr(500);let r=e==="123456"||e.length===6;return console.log("[Mock] OTP verification result:",r),r},ba=async e=>{console.log("[Mock] Processing payment:",e),await kr(2e3);let r={success:!0,transactionId:`txn_mock_${Date.now()}`,amount:e.amount,cardLast4:e.cardData.last4,timestamp:Date.now()};return console.log("[Mock] Payment processed successfully:",r),r};function ro({mode:e,amount:r,savedCards:t,onSuccess:a,onError:n}){let[i,o]=Lt({phase:"PHONE_INPUT",phoneNumber:"",email:"",cardData:null,billingAddress:null,error:null,isLoading:!1}),[p,l]=Lt(t&&t.length>0?t.find(I=>I.isDefault)?.id||t[0].id:null),[f,m]=Lt(t&&t.length>0?"checkout":"add"),[N,b]=Lt(""),s=te(I=>{o(P=>({...P,error:I,isLoading:!1}))},[]),c=te(I=>{o(P=>({...P,isLoading:I}))},[]),d=te(async I=>{c(!0),s(null);try{await ya(I),o(P=>({...P,phoneNumber:I,phase:"OTP_VERIFY",isLoading:!1}))}catch(P){s("Failed to send OTP. Please try again."),n?.(P)}},[c,s,n]),g=te(async I=>{c(!0),s(null);try{if(await wa(I))if(o(C=>({...C,phase:"PAYMENT",isLoading:!1})),t&&t.length>0){m("checkout");let C=t.find(H=>H.isDefault)||t[0];l(C.id)}else m("add"),l(null);else s("Invalid code. Please try again.")}catch(P){s("Failed to verify OTP. Please try again."),n?.(P)}},[c,s,n,t]),y=te(async(I,P,C)=>{c(!0),s(null),o(H=>({...H,phase:"PROCESSING"}));try{let H=await ba({phoneNumber:i.phoneNumber,email:I,cardData:P,amount:r,mode:e});o(ne=>({...ne,email:I,cardData:P,billingAddress:C,phase:"SUCCESS",isLoading:!1})),setTimeout(()=>{a?.(H)},3e3)}catch(H){s("Payment failed. Please try again."),o(ne=>({...ne,phase:"PAYMENT"})),n?.(H)}},[i.phoneNumber,r,e,s,a,n]),L=te(I=>{l(I),m("checkout")},[]),A=te(async I=>{c(!0),s(null);try{await new Promise(P=>setTimeout(P,500)),o(P=>({...P,cardData:I,isLoading:!1})),e==="agent"?o(P=>({...P,phase:"AGENT_REGISTRATION"})):m("checkout")}catch(P){s("Failed to add card. Please try again."),n?.(P)}},[c,s,n,e]),G=te(()=>{if(o({phase:"PHONE_INPUT",phoneNumber:"",email:"",cardData:null,billingAddress:null,error:null,isLoading:!1}),t&&t.length>0){let I=t.find(P=>P.isDefault)||t[0];l(I.id),m("checkout")}else l(null),m("add");b("")},[t]),k=te(()=>{m("methods")},[]),S=te(()=>{m("add")},[]),K=te(()=>{m("checkout")},[]),J=te(()=>{if(o(I=>({...I,phase:"PAYMENT",phoneNumber:"+15551234567",error:null,isLoading:!1})),t&&t.length>0){let I=t.find(P=>P.isDefault)||t[0];l(I.id),m("checkout")}else l(null),m("add");b("")},[t]),X=te(()=>{o(I=>({...I,phase:"PAYMENT"})),m("checkout")},[]);return{state:i,selectedCardId:p,paymentView:f,cvc:N,setCvc:b,submitPhone:d,verifyOTP:g,submitPayment:y,selectCard:L,addCard:A,logout:G,setError:s,showMethodList:k,showAddCard:S,returnToCheckout:K,skipToPayment:J,completeAgentRegistration:X}}var Ae=[{id:"card_visa_001",brand:"visa",last4:"4242",expiryMonth:"12",expiryYear:"2027",cardholderName:"John Doe",isDefault:!0,network:"visa",passkeyEnrolled:!0,cardArtUrl:"https://cdn.payos.io/card-art/visa-signature-blue.png"},{id:"card_mc_002",brand:"mastercard",last4:"5555",expiryMonth:"08",expiryYear:"2026",cardholderName:"John Doe",isDefault:!1,network:"mastercard",passkeyEnrolled:!1,cardArtUrl:"https://cdn.payos.io/card-art/mastercard-world-elite.png"},{id:"card_amex_003",brand:"amex",last4:"0005",expiryMonth:"03",expiryYear:"2028",cardholderName:"John Doe",isDefault:!1,network:"amex",passkeyEnrolled:!1,cardArtUrl:"https://cdn.payos.io/card-art/amex-platinum.png"}],Be={id:"wu_mock_001",email:"john.doe@example.com",phone:"+14155551234",firstName:"John",lastName:"Doe",defaultCardId:"card_visa_001"};function Ce(e){let r=new Date().toISOString();return{id:`pay_${Date.now()}_${Math.random().toString(36).substring(7)}`,merchantUrl:void 0,merchantCategory:void 0,merchantCategoryCode:void 0,description:void 0,quantity:1,expiresAt:void 0,selectedCardId:void 0,credentialId:void 0,credentialStatus:"not_created",mandateId:void 0,assignedChildIntentId:void 0,status:"pending",createdAt:r,updatedAt:r,...e}}function Ze(e){let r=new Date().toISOString(),{payments:t,totalAmount:a,...n}=e,i=t.reduce((f,m)=>f+m.subtotal,0),o=t.reduce((f,m)=>f+(m.tax??0),0),p=t.reduce((f,m)=>f+(m.shipping??0),0),l=a??i+o+p;return{id:`payint_${Date.now()}`,type:"online_checkout",currency:"USD",walletUserId:void 0,organizationId:"org_demo_001",status:"created",payments:t,totalAmount:l,totalSubtotal:i,totalTax:o||void 0,totalShipping:p||void 0,consumerPrompt:void 0,intentType:"standard",parentIntentId:void 0,selectedCardId:void 0,networkProvider:void 0,networkInstructionId:void 0,requireHitl:!1,hitlAttemptCount:0,hitlApproved:!1,networkAuthRequired:!0,networkAuthCompleted:!1,authData:void 0,authValid:!1,authSubmittedAt:void 0,authInvalidatedAt:void 0,authInvalidReason:void 0,credentialType:"network_token_long",riskAssessment:void 0,createdAt:r,updatedAt:r,...n}}var Qe=Ze({id:"payint_online_001",type:"online_checkout",payments:[Ce({id:"pay_online_001",merchantName:"Demo Store",merchantUrl:"https://demo-store.example.com",amount:21136,subtotal:19525,tax:1611,description:"Order #12345"})]}),Cr=Ze({id:"payint_agent_001",type:"pay_on_behalf",facilitationFee:{amount:100,currency:"usd"},payments:[Ce({id:"pay_agent_001",merchantName:"Agent Commerce",merchantUrl:"https://agent.example.com",amount:1e3,subtotal:1e3,tax:100,shipping:100,description:"Agent-assisted purchase"})]}),xa=Ze({id:"payint_multi_001",type:"agentic_multi",requireHitl:!0,consumerPrompt:"Complete your shopping cart",payments:[Ce({id:"pay_multi_001",merchantName:"Amazon",merchantUrl:"https://amazon.com",amount:5911,subtotal:4999,tax:412,shipping:500,description:"Wireless Headphones",quantity:1}),Ce({id:"pay_multi_002",merchantName:"Best Buy",merchantUrl:"https://bestbuy.com",amount:14072,subtotal:12999,tax:1073,description:"USB-C Hub",quantity:1}),Ce({id:"pay_multi_003",merchantName:"Target",merchantUrl:"https://target.com",amount:2705,subtotal:2499,tax:206,description:"Phone Case",quantity:2})]}),Xd=Ze({id:"payint_small_001",type:"online_checkout",payments:[Ce({id:"pay_small_001",merchantName:"Quick Shop",amount:1081,subtotal:999,tax:82,description:"Test purchase"})]}),ao={id:"ses_new_001",status:"initialized",paymentIntent:{...Qe},organizationId:"org_demo_001",deviceVerified:!1,savedCards:[],linkToken:"link_tok_new_001_mock",expiresAt:new Date(Date.now()+60*60*1e3).toISOString(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},no={id:"ses_return_001",status:"verified",paymentIntent:{...Qe},walletUser:{...Be},organizationId:"org_demo_001",deviceVerified:!0,savedCards:[...Ae],linkToken:"link_tok_return_001_mock",expiresAt:new Date(Date.now()+60*60*1e3).toISOString(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},oo={id:"ses_agent_001",status:"initialized",paymentIntent:{...Cr},organizationId:"org_agent_001",deviceVerified:!1,savedCards:[],linkToken:"link_tok_agent_001_mock",expiresAt:new Date(Date.now()+60*60*1e3).toISOString(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},so={id:"ses_agent_002",status:"verified",paymentIntent:{...Cr},walletUser:{...Be},organizationId:"org_agent_001",deviceVerified:!0,savedCards:[...Ae],linkToken:"link_tok_agent_002_mock",expiresAt:new Date(Date.now()+60*60*1e3).toISOString(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},io={id:"ses_multi_001",status:"initialized",paymentIntent:{...xa},organizationId:"org_agent_001",deviceVerified:!1,savedCards:[],linkToken:"link_tok_multi_001_mock",expiresAt:new Date(Date.now()+60*60*1e3).toISOString(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},lo={id:"ses_multi_002",status:"verified",paymentIntent:{...xa},walletUser:{...Be},organizationId:"org_agent_001",deviceVerified:!0,savedCards:[...Ae],linkToken:"link_tok_multi_002_mock",expiresAt:new Date(Date.now()+60*60*1e3).toISOString(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},co={id:"ses_otp_001",status:"otp_pending",paymentIntent:{...Qe},organizationId:"org_demo_001",deviceVerified:!1,verificationMethod:"phone",savedCards:[],linkToken:"link_tok_otp_001_mock",expiresAt:new Date(Date.now()+60*60*1e3).toISOString(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},po={id:"ses_payment_001",status:"payment_pending",paymentIntent:{...Qe},walletUser:{...Be},organizationId:"org_demo_001",deviceVerified:!0,savedCards:[...Ae],selectedCard:{...Ae[0]},linkToken:"link_tok_payment_001_mock",expiresAt:new Date(Date.now()+60*60*1e3).toISOString(),createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};function va(e={}){let{type:r="online_checkout",status:t="initialized",hasWalletUser:a=!1,hasSavedCards:n=!1,deviceVerified:i=!1,amount:o,subtotal:p,tax:l,shipping:f,merchantName:m,payments:N}=e,b=new Date,s;if(N&&N.length>0)s=N.map((g,y)=>Ce({id:`pay_custom_${Date.now()}_${y}`,merchantName:g.merchantName,amount:g.amount,subtotal:g.subtotal,tax:g.tax,shipping:g.shipping,description:g.description}));else{let g=r==="pay_on_behalf"||r==="agentic_multi"?Cr.payments[0]:Qe.payments[0];s=[Ce({...g,id:`pay_${Date.now()}`,...o!==void 0&&{amount:o},...p!==void 0&&{subtotal:p},...l!==void 0&&{tax:l},...f!==void 0&&{shipping:f},...m!==void 0&&{merchantName:m}})]}let c=Ze({id:`payint_${Date.now()}`,type:r,payments:s,requireHitl:r==="pay_on_behalf"||r==="agentic_multi"}),d=`ses_${Date.now()}`;return{id:d,status:t,paymentIntent:c,walletUser:a?{...Be}:void 0,organizationId:"org_demo_001",deviceVerified:i,savedCards:n?[...Ae]:[],selectedCard:void 0,linkToken:`link_tok_${d}_${Math.random().toString(36).slice(2)}`,expiresAt:new Date(b.getTime()+60*60*1e3).toISOString(),createdAt:b.toISOString(),updatedAt:b.toISOString()}}var ka={ses_new_001:ao,ses_return_001:no,ses_agent_001:oo,ses_agent_002:so,ses_multi_001:io,ses_multi_002:lo,ses_otp_001:co,ses_payment_001:po};var mo="https://sandbox.api.payos.ai",Ca=new Map;Object.entries(ka).forEach(([e,r])=>{Ca.set(e,JSON.parse(JSON.stringify(r)))});function uo(e){return{id:e.id,type:e.type,currency:e.currency,walletUserId:e.walletUserId,organizationId:e.organizationId,status:e.status,payments:e.payments.map(r=>({id:r.id,merchantName:r.merchantName,merchantUrl:r.merchantUrl,merchantCategory:r.merchantCategory,merchantCategoryCode:r.merchantCategoryCode,amount:r.amount,subtotal:r.subtotal||r.amount,tax:r.tax,shipping:r.shipping,description:r.description,quantity:r.quantity||1,selectedCardId:r.selectedCardId,credentialId:r.credentialId,credentialStatus:r.credentialStatus||"not_created",status:r.status||"pending",createdAt:r.createdAt,updatedAt:r.updatedAt})),totalAmount:e.totalAmount,totalSubtotal:e.totalSubtotal||e.totalAmount,totalTax:e.totalTax,totalShipping:e.totalShipping,consumerPrompt:e.consumerPrompt,intentType:e.intentType||"standard",selectedCardId:e.selectedCardId,requireHitl:e.requireHitl||!1,hitlAttemptCount:e.hitlAttemptCount||0,hitlApproved:e.hitlApproved||!1,networkAuthRequired:e.networkAuthRequired??!0,networkAuthCompleted:e.networkAuthCompleted||!1,authValid:e.authValid||!1,credentialType:e.credentialType||"network_token_long",createdAt:e.createdAt,updatedAt:e.updatedAt}}async function go(e){console.log("[Mock] Creating test session with REAL payment intent...");let r=await ua();console.log("[Mock] Link token fetched");let{sessionOptions:t,...a}=e,n=await Qr(mo,r.token,a);console.log("[Mock] Real payment intent created:",n.id);let i=`ses_real_${Date.now()}`,o=va(t||{});return o.id=i,o.paymentIntent=uo(n),o.linkToken=r.token,Ca.set(i,o),console.log("[Mock] Test session created with REAL payment intent:",{sessionId:i,paymentIntentId:n.id,type:n.type,totalAmount:n.totalAmount,paymentsCount:n.payments.length}),i}export{xt as ActiveCardWidget,Mt as AgentRegistrationView,M as Button,O as Card,At as CardAddView,Ar as CardContent,Tr as CardDescription,Or as CardFooter,Rr as CardHeader,Er as CardTitle,Pt as CheckoutView,Ue as IdentityView,Ir as Input,Dr as Label,It as MethodListView,Me as OTPInput,Ct as OTPView,Gr as OrderSummary,ht as PayOSDrawer,ut as PayOSFooter,bt as PaymentMethodRow,to as PaymentSheet,lt as PhoneInput,Ye as PriceTag,mt as ReceiptPanel,Vr as Separator,Ot as SuccessView,Q as ViewHeader,_t as VisaMethodView,Dt as VisaOtpView,pt as WelcomeBackView,R as cn,go as createTestSessionWithRealIntent,tr as useBodyScrollLock,ro as useCheckoutFlow,wr as useSession,gt as useVisualViewport,wn as useVisualViewportStyle};
|
|
23
|
+
`,children:[ae("div",{className:"flex-shrink-0",children:o(n.type)}),ae("div",{className:"flex-1 text-left",children:ae("p",{className:"text-sm font-medium text-slate-900 dark:text-white",children:i(n.type,n.maskedValue)})}),ae("div",{className:"flex-shrink-0",children:ae(Ro,{className:"w-5 h-5",style:{color:$e}})})]},n.id))})]})};Et.displayName="VisaMethodView";import*as We from"react";import{ShieldCheck as Eo}from"lucide-react";import{jsx as de,jsxs as Ge}from"react/jsx-runtime";var Ye="#0055BB",It=({methodDescription:e,otp:r,onOtpChange:t,onVerify:a,onBack:o,onResend:i,onVerifyAnotherWay:n,isLoading:p=!1,error:l,canRetry:h=!0})=>{let m=We.useRef(!1);We.useEffect(()=>{r.length<6&&(m.current=!1)},[r]);let E=s=>{s.preventDefault(),r.length===6&&h&&!p&&(m.current=!0,a())};We.useEffect(()=>{r.length===6&&!p&&h&&!m.current&&(m.current=!0,a())},[r,p,a,h]);let v=!h;return Ge("form",{onSubmit:E,className:"space-y-4",children:[Ge("div",{className:"flex items-center justify-center gap-2 py-2",children:[de(Eo,{className:"w-5 h-5",style:{color:Ye}}),de("span",{className:"text-sm font-semibold",style:{color:Ye},children:"Verified by Visa"})]}),de(Z,{title:"Enter Bank Code",onBack:o}),Ge("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center px-4",children:["Code sent to ",e]}),Ge(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-6",children:[de("div",{className:p||v?"opacity-50 pointer-events-none":"",children:de(Ve,{value:r,onChange:t,length:6})}),l&&de("p",{className:"text-sm text-red-600 dark:text-red-400 text-center",children:l}),de(M,{type:"submit",className:"w-full",style:{backgroundColor:Ye},disabled:r.length!==6||p||v,isLoading:p,loadingText:"Verifying...",children:"Verify"}),v&&n&&de("div",{className:"text-center",children:de("button",{type:"button",onClick:n,className:"text-sm hover:underline",style:{color:Ye},children:"Verify another way"})}),i&&!v&&de("div",{className:"text-center mt-4",children:Ge("p",{className:"text-xs text-gray-500 dark:text-slate-400",children:["Didn't receive a code?"," ",de("button",{type:"button",onClick:i,disabled:p,className:"font-bold hover:underline disabled:opacity-50",style:{color:Ye},children:"Resend"})]})})]})]})};It.displayName="VisaOtpView";import{Sparkles as Io,Fingerprint as To,AlertCircle as Ao}from"lucide-react";import{jsx as Q,jsxs as je}from"react/jsx-runtime";var Tt=({cardNetwork:e,onCreatePasskey:r,onSkip:t,onBack:a,isLoading:o=!1,error:i,showSkip:n=!1})=>je("div",{className:"space-y-4",children:[je(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-4",children:[Q("div",{className:"flex justify-center",children:Q("div",{className:"w-12 h-12 bg-indigo-100 dark:bg-indigo-900/30 rounded-full flex items-center justify-center",children:Q(Io,{className:"w-6 h-6 text-indigo-600 dark:text-indigo-400"})})}),Q("h2",{className:"text-xl font-bold text-slate-900 dark:text-white text-center",children:"One final step"}),Q("p",{className:"text-sm text-gray-600 dark:text-slate-400 text-center leading-relaxed",children:"To allow the AI Agent to securely purchase this item for you, you must enable biometric access."})]}),e==="visa"&&Q("div",{id:"visa-auth-container",className:"w-full max-w-md mx-auto min-h-[10px] bg-gray-50 dark:bg-slate-800 rounded-2xl overflow-hidden"}),je(O,{className:"w-full max-w-md mx-auto shadow-sm border border-gray-200 dark:border-slate-700 rounded-2xl p-6 space-y-4",children:[i&&je("div",{className:"flex items-center gap-2 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 rounded-lg",children:[Q(Ao,{className:"w-4 h-4 text-red-500 flex-shrink-0"}),Q("p",{className:"text-sm text-red-700 dark:text-red-300",children:i})]}),je(M,{onClick:r,className:"w-full",disabled:o,isLoading:o,loadingText:e==="mastercard"?"Creating Passkey...":"Verifying...",children:[Q(To,{className:"w-5 h-5 mr-2"}),e==="visa"?"Create Visa Passkey":"Create Mastercard Passkey"]}),n&&t&&Q("button",{type:"button",onClick:t,disabled:o,className:"w-full text-sm text-gray-500 dark:text-slate-400 hover:underline disabled:opacity-50",children:"Skip for now"}),Q("p",{className:"text-xs text-gray-500 dark:text-slate-400 text-center",children:"This grants the agent permission for this specific transaction."})]}),a&&Q("div",{className:"text-center px-4 mt-4",children:Q("button",{type:"button",onClick:a,disabled:o,className:"text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",children:"Back to checkout"})})]});Tt.displayName="AgentRegistrationView";import{useEffect as Ie,useCallback as sa,useState as he,useRef as Fo}from"react";import{Loader2 as zo,AlertCircle as ia}from"lucide-react";import{useState as fe,useEffect as dr,useCallback as F,useRef as lr}from"react";var U=class extends Error{constructor(t,a,o){super(t);this.name="ApiError",this.status=a,this.details=o}};function zr(e){if(!e)return e;let r=e.startsWith("+"),t=e.replace(/\D/g,"");return r?`+${t}`:t.length===10?`+1${t}`:t.length===11&&t.startsWith("1")?`+${t}`:`+${t}`}function Hr(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}}async function ee(e,r,t,a={}){let o=`${e}${r}`,i={"Content-Type":"application/json",Authorization:`Bearer ${t}`,"ngrok-skip-browser-warning":"true"};try{let n=await fetch(o,{...a,headers:{...i,...a.headers}}),p=n.headers.get("content-type"),l;if(p&&p.includes("application/json"))l=await n.json();else{let h=await n.text();try{l=JSON.parse(h)}catch{throw h.includes("<!DOCTYPE")||h.includes("<html")?new U("Received HTML instead of JSON. Ngrok bypass header may not be working.",n.status,"HTML response received"):new U("Invalid JSON response from server",n.status,h.substring(0,200))}}if(!n.ok)throw new U(l.message||"An error occurred",n.status);return l}catch(n){throw n instanceof U?n:new U(n instanceof Error?n.message:"Network error",0)}}async function nr(e,r,t){let a=zr(t);console.log("[ApiService] Sending OTP to:",t,"\u2192",a);let o=await ee(e,"/api/otp/payos-link/generate",r,{method:"POST",body:JSON.stringify({phone:a,channel:"sms"})});if(o.error||!o.data)throw new U(o.message||"Failed to send verification code",400);return console.log("[ApiService] OTP sent, reference:",o.data.reference),o.data.reference}async function $r(e,r,t,a){console.log("[ApiService] Verifying OTP, reference:",t);let o=await ee(e,"/api/otp/payos-link/verify",r,{method:"POST",body:JSON.stringify({reference:t,code:a})});if(o.error||!o.data)throw new U(o.message||"Invalid verification code",400);return console.log("[ApiService] OTP verified for phone:",o.data.phone),o.data}async function Oo(e,r,t){let a=await ee(e,`/api/otp/payos-link/status/${t}`,r,{method:"GET"});if(a.error||!a.data)throw new U(a.message||"Failed to get verification status",400);return a.data}async function Yr(e,r,t,a){console.log("[ApiService] Resending OTP, previous reference:",t);try{let o=await Oo(e,r,t),i=new Date(o.createdAt),n=Date.now()-i.getTime(),p=30*1e3;if(n<p&&o.status==="pending"){let h=Math.ceil((p-n)/1e3);return console.log("[ApiService] Rate limited, wait time remaining:",h),{reference:t,waitTimeRemaining:h}}return{reference:await nr(e,r,a)}}catch(o){throw console.error("[ApiService] Failed to resend verification:",o),o}}async function Gr(e,r,t,a){let o=zr(t);console.log("[ApiService] Processing verified wallet user, phone:",t,"\u2192",o);let i=await ee(e,"/api/wallet-users/process-verified-wallet-user",r,{method:"POST",body:JSON.stringify({phone:o,verificationId:a})});if(i.error||!i.data)throw new U(i.message||"Failed to process wallet user",400);let n=(i.data.savedCards||[]).map(Hr);return console.log("[ApiService] Wallet user processed:",{walletUserId:i.data.walletUserId,isNewUser:i.data.isNewUser,savedCardsCount:n.length}),{...i.data,savedCards:n}}async function Wr(e,r,t){console.log("[ApiService] Getting cards for wallet user:",t);let a=await ee(e,`/api/wallet-users/${t}/cards`,r,{method:"GET"});if(a.error)throw new U(a.message||"Failed to get wallet user cards",400);return(a.data||[]).map(Hr)}async function sr(e,r){console.log("[ApiService] Getting current session");let t=await ee(e,"/web/sessions/current",r,{method:"GET"});if(t.error||!t.data)throw new U(t.message||"Failed to get session",400);return t.data}async function jr(e,r){console.log("[ApiService] Starting session");let t=await ee(e,"/web/sessions/current/start",r,{method:"PATCH"});if(t.error||!t.data)throw new U(t.message||"Failed to start session",400);return console.log("[ApiService] Session started:",t.data.id),t.data}async function Kr(e,r){console.log("[ApiService] Completing session");let t=await ee(e,"/web/sessions/current/complete",r,{method:"POST"});if(t.error||!t.data)throw new U(t.message||"Failed to complete session",400);return console.log("[ApiService] Session completed:",t.data.id),t.data}async function qr(e,r){console.log("[ApiService] Abandoning session");let t=await ee(e,"/web/sessions/current/abandon",r,{method:"POST"});if(t.error||!t.data)throw new U(t.message||"Failed to abandon session",400);return console.log("[ApiService] Session abandoned:",t.data.id),t.data}async function Ke(e,r,t){console.log("[ApiService] Updating session payment intent:",t);let a=await ee(e,"/web/sessions/current/payment-intent",r,{method:"PATCH",body:JSON.stringify(t)});if(a.error||!a.data)throw new U(a.message||"Failed to update payment intent",400);return console.log("[ApiService] Session payment intent updated"),a.data}async function Xr(e,r,t){console.log("[ApiService] Generating credentials for payment intent:",t);let a=`${e}/api/payment-credentials/generate`,o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`,"ngrok-skip-browser-warning":"true"},body:JSON.stringify({paymentIntentId:t})}),i=o.headers.get("content-type"),n;if(i&&i.includes("application/json"))n=await o.json();else{let p=await o.text();try{n=JSON.parse(p)}catch{throw new U("Invalid response from credential generation",o.status,p.substring(0,200))}}if(!o.ok)throw new U(n.message||"Failed to generate credentials",o.status,n.data?.status);return console.log("[ApiService] Credential generation result:",n.data?.status||n.message),{status:n.data?.status||"success",message:n.message,retrievalToken:n.data?.retrievalToken,approvalId:n.data?.approvalId}}async function Jr(e,r,t,a){console.log("[ApiService] Deleting card:",{walletUserId:t,cardId:a});let o=await ee(e,`/api/wallet-users/${t}/cards/${a}`,r,{method:"DELETE"});if(o.error)throw new U(o.message||"Failed to delete card",400);return console.log("[ApiService] Card deleted successfully"),{success:!0}}async function Zr(e,r,t,a){console.log("[ApiService] Checking device trust:",{deviceId:t,walletUserId:a});let o=new URLSearchParams({deviceId:t});a&&o.set("walletUserId",a);let i=await ee(e,`/web/device-trust?${o}`,r,{method:"GET"});return i.error?(console.warn("[ApiService] Device trust check failed, defaulting to untrusted"),{isTrusted:!1}):(console.log("[ApiService] Device trust result:",i.data),{isTrusted:i.data?.isTrusted??!1,expiresAt:i.data?.expiresAt,walletUserId:i.data?.walletUserId})}async function Qr(e,r,t,a){return console.log("[ApiService] Registering trusted device:",{deviceId:t,walletUserId:a}),(await ee(e,"/web/device-trust",r,{method:"POST",body:JSON.stringify({deviceId:t,walletUserId:a})})).error?(console.warn("[ApiService] Device trust registration failed"),{success:!1}):(console.log("[ApiService] Device registered as trusted"),{success:!0})}var ea="payos_device_id",Vo="payos_device_created";function Lo(){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 r=navigator;e.push(String(r.deviceMemory||0));let t=e.join("|");return Mo(t)}function Mo(e){let r=2166136261;for(let t=0;t<e.length;t++)r^=e.charCodeAt(t),r=Math.imul(r,16777619);return(r>>>0).toString(16).padStart(8,"0")}function ta(){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function ir(){try{let e=localStorage.getItem(ea);if(e)return e;let r=Lo(),t=ta().substring(0,8),a=`${r}-${t}`;return localStorage.setItem(ea,a),localStorage.setItem(Vo,new Date().toISOString()),a}catch{return ta()}}function cr(e,r){let{apiBaseUrl:t}=r,[a,o]=fe(null),[i,n]=fe("LOADING"),[p,l]=fe(!0),[h,m]=fe(null),[E,v]=fe("checkout"),[s,c]=fe(""),[d,u]=fe("initial"),[w,_]=fe(null),[A,G]=fe(null),k=lr(!0),S=lr(e),j=lr(!1);dr(()=>{S.current!==e&&(j.current=!1),S.current=e},[e]);let q=F((x,y)=>{let{session:f,paymentIntent:g}=x,I=g?{id:g.id,type:g.type,currency:g.currency,organizationId:g.organizationId,status:g.status,totalAmount:g.totalAmount,totalSubtotal:g.totalSubtotal??g.totalAmount,totalTax:g.totalTax,totalShipping:g.totalShipping,payments:g.payments.map(D=>({id:D.id,merchantName:D.merchantName,merchantUrl:D.merchantUrl,amount:D.amount,subtotal:D.subtotal||D.amount,tax:D.tax,shipping:D.shipping,description:D.description,quantity:D.quantity,credentialStatus:D.credentialStatus,status:D.status,createdAt:D.createdAt,updatedAt:D.updatedAt})),intentType:g.intentType||"standard",walletUserId:g.walletUserId,selectedCardId:g.selectedCardId,requireHitl:g.requireHitl??!1,hitlAttemptCount:g.hitlAttemptCount??0,hitlApproved:g.hitlApproved??!1,networkAuthRequired:g.networkAuthRequired??!1,networkAuthCompleted:g.networkAuthCompleted??!1,authValid:g.authValid??!1,credentialType:g.credentialType||"pci_vault_token",createdAt:g.createdAt,updatedAt:g.updatedAt,facilitationFee:void 0}:y?.paymentIntent;if(!I)throw new Error("No payment intent available");let T="initialized";return f.status==="complete"?T="completed":f.status==="expired"?T="expired":f.status==="abandoned"?T="abandoned":y?.deviceVerified&&(T="verified"),{id:f.id,status:T,organizationId:f.organizationId,paymentIntent:I,linkToken:S.current,walletUser:y?.walletUser,savedCards:y?.savedCards||[],selectedCard:y?.selectedCard,deviceVerified:y?.deviceVerified||!1,verificationMethod:"phone",verificationReference:w||"",verificationPhone:A||"",expiresAt:f.expiresAt,createdAt:f.createdAt,updatedAt:f.updatedAt}},[w,A]),X=F(x=>{if(!x)return"LOADING";switch(x.status){case"initialized":return x.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"}},[]);dr(()=>(k.current=!0,j.current?void 0:((async()=>{j.current=!0,l(!0),m(null);try{let y=await sr(t,e),f=y.paymentIntent?.status;if(f&&["approved","credentials_ready","completed","awaiting_payment"].includes(f)){k.current&&(m({code:"PAYMENT_INTENT_ALREADY_PROCESSED",message:f==="completed"?"This payment has already been completed.":f==="awaiting_payment"?"This payment is already in progress.":"This payment has already been approved. Use the credentials API to retrieve or regenerate.",sessionId:y.session.id}),n("ERROR"));return}await jr(t,e);let I=q(y),T=y.paymentIntent?.walletUserId;if(T)try{let D=ir();if((await Zr(t,e,D,T)).isTrusted){console.log("[useSession] Device is trusted, skipping OTP verification"),I.deviceVerified=!0,I.status="verified";let Bt=await Wr(t,e,T);if(I.walletUser={id:T},I.savedCards=Bt||[],I.savedCards.length>0){let Qe=I.savedCards.find(Be=>Be.isDefault)||I.savedCards[0];I.selectedCard=Qe}}}catch{console.log("[useSession] Device trust check failed, requiring OTP")}k.current&&(o(I),n(X(I)))}catch(y){if(k.current){let f=y,g=f.status===410||f.message?.toLowerCase().includes("expired");m({code:g?"SESSION_EXPIRED":"LOAD_FAILED",message:f.message||"Failed to load session",sessionId:e}),n(g?"EXPIRED":"ERROR")}}finally{k.current&&l(!1)}})(),()=>{k.current=!1})),[e,X,q,t]);let R=a?.paymentIntent.type==="pay_on_behalf"||a?.paymentIntent.type==="agent_to_agent"||a?.paymentIntent.type==="agentic_multi",P=!!a?.selectedCard,C=(a?.savedCards?.length??0)>0;dr(()=>{i==="PAYMENT"&&v(P?"checkout":C?"methods":"add")},[i,P,C]);let $=F(()=>{v("methods")},[]),oe=F(()=>{v("add")},[]),Vt=F(()=>{v(P?"checkout":C?"methods":"add")},[P,C]),Lt=F(()=>{n("IDENTITY")},[]),be=F(async x=>{if(!a||!x.phone)return!1;l(!0);try{let y=await nr(t,S.current,x.phone);return k.current&&(_(y),G(x.phone),o(f=>f?{...f,status:"otp_pending",verificationReference:y,verificationPhone:x.phone}:null),n("OTP_VERIFY")),!0}catch(y){let f=y;return k.current&&m({code:"VERIFICATION_FAILED",message:f.message||"Failed to send verification",sessionId:a.id}),!1}finally{k.current&&l(!1)}},[a,t]),ne=F(async x=>{if(!a||!w||!A)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session or verification context"}};l(!0);try{let y=await $r(t,S.current,w,x),f=await Gr(t,S.current,y.phone,y.reference);if(k.current){let g,I;if(a.paymentIntent.selectedCardId?g=f.savedCards.find(T=>T.id===a.paymentIntent.selectedCardId):f.savedCards.length>0&&(g=f.savedCards.find(T=>T.isDefault)||f.savedCards[0],I=g?.id),I)try{await Ke(t,S.current,{selectedCardId:I})}catch(T){console.warn("[useSession] Failed to auto-select card on backend:",T)}o(T=>T?{...T,status:"verified",deviceVerified:!0,walletUser:{id:f.walletUserId,phone:y.phone},savedCards:f.savedCards,selectedCard:g,paymentIntent:{...T.paymentIntent,walletUserId:f.walletUserId,...I&&{selectedCardId:I}}}:null),n("PAYMENT");try{let T=ir();await Qr(t,S.current,T,f.walletUserId),console.log("[useSession] Device registered as trusted for 90 days")}catch(T){console.warn("[useSession] Failed to register device trust:",T)}}return{success:!0,walletUserId:f.walletUserId}}catch(y){let g={success:!1,error:{code:"INVALID_OTP",message:y.message||"Invalid verification code"}};return k.current&&m({code:g.error.code,message:g.error.message,sessionId:a.id}),g}finally{k.current&&l(!1)}},[a,w,A,t]),qe=F(async()=>{if(!a||!w||!A)return!1;l(!0);try{let x=await Yr(t,S.current,w,A);return x.waitTimeRemaining?!1:(k.current&&x.reference!==w&&_(x.reference),!0)}catch{return!1}finally{k.current&&l(!1)}},[a,w,A,t]),Mt=F(async x=>{if(!a)return!1;l(!0);try{await Ke(t,S.current,{selectedCardId:x});let y=a.savedCards.find(f=>f.id===x);return k.current&&(o(f=>f?{...f,selectedCard:y,paymentIntent:{...f.paymentIntent,selectedCardId:x}}:null),v("checkout")),!0}catch(y){let f=y;return k.current&&m({code:"CARD_SELECT_FAILED",message:f.message||"Failed to select card",sessionId:a.id}),!1}finally{k.current&&l(!1)}},[a,t]),Dt=F(async x=>{if(!a)return{success:!1};l(!0);try{let y={id:x.cardId,brand:x.brand?.toLowerCase()||"unknown",last4:x.last4,expiryMonth:x.expiryMonth||"",expiryYear:x.expiryYear||"",cardholderName:x.cardholderName,isDefault:!1,network:x.network?.toLowerCase()||"visa",cardArtUrl:x.cardArtUrl};if(await Ke(t,S.current,{selectedCardId:y.id}),k.current){o(I=>I?{...I,savedCards:[...I.savedCards,y],selectedCard:y,paymentIntent:{...I.paymentIntent,selectedCardId:y.id}}:null);let f=a.paymentIntent.type;f==="pay_on_behalf"||f==="agent_to_agent"||f==="agentic_multi"?(u("initial"),n("AGENT_REGISTRATION")):v("checkout")}return{success:!0,card:y}}catch(y){let f=y;return k.current&&m({code:"CARD_ADD_FAILED",message:f.message||"Failed to add card",sessionId:a.id}),{success:!1}}finally{k.current&&l(!1)}},[a,t]),_e=F(async x=>{if(!a||!a.walletUser?.id)return console.warn("[useSession] Cannot delete card: no wallet user"),!1;l(!0);try{if(await Jr(t,S.current,a.walletUser.id,x),k.current){let y=a.savedCards.filter(g=>g.id!==x),f=a.selectedCard?.id===x;o(g=>g?{...g,savedCards:y,selectedCard:f?void 0:g.selectedCard,paymentIntent:{...g.paymentIntent,selectedCardId:f?void 0:g.paymentIntent.selectedCardId}}:null),y.length===0&&v("add")}return!0}catch(y){let f=y;return k.current&&m({code:"CARD_DELETE_FAILED",message:f.message||"Failed to delete card",sessionId:a.id}),!1}finally{k.current&&l(!1)}},[a,t]),Xe=F(async()=>{if(a)try{await Ke(t,S.current,{selectedCardId:void 0}),k.current&&o(x=>x?{...x,selectedCard:void 0,paymentIntent:{...x.paymentIntent,selectedCardId:void 0}}:null)}catch{}},[a,t]),Ut=F(()=>{u("initial"),n("PAYMENT"),v("checkout")},[]),V=F(()=>{u("initial"),n("PAYMENT"),v("checkout")},[]),we=F(async x=>{if(!a)return{success:!1,error:{code:"SESSION_NOT_FOUND",message:"No session"}};n("PROCESSING"),l(!0);try{return R&&x?.passkeyAuthenticated&&(console.log("[useSession] Generating credentials for agent mode passkey authentication"),await Xr(t,S.current,a.paymentIntent.id),console.log("[useSession] Credentials generated successfully")),await Kr(t,S.current),k.current&&(o(y=>y?{...y,status:"completed"}:null),n("SUCCESS")),{success:!0,walletUserId:a.walletUser?.id,paymentIntentId:a.paymentIntent.id,credentialGenerated:R&&x?.passkeyAuthenticated}}catch(y){let f=y,I={success:!1,error:{code:f.message?.includes("credential")||f.message?.includes("generate")?"CREDENTIAL_GENERATION_FAILED":"PAYMENT_FAILED",message:f.message||"Payment failed"}};return k.current&&(m({code:I.error.code,message:I.error.message,sessionId:a.id}),n("PAYMENT")),I}finally{k.current&&l(!1)}},[a,R,t]),Je=F(async()=>{if(a)try{await qr(t,S.current)}catch{}},[a,t]),Te=F(()=>{m(null)},[]),_t=F(async()=>{if(a){l(!0);try{let x=await sr(t,S.current),y=q(x,a);k.current&&(o(y),n(X(y)))}catch(x){let y=x;k.current&&m({code:"LOAD_FAILED",message:y.message||"Failed to refresh session",sessionId:a.id})}finally{k.current&&l(!1)}}},[a,X,q,t]);return{session:a,phase:i,loading:p,error:h,isAgentMode:R,hasSelectedCard:P,hasSavedCards:C,paymentView:E,cvc:s,setCvc:c,showMethodList:$,showAddCard:oe,returnToCheckout:Vt,submitIdentity:be,goBackToIdentity:Lt,submitOTP:ne,resendCode:qe,selectPaymentCard:Mt,addPaymentCard:Dt,deletePaymentCard:_e,clearCard:Xe,registrationSubPhase:d,setRegistrationSubPhase:u,skipRegistration:Ut,completeAgentRegistration:V,setPhase:n,setPaymentView:v,complete:we,abandon:Je,clearError:Te,refresh:_t}}import{useRef as Do,useState as ra,useEffect as Uo,useCallback as ke}from"react";import{PayOSPasskey as _o}from"@payos-inc/payos-passkey-js";var pr={enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,isLoading:!1,error:null,canRetry:!0,attemptsRemaining:void 0};function aa(e){let r=Do(null),[t,a]=ra(!1),[o,i]=ra(pr);Uo(()=>{if(!e.sessionSecret){a(!1);return}try{r.current=new _o(e.sessionSecret,{sandbox:e.sandbox,debug:e.debug,visaContainerId:e.visaContainerId,apiBaseUrl:e.apiBaseUrl}),a(!0)}catch(c){console.error("[usePasskeySDK] Failed to initialize SDK:",c),i(d=>({...d,error:c?.message||"Failed to initialize passkey SDK"})),a(!1)}return()=>{r.current?.cleanup(),r.current=null,a(!1)}},[e.sessionSecret,e.sandbox,e.debug,e.visaContainerId,e.apiBaseUrl]);let n=ke(async c=>{if(!r.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};i(d=>({...d,isLoading:!0,error:null}));try{let d=await r.current.register(c);if(d.requiresStepUp){let u=(d.stepUpMethods||[]).map((w,_)=>({id:String(_),type:w.type?.toLowerCase()==="email"?"email":"sms",maskedValue:w.maskedValue||w.value||`Method ${_+1}`}));i(w=>({...w,isLoading:!1,enrollmentId:d.enrollmentId||null,stepUpMethods:u}))}else i(u=>({...u,isLoading:!1}));return d}catch(d){let u=d?.message||"Registration failed";return i(w=>({...w,isLoading:!1,error:u})),{success:!1,message:u,error:{code:"REGISTRATION_ERROR",message:u}}}},[]),p=ke(async c=>{if(!r.current||!o.enrollmentId)return{success:!1};i(d=>({...d,isLoading:!0,error:null}));try{let d=await r.current.submitStepUpMethod(o.enrollmentId,c),u=o.stepUpMethods[c];return i(w=>({...w,isLoading:!1,selectedMethodDescription:u?.maskedValue||null})),d}catch(d){let u=d?.message||"Failed to send OTP";return i(w=>({...w,isLoading:!1,error:u})),{success:!1}}},[o.enrollmentId,o.stepUpMethods]),l=ke(async c=>{if(!r.current||!o.enrollmentId)return{success:!1,message:"No enrollment in progress",error:{code:"NO_ENROLLMENT",message:"No active enrollment"}};i(d=>({...d,isLoading:!0,error:null}));try{let d=await r.current.validateStepUpOTP(o.enrollmentId,c);return d.success?i(u=>({...u,isLoading:!1,canRetry:!0,attemptsRemaining:void 0})):i(u=>({...u,isLoading:!1,error:d.message||"OTP validation failed",canRetry:d.canRetry??!0,attemptsRemaining:d.attemptsRemaining})),d}catch(d){let u=d?.message||"OTP validation failed";return i(w=>({...w,isLoading:!1,error:u})),{success:!1,message:u,error:{code:"OTP_ERROR",message:u}}}},[o.enrollmentId]),h=ke(async c=>{if(!r.current||!o.enrollmentId)return{success:!1,message:"No enrollment in progress",error:{code:"NO_ENROLLMENT",message:"No active enrollment"}};i(d=>({...d,isLoading:!0,error:null}));try{let d=await r.current.completeVisaRegistration(o.enrollmentId,c);return i(u=>({...u,isLoading:!1,enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,error:d.success?null:d.message||"Registration failed"})),d}catch(d){let u=d?.message||"Registration failed";return i(w=>({...w,isLoading:!1,enrollmentId:null,stepUpMethods:[],selectedMethodDescription:null,error:u})),{success:!1,message:u,error:{code:"REGISTRATION_ERROR",message:u}}}},[o.enrollmentId]),m=ke(async(c,d)=>{if(!r.current)return{success:!1,message:"SDK not initialized",error:{code:"SDK_NOT_READY",message:"Passkey SDK is not ready"}};i(u=>({...u,isLoading:!0,error:null}));try{let u=await r.current.authenticate(c,d);return i(w=>({...w,isLoading:!1})),u}catch(u){let w=u?.message||"Authentication failed";return i(_=>({..._,isLoading:!1,error:w})),{success:!1,message:w,error:{code:"AUTH_ERROR",message:w}}}},[]),E=ke(()=>{i(c=>({...c,error:null}))},[]),v=ke(()=>{i(pr)},[]),s=ke(()=>{r.current?.cleanup(),i(pr)},[]);return{sdk:r.current,isReady:t,state:o,startRegistration:n,selectStepUpMethod:p,submitVisaOtp:l,completeVisaRegistration:h,authenticate:m,clearError:E,resetState:v,cleanup:s}}import{jsx as mr,jsxs as Bo}from"react/jsx-runtime";var gr=({onCancel:e})=>Bo("div",{className:"space-y-4",children:[mr(Z,{title:"Complete Passkey Setup",onBack:e}),mr("p",{className:"text-sm text-gray-500 dark:text-slate-400 text-center px-4",children:"Follow the instructions below to create your passkey"}),mr("div",{id:"visa-auth-container",className:"w-full max-w-sm mx-auto min-h-[300px] bg-gray-50 dark:bg-slate-800 rounded-2xl overflow-hidden"})]});gr.displayName="VisaIframeView";function Ee(e,r="USD"){let t=e/100;return new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(t)}function oa(e,r){return r||(e==="sandbox"?"https://sandbox.api.payos.ai":"https://api.payos.ai")}var na="https://wallet-onboard.payos.ai";import{jsx as L,jsxs as At}from"react/jsx-runtime";var Ho=({sessionSecret:e,open:r,onClose:t,onSuccess:a,onError:o,onCancel:i,title:n,environment:p="sandbox",developmentApiUrl:l,cardElementApiUrl:h,cardElementUrl:m,debug:E=!1})=>{let v=oa(p,l),{session:s,phase:c,loading:d,error:u,isAgentMode:w,hasSelectedCard:_,hasSavedCards:A,paymentView:G,cvc:k,setCvc:S,showMethodList:j,showAddCard:q,returnToCheckout:X,submitIdentity:R,goBackToIdentity:P,submitOTP:C,resendCode:$,selectPaymentCard:oe,addPaymentCard:Vt,deletePaymentCard:Lt,registrationSubPhase:be,setRegistrationSubPhase:ne,skipRegistration:qe,completeAgentRegistration:Mt,setPhase:Dt,complete:_e,abandon:Xe,clearError:Ut}=cr(e,{apiBaseUrl:v}),V=aa({sessionSecret:e,sandbox:p==="sandbox",debug:E,apiBaseUrl:v,visaContainerId:"visa-auth-container"}),[we,Je]=he(""),[Te,_t]=he("US"),[x,y]=he(""),[f,g]=he(null),[I,T]=he(!1),[D,Ze]=he(0),[Bt,Qe]=he(0),[Be,Ae]=he(""),[Ft,fr]=he(null),zt=Fo(!1);Ie(()=>{u&&o(u)},[u,o]),Ie(()=>{if(c==="SUCCESS"&&s){let b=setTimeout(()=>{a({success:!0,sessionId:s.id,paymentIntent:s.paymentIntent,walletUserId:s.walletUser?.id,paymentIntentId:s.paymentIntent.id,credentialGenerated:w})},3e3);return()=>clearTimeout(b)}},[c,s,a,w]),Ie(()=>{if(s?.walletUser?.phone&&!we){let b=at(s.walletUser.phone,Te);Je(b)}},[s?.walletUser?.phone,we,Te]),Ie(()=>{if(D<=0)return;let b=setTimeout(()=>Ze(B=>B-1),1e3);return()=>clearTimeout(b)},[D]),Ie(()=>{c==="IDENTITY"&&(Ze(0),Qe(0),y(""))},[c]),Ie(()=>{g(null),V.clearError()},[be]),Ie(()=>{if(be==="visa_iframe"&&Ft&&!zt.current){zt.current=!0;let b=setTimeout(async()=>{try{let B=await V.completeVisaRegistration(Ft);fr(null),B.success?qe():(g(B.message||"Registration failed"),ne("initial"))}finally{zt.current=!1}},100);return()=>clearTimeout(b)}},[be,Ft]);let Fe=sa(()=>{c!=="PROCESSING"&&(Xe(),i?.(),t())},[c,Xe,i,t]),pa=async()=>{if(g(null),!nt(we,Te)){g("Please enter a valid phone number");return}await R({phone:we})&&y("")},ma=async b=>{let B=b||x;g(null),console.log("[PaymentSheet] Submitting OTP:",{otpCode:B,length:B.length});let Y=await C(B);console.log("[PaymentSheet] OTP result:",Y),!Y.success&&Y.error&&(Qe(tt=>tt+1),g(Y.error.message))},ga=sa(async()=>{g(null),y(""),T(!0),Ze(30);try{await $()}finally{T(!1)}},[$]),ua=async b=>{await oe(b)},fa=async(b,B)=>{(await Vt({cardId:b.cardId||`card_${Date.now()}`,last4:b.last4||"",brand:b.brand||"unknown",network:b.brand||"unknown",cardholderName:b.cardholderName,cardArtUrl:b.cardArtUrl})).success||g("Failed to add card. Please try again.")},ha=async()=>{if(!s?.selectedCard){g("Please select a card");return}if(g(null),!w){let b=await _e();!b.success&&b.error&&g(b.error.message);return}try{let b=await V.authenticate(s.paymentIntent.id,s.paymentIntent.payments?.[0]?.id);if(b.success){let Y=await _e({passkeyAuthenticated:!0});!Y.success&&Y.error&&g(Y.error.message);return}if(b.requiresRegistration||b.error?.code==="NOT_ENROLLED"||b.error?.code==="DEVICE_NOT_REGISTERED"||b.message?.toLowerCase().includes("not enrolled")||b.message?.toLowerCase().includes("no enrollment")){let Y=await V.startRegistration(s.selectedCard.id);if(Y.requiresStepUp&&Y.network==="visa"){Dt("AGENT_REGISTRATION"),ne("visa_method_select");return}if(Y.success){let tt=await V.authenticate(s.paymentIntent.id,s.paymentIntent.payments?.[0]?.id);if(tt.success){let Ht=await _e({passkeyAuthenticated:!0});!Ht.success&&Ht.error&&g(Ht.error.message)}else g(tt.message||"Authentication failed after registration");return}g(Y.message||"Registration failed");return}g(b.message||"Authentication failed")}catch(b){let B=b instanceof Error?b.message:"Passkey authentication failed";g(B)}},ba=async()=>{if(!s?.selectedCard?.id)return;g(null);let b=await V.startRegistration(s.selectedCard.id);b.requiresStepUp&&b.network==="visa"?ne("visa_method_select"):b.success?Mt():g(b.message||"Registration failed")},wa=async b=>{g(null);let B=parseInt(b,10);(await V.selectStepUpMethod(B)).success?(Ae(""),ne("visa_otp_entry")):g("Failed to send verification code")},ya=async()=>{if(!Be)return;g(null);let b=await V.submitVisaOtp(Be);b.success&&b.registrationContext?(Ae(""),fr(b.registrationContext),ne("visa_iframe")):b.success||(Ae(""),g(b.message||"Invalid verification code"))},va=()=>{g(null),V.resetState(),qe()},xa=s?.paymentIntent.payments.map(b=>({label:b.description||b.merchantName,value:Ee(b.subtotal,s.paymentIntent.currency),quantity:b.quantity})),ka=s?.paymentIntent.totalSubtotal?Ee(s.paymentIntent.totalSubtotal,s.paymentIntent.currency):void 0,Ca=s?.paymentIntent.totalTax?Ee(s.paymentIntent.totalTax,s.paymentIntent.currency):void 0,Sa=s?.paymentIntent.totalShipping?Ee(s.paymentIntent.totalShipping,s.paymentIntent.currency):void 0,Pa=s?.paymentIntent.facilitationFee?Ee(s.paymentIntent.facilitationFee.amount,s.paymentIntent.currency):void 0,Ra=s?Ee(s.paymentIntent.totalAmount+(s.paymentIntent.facilitationFee?.amount||0),s.paymentIntent.currency):void 0,Na=()=>{if(c==="PAYMENT"){if(G==="methods")return"Payment Methods";if(G==="add")return A?"Add Card":"Secure Checkout"}return c==="AGENT_REGISTRATION"?"Authorization Required":n||"Checkout"},et=f||u?.message,Ea=()=>{if(c==="LOADING")return At("div",{className:"flex flex-col items-center justify-center py-12 space-y-4",children:[L(zo,{className:"w-12 h-12 text-gray-400 animate-spin"}),L("p",{className:"text-gray-600 dark:text-slate-400",children:"Loading checkout..."})]});if(c==="ERROR")return At("div",{className:"flex flex-col items-center justify-center py-12 space-y-4 text-center",children:[L(ia,{className:"w-16 h-16 text-red-500"}),L("h3",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"Something went wrong"}),L("p",{className:"text-sm text-gray-600 dark:text-slate-400",children:u?.message||"Unable to load checkout session"}),L("button",{onClick:Fe,className:"mt-4 px-6 py-2 bg-gray-900 text-white rounded-lg hover:bg-gray-800 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-100",children:"Close"})]});if(c==="EXPIRED")return At("div",{className:"flex flex-col items-center justify-center py-12 space-y-4 text-center",children:[L(ia,{className:"w-16 h-16 text-amber-500"}),L("h3",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"Session Expired"}),L("p",{className:"text-sm text-gray-600 dark:text-slate-400",children:"This checkout session has expired. Please start a new checkout."}),L("button",{onClick:Fe,className:"mt-4 px-6 py-2 bg-gray-900 text-white rounded-lg hover:bg-gray-800 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-100",children:"Close"})]});if(c==="IDENTITY")return L(Me,{phone:we,onPhoneChange:b=>{Je(b),g(null),Ut()},countryCode:Te,onCountryChange:_t,onSubmit:pa,isLoading:d,error:et||void 0});if(c==="OTP_VERIFY")return L(wt,{phoneNumber:we,otp:x,onOtpChange:y,onSubmit:ma,onEdit:P,onResend:ga,isLoading:d,isResending:I,error:et||void 0,resendCooldown:D,retryCount:Bt,maxRetries:3});if(c==="AGENT_REGISTRATION"&&s){let b=s.selectedCard?.network||"visa";return be==="visa_method_select"?L(Et,{methods:V.state.stepUpMethods.map((B,Y)=>({id:String(Y),type:B.type,maskedValue:B.maskedValue})),onSelectMethod:wa,onBack:()=>ne("initial"),isLoading:V.state.isLoading}):be==="visa_otp_entry"?L(It,{methodDescription:V.state.selectedMethodDescription||"your phone",otp:Be,onOtpChange:B=>{Ae(B),f&&g(null),V.state.error&&V.clearError()},onVerify:ya,onBack:()=>ne("visa_method_select"),onResend:async()=>{Ae(""),g(null),V.clearError()},onVerifyAnotherWay:()=>{Ae(""),g(null),V.clearError(),V.resetState(),ne("visa_method_select")},isLoading:V.state.isLoading,error:f||V.state.error||void 0,canRetry:V.state.canRetry}):be==="visa_iframe"?L(gr,{onCancel:()=>ne("initial")}):L(Tt,{cardNetwork:b,onCreatePasskey:ba,onSkip:f?va:void 0,onBack:X,isLoading:V.state.isLoading,error:f||void 0,showSkip:!!f,paymentIntent:s.paymentIntent,merchantName:s.paymentIntent.payments[0]?.merchantName||"Merchant"})}if(c==="PAYMENT"&&s){if(G==="checkout"&&_&&s.selectedCard){let b=d||V.state.isLoading;return L(vt,{selectedCard:s.selectedCard,cvc:k,onCvcChange:S,onChangeCard:j,paymentIntent:s.paymentIntent,onSubmit:ha,isLoading:b,error:et||void 0})}if(G==="methods")return L(kt,{cards:s.savedCards||[],selectedCardId:s.selectedCard?.id||null,onSelectCard:ua,onAddNewCard:q,onBack:_?X:Fe,onDeleteCard:Lt});if(G==="add")return L(Rt,{linkToken:s.linkToken,walletUserId:s.paymentIntent.walletUserId,onSubmit:fa,onBack:A?j:void 0,isLoading:d,error:et||void 0,isFirstCard:!A,customBaseUrl:m||na,environment:p,devApiUrl:h})}return c==="PROCESSING"?At("div",{className:"flex flex-col items-center justify-center py-12 space-y-4",children:[L("div",{className:"w-16 h-16 border-4 border-gray-200 dark:border-slate-700 border-t-black dark:border-t-white rounded-full animate-spin"}),L("p",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:w?"Generating Credentials...":"Processing Payment..."}),L("p",{className:"text-sm text-gray-600 dark:text-slate-400",children:"Please wait while we process your request"})]}):c==="SUCCESS"&&s?L(Nt,{paymentIntent:s.paymentIntent,walletUser:s.walletUser,cardNetwork:s.selectedCard?.network,onDismiss:Fe,passkeyEnrolled:s.selectedCard?.passkeyEnrolled}):null};return r?L(pt,{open:r,onClose:Fe,title:Na(),amount:Ra,orderItems:xa,subtotal:ka,shipping:Sa,tax:Ca,orderAgentFee:Pa,mode:w?"agent":"standard",children:Ea()}):null};import{useState as Ot,useCallback as te}from"react";var ur=e=>new Promise(r=>setTimeout(r,e)),da=async e=>{console.log("[Mock] Sending OTP to:",e),await ur(800),console.log("[Mock] OTP sent successfully")},la=async e=>{console.log("[Mock] Verifying OTP:",e),await ur(500);let r=e==="123456"||e.length===6;return console.log("[Mock] OTP verification result:",r),r},ca=async e=>{console.log("[Mock] Processing payment:",e),await ur(2e3);let r={success:!0,transactionId:`txn_mock_${Date.now()}`,amount:e.amount,cardLast4:e.cardData.last4,timestamp:Date.now()};return console.log("[Mock] Payment processed successfully:",r),r};function $o({mode:e,amount:r,savedCards:t,onSuccess:a,onError:o}){let[i,n]=Ot({phase:"PHONE_INPUT",phoneNumber:"",email:"",cardData:null,billingAddress:null,error:null,isLoading:!1}),[p,l]=Ot(t&&t.length>0?t.find(R=>R.isDefault)?.id||t[0].id:null),[h,m]=Ot(t&&t.length>0?"checkout":"add"),[E,v]=Ot(""),s=te(R=>{n(P=>({...P,error:R,isLoading:!1}))},[]),c=te(R=>{n(P=>({...P,isLoading:R}))},[]),d=te(async R=>{c(!0),s(null);try{await da(R),n(P=>({...P,phoneNumber:R,phase:"OTP_VERIFY",isLoading:!1}))}catch(P){s("Failed to send OTP. Please try again."),o?.(P)}},[c,s,o]),u=te(async R=>{c(!0),s(null);try{if(await la(R))if(n(C=>({...C,phase:"PAYMENT",isLoading:!1})),t&&t.length>0){m("checkout");let C=t.find($=>$.isDefault)||t[0];l(C.id)}else m("add"),l(null);else s("Invalid code. Please try again.")}catch(P){s("Failed to verify OTP. Please try again."),o?.(P)}},[c,s,o,t]),w=te(async(R,P,C)=>{c(!0),s(null),n($=>({...$,phase:"PROCESSING"}));try{let $=await ca({phoneNumber:i.phoneNumber,email:R,cardData:P,amount:r,mode:e});n(oe=>({...oe,email:R,cardData:P,billingAddress:C,phase:"SUCCESS",isLoading:!1})),setTimeout(()=>{a?.($)},3e3)}catch($){s("Payment failed. Please try again."),n(oe=>({...oe,phase:"PAYMENT"})),o?.($)}},[i.phoneNumber,r,e,s,a,o]),_=te(R=>{l(R),m("checkout")},[]),A=te(async R=>{c(!0),s(null);try{await new Promise(P=>setTimeout(P,500)),n(P=>({...P,cardData:R,isLoading:!1})),e==="agent"?n(P=>({...P,phase:"AGENT_REGISTRATION"})):m("checkout")}catch(P){s("Failed to add card. Please try again."),o?.(P)}},[c,s,o,e]),G=te(()=>{if(n({phase:"PHONE_INPUT",phoneNumber:"",email:"",cardData:null,billingAddress:null,error:null,isLoading:!1}),t&&t.length>0){let R=t.find(P=>P.isDefault)||t[0];l(R.id),m("checkout")}else l(null),m("add");v("")},[t]),k=te(()=>{m("methods")},[]),S=te(()=>{m("add")},[]),j=te(()=>{m("checkout")},[]),q=te(()=>{if(n(R=>({...R,phase:"PAYMENT",phoneNumber:"+15551234567",error:null,isLoading:!1})),t&&t.length>0){let R=t.find(P=>P.isDefault)||t[0];l(R.id),m("checkout")}else l(null),m("add");v("")},[t]),X=te(()=>{n(R=>({...R,phase:"PAYMENT"})),m("checkout")},[]);return{state:i,selectedCardId:p,paymentView:h,cvc:E,setCvc:v,submitPhone:d,verifyOTP:u,submitPayment:w,selectCard:_,addCard:A,logout:G,setError:s,showMethodList:k,showAddCard:S,returnToCheckout:j,skipToPayment:q,completeAgentRegistration:X}}export{ft as ActiveCardWidget,Tt as AgentRegistrationView,M as Button,O as Card,Rt as CardAddView,kr as CardContent,xr as CardDescription,Cr as CardFooter,yr as CardHeader,vr as CardTitle,vt as CheckoutView,Me as IdentityView,wr as Input,Pr as Label,kt as MethodListView,Ve as OTPInput,wt as OTPView,Dr as OrderSummary,pt as PayOSDrawer,dt as PayOSFooter,ut as PaymentMethodRow,Ho as PaymentSheet,ot as PhoneInput,ze as PriceTag,it as ReceiptPanel,Nr as Separator,Nt as SuccessView,Z as ViewHeader,Et as VisaMethodView,It as VisaOtpView,st as WelcomeBackView,N as cn,qt as useBodyScrollLock,$o as useCheckoutFlow,cr as useSession,lt as useVisualViewport,oo as useVisualViewportStyle};
|