@aifeatures/admin-react 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use client";
2
- import*as ia from"react";var na=class extends Error{constructor(a,s,r){super(a);this.status=s;this.details=r;this.name="AifeaturesApiError"}};function gs(e,t){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${t}`}function vs(e,t="https://aifeatures.dev"){async function a(s,r={}){let i=`${t}${s}`,l=await fetch(i,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!l.ok){let u;try{u=await l.json()}catch{}throw new na(gs(u?.error,l.status),l.status,u)}if(l.status!==204)return l.json()}return{async getForms(){return(await a("/api/v1/forms")).forms},async getForm(s){return a(`/api/v1/forms/${s}`)},async createForm(s){return a("/api/v1/forms",{method:"POST",body:JSON.stringify(s)})},async updateForm(s,r){return a(`/api/v1/forms/${s}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(s){await a(`/api/v1/forms/${s}`,{method:"DELETE"})},async getSubmissions(s,r={}){let i=new URLSearchParams;r.limit!==void 0&&i.set("limit",String(r.limit)),r.offset!==void 0&&i.set("offset",String(r.offset));let l=i.toString(),u=`/api/v1/forms/${s}/submissions${l?`?${l}`:""}`;return a(u)},async getSubmission(s){return a(`/api/v1/submissions/${s}`)},async deleteSubmission(s){await a(`/api/v1/submissions/${s}`,{method:"DELETE"})},async downloadAttachment(s,r){let i=typeof r=="string"?{name:r}:r,l=i.name,u=i.id??i.name,f=`${t}/api/v1/submissions/${s}/attachments/${encodeURIComponent(u)}`,d=await fetch(f,{headers:{Authorization:`Bearer ${e}`}});if(!d.ok){let h;try{h=await d.json()}catch{}throw new na(gs(h?.error,d.status),d.status,h)}let n=await d.blob(),m=URL.createObjectURL(n),x=document.createElement("a");x.href=m,x.download=l,document.body.appendChild(x),x.click(),document.body.removeChild(x),URL.revokeObjectURL(m)},async getPaymentsStatus(){return a("/api/v1/payments/status")},async getProducts(s={}){let r=new URLSearchParams;s.include&&r.set("include",s.include);let i=r.toString();return(await a(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(s){return a(`/api/v1/products/${s}`)},async createProduct(s){return a("/api/v1/products",{method:"POST",body:JSON.stringify(s)})},async updateProduct(s,r){return a(`/api/v1/products/${s}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(s){await a(`/api/v1/products/${s}`,{method:"DELETE"})},async attachProductFile(s,r){let i=new FormData;i.append("file",r);let l=await fetch(`${t}/api/v1/products/${s}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!l.ok){let u;try{u=await l.json()}catch{}throw new na(gs(u?.error,l.status),l.status,u)}return l.json()},async attachProductFileFromUrl(s,r){return a(`/api/v1/products/${s}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(s,r){return a(`/api/v1/products/${s}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(s,r){return a(`/api/v1/options/${s}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(s){await a(`/api/v1/options/${s}`,{method:"DELETE"})},async createVariant(s,r){return a(`/api/v1/products/${s}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(s,r){return a(`/api/v1/variants/${s}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(s){await a(`/api/v1/variants/${s}`,{method:"DELETE"})},async setVariantInventory(s,r){return a(`/api/v1/variants/${s}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(s,r){return a(`/api/v1/variants/${s}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(s={}){let r=new URLSearchParams;s.email&&r.set("email",s.email),s.limit!==void 0&&r.set("limit",String(s.limit)),s.offset!==void 0&&r.set("offset",String(s.offset));let i=r.toString();return a(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(s){return a(`/api/v1/customers/${s}`)},async getOrders(s={}){let r=new URLSearchParams;s.status&&r.set("status",s.status),s.excludeStatus?.length&&r.set("exclude_status",s.excludeStatus.join(",")),s.customerEmail&&r.set("customer_email",s.customerEmail),s.from&&r.set("from",s.from),s.to&&r.set("to",s.to),s.unfulfilledOnly&&r.set("unfulfilled_only","true"),s.limit!==void 0&&r.set("limit",String(s.limit)),s.offset!==void 0&&r.set("offset",String(s.offset));let i=r.toString();return a(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(s){return a(`/api/v1/orders/${s}`)},async resendOrderReceipt(s){await a(`/api/v1/orders/${s}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(s){return a(`/api/v1/orders/${s}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(s,r){return a(`/api/v1/orders/${s}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(s={}){let r=new URLSearchParams;s.status&&r.set("status",s.status),s.limit!==void 0&&r.set("limit",String(s.limit)),s.offset!==void 0&&r.set("offset",String(s.offset));let i=r.toString();return a(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getBusinessSummary(s){let r=new URLSearchParams;return r.set("tz_offset_minutes",String(s.tzOffsetMinutes)),a(`/api/v1/summary?${r.toString()}`)},async getPeople(s={}){let r=new URLSearchParams;s.since&&r.set("since",s.since),s.q&&r.set("q",s.q),s.limit!==void 0&&r.set("limit",String(s.limit)),s.offset!==void 0&&r.set("offset",String(s.offset));let i=r.toString();return a(`/api/v1/people${i?`?${i}`:""}`)},async getPerson(s){return a(`/api/v1/people/${encodeURIComponent(s)}`)}}}import{jsx as Oa,jsxs as en}from"react/jsx-runtime";var Ms=ia.createContext(null);function Yr(e){return e?e.startsWith("sk_")?"Invalid token type: You passed an organization API key (sk_xxx) but AifeaturesProvider requires a site token (st_xxx). Site tokens are returned when you create a site via the API.":e.startsWith("st_")?null:`Invalid token format: Expected a site token starting with "st_" but got "${e.slice(0,10)}...". Site tokens are returned when you create a site via the API.`:"No siteToken provided to AifeaturesProvider"}function Xr({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:r}){let i=ia.useMemo(()=>Yr(e),[e]),l=ia.useMemo(()=>vs(e,t),[e,t]),u=ia.useMemo(()=>({siteToken:e,apiUrl:t,api:l}),[e,t,l]);return i?Oa("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:en("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[Oa("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),Oa("p",{className:"af-text-sm af-text-destructive",children:i})]})}):Oa(Ms.Provider,{value:u,children:Oa("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:r})})}function Y(){let e=ia.useContext(Ms);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as la from"react";import{ArrowLeft as zn,Settings as jn,Inbox as qn}from"lucide-react";import*as Aa from"react";import*as Pt from"@radix-ui/react-tabs";import{clsx as tn}from"clsx";import{twMerge as an}from"tailwind-merge";function D(...e){return an(tn(e))}import{jsx as bs}from"react/jsx-runtime";var Fa=Pt.Root,La=Aa.forwardRef(({className:e,...t},a)=>bs(Pt.List,{ref:a,className:D("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));La.displayName=Pt.List.displayName;var qt=Aa.forwardRef(({className:e,...t},a)=>bs(Pt.Trigger,{ref:a,className:D("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));qt.displayName=Pt.Trigger.displayName;var Gt=Aa.forwardRef(({className:e,...t},a)=>bs(Pt.Content,{ref:a,className:D("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));Gt.displayName=Pt.Content.displayName;import*as zs from"react";import{Slot as sn}from"@radix-ui/react-slot";import{cva as rn}from"class-variance-authority";import{jsx as on}from"react/jsx-runtime";var nn=rn("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),N=zs.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...r},i)=>on(s?sn:"button",{className:D(nn({variant:t,size:a,className:e})),ref:i,...r}));N.displayName="Button";import{Inbox as js,Settings as cn}from"lucide-react";import*as Kt from"react";import{jsx as Wt}from"react/jsx-runtime";var be=Kt.forwardRef(({className:e,...t},a)=>Wt("div",{className:"af-relative af-w-full af-overflow-auto",children:Wt("table",{ref:a,className:D("af-w-full af-caption-bottom af-text-sm",e),...t})}));be.displayName="Table";var ye=Kt.forwardRef(({className:e,...t},a)=>Wt("thead",{ref:a,className:D("[&_tr]:af-border-b",e),...t}));ye.displayName="TableHeader";var he=Kt.forwardRef(({className:e,...t},a)=>Wt("tbody",{ref:a,className:D("[&_tr:last-child]:af-border-0",e),...t}));he.displayName="TableBody";var ln=Kt.forwardRef(({className:e,...t},a)=>Wt("tfoot",{ref:a,className:D("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));ln.displayName="TableFooter";var X=Kt.forwardRef(({className:e,...t},a)=>Wt("tr",{ref:a,className:D("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));X.displayName="TableRow";var C=Kt.forwardRef(({className:e,...t},a)=>Wt("th",{ref:a,className:D("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));C.displayName="TableHead";var k=Kt.forwardRef(({className:e,...t},a)=>Wt("td",{ref:a,className:D("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));k.displayName="TableCell";var fn=Kt.forwardRef(({className:e,...t},a)=>Wt("caption",{ref:a,className:D("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));fn.displayName="TableCaption";import*as St from"react";function Na(){let{api:e}=Y(),[t,a]=St.useState([]),[s,r]=St.useState(!0),[i,l]=St.useState(null),u=St.useCallback(async()=>{try{r(!0),l(null);let m=await e.getForms();a(m)}catch(m){l(m instanceof Error?m:new Error("Failed to fetch forms"))}finally{r(!1)}},[e]);St.useEffect(()=>{u()},[u]);let f=St.useCallback(async m=>{let x=await e.createForm(m);return a(h=>[...h,x]),x},[e]),d=St.useCallback(async(m,x)=>{let h=await e.updateForm(m,x);return a(b=>b.map(v=>v.id===m?h:v)),h},[e]),n=St.useCallback(async m=>{await e.deleteForm(m),a(x=>x.filter(h=>h.id!==m))},[e]);return{forms:t,isLoading:s,error:i,refetch:u,createForm:f,updateForm:d,deleteForm:n}}import{jsx as Qe,jsxs as Qt}from"react/jsx-runtime";function Ua({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:r}=Na();return s?Qe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Qe("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):r?Qe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Qt("div",{className:"af-text-destructive",children:["Error: ",r.message]})}):a.length===0?Qt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Qe(js,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Qt("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",Qe("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):Qe("div",{className:t,children:Qt(be,{children:[Qe(ye,{children:Qt(X,{children:[Qe(C,{children:"Name"}),Qe(C,{children:"Endpoint"}),Qe(C,{className:"af-text-right",children:"Actions"})]})}),Qe(he,{children:a.map(i=>Qt(X,{children:[Qe(k,{className:"af-font-medium",children:i.name}),Qe(k,{children:Qe("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url.replace("https://aifeatures.dev","")})}),Qe(k,{className:"af-text-right",children:Qt("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Qt(N,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[Qe(js,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Qt(N,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[Qe(cn,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import*as Ba from"react";import{ChevronLeft as Sn,ChevronRight as Rn,Eye as Tn,Inbox as Cn,Paperclip as kn}from"lucide-react";import*as oa from"react";import*as ae from"@radix-ui/react-select";import{Check as dn,ChevronDown as qs,ChevronUp as un}from"lucide-react";import{jsx as at,jsxs as ys}from"react/jsx-runtime";var ht=ae.Root;var xt=ae.Value,dt=oa.forwardRef(({className:e,children:t,...a},s)=>ys(ae.Trigger,{ref:s,className:D("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...a,children:[t,at(ae.Icon,{asChild:!0,children:at(qs,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));dt.displayName=ae.Trigger.displayName;var Gs=oa.forwardRef(({className:e,...t},a)=>at(ae.ScrollUpButton,{ref:a,className:D("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:at(un,{className:"af-h-4 af-w-4"})}));Gs.displayName=ae.ScrollUpButton.displayName;var Ws=oa.forwardRef(({className:e,...t},a)=>at(ae.ScrollDownButton,{ref:a,className:D("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:at(qs,{className:"af-h-4 af-w-4"})}));Ws.displayName=ae.ScrollDownButton.displayName;var ut=oa.forwardRef(({className:e,children:t,position:a="popper",...s},r)=>at(ae.Portal,{children:ys(ae.Content,{ref:r,className:D("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:a,...s,children:[at(Gs,{}),at(ae.Viewport,{className:D("af-p-1",a==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),at(Ws,{})]})}));ut.displayName=ae.Content.displayName;var mn=oa.forwardRef(({className:e,...t},a)=>at(ae.Label,{ref:a,className:D("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));mn.displayName=ae.Label.displayName;var xe=oa.forwardRef(({className:e,children:t,...a},s)=>ys(ae.Item,{ref:s,className:D("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...a,children:[at("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:at(ae.ItemIndicator,{children:at(dn,{className:"af-h-4 af-w-4"})})}),at(ae.ItemText,{children:t})]}));xe.displayName=ae.Item.displayName;var pn=oa.forwardRef(({className:e,...t},a)=>at(ae.Separator,{ref:a,className:D("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));pn.displayName=ae.Separator.displayName;import*as Nt from"react";function Va({formId:e,initialPageSize:t=25}){let{api:a}=Y(),[s,r]=Nt.useState([]),[i,l]=Nt.useState(0),[u,f]=Nt.useState(!0),[d,n]=Nt.useState(null),[m,x]=Nt.useState(0),[h,b]=Nt.useState(t),v=Nt.useCallback(async()=>{if(e)try{f(!0),n(null);let R={limit:h,offset:m*h},A=await a.getSubmissions(e,R);r(A.submissions),l(A.total)}catch(R){n(R instanceof Error?R:new Error("Failed to fetch submissions"))}finally{f(!1)}},[a,e,m,h]);Nt.useEffect(()=>{v()},[v]);let p=Nt.useCallback(async R=>{await a.deleteSubmission(R),r(A=>A.filter(W=>W.id!==R)),l(A=>A-1)},[a]),S=Math.ceil(i/h);return{submissions:s,total:i,isLoading:u,error:d,page:m,pageSize:h,hasNextPage:m<S-1,hasPreviousPage:m>0,setPage:x,setPageSize:R=>{b(R),x(0)},refetch:v,deleteSubmission:p}}import*as Qs from"react";import{ArrowLeft as gn,Download as vn,Globe as bn,Clock as yn,FileText as hn,Loader2 as xn,Monitor as Nn,Mail as wn}from"lucide-react";import{jsx as Ae,jsxs as Ee}from"react/jsx-runtime";function Ks(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Pn(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function Ha({submission:e,onBack:t}){let{api:a}=Y(),[s,r]=Qs.useState(null),i=f=>f.id??f.name,l=async f=>{r(i(f));try{await a.downloadAttachment(e.id,f)}catch(d){console.error("Download failed:",d)}finally{r(null)}},u=Object.entries(e.data).filter(([f])=>!f.startsWith("_"));return Ee("div",{children:[Ee("div",{className:"af-mb-6",children:[Ee(N,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[Ae(gn,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Ae("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),Ee("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Ks(e.metadata.submitted_at)]})]}),Ee("div",{className:"af-space-y-6",children:[Ee("div",{children:[Ae("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),Ee("div",{className:"af-space-y-3",children:[u.map(([f,d])=>Ee("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[Ae("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:f.replace(/_/g," ")}),Ae("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof d=="string"&&d.includes(`
3
- `)?Ae("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:d}):String(d)})]},f)),u.length===0&&Ae("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&Ee("div",{children:[Ae("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),Ae("div",{className:"af-space-y-2",children:e.attachments.map((f,d)=>Ee("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[Ee("div",{className:"af-flex af-items-center af-gap-2",children:[Ae(hn,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Ae("span",{className:"af-text-sm",children:f.name}),Ee("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Pn(f.size),")"]})]}),Ee(N,{variant:"ghost",size:"sm",onClick:()=>l(f),disabled:s===i(f),children:[s===i(f)?Ae(xn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Ae(vn,{className:"af-h-4 af-w-4 af-mr-1"}),s===i(f)?"Downloading...":"Download"]})]},d))})]}),Ee("div",{children:[Ae("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),Ee("div",{className:"af-space-y-2 af-text-sm",children:[Ee("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Ae(yn,{className:"af-h-4 af-w-4"}),Ae("span",{children:Ks(e.metadata.submitted_at)})]}),e.metadata.ip_address&&Ee("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Ae(bn,{className:"af-h-4 af-w-4"}),Ee("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&Ee("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[Ae(Nn,{className:"af-h-4 af-w-4 af-mt-0.5"}),Ae("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&Ee("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Ae(wn,{className:"af-h-4 af-w-4"}),Ee("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as le,jsxs as Ze}from"react/jsx-runtime";function _n(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function On(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let a of t)if(typeof e[a]=="string")return e[a];return null}function Ln(e){let t=Object.entries(e).filter(([r])=>!r.startsWith("_")&&!r.toLowerCase().includes("email"));if(t.length===0)return"";let[,a]=t[0],s=String(a);return s.length>50?s.slice(0,50)+"...":s}function $a({formId:e,className:t,defaultSubmissionId:a}){let{submissions:s,total:r,isLoading:i,error:l,page:u,pageSize:f,hasNextPage:d,hasPreviousPage:n,setPage:m,setPageSize:x}=Va({formId:e}),[h,b]=Ba.useState("list"),[v,p]=Ba.useState(null);Ba.useEffect(()=>{if(a&&s.length>0){let _=s.find(F=>F.id===a);_&&(p(_),b("detail"))}},[a,s]);let S=_=>{p(_),b("detail")},R=()=>{b("list"),p(null)};if(h==="detail"&&v)return le("div",{className:t,children:le(Ha,{submission:v,onBack:R})});if(i)return le("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:le("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(l)return le("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ze("div",{className:"af-text-destructive",children:["Error: ",l.message]})});if(s.length===0&&u===0)return Ze("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[le(Cn,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ze("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",le("br",{}),"Submissions will appear here when visitors use your form."]})]});let A=u*f+1,W=Math.min((u+1)*f,r);return Ze("div",{className:t,children:[Ze(be,{children:[le(ye,{children:Ze(X,{children:[le(C,{children:"Email"}),le(C,{children:"Preview"}),le(C,{children:"Date"}),le(C,{className:"af-text-right",children:"Actions"})]})}),le(he,{children:s.map(_=>{let F=On(_.data),M=Ln(_.data);return Ze(X,{children:[le(k,{className:"af-font-medium",children:Ze("div",{className:"af-flex af-items-center af-gap-2",children:[F||le("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),_.attachments.length>0&&Ze("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${_.attachments.length} attachment(s)`,children:[le(kn,{className:"af-h-3 af-w-3"}),le("span",{className:"af-text-xs",children:_.attachments.length})]})]})}),le(k,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:M||le("span",{className:"af-italic",children:"No preview available"})}),le(k,{className:"af-text-muted-foreground",children:_n(_.metadata.submitted_at)}),le(k,{className:"af-text-right",children:le(N,{variant:"ghost",size:"icon",onClick:()=>S(_),title:"View details",children:le(Tn,{className:"af-h-4 af-w-4"})})})]},_.id)})})]}),Ze("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Ze("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ze("span",{children:["Showing ",A,"-",W," of ",r]}),Ze(ht,{value:String(f),onValueChange:_=>x(Number(_)),children:[le(dt,{className:"af-w-[70px] af-h-8",children:le(xt,{})}),Ze(ut,{children:[le(xe,{value:"10",children:"10"}),le(xe,{value:"25",children:"25"}),le(xe,{value:"50",children:"50"}),le(xe,{value:"100",children:"100"})]})]}),le("span",{children:"per page"})]}),Ze("div",{className:"af-flex af-items-center af-gap-2",children:[Ze(N,{variant:"outline",size:"sm",onClick:()=>m(u-1),disabled:!n,children:[le(Sn,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ze(N,{variant:"outline",size:"sm",onClick:()=>m(u+1),disabled:!d,children:["Next",le(Rn,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as mt from"react";import{Plus as Vn,X as Hn,Loader2 as $n,Check as Mn}from"lucide-react";import*as Zs from"react";import{jsx as Bn}from"react/jsx-runtime";var ie=Zs.forwardRef(({className:e,type:t,...a},s)=>Bn("input",{type:t,className:D("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...a}));ie.displayName="Input";import*as Js from"react";import{cva as En}from"class-variance-authority";import{jsx as In}from"react/jsx-runtime";var Dn=En("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),se=Js.forwardRef(({className:e,...t},a)=>In("label",{ref:a,className:D(Dn(),e),...t}));se.displayName="Label";import{cva as An}from"class-variance-authority";import{jsx as Un}from"react/jsx-runtime";var Fn=An("af-inline-flex af-items-center af-rounded-md af-border af-px-2.5 af-py-0.5 af-text-xs af-font-semibold af-transition-colors focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2",{variants:{variant:{default:"af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",secondary:"af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",destructive:"af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",outline:"af-text-foreground",success:"af-border-transparent af-bg-green-100 af-text-green-800",warning:"af-border-transparent af-bg-yellow-100 af-text-yellow-800"}},defaultVariants:{variant:"default"}});function q({className:e,variant:t,...a}){return Un("div",{className:D(Fn({variant:t}),e),...a})}import{jsx as ue,jsxs as Rt}from"react/jsx-runtime";function Ma({form:e,onSaved:t,className:a}){let{updateForm:s}=Na(),[r,i]=mt.useState(!1),[l,u]=mt.useState(null),[f,d]=mt.useState(null),[n,m]=mt.useState(e.name),[x,h]=mt.useState(e.redirect_url||""),[b,v]=mt.useState(e.email_recipients),[p,S]=mt.useState("");mt.useEffect(()=>{m(e.name),h(e.redirect_url||""),v(e.email_recipients),d(null)},[e]);let R=mt.useCallback(async M=>{try{i(!0),d(null);let Z=await s(e.id,M);u(new Date),t?.(Z)}catch(Z){d(Z instanceof Error?Z.message:"Failed to save")}finally{i(!1)}},[e.id,s,t]);mt.useEffect(()=>{if(l){let M=setTimeout(()=>u(null),2e3);return()=>clearTimeout(M)}},[l]);let A=async()=>{let M=p.trim().toLowerCase();if(!M)return;if(!M.includes("@")){d("Please enter a valid email address");return}if(b.includes(M)){d("This email is already added");return}let Z=[...b,M];v(Z),S(""),d(null),await R({email_recipients:Z})},W=async M=>{let Z=b.filter(j=>j!==M);v(Z),await R({email_recipients:Z})},_=async()=>{n!==e.name&&await R({name:n})},F=async()=>{let M=x||null;M!==e.redirect_url&&await R({redirect_url:M})};return Rt("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(r||l)&&ue("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:r?Rt("div",{className:"af-flex af-items-center af-gap-2 af-bg-background af-border af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[ue($n,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),ue("span",{className:"af-text-sm",children:"Saving..."})]}):Rt("div",{className:"af-flex af-items-center af-gap-2 af-bg-green-50 af-border af-border-green-200 af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[ue(Mn,{className:"af-h-4 af-w-4 af-text-green-600"}),ue("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Rt("div",{className:"af-space-y-2",children:[ue(se,{htmlFor:"form-name",children:"Form Name"}),ue(ie,{id:"form-name",value:n,onChange:M=>m(M.target.value),onBlur:_,placeholder:"Contact Form"}),ue("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),Rt("div",{className:"af-space-y-2",children:[ue(se,{children:"Email Recipients"}),ue("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),Rt("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[b.map(M=>Rt(q,{variant:"secondary",className:"af-gap-1",children:[M,ue("button",{type:"button",onClick:()=>W(M),className:"af-ml-1 hover:af-text-destructive",disabled:r,children:ue(Hn,{className:"af-h-3 af-w-3"})})]},M)),b.length===0&&ue("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Rt("div",{className:"af-flex af-gap-2",children:[ue(ie,{type:"email",value:p,onChange:M=>S(M.target.value),placeholder:"Add email address",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),A())},disabled:r}),ue(N,{type:"button",variant:"outline",onClick:A,disabled:!p.trim()||r,children:ue(Vn,{className:"af-h-4 af-w-4"})})]})]}),Rt("div",{className:"af-space-y-2",children:[ue(se,{htmlFor:"redirect-url",children:"Redirect URL"}),ue(ie,{id:"redirect-url",value:x,onChange:M=>h(M.target.value),onBlur:F,placeholder:"/thank-you"}),ue("p",{className:"af-text-xs af-text-muted-foreground",children:"Where to send visitors after a successful submission. Use a site path (/thank-you) or a full URL (https://example.com/thank-you). Leave empty for a default success page."})]}),Rt("div",{className:"af-space-y-2",children:[ue(se,{children:"Form Endpoint"}),ue("div",{className:"af-flex af-items-center af-gap-2",children:ue("code",{className:"af-flex-1 af-text-xs af-bg-muted af-px-3 af-py-2 af-rounded af-border",children:e.endpoint_url})}),ue("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),Rt("div",{className:"af-space-y-2",children:[ue(se,{children:"Captcha Protection"}),ue("div",{className:"af-flex af-items-center af-gap-2",children:ue(q,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),ue("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),f&&ue("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f})]})}import{jsx as nt,jsxs as It}from"react/jsx-runtime";function Ys({className:e,submissionId:t}){let{api:a}=Y(),[s,r]=la.useState("list"),[i,l]=la.useState(null),[u,f]=la.useState("submissions"),[d,n]=la.useState(t),[m,x]=la.useState(!!t);la.useEffect(()=>{if(!t)return;async function p(){try{let S=await a.getSubmission(t),R=await a.getForm(S.form_id);l(R),r("detail"),f("submissions"),n(t)}catch(S){console.error("Failed to load submission for deep link:",S)}finally{x(!1)}}p()},[t,a]);let h=(p,S)=>{l(p),r("detail"),f(S),n(void 0)},b=()=>{r("list"),l(null),n(void 0)},v=p=>{l(p)};return m?nt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:nt("div",{className:"af-text-muted-foreground",children:"Loading..."})}):It("div",{className:e,children:[s==="list"&&It("div",{children:[It("div",{className:"af-mb-6",children:[nt("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),nt("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),nt(Ua,{onSelectForm:h})]}),s==="detail"&&i&&It("div",{children:[It("div",{className:"af-mb-6",children:[It(N,{variant:"ghost",size:"sm",onClick:b,className:"af-mb-2 af--ml-2",children:[nt(zn,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),nt("h2",{className:"af-text-lg af-font-semibold",children:i.name}),nt("p",{className:"af-text-sm af-text-muted-foreground",children:nt("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),It(Fa,{value:u,onValueChange:p=>f(p),children:[It(La,{className:"af-mb-4",children:[It(qt,{value:"submissions",className:"af-gap-2",children:[nt(qn,{className:"af-h-4 af-w-4"}),"Submissions"]}),It(qt,{value:"settings",className:"af-gap-2",children:[nt(jn,{className:"af-h-4 af-w-4"}),"Settings"]})]}),nt(Gt,{value:"submissions",children:nt($a,{formId:i.id,defaultSubmissionId:d})}),nt(Gt,{value:"settings",children:nt(Ma,{form:i,onSaved:v})})]})]})]})}import*as ns from"react";import{ArrowLeft as Ji,Package as Yi,Receipt as Xi,Settings as eo,Users as to}from"lucide-react";import*as za from"react";import{Package as Qn,Pencil as Zn,Plus as er,Trash2 as Jn}from"lucide-react";import*as Ea from"react";import*as He from"@radix-ui/react-dialog";import{X as Gn}from"lucide-react";import{jsx as Zt,jsxs as hs}from"react/jsx-runtime";var fa=He.Root;var Wn=He.Portal;var Xs=Ea.forwardRef(({className:e,...t},a)=>Zt(He.Overlay,{ref:a,className:D("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Xs.displayName=He.Overlay.displayName;var Jt=Ea.forwardRef(({className:e,children:t,...a},s)=>Zt(Wn,{children:hs("div",{className:"aifeatures-admin",children:[Zt(Xs,{}),hs(He.Content,{ref:s,className:D("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...a,children:[t,hs(He.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[Zt(Gn,{className:"af-h-4 af-w-4"}),Zt("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Jt.displayName=He.Content.displayName;var Yt=({className:e,...t})=>Zt("div",{className:D("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Yt.displayName="DialogHeader";var Xt=({className:e,...t})=>Zt("div",{className:D("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Xt.displayName="DialogFooter";var ea=Ea.forwardRef(({className:e,...t},a)=>Zt(He.Title,{ref:a,className:D("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));ea.displayName=He.Title.displayName;var ta=Ea.forwardRef(({className:e,...t},a)=>Zt(He.Description,{ref:a,className:D("af-text-sm af-text-muted-foreground",e),...t}));ta.displayName=He.Description.displayName;var Kn=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function At(e){return Kn.has(e.toLowerCase())}function U(e,t,a){let s=At(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Tt(e){let t=e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0;return e.amount_total+(e.shipping_total??0)+t}function Ct(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=At(t)?a:a*100;return Math.round(s)}function Je(e,t){return At(t)?e:e/100}import{jsx as me,jsxs as st}from"react/jsx-runtime";function Yn(e){if(e.allow_custom_amount){let t=e.min_amount!==null?U(e.min_amount,e.currency):"?",a=e.max_amount!==null?U(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":U(e.unit_amount,e.currency)}function Xn(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function ja({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:r,isLoading:i,error:l,deleteProduct:u}=e,[f,d]=za.useState(null),[n,m]=za.useState(!1),[x,h]=za.useState(null),b=async()=>{if(f)try{m(!0),h(null),await u(f.id),d(null)}catch(v){h(v instanceof Error?v.message:"Failed to delete product")}finally{m(!1)}};return i?me("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:me("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):l?me("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:st("div",{className:"af-text-destructive",children:["Error: ",l.message]})}):r.length===0?st("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[me(Qn,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),st("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",me("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),st(N,{variant:"outline",onClick:()=>a?.(),children:[me(er,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):st("div",{className:s,children:[me("div",{className:"af-flex af-justify-end af-mb-4",children:st(N,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[me(er,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),st(be,{children:[me(ye,{children:st(X,{children:[me(C,{children:"Name"}),me(C,{children:"Price"}),me(C,{children:"Fulfillment"}),me(C,{children:"Status"}),me(C,{className:"af-text-right",children:"Actions"})]})}),me(he,{children:r.map(v=>st(X,{children:[me(k,{className:"af-font-medium",children:v.name}),me(k,{children:Yn(v)}),me(k,{className:"af-text-muted-foreground",children:Xn(v)}),me(k,{children:me(q,{variant:v.active?"success":"secondary",children:v.active?"Active":"Inactive"})}),me(k,{className:"af-text-right",children:st("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[st(N,{variant:"ghost",size:"sm",onClick:()=>t?.(v),children:[me(Zn,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),st(N,{variant:"ghost",size:"sm",onClick:()=>{h(null),d(v)},children:[me(Jn,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},v.id))})]}),me(fa,{open:!!f,onOpenChange:v=>{!v&&!n&&d(null)},children:st(Jt,{children:[st(Yt,{children:[me(ea,{children:"Delete product?"}),st(ta,{children:['"',f?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),x&&me("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:x}),st(Xt,{children:[me(N,{variant:"outline",onClick:()=>d(null),disabled:n,children:"Cancel"}),me(N,{variant:"destructive",onClick:b,disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}import*as we from"react";import{FileText as ti,Link2 as ai,Loader2 as sr,Plus as si,Upload as ri,X as ni}from"lucide-react";import*as Fe from"react";import{Loader2 as tr,Plus as xs,Trash2 as ar,X as ei}from"lucide-react";import{jsx as L,jsxs as K}from"react/jsx-runtime";function Ns(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function qa({productId:e,currency:t,className:a}){let{api:s}=Y(),r=At(t)?"1":"0.01",[i,l]=Fe.useState(null),[u,f]=Fe.useState(!0),[d,n]=Fe.useState(null),[m,x]=Fe.useState(null),[h,b]=Fe.useState(!1),v=Fe.useRef(!0);Fe.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);let p=Fe.useCallback(async()=>{try{let y=await s.getProduct(e);if(!v.current)return;l(y)}catch(y){if(!v.current)return;n(y instanceof Error?y.message:"Failed to load product")}finally{v.current&&f(!1)}},[s,e]);Fe.useEffect(()=>{p()},[p]);let S=async y=>{x(null),b(!0);try{await y(),await p()}catch(T){v.current&&x(T instanceof Error?T.message:"Something went wrong")}finally{v.current&&b(!1)}},[R,A]=Fe.useState(""),[W,_]=Fe.useState(""),[F,M]=Fe.useState({}),Z=()=>S(async()=>{let y=R.trim(),T=W.split(",").map(ne=>ne.trim()).filter(Boolean);if(!y)throw new Error("Option name is required");if(T.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:y,values:T}),v.current&&(A(""),_(""))}),j=y=>S(async()=>{let T=(F[y.id]??"").trim();if(!T)throw new Error("Enter a value");await s.updateOption(y.id,{add_values:[T]}),v.current&&M(ne=>({...ne,[y.id]:""}))}),I=(y,T)=>S(()=>s.updateOption(y.id,{remove_values:[T]})),pe=y=>S(()=>s.deleteOption(y.id)),[g,te]=Fe.useState(null),[Se,Ne]=Fe.useState(null),[fe,Ve]=Fe.useState(!1),[J,de]=Fe.useState(null),ke=i?.options??[],We=i?.variants??[],Me=()=>{Ne(null),te({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(ke.map(y=>[y.id,y.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Ot=y=>{Ne(null);let T=y.inventory?.on_hand??0,ne=T<0?"":String(T);te({variant:y,title:y.title??"",sku:y.sku??"",unitAmount:y.unit_amount!=null?String(Je(y.unit_amount,t)):"",compareAt:y.compare_at_amount!=null?String(Je(y.compare_at_amount,t)):"",active:y.active,optionValues:{},tracked:y.inventory?.tracked??!1,onHand:ne,initialOnHand:ne,allowBackorder:y.inventory?.allow_backorder??!1})},Lt=async()=>{if(!g)return;Ne(null);let y=g.variant?.allow_custom_amount??!1,T=null,ne=null;if(!y){if(T=Ct(g.unitAmount,t),T===null||T<=0){Ne("Enter a valid price");return}if(g.compareAt.trim()&&(ne=Ct(g.compareAt,t),ne===null||ne<=T)){Ne("Compare-at price must be greater than the price");return}}let Xe=g.onHand.trim()!==g.initialOnHand.trim(),et=parseInt(g.onHand,10);if(g.tracked&&Xe&&(!Number.isFinite(et)||et<0)){Ne("On-hand quantity must be zero or more");return}try{if(Ve(!0),g.variant)await s.updateVariant(g.variant.id,{title:g.title.trim()||null,sku:g.sku.trim()||null,...y?{}:{unit_amount:T,compare_at_amount:ne},active:g.active}),await s.setVariantInventory(g.variant.id,{tracked:g.tracked,on_hand:g.tracked&&Xe?et:void 0,allow_backorder:g.allowBackorder});else{let tt={};for(let Ke of ke){let Et=g.optionValues[Ke.id];if(!Et){Ne(`Choose a ${Ke.title}`),Ve(!1);return}tt[Ke.title]=Et}await s.createVariant(e,{title:g.title.trim()||null,sku:g.sku.trim()||null,unit_amount:T,compare_at_amount:ne,active:g.active,option_values:ke.length>0?tt:void 0,inventory:g.tracked?{tracked:!0,on_hand:et,allow_backorder:g.allowBackorder}:{tracked:!1,allow_backorder:g.allowBackorder}})}await p(),v.current&&te(null)}catch(tt){if(v.current&&Ne(tt instanceof Error?tt.message:"Failed to save variant"),g.variant)try{let Ke=await s.getProduct(e);v.current&&l(Ke)}catch{}}finally{v.current&&Ve(!1)}},Le=()=>S(async()=>{J&&(await s.deleteVariant(J.id),v.current&&de(null))}),vt=g?.variant?.allow_custom_amount??!1,bt=g?.variant!=null&&g.variant.option_values.length===0&&ke.length>0&&!g.variant.active,Ie=g?.variant?.inventory!=null&&g.variant.inventory.on_hand<0?-g.variant.inventory.on_hand:null;function Bt(y){let T=y.inventory;if(!T||!T.tracked)return L("span",{className:"af-text-muted-foreground",children:"Unlimited"});let ne=T.available??T.on_hand;return ne<0?K("span",{children:[-ne," backordered"]}):K("span",{children:[ne," in stock",T.allow_backorder&&L("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return u?L("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:L(tr,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):d?L("div",{className:a,children:L("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})}):K("div",{className:`af-space-y-6 ${a||""}`,children:[K("div",{className:"af-space-y-3",children:[K("div",{children:[L(se,{children:"Options"}),L("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),ke.length>0&&L("div",{className:"af-space-y-3",children:ke.map(y=>K("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[K("div",{className:"af-flex af-items-center af-justify-between",children:[L("span",{className:"af-text-sm af-font-medium",children:y.title}),L(N,{variant:"ghost",size:"sm",onClick:()=>pe(y),disabled:h,children:L(ar,{className:"af-h-4 af-w-4"})})]}),L("div",{className:"af-flex af-flex-wrap af-gap-2",children:y.values.map(T=>K(q,{variant:"secondary",className:"af-gap-1",children:[T.value,L("button",{type:"button",onClick:()=>I(y,T.value),className:"af-ml-1 hover:af-text-destructive",disabled:h,title:"Remove value",children:L(ei,{className:"af-h-3 af-w-3"})})]},T.id))}),K("div",{className:"af-flex af-gap-2",children:[L(ie,{value:F[y.id]??"",onChange:T=>M(ne=>({...ne,[y.id]:T.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),j(y))},disabled:h}),L(N,{type:"button",variant:"outline",size:"sm",onClick:()=>j(y),disabled:h||!(F[y.id]??"").trim(),children:L(xs,{className:"af-h-4 af-w-4"})})]})]},y.id))}),K("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[K("div",{className:"af-space-y-1",children:[L(se,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),L(ie,{id:"new-option-title",value:R,onChange:y=>A(y.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:h})]}),K("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[L(se,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),L(ie,{id:"new-option-values",value:W,onChange:y=>_(y.target.value),placeholder:"S, M, L",disabled:h})]}),K(N,{type:"button",variant:"outline",onClick:Z,disabled:h||!R.trim()||!W.trim(),children:[L(xs,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),K("div",{className:"af-space-y-3",children:[K("div",{className:"af-flex af-items-center af-justify-between",children:[L(se,{children:"Variants"}),K(N,{type:"button",variant:"outline",size:"sm",onClick:Me,disabled:h||ke.length===0,children:[L(xs,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ke.length===0&&L("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),We.length===0?L("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):K(be,{children:[L(ye,{children:K(X,{children:[L(C,{children:"Variant"}),L(C,{children:"SKU"}),L(C,{children:"Price"}),L(C,{children:"Stock"}),L(C,{children:"Status"}),L(C,{className:"af-text-right",children:"Actions"})]})}),L(he,{children:We.map(y=>K(X,{children:[L(k,{className:"af-font-medium",children:Ns(y)}),L(k,{className:"af-text-muted-foreground",children:y.sku||"-"}),L(k,{children:y.unit_amount!=null?K("span",{children:[y.compare_at_amount!=null&&L("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:U(y.compare_at_amount,y.currency)}),U(y.unit_amount,y.currency)]}):y.allow_custom_amount?L("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),L(k,{children:Bt(y)}),L(k,{children:L(q,{variant:y.active?"success":"secondary",children:y.active?"Active":"Inactive"})}),L(k,{className:"af-text-right",children:K("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[L(N,{variant:"ghost",size:"sm",onClick:()=>Ot(y),disabled:h,children:"Edit"}),L(N,{variant:"ghost",size:"icon",onClick:()=>de(y),disabled:h,title:"Delete variant",children:L(ar,{className:"af-h-4 af-w-4"})})]})})]},y.id))})]})]}),m&&L("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m}),L(fa,{open:g!==null,onOpenChange:y=>{!y&&!fe&&te(null)},children:K(Jt,{children:[K(Yt,{children:[L(ea,{children:g?.variant?"Edit variant":"Add variant"}),L(ta,{children:"Price, markdown, and stock live on the variant."})]}),g&&K("div",{className:"af-space-y-3",children:[g.variant?g.variant.option_values.length>0&&K("div",{className:"af-text-sm",children:[L("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Ns(g.variant)]}):ke.map(y=>K("div",{className:"af-space-y-1",children:[L(se,{className:"af-text-xs af-text-muted-foreground",children:y.title}),K(ht,{value:g.optionValues[y.id]??"",onValueChange:T=>te(ne=>ne&&{...ne,optionValues:{...ne.optionValues,[y.id]:T}}),children:[L(dt,{children:L(xt,{placeholder:`Choose ${y.title}`})}),L(ut,{children:y.values.map(T=>L(xe,{value:T.value,children:T.value},T.id))})]})]},y.id)),vt?K("div",{className:"af-space-y-1",children:[L(se,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),L("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):K("div",{className:"af-flex af-gap-3",children:[K("div",{className:"af-space-y-1",children:[K(se,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),L(ie,{id:"variant-price",type:"number",min:"0",step:r,value:g.unitAmount,onChange:y=>te(T=>T&&{...T,unitAmount:y.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),K("div",{className:"af-space-y-1",children:[L(se,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),L(ie,{id:"variant-compare",type:"number",min:"0",step:r,value:g.compareAt,onChange:y=>te(T=>T&&{...T,compareAt:y.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),K("div",{className:"af-space-y-1",children:[L(se,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),L(ie,{id:"variant-sku",value:g.sku,onChange:y=>te(T=>T&&{...T,sku:y.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),K("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[K("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[L("input",{type:"checkbox",checked:g.tracked,onChange:y=>te(T=>T&&{...T,tracked:y.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),g.tracked&&K("div",{className:"af-space-y-1 af-pl-6",children:[K("div",{className:"af-flex af-items-end af-gap-3",children:[K("div",{className:"af-space-y-1",children:[L(se,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),L(ie,{id:"variant-onhand",type:"number",min:"0",step:"1",value:g.onHand,onChange:y=>te(T=>T&&{...T,onHand:y.target.value}),placeholder:Ie!=null?"0":void 0,className:"af-w-[100px]"})]}),K("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[L("input",{type:"checkbox",checked:g.allowBackorder,onChange:y=>te(T=>T&&{...T,allowBackorder:y.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Ie!=null&&K("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Ie," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),K("div",{className:"af-space-y-1",children:[K("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[L("input",{type:"checkbox",checked:g.active,onChange:y=>te(T=>T&&{...T,active:y.target.checked}),className:"af-h-4 af-w-4",disabled:bt}),"Active (buyers can purchase this variant)"]}),bt&&L("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),Se&&L("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Se})]}),K(Xt,{children:[L(N,{variant:"outline",onClick:()=>te(null),disabled:fe,children:"Cancel"}),K(N,{onClick:Lt,disabled:fe,children:[fe?L(tr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,g?.variant?"Save":"Add variant"]})]})]})}),L(fa,{open:J!==null,onOpenChange:y=>{!y&&!h&&de(null)},children:K(Jt,{children:[K(Yt,{children:[L(ea,{children:"Delete variant?"}),L(ta,{children:J&&`"${Ns(J)}" will no longer be purchasable. Past orders are unaffected.`})]}),K(Xt,{children:[L(N,{variant:"outline",onClick:()=>de(null),disabled:h,children:"Cancel"}),L(N,{variant:"destructive",onClick:Le,disabled:h,children:"Delete"})]})]})})]})}import{Fragment as oi,jsx as Q,jsxs as re}from"react/jsx-runtime";function ii(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function Ga({productsState:e,product:t,currency:a,onSaved:s,className:r}){let{createProduct:i,updateProduct:l,attachProductFile:u,attachProductFileFromUrl:f}=e,d=!!t,n=t?.currency??a,m=At(n)?"1":"0.01",x=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[h,b]=we.useState(!1),[v,p]=we.useState(null),S=we.useRef(!0);we.useEffect(()=>(S.current=!0,()=>{S.current=!1}),[]);let[R,A]=we.useState(t?.name??""),[W,_]=we.useState(t?.description??""),[F,M]=we.useState(t?.allow_custom_amount?"custom":"fixed"),[Z,j]=we.useState(t?.unit_amount!=null?String(Je(t.unit_amount,n)):""),[I,pe]=we.useState(t?.min_amount!=null?String(Je(t.min_amount,n)):""),[g,te]=we.useState(t?.max_amount!=null?String(Je(t.max_amount,n)):""),[Se,Ne]=we.useState(String(t?.max_quantity??10)),fe=we.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(Je(t.unit_amount,n)):"",minAmount:t?.min_amount!=null?String(Je(t.min_amount,n)):"",maxAmount:t?.max_amount!=null?String(Je(t.max_amount,n)):"",maxQuantity:String(t?.max_quantity??10)}).current,[Ve,J]=we.useState(t?.collect_shipping_address??!1),[de,ke]=we.useState(t?.active??!0),[We,Me]=we.useState(t?.images??[]),[Ot,Lt]=we.useState(""),[Le,vt]=we.useState(t?.fulfillment??null),[bt,Ie]=we.useState(!1),[Bt,y]=we.useState(""),[T,ne]=we.useState(null),Xe=we.useRef(null),et=h||bt,tt=()=>{let G=Ot.trim();if(G){if(We.includes(G)){p("This image URL is already added");return}Me(ve=>[...ve,G]),Lt(""),p(null)}},Ke=G=>{Me(ve=>ve.filter(_e=>_e!==G))},Et=async()=>{if(p(null),!R.trim()){p("Product name is required");return}let G=null,ve=null,_e=null,ra=!d||F!==fe.pricingMode||(F==="fixed"?Z!==fe.unitAmount:I!==fe.minAmount||g!==fe.maxAmount),Dt=!d||Se!==fe.maxQuantity,xa=x||F==="fixed";if(!(x||!ra))if(F==="fixed"){if(G=Ct(Z,n),G===null||G<=0){p("Enter a valid price");return}}else{if(ve=Ct(I,n),_e=Ct(g,n),ve===null||_e===null){p("Enter valid minimum and maximum amounts");return}if(_e<ve){p("Maximum amount must be at least the minimum amount");return}}let yt=parseInt(Se,10);if(xa&&Dt&&(!Number.isFinite(yt)||yt<1)){p("Max quantity must be at least 1");return}try{b(!0);let Be;if(d&&t){let ze={name:R.trim(),description:W.trim()||null,images:We,collect_shipping_address:Ve,active:de};!x&&ra&&(ze.allow_custom_amount=F==="custom",F==="fixed"?ze.unit_amount=G:(ze.min_amount=ve,ze.max_amount=_e)),xa&&Dt&&(ze.max_quantity=yt),Be=await l(t.id,ze),fe.pricingMode=Be.allow_custom_amount?"custom":"fixed",fe.unitAmount=Be.unit_amount!=null?String(Je(Be.unit_amount,n)):"",fe.minAmount=Be.min_amount!=null?String(Je(Be.min_amount,n)):"",fe.maxAmount=Be.max_amount!=null?String(Je(Be.max_amount,n)):"",fe.maxQuantity=String(Be.max_quantity)}else{let ze={name:R.trim(),allow_custom_amount:F==="custom",collect_shipping_address:Ve,active:de};W.trim()&&(ze.description=W.trim()),We.length>0&&(ze.images=We),F==="fixed"?(ze.unit_amount=G,ze.max_quantity=yt):(ze.min_amount=ve,ze.max_amount=_e),Be=await i(ze)}if(!S.current)return;vt(Be.fulfillment),s?.(Be)}catch(Be){if(!S.current)return;p(Be instanceof Error?Be.message:"Failed to save product")}finally{S.current&&b(!1)}},ya=async G=>{let ve=G.target.files?.[0];if(!(!ve||!t))try{Ie(!0),ne(null);let _e=await u(t.id,ve);if(!S.current)return;vt(_e.fulfillment),s?.(_e)}catch(_e){if(!S.current)return;ne(_e instanceof Error?_e.message:"Failed to upload file")}finally{S.current&&(Ie(!1),Xe.current&&(Xe.current.value=""))}},ha=async()=>{let G=Bt.trim();if(!(!G||!t))try{Ie(!0),ne(null);let ve=await f(t.id,G);if(!S.current)return;vt(ve.fulfillment),y(""),s?.(ve)}catch(ve){if(!S.current)return;ne(ve instanceof Error?ve.message:"Failed to fetch file")}finally{S.current&&Ie(!1)}};return re("div",{className:`af-space-y-6 ${r||""}`,children:[re("div",{className:"af-space-y-2",children:[Q(se,{htmlFor:"product-name",children:"Name"}),Q(ie,{id:"product-name",value:R,onChange:G=>A(G.target.value),placeholder:"My product"})]}),re("div",{className:"af-space-y-2",children:[Q(se,{htmlFor:"product-description",children:"Description"}),Q("textarea",{id:"product-description",value:W,onChange:G=>_(G.target.value),rows:3,placeholder:"Shown on the Stripe checkout page.",className:"af-flex af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring"})]}),re("div",{className:"af-space-y-2",children:[Q(se,{children:"Pricing"}),x?Q("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):re(oi,{children:[re(ht,{value:F,onValueChange:G=>M(G),children:[Q(dt,{className:"af-w-[260px]",children:Q(xt,{})}),re(ut,{children:[Q(xe,{value:"fixed",children:"Fixed price"}),Q(xe,{value:"custom",children:"Buyer chooses the amount"})]})]}),F==="fixed"?Q("div",{className:"af-flex af-items-end af-gap-3",children:re("div",{className:"af-space-y-1",children:[re(se,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",n.toUpperCase(),")"]}),Q(ie,{id:"product-price",type:"number",min:"0",step:m,value:Z,onChange:G=>j(G.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):re("div",{className:"af-space-y-1",children:[re("div",{className:"af-flex af-items-end af-gap-3",children:[re("div",{className:"af-space-y-1",children:[re(se,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",n.toUpperCase(),")"]}),Q(ie,{id:"product-min-amount",type:"number",min:"0",step:m,value:I,onChange:G=>pe(G.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),re("div",{className:"af-space-y-1",children:[re(se,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",n.toUpperCase(),")"]}),Q(ie,{id:"product-max-amount",type:"number",min:"0",step:m,value:g,onChange:G=>te(G.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),Q("p",{className:"af-text-xs af-text-muted-foreground",children:"Buyers pick their own amount within these bounds (tip jar, pay-what-you-want). Quantity is always 1."})]}),re("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",n.toUpperCase(),"), which follows the country of your payment account."]})]}),(x||F==="fixed")&&re("div",{className:"af-space-y-1",children:[Q(se,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),Q(ie,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:Se,onChange:G=>Ne(G.target.value),className:"af-w-[140px]"})]})]}),re("div",{className:"af-space-y-2",children:[Q(se,{children:"Images"}),Q("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),re("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[We.map(G=>re(q,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[Q("span",{className:"af-truncate",children:G}),Q("button",{type:"button",onClick:()=>Ke(G),className:"af-ml-1 hover:af-text-destructive",disabled:h,children:Q(ni,{className:"af-h-3 af-w-3"})})]},G)),We.length===0&&Q("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),re("div",{className:"af-flex af-gap-2",children:[Q(ie,{type:"url",value:Ot,onChange:G=>Lt(G.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),tt())},disabled:h}),Q(N,{type:"button",variant:"outline",onClick:tt,disabled:!Ot.trim()||h,children:Q(si,{className:"af-h-4 af-w-4"})})]})]}),re("div",{className:"af-space-y-2",children:[Q(se,{children:"Digital File"}),Q("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),d?re("div",{className:"af-space-y-3",children:[Le?.type==="download"&&re("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Q(ti,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Q("span",{className:"af-text-sm",children:Le.filename}),Le.size!=null&&re("span",{className:"af-text-xs af-text-muted-foreground",children:["(",ii(Le.size),")"]})]}),Le?.type==="redirect"&&Le.url&&re("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Q(ai,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),re("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Le.url]})]}),re("div",{className:"af-flex af-items-center af-gap-2",children:[Q("input",{ref:Xe,type:"file",onChange:ya,className:"af-hidden",disabled:et}),re(N,{type:"button",variant:"outline",size:"sm",onClick:()=>Xe.current?.click(),disabled:et,children:[bt?Q(sr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Q(ri,{className:"af-h-4 af-w-4 af-mr-1"}),Le?.type==="download"?"Replace file":"Upload file"]}),Q("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),Q(ie,{type:"url",value:Bt,onChange:G=>y(G.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:bt}),Q(N,{type:"button",variant:"outline",size:"sm",onClick:ha,disabled:!Bt.trim()||et,children:"Fetch from URL"})]}),T&&Q("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:T})]}):Q("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),re("div",{className:"af-space-y-2",children:[Q(se,{children:"Settings"}),re("div",{className:"af-space-y-2",children:[re("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Q("input",{type:"checkbox",checked:Ve,onChange:G=>J(G.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),re("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Q("input",{type:"checkbox",checked:de,onChange:G=>ke(G.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),d&&t&&re("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[Q(se,{children:"Options & Variants"}),Q(qa,{productId:t.id,currency:n})]}),v&&Q("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),Q("div",{className:"af-flex af-items-center af-gap-2",children:re(N,{type:"button",onClick:Et,disabled:et,children:[h?Q(sr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?"Save changes":"Create product"]})})]})}import*as je from"react";import{ChevronLeft as Li,ChevronRight as vr,Loader2 as Bi,Receipt as Ei,Search as Di,SlidersHorizontal as Ii}from"lucide-react";import*as Oe from"react";var li=["pending","paid","failed","expired","refunded","partially_refunded","disputed"];function Wa({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=Y(),[s,r]=Oe.useState([]),[i,l]=Oe.useState(0),[u,f]=Oe.useState(!0),[d,n]=Oe.useState(null),[m,x]=Oe.useState(0),[h,b]=Oe.useState(e),[v,p]=Oe.useState(void 0),[S,R]=Oe.useState(""),[A,W]=Oe.useState(""),[_,F]=Oe.useState(""),[M,Z]=Oe.useState(!1),[j,I]=Oe.useState(!1),[pe,g]=Oe.useState(void 0),te=pe?pe.join(","):"",Se=Oe.useMemo(()=>{if(!te)return;let J=new Set(te.split(","));return li.filter(de=>!J.has(de))},[te]),Ne=Oe.useRef(0),fe=Oe.useCallback(async()=>{let J=++Ne.current;try{f(!0),n(null);let de={limit:h,offset:m*h};v?de.status=v:Se?de.excludeStatus=Se:M||(de.excludeStatus=["pending","expired"]),S.trim()&&(de.customerEmail=S.trim()),A.trim()&&(de.from=A.trim()),_.trim()&&(de.to=_.trim()),j&&(de.unfulfilledOnly=!0);let ke=await a.getOrders(de);if(J!==Ne.current)return;r(ke.orders),l(ke.total)}catch(de){if(J!==Ne.current)return;n(de instanceof Error?de:new Error("Failed to fetch orders"))}finally{J===Ne.current&&f(!1)}},[a,m,h,v,Se,M,j,S,A,_,t]);Oe.useEffect(()=>{fe()},[fe]);let Ve=Math.ceil(i/h);return{orders:s,total:i,isLoading:u,error:d,page:m,pageSize:h,hasNextPage:m<Ve-1,hasPreviousPage:m>0,setPage:x,setPageSize:J=>{b(J),x(0)},status:v,setStatus:J=>{p(J),x(0)},statusIn:pe,setStatusIn:J=>{g(J&&J.length>0?J:void 0),x(0)},customerEmail:S,setCustomerEmail:J=>{R(J),x(0)},from:A,setFrom:J=>{W(J),x(0)},to:_,setTo:J=>{F(J),x(0)},showAbandoned:M,setShowAbandoned:J=>{Z(J),x(0)},unfulfilledOnly:j,setUnfulfilledOnly:J=>{I(J),x(0)},clearFilters:()=>{p(void 0),g(void 0),Z(!1),I(!1),R(""),W(""),F(""),x(0)},refetch:fe}}import*as De from"react";import{ArrowLeft as di,Check as lr,ChevronLeft as ui,ChevronRight as mi,ClipboardCopy as pi,Copy as gi,Download as vi,Loader2 as Qa,Mail as fr,MoreHorizontal as bi,Package as yi,RotateCcw as hi,Truck as xi,Undo2 as cr}from"lucide-react";import*as rr from"react";import*as Ft from"@radix-ui/react-popover";import{jsx as ws}from"react/jsx-runtime";var nr=Ft.Root,ir=Ft.Trigger;var Ps=rr.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},r)=>ws(Ft.Portal,{children:ws("div",{className:"aifeatures-admin",children:ws(Ft.Content,{ref:r,align:t,sideOffset:a,className:D("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...s})})}));Ps.displayName=Ft.Content.displayName;import{jsx as Ka}from"react/jsx-runtime";var fi={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed"};function ci(e){return fi[e]??e}function or(e){switch(e){case"paid":return"success";case"pending":return"secondary";case"refunded":case"partially_refunded":return"warning";case"disputed":return"destructive";default:return"outline"}}function ma({status:e,className:t}){return Ka(q,{variant:or(e),className:t,children:ci(e)})}function pa({status:e}){return Ka(ma,{status:e})}function wa({order:e,className:t}){return e.shipping_address?typeof e.merchant_fulfilled_at=="string"?Ka(q,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?Ka(q,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function aa(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as ki,jsx as c,jsxs as B}from"react/jsx-runtime";var pr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ga="af-text-xs af-text-muted-foreground";function Ss(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Ni(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gr(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var Za=24,wi=["paid","partially_refunded"],Pi=["paid","partially_refunded","disputed"],Si=/^[A-Za-z0-9 _-]*$/,dr=100;function Cs(e,t,a,s,r){let i=wi.includes(s);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${a} of ${Za} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${Za} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?a<Za&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:a<Za&&e==="buyer"&&!r?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${a} attempt${a===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${s==="refunded"?"because the order was refunded":s==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function ur({title:e,recipient:t,status:a,attempts:s,side:r,orderStatus:i,action:l}){let u=Cs(r,a,s,i,t);return B("div",{children:[B("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[B("div",{className:"af-min-w-0",children:[c("div",{className:"af-text-sm",children:e}),t&&c("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),c(q,{variant:u.variant,className:"af-shrink-0",children:u.label})]}),u.detail&&c("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:u.detail}),l&&c("div",{className:"af-mt-2",children:l})]})}function mr(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=Ni(e.address)?e.address:null;if(a){for(let r of["line1","line2"]){let i=a[r];typeof i=="string"&&i&&t.push(i)}let s=["city","state","postal_code"].map(r=>a[r]).filter(r=>typeof r=="string"&&!!r).join(", ");s&&t.push(s),typeof a.country=="string"&&a.country&&t.push(a.country)}return t.length>0?t:Object.entries(e).map(([s,r])=>`${s}: ${gr(r)}`)}function Ri(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function ks({value:e,label:t,children:a,className:s,size:r="icon"}){let[i,l]=De.useState(!1);if(!Ri())return null;let u=async()=>{try{await navigator.clipboard.writeText(e),l(!0),setTimeout(()=>l(!1),1500)}catch{}},f=i?c(lr,{className:"af-h-3 af-w-3"}):c(gi,{className:"af-h-3 af-w-3"});return r==="icon"?c(N,{variant:"ghost",size:"icon",className:D("af-h-6 af-w-6 af-shrink-0",s),onClick:u,title:t,"aria-label":t,children:f}):B(N,{variant:"outline",size:"sm",className:s,onClick:u,"aria-label":t,children:[i?c(lr,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):c(pi,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":a]})}function Rs({label:e,value:t}){return B("div",{children:[c("div",{className:ga,children:e}),B("div",{className:"af-flex af-items-center af-gap-1",children:[c("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),c(ks,{value:t,label:`Copy ${e}`})]})]})}function Ti({src:e}){let[t,a]=De.useState(!1);return!e||t?c("div",{"aria-hidden":"true",className:"af-flex af-h-10 af-w-10 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-muted",children:c(yi,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):c("img",{src:e,alt:"","aria-hidden":"true",onError:()=>a(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function ca({title:e,action:t,children:a,className:s}){return B("section",{className:D("af-rounded-lg af-border af-p-4",s),children:[B("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[c("h4",{className:pr,children:e}),t]}),c("div",{className:"af-mt-3",children:a})]})}function da({label:e,emphasis:t,children:a}){return B("div",{className:D("af-flex af-items-baseline af-justify-between af-gap-6",t&&"af-mt-2 af-border-t af-pt-2"),children:[c("span",{className:t?"af-text-base af-font-semibold":ga,children:e}),c("span",{className:D("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:a})]})}function Ts({onSelect:e,disabled:t,icon:a,children:s}){return B(N,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[c("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function Ci(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${U(Tt(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let a=Cs("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${a.label.toLowerCase()}`,at:null,tone:a.variant==="destructive"?"destructive":a.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let a=Cs("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"?"You were notified of this sale":`Sale alert to you \u2014 ${a.label.toLowerCase()}`,at:null,tone:a.variant==="destructive"?"destructive":a.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${U(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function Ja({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:r=!1,onPrevOrder:i,onNextOrder:l,hasPrevOrder:u=!1,hasNextOrder:f=!1}){let{api:d}=Y(),[n,m]=De.useState(e),[x,h]=De.useState(null),[b,v]=De.useState(null),[p,S]=De.useState(!1),[R,A]=De.useState(!1),[W,_]=De.useState(!1),[F,M]=De.useState(!1),[Z,j]=De.useState(""),[I,pe]=De.useState(!1),[g,te]=De.useState(null),[Se,Ne]=De.useState(!1),[fe,Ve]=De.useState(""),[J,de]=De.useState([]),[ke,We]=De.useState(!1),[Me,Ot]=De.useState(!1),[Lt,Le]=De.useState(null);De.useEffect(()=>{m(e)},[e]);let vt=P=>{m(P),s?.(P)},bt=Object.entries(n.metadata??{}),Ie=Tt(n)-n.amount_refunded,Bt=(n.status==="paid"||n.status==="partially_refunded")&&Ie>0,y=P=>(typeof P.unitAmount=="number"?P.unitAmount:0)*(typeof P.quantity=="number"&&P.quantity>0?P.quantity:1),T=Math.max(0,(n.shipping_total??0)-(n.shipping_refunded??0)),ne=J.reduce((P,ge)=>P+y(n.line_items[ge]??{}),0)+(ke?T:0),Xe=n.tax_total??0,et=n.automatic_tax&&n.tax_behavior==="exclusive"&&Xe>0&&n.amount_total+(n.shipping_total??0)>0?Math.min(Math.max(0,Xe-(n.tax_refunded??0)),Math.round(Xe*ne/(n.amount_total+(n.shipping_total??0)))):0,tt=ne+et,Ke=J.length>0||ke,Et=Ke?tt:Ct(fe,n.currency),ya=At(n.currency)?"1":"0.01",ha=async()=>{try{S(!0),h(null),v(null),await d.resendOrderReceipt(n.id);let P=await d.getOrder(n.id);vt(P),v("Receipt email queued.")}catch(P){h(P instanceof Error?P.message:"Failed to resend receipt")}finally{S(!1)}},G=async()=>{try{A(!0),h(null),v(null);let P=await d.resetOrderDownloads(n.id);vt(P),_(!1),v("Download count reset.")}catch(P){h(P instanceof Error?P.message:"Failed to reset downloads")}finally{A(!1)}},ve=!!n.shipping_address,_e=typeof n.merchant_fulfilled_at=="string",ra=Pi.includes(n.status),Dt=Z.trim(),xa=Si.test(Dt)&&Dt.length<=dr,yt=async P=>{try{pe(!0),te(null),v(null);let ge=await d.setOrderFulfillment(n.id,{fulfilled:P,...P&&Dt?{trackingNumber:Dt}:{}});vt(ge),j(""),v(P?"Marked as shipped.":"Marked as not shipped.")}catch(ge){ge instanceof na&&ge.status===409?te(`This order is ${n.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):te(ge instanceof Error?ge.message:"Failed to update the order")}finally{pe(!1)}},Be=()=>{Le(null),Ve(String(Je(Ie,n.currency))),de([]),We(!1),Ne(!0)},ze=P=>de(ge=>ge.includes(P)?ge.filter(lt=>lt!==P):[...ge,P]),ka=async(P,ge)=>{if(a)try{Ot(!0),Le(null),await a(n,P,ge);let lt=await d.getOrder(n.id);vt(lt),Ne(!1),v("Refund issued.")}catch(lt){Le(lt instanceof Error?lt.message:"Refund failed")}finally{Ot(!1)}},O=async()=>{if(Ke){if(tt<=0){Le("The lines you picked were charged nothing");return}if(tt>Ie){Le(`That selection exceeds the refundable remainder (${U(Ie,n.currency)})`);return}await ka(tt,{...J.length>0?{line_items:[...J].sort((ge,lt)=>ge-lt)}:{},...ke?{shipping:!0}:{}});return}let P=Ct(fe,n.currency);if(P===null||P<=0){Le("Enter a valid refund amount");return}if(P>Ie){Le(`Amount exceeds the refundable remainder (${U(Ie,n.currency)})`);return}await ka(P,{amount:P})},ot=()=>ka(Ie,{full:!0}),As=n.fulfillment_type==="download",Fs=r&&ve,Kr=Ci(n),Qr=n.shipping_address?mr(n.shipping_address).join(`
4
- `):"",Us=n.shipping_total!=null,Vs=!!n.automatic_tax&&n.tax_behavior==="exclusive"&&(n.tax_total??0)>0,Zr=!(n.automatic_tax&&n.tax_behavior==="exclusive")&&(n.tax_total??0)>0,Jr=Us||Vs,_a=[];return _a.push(c(Ts,{icon:p?c(Qa,{className:"af-h-4 af-w-4 af-animate-spin"}):c(fr,{className:"af-h-4 af-w-4"}),disabled:p||n.fulfillment_status!=="fulfilled",onSelect:()=>{M(!1),ha()},children:"Resend receipt"},"resend")),As&&_a.push(c(Ts,{icon:c(hi,{className:"af-h-4 af-w-4"}),disabled:R,onSelect:()=>{M(!1),_(!0)},children:"Reset download count"},"reset")),Bt&&_a.push(B("div",{children:[c(Ts,{icon:c(cr,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{M(!1),Be()},children:"Refund\u2026"}),!a&&c("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),B("div",{children:[B("div",{className:"af-mb-6",children:[B(N,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[c(di,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),B("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[B("div",{className:"af-min-w-0",children:[B("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[c("h3",{className:"af-text-xl af-font-semibold",children:aa(n)}),c(ma,{status:n.status}),r&&c(wa,{order:n}),n.is_test&&c(q,{variant:"outline",children:"Test"})]}),B("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Ss(n.created_at)]}),n.is_test&&c("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),B("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||l)&&B("div",{className:"af-flex af-items-center",children:[c(N,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!u,"aria-label":"Previous order",children:c(ui,{className:"af-h-4 af-w-4"})}),c(N,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:l,disabled:!f,"aria-label":"Next order",children:c(mi,{className:"af-h-4 af-w-4"})})]}),Fs&&(_e?B("div",{className:"af-flex af-items-center af-gap-1",children:[B("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",n.merchant_fulfilled_at?` \xB7 ${Ss(n.merchant_fulfilled_at)}`:""]}),ra&&B(N,{variant:"ghost",size:"sm",onClick:()=>yt(!1),disabled:I,children:[I?c(Qa,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):c(cr,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):ra?B("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[c(ie,{value:Z,onChange:P=>j(P.target.value),placeholder:"Tracking number (optional)",maxLength:dr,className:"af-w-[200px]","aria-label":"Tracking number (optional)",disabled:I}),B(N,{variant:"default",onClick:()=>yt(!0),disabled:I||!xa,children:[I?c(Qa,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):c(xi,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),_a.length>0&&B(nr,{open:F,onOpenChange:M,children:[c(ir,{asChild:!0,children:c(N,{variant:"outline",size:"icon","aria-label":"More actions",children:c(bi,{className:"af-h-4 af-w-4"})})}),c(Ps,{children:c("div",{className:"af-space-y-0.5",children:_a})})]})]})]}),Fs&&!_e&&!xa&&c("p",{className:"af-mt-2 af-text-xs af-text-destructive",children:"Tracking numbers can use letters, numbers, spaces, dashes and underscores \u2014 up to 100 characters."}),g&&c("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:g}),b&&c("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:b}),x&&c("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:x})]}),B("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[B("div",{className:"af-space-y-6",children:[n.line_items.length>0&&c(ca,{title:"Items",children:c("ul",{className:"af-space-y-3",children:n.line_items.map((P,ge)=>{let lt=typeof P.name=="string"&&P.name?P.name:"Item",Hs=typeof P.quantity=="number"&&P.quantity>0?P.quantity:1,$s=typeof P.unitAmount=="number";return B("li",{className:"af-flex af-items-start af-gap-3",children:[c(Ti,{src:typeof P.imageUrl=="string"&&P.imageUrl?P.imageUrl:void 0}),B("div",{className:"af-min-w-0 af-flex-1",children:[B("div",{className:"af-text-sm af-font-medium",children:[lt,typeof P.variantTitle=="string"&&P.variantTitle&&B("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",P.variantTitle]})]}),B("div",{className:ga,children:[Hs," \xD7"," ",$s?U(P.unitAmount,n.currency):"\u2014"]}),P.refunded===!0&&c(q,{variant:"secondary",className:"af-mt-1",children:P.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),c("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:$s?U(P.unitAmount*Hs,n.currency):"\u2014"})]},ge)})})}),bt.length>0&&c(ca,{title:"Order details",children:c("dl",{className:"af-space-y-2",children:bt.map(([P,ge])=>B("div",{children:[c("dt",{className:D(ga,"af-capitalize"),children:P.replace(/_/g," ")}),c("dd",{className:"af-text-sm af-break-words",children:gr(ge)})]},P))})}),c(ca,{title:"Payment",children:B("div",{className:"af-ml-auto af-w-full sm:af-max-w-xs",children:[Jr&&c(da,{label:"Subtotal",children:U(n.amount_total,n.currency)}),Us&&c(da,{label:"Shipping",children:n.shipping_total===0?"Free":U(n.shipping_total??0,n.currency)}),Vs&&c(da,{label:"Tax",children:U(n.tax_total??0,n.currency)}),c(da,{label:"Total",emphasis:!0,children:U(Tt(n),n.currency)}),Zr&&c(da,{label:"incl. tax",children:U(n.tax_total??0,n.currency)}),n.base_currency!=null&&n.base_amount_total!=null&&B(da,{label:"Your price",children:[U(n.base_amount_total,n.base_currency),B("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",n.currency.toUpperCase()]})]}),n.amount_refunded>0&&B(ki,{children:[B(da,{label:"Refunded",children:["\u2212",U(n.amount_refunded,n.currency),(n.shipping_refunded??0)>0&&B("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",U(n.shipping_refunded??0,n.currency)," ","shipping"]})]}),c(da,{label:"Net",children:c("span",{className:"af-font-medium",children:U(Math.max(0,Tt(n)-n.amount_refunded),n.currency)})})]})]})}),c(ca,{title:"Timeline",children:c("ol",{className:"af-space-y-3",children:Kr.map(P=>B("li",{className:"af-flex af-gap-3",children:[c("span",{"aria-hidden":"true",className:D("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",P.tone==="destructive"?"af-bg-destructive":P.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),B("div",{className:"af-min-w-0",children:[c("div",{className:"af-text-sm af-break-words",children:P.text}),P.at&&c("div",{className:"af-text-xs af-text-muted-foreground",children:Ss(P.at)})]})]},P.key))})})]}),B("div",{className:"af-space-y-6",children:[c(ca,{title:"Customer",children:B("div",{className:"af-space-y-2",children:[B("div",{children:[c("div",{className:ga,children:"Email"}),B("div",{className:"af-flex af-items-center af-gap-1",children:[c("span",{className:"af-min-w-0 af-break-all af-text-sm",children:n.customer_email||c("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),n.customer_email&&c(ks,{value:n.customer_email,label:"Copy email"})]})]}),n.customer_name&&B("div",{children:[c("div",{className:ga,children:"Name"}),c("div",{className:"af-text-sm",children:n.customer_name})]}),n.customer&&B("div",{children:[c("div",{className:ga,children:"Customer record"}),B("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[c("span",{className:"af-break-all af-text-sm",children:n.customer.name||n.customer.email}),c(q,{variant:"secondary",children:"Linked"})]})]})]})}),n.shipping_address&&c(ca,{title:"Ship to",action:c(ks,{value:Qr,label:"Copy address",size:"sm",children:"Copy address"}),children:c("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:mr(n.shipping_address).map((P,ge)=>c("div",{children:P},ge))})}),c(ca,{title:"Emails",children:B("div",{className:"af-space-y-4",children:[c(ur,{side:"buyer",title:"Receipt to buyer",recipient:n.customer_email,status:n.buyer_email_status,attempts:n.buyer_email_attempts,orderStatus:n.status,action:B(N,{variant:"outline",size:"sm",onClick:ha,disabled:p||n.fulfillment_status!=="fulfilled",children:[p?c(Qa,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):c(fr,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),c(ur,{side:"merchant",title:"Sale alert to you",recipient:null,status:n.merchant_email_status,attempts:n.merchant_email_attempts,orderStatus:n.status})]})}),As&&c(ca,{title:"Download",children:B("div",{className:"af-space-y-2",children:[B("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[c(vi,{className:"af-h-4 af-w-4"}),B("span",{children:["Downloaded ",n.download_count," time",n.download_count===1?"":"s"]})]}),n.download_url&&c("a",{href:n.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),B("details",{className:"af-rounded-lg af-border af-p-4",children:[c("summary",{className:D(pr,"af-cursor-pointer af-select-none"),children:"Technical details"}),B("div",{className:"af-mt-3 af-space-y-2",children:[c(Rs,{label:"Order ID",value:n.id}),n.stripe_checkout_session_id&&c(Rs,{label:"Checkout session",value:n.stripe_checkout_session_id}),n.stripe_payment_intent_id&&c(Rs,{label:"Payment",value:n.stripe_payment_intent_id})]})]})]})]}),c(fa,{open:W,onOpenChange:P=>{!P&&!R&&_(!1)},children:B(Jt,{children:[B(Yt,{children:[c(ea,{children:"Reset download count?"}),c(ta,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),B(Xt,{children:[c(N,{variant:"outline",onClick:()=>_(!1),disabled:R,children:"Cancel"}),c(N,{onClick:G,disabled:R,children:R?"Resetting...":"Reset"})]})]})}),c(fa,{open:Se,onOpenChange:P=>{!P&&!Me&&Ne(!1)},children:B(Jt,{children:[B(Yt,{children:[c(ea,{children:"Refund order"}),B(ta,{children:["Refund up to ",U(Ie,n.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),B("div",{className:"af-space-y-4",children:[(n.line_items.length>0||T>0)&&B("div",{className:"af-space-y-2",children:[c(se,{children:"Items"}),B("div",{className:"af-space-y-2",children:[n.line_items.map((P,ge)=>{let lt=P.refunded===!0;return B("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[c("input",{type:"checkbox",checked:J.includes(ge),onChange:()=>ze(ge),disabled:Me||lt,className:"af-h-4 af-w-4"}),B("span",{className:lt?"af-text-muted-foreground af-line-through":void 0,children:[typeof P.name=="string"&&P.name?P.name:"Item",typeof P.variantTitle=="string"&&P.variantTitle?` \u2014 ${P.variantTitle}`:"",typeof P.quantity=="number"&&P.quantity>1?` \xD7 ${P.quantity}`:""]}),c("span",{className:"af-ml-auto af-text-muted-foreground",children:lt?"Refunded":U(y(P),n.currency)})]},ge)}),T>0&&B("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[c("input",{type:"checkbox",checked:ke,onChange:P=>We(P.target.checked),disabled:Me,className:"af-h-4 af-w-4"}),c("span",{children:"Shipping"}),c("span",{className:"af-ml-auto af-text-muted-foreground",children:U(T,n.currency)})]})]})]}),B("div",{className:"af-space-y-2",children:[B(se,{htmlFor:"refund-amount",children:["Amount (",n.currency.toUpperCase(),")"]}),c(ie,{id:"refund-amount",type:"number",min:"0",step:ya,value:Ke?String(Je(tt,n.currency)):fe,onChange:P=>Ve(P.target.value),disabled:Me||Ke}),Ke&&c("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Lt&&c("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Lt}),B(Xt,{children:[c(N,{variant:"outline",onClick:()=>Ne(!1),disabled:Me,children:"Cancel"}),c(N,{variant:"outline",onClick:ot,disabled:Me,children:"Refund everything"}),c(N,{variant:"destructive",onClick:O,disabled:Me,children:Me?"Refunding...":Et!==null&&Et>0?`Refund ${U(Et,n.currency)}`:"Refund"})]})]})})]})}import*as Ya from"react";import{ArrowLeft as _i,RefreshCw as Oi}from"lucide-react";import{jsx as Ut,jsxs as va}from"react/jsx-runtime";function Vt({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:r}){let i=Ya.useRef(null);return Ya.useEffect(()=>{i.current?.focus()},[]),va("div",{className:D("af-bg-background",r),children:[va("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-justify-between af-gap-2 af-border-b af-bg-background af-px-4 af-py-2",children:[Ut("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!a&&va(N,{type:"button",variant:"outline",size:"sm",onClick:t,children:[Ut(_i,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Ut("div",{className:"af-p-4",children:s})]})}function z({className:e}){return Ut("div",{"aria-hidden":"true",className:D("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function rt({label:e,children:t,detail:a,valueClassName:s}){return va("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Ut("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Ut("div",{className:D("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&Ut("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function pt({message:e,onRetry:t}){return va("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ut("span",{children:e}),va(N,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[Ut(Oi,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Ht({icon:e,children:t}){return va("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Ut("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}import{Fragment as Fi,jsx as w,jsxs as ee}from"react/jsx-runtime";var Ai={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},br={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function yr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function hr(e){let t=Array.isArray(e.line_items)?e.line_items:[],a=t[0];if(!a)return"\u2014";let s=typeof a.name=="string"&&a.name?a.name:"Item",r=typeof a.quantity=="number"&&a.quantity>0?a.quantity:1,i=r>1?`${s} \xD7${r}`:s;return t.length>1?`${i} +${t.length-1} more`:i}function Xa(e){return e.customer?.name||e.customer_name||null}function Pa({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:r=!1,emptyMessage:i,onDetailOpenChange:l}){let{api:u}=Y(),f=Wa({refreshKey:a}),{orders:d,total:n,isLoading:m,error:x,page:h,pageSize:b,hasNextPage:v,hasPreviousPage:p,setPage:S,setPageSize:R,customerEmail:A,setCustomerEmail:W,setStatusIn:_,from:F,setFrom:M,to:Z,setTo:j,showAbandoned:I,setShowAbandoned:pe,setUnfulfilledOnly:g,refetch:te}=f,[Se,Ne]=je.useState("list"),[fe,Ve]=je.useState(null),[J,de]=je.useState(""),[ke,We]=je.useState(""),[Me,Ot]=je.useState(r?"needs_shipping":"all"),[Lt,Le]=je.useState(!1),[vt,bt]=je.useState(!!s),[Ie,Bt]=je.useState(null);je.useEffect(()=>{if(!s)return;let O=!1;return bt(!0),Bt(null),u.getOrder(s).then(ot=>{O||(Ve(ot),Ne("detail"))}).catch(()=>{O||Bt("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{O||bt(!1)}),()=>{O=!0}},[u,s]);let y=je.useCallback(O=>{Ot(O);let ot=br[O];_(ot.statusIn),g(ot.unfulfilledOnly)},[_,g]);je.useEffect(()=>{r&&g(!0)},[]);let T=je.useRef(!r);je.useEffect(()=>{T.current||m||(T.current=!0,d.length===0&&y("all"))},[m,d.length,y]);let ne=Se==="detail"&&!!fe;je.useEffect(()=>{l?.(ne)},[ne,l]);let Xe=(F?1:0)+(Z?1:0)+(I?1:0),et=Xe>0||!!A||!!ke,tt=!!F&&!!Z&&F>Z,Ke=O=>{Ve(O),Ne("detail")},Et=()=>{Ne("list"),Ve(null),te()},ya=O=>{let ot=O.trim();if(!ot){We(""),A&&W("");return}if(ot.startsWith("#")||/^\d+$/.test(ot)){We(ot),A&&W("");return}We(""),W(ot)},ha=()=>{de(""),We(""),W(""),M(""),j(""),pe(!1),Le(!1)},G=ke.replace(/^#/,"").toLowerCase(),ve=G?d.filter(O=>String(O.order_number??"")===G||O.id.toLowerCase().startsWith(G)):d,_e=fe?d.findIndex(O=>O.id===fe.id):-1,ra=_e>0,Dt=_e>=0&&_e<d.length-1;if(vt)return w("div",{className:t,children:w("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:w(Bi,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(Se==="detail"&&fe)return w("div",{className:t,children:w(Ja,{order:fe,onBack:Et,onRefund:e,onOrderUpdated:O=>Ve(O),allowFulfillment:r,onPrevOrder:ra?()=>Ve(d[_e-1]):void 0,onNextOrder:Dt?()=>Ve(d[_e+1]):void 0,hasPrevOrder:ra,hasNextOrder:Dt},fe.id)});let yt=ee("div",{className:"af-mb-4 af-space-y-3",children:[Ie&&w("p",{className:"af-text-xs af-text-muted-foreground",children:Ie}),ee("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[w("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(r?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(O=>w("button",{type:"button","aria-pressed":Me===O,onClick:()=>y(O),className:D("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Me===O?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ai[O]},O))}),ee("div",{className:"af-relative af-w-full af-max-w-xs",children:[w(Di,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),w(ie,{type:"text",value:J,onChange:O=>de(O.target.value),onBlur:()=>ya(J),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),ya(J))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),ee(N,{type:"button",variant:Xe>0?"secondary":"ghost",size:"sm",onClick:()=>Le(O=>!O),"aria-expanded":Lt,children:[w(Ii,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Xe>0&&w(q,{variant:"secondary",className:"af-ml-2",children:Xe})]}),et&&w(N,{type:"button",variant:"ghost",size:"sm",onClick:ha,children:"Clear filters"})]}),(Lt||!!F||!!Z)&&ee("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2",children:[w(se,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),w(ie,{id:"orders-from",type:"date",value:F,max:Z||void 0,onChange:O=>M(O.target.value),className:"af-w-[170px]"}),w(se,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),w(ie,{id:"orders-to",type:"date",value:Z,min:F||void 0,onChange:O=>j(O.target.value),className:"af-w-[170px]"}),!br[Me].statusIn&&w(N,{type:"button",variant:I?"secondary":"ghost",size:"sm",onClick:()=>pe(!I),"aria-pressed":I,children:I?"Hide abandoned":"Show abandoned"})]}),tt&&w("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(m)return ee("div",{className:t,children:[yt,w("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(O=>ee("div",{className:"af-rounded-md af-border af-p-3",children:[ee("div",{className:"af-flex af-items-center af-justify-between",children:[w(z,{className:"af-h-4 af-w-16"}),w(z,{className:"af-h-4 af-w-14"})]}),w(z,{className:"af-mt-2 af-h-3 af-w-40"}),w(z,{className:"af-mt-2 af-h-3 af-w-24"})]},O))}),w("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ee(be,{children:[w(ye,{children:ee(X,{children:[w(C,{children:"Order"}),w(C,{children:"Date"}),w(C,{children:"Customer"}),w(C,{children:"Items"}),w(C,{className:"af-text-right",children:"Total"}),w(C,{children:"Status"}),w(C,{className:"af-w-8"})]})}),w(he,{"aria-hidden":"true",children:[0,1,2,3,4].map(O=>ee(X,{children:[w(k,{children:w(z,{className:"af-h-4 af-w-14"})}),w(k,{children:w(z,{className:"af-h-4 af-w-24"})}),w(k,{children:w(z,{className:"af-h-4 af-w-40"})}),w(k,{children:w(z,{className:"af-h-4 af-w-32"})}),w(k,{children:w(z,{className:"af-ml-auto af-h-4 af-w-16"})}),w(k,{children:w(z,{className:"af-h-5 af-w-16"})}),w(k,{})]},O))})]})}),w("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(x)return ee("div",{className:t,children:[yt,ee("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[w("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),w(N,{type:"button",variant:"ghost",size:"sm",onClick:()=>te(),children:"Try again"})]})]});let Be=Me!=="all";if(ve.length===0&&h===0)return ee("div",{className:t,children:[(et||Be)&&yt,ee("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[w(Ei,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),w("p",{className:"af-text-muted-foreground af-text-center",children:et||Be?"No orders match these filters.":i??ee(Fi,{children:["No orders yet.",w("br",{}),"Orders will appear here when someone buys from your website."]})}),!et&&!Be&&w(N,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>pe(!0),children:"Show abandoned checkouts"})]})]});let ze=h*b+1,ka=Math.min((h+1)*b,n);return ee("div",{className:t,children:[yt,w("div",{className:"af-space-y-3 lg:af-hidden",children:ve.map(O=>ee("button",{type:"button",onClick:()=>Ke(O),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[ee("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[w("span",{className:"af-font-medium",children:aa(O)}),w("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:U(Tt(O),O.currency)})]}),ee("div",{className:"af-mt-1 af-min-w-0",children:[ee("div",{className:"af-truncate af-text-sm",children:[O.customer_email||w("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Xa(O)&&ee("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Xa(O)]})]}),w("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:hr(O)}),O.amount_refunded>0&&ee("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",U(O.amount_refunded,O.currency)," refunded"]})]}),ee("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[w(ma,{status:O.status}),O.is_test&&w(q,{variant:"outline",children:"Test"}),r&&w(wa,{order:O}),w("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:yr(O.created_at)})]})]},O.id))}),w("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ee(be,{children:[w(ye,{children:ee(X,{children:[w(C,{children:"Order"}),w(C,{children:"Date"}),w(C,{children:"Customer"}),w(C,{children:"Items"}),w(C,{className:"af-text-right",children:"Total"}),w(C,{children:"Status"}),w(C,{className:"af-w-8"})]})}),w(he,{children:ve.map(O=>ee(X,{onClick:()=>Ke(O),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[ee(k,{className:"af-whitespace-nowrap af-font-medium",children:[w("button",{type:"button",onClick:ot=>{ot.stopPropagation(),Ke(O)},"aria-label":`Open order ${aa(O)}`,className:"af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:aa(O)}),O.is_test&&w(q,{variant:"outline",className:"af-ml-2",children:"Test"})]}),w(k,{className:"af-whitespace-nowrap af-text-muted-foreground",children:yr(O.created_at)}),ee(k,{className:"af-max-w-[220px]",children:[w("div",{className:"af-truncate",children:O.customer_email||w("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Xa(O)&&w("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Xa(O)})]}),w(k,{className:"af-max-w-[220px]",children:w("div",{className:"af-truncate af-text-muted-foreground",children:hr(O)})}),ee(k,{className:"af-whitespace-nowrap af-text-right",children:[w("div",{className:"af-font-medium af-tabular-nums",children:U(Tt(O),O.currency)}),O.amount_refunded>0&&ee("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",U(O.amount_refunded,O.currency)," ","refunded"]})]}),w(k,{children:ee("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[w(ma,{status:O.status}),r&&w(wa,{order:O})]})}),w(k,{className:"af-w-8 af-text-right",children:w(vr,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},O.id))})]})}),ee("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[ee("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[w("span",{children:G?`${ve.length} matching this page`:`Showing ${ze}-${ka} of ${n}`}),ee(ht,{value:String(b),onValueChange:O=>R(Number(O)),children:[w(dt,{className:"af-w-[70px] af-h-8",children:w(xt,{})}),ee(ut,{children:[w(xe,{value:"10",children:"10"}),w(xe,{value:"25",children:"25"}),w(xe,{value:"50",children:"50"}),w(xe,{value:"100",children:"100"})]})]}),w("span",{children:"per page"})]}),ee("div",{className:"af-flex af-items-center af-gap-2",children:[ee(N,{variant:"outline",size:"sm",onClick:()=>S(h-1),disabled:!p,children:[w(Li,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ee(N,{variant:"outline",size:"sm",onClick:()=>S(h+1),disabled:!v,children:["Next",w(vr,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as as from"react";import{ChevronLeft as $i,ChevronRight as Mi,Eye as zi,Search as ji,Users as qi}from"lucide-react";import*as ft from"react";function es({initialPageSize:e=25}={}){let{api:t}=Y(),[a,s]=ft.useState([]),[r,i]=ft.useState(0),[l,u]=ft.useState(!0),[f,d]=ft.useState(null),[n,m]=ft.useState(0),[x,h]=ft.useState(e),[b,v]=ft.useState(""),p=ft.useRef(0),S=ft.useCallback(async()=>{let A=++p.current;try{u(!0),d(null);let W={limit:x,offset:n*x};b.trim()&&(W.email=b.trim());let _=await t.getCustomers(W);if(A!==p.current)return;s(_.customers),i(_.total)}catch(W){if(A!==p.current)return;d(W instanceof Error?W:new Error("Failed to fetch customers"))}finally{A===p.current&&u(!1)}},[t,n,x,b]);ft.useEffect(()=>{S()},[S]);let R=Math.ceil(r/x);return{customers:a,total:r,isLoading:l,error:f,page:n,pageSize:x,hasNextPage:n<R-1,hasPreviousPage:n>0,setPage:m,setPageSize:A=>{h(A),m(0)},email:b,setEmail:A=>{v(A),m(0)},refetch:S}}import*as ba from"react";import{ArrowLeft as Ui,Loader2 as Vi}from"lucide-react";import{jsx as ce,jsxs as Ye}from"react/jsx-runtime";function xr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Hi(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let a=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return a&&t.push(a),e.country&&t.push(e.country),t}function ts({customer:e,onBack:t,className:a}){let{api:s}=Y(),[r,i]=ba.useState(null),[l,u]=ba.useState([]),[f,d]=ba.useState(!0),[n,m]=ba.useState(null);ba.useEffect(()=>{let b=!1;return d(!0),m(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([v,p])=>{b||(i(v),u(p.orders))}).catch(v=>{b||m(v instanceof Error?v.message:"Failed to load customer")}).finally(()=>{b||d(!1)}),()=>{b=!0}},[s,e.id,e.email]);let x=r?.addresses??[],h=r?.order_count??l.length;return Ye("div",{className:a,children:[Ye("div",{className:"af-mb-6",children:[Ye(N,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[ce(Ui,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),ce("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),Ye("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",xr(e.created_at)]})]}),f?ce("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:ce(Vi,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):n?ce("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:n}):Ye("div",{className:"af-space-y-6",children:[Ye("div",{children:[ce("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),Ye("div",{className:"af-space-y-1 af-text-sm",children:[Ye("div",{className:"af-flex af-gap-2",children:[ce("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),ce("span",{children:e.email})]}),e.name&&Ye("div",{className:"af-flex af-gap-2",children:[ce("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),ce("span",{children:e.name})]}),e.phone&&Ye("div",{className:"af-flex af-gap-2",children:[ce("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),ce("span",{children:e.phone})]}),Ye("div",{className:"af-flex af-gap-2",children:[ce("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),ce("span",{children:h})]})]})]}),x.length>0&&Ye("div",{children:[ce("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),ce("div",{className:"af-flex af-flex-wrap af-gap-3",children:x.map(b=>Ye("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[b.is_default&&ce(q,{variant:"secondary",className:"af-mb-1",children:"Default"}),Hi(b).map((v,p)=>ce("div",{children:v},p))]},b.id))})]}),Ye("div",{children:[ce("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),l.length===0?ce("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):Ye(be,{children:[ce(ye,{children:Ye(X,{children:[ce(C,{children:"Date"}),ce(C,{children:"Amount"}),ce(C,{children:"Status"})]})}),ce(he,{children:l.map(b=>Ye(X,{children:[ce(k,{className:"af-text-muted-foreground",children:xr(b.created_at)}),ce(k,{children:U(Tt(b),b.currency)}),ce(k,{children:ce(pa,{status:b.status})})]},b.id))})]})]})]})]})}import{Fragment as Wi,jsx as oe,jsxs as Ue}from"react/jsx-runtime";function Gi(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function ss({className:e}){let{customers:t,total:a,isLoading:s,error:r,page:i,pageSize:l,hasNextPage:u,hasPreviousPage:f,setPage:d,setPageSize:n,email:m,setEmail:x,refetch:h}=es(),[b,v]=as.useState("list"),[p,S]=as.useState(null),[R,A]=as.useState(""),W=j=>{S(j),v("detail")},_=()=>{v("list"),S(null),h()};if(b==="detail"&&p)return oe("div",{className:e,children:oe(ts,{customer:p,onBack:_})});let F=Ue("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[oe(ie,{type:"email",value:R,onChange:j=>A(j.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),x(R.trim()))}}),Ue(N,{type:"button",variant:"outline",size:"sm",onClick:()=>x(R.trim()),children:[oe(ji,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),m&&oe(N,{type:"button",variant:"ghost",size:"sm",onClick:()=>{A(""),x("")},children:"Clear"})]});if(s)return Ue("div",{className:e,children:[F,oe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:oe("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(r)return Ue("div",{className:e,children:[F,oe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ue("div",{className:"af-text-destructive",children:["Error: ",r.message]})})]});if(t.length===0&&i===0)return Ue("div",{className:e,children:[m&&F,Ue("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[oe(qi,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),oe("p",{className:"af-text-muted-foreground af-text-center",children:m?"No customers match that email.":Ue(Wi,{children:["No customers yet.",oe("br",{}),"Customers appear here after their first purchase."]})})]})]});let M=i*l+1,Z=Math.min((i+1)*l,a);return Ue("div",{className:e,children:[F,Ue(be,{children:[oe(ye,{children:Ue(X,{children:[oe(C,{children:"Email"}),oe(C,{children:"Name"}),oe(C,{children:"Customer since"}),oe(C,{className:"af-text-right",children:"Actions"})]})}),oe(he,{children:t.map(j=>Ue(X,{children:[oe(k,{className:"af-font-medium",children:j.email}),oe(k,{children:j.name||oe("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),oe(k,{className:"af-text-muted-foreground",children:Gi(j.created_at)}),oe(k,{className:"af-text-right",children:oe(N,{variant:"ghost",size:"icon",onClick:()=>W(j),title:"View customer",children:oe(zi,{className:"af-h-4 af-w-4"})})})]},j.id))})]}),Ue("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Ue("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ue("span",{children:["Showing ",M,"-",Z," of ",a]}),Ue(ht,{value:String(l),onValueChange:j=>n(Number(j)),children:[oe(dt,{className:"af-w-[70px] af-h-8",children:oe(xt,{})}),Ue(ut,{children:[oe(xe,{value:"10",children:"10"}),oe(xe,{value:"25",children:"25"}),oe(xe,{value:"50",children:"50"}),oe(xe,{value:"100",children:"100"})]})]}),oe("span",{children:"per page"})]}),Ue("div",{className:"af-flex af-items-center af-gap-2",children:[Ue(N,{variant:"outline",size:"sm",onClick:()=>d(i-1),disabled:!f,children:[oe($i,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ue(N,{variant:"outline",size:"sm",onClick:()=>d(i+1),disabled:!u,children:["Next",oe(Mi,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as wr from"react";import{AlertTriangle as Nr,CheckCircle2 as Ki,CreditCard as _s,Loader2 as Qi,RefreshCw as Zi}from"lucide-react";import*as $t from"react";function Sa(){let{api:e}=Y(),[t,a]=$t.useState(null),[s,r]=$t.useState(!0),[i,l]=$t.useState(null),u=$t.useRef(0),f=$t.useCallback(async()=>{let d=++u.current;try{r(!0),l(null);let n=await e.getPaymentsStatus();if(d!==u.current)return;a(n)}catch(n){if(d!==u.current)return;l(n instanceof Error?n:new Error("Failed to fetch payments status"))}finally{d===u.current&&r(!1)}},[e]);return $t.useEffect(()=>{f()},[f]),{status:t,isLoading:s,error:i,refetch:f}}import{jsx as Re,jsxs as qe}from"react/jsx-runtime";function rs({onConnectStripe:e,onUpgradePlan:t,className:a}){let{status:s,isLoading:r,error:i,refetch:l}=Sa(),[u,f]=wr.useState(!1),d=async()=>{f(!0);try{await l()}finally{f(!1)}};return r&&!s?Re("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Re("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!s?Re("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:qe("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):s.status==="active"?Re("div",{className:a,children:qe("div",{className:"af-flex af-items-start af-gap-3 af-bg-green-50 af-border af-border-green-200 af-rounded-lg af-p-4",children:[Re(Ki,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),qe("div",{children:[Re("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),qe("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",s.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):qe("div",{className:`af-space-y-4 ${a||""}`,children:[s.reason==="needs_stripe"&&qe("div",{className:"af-space-y-3",children:[qe("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Re(_s,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),qe("div",{children:[Re("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),Re("p",{className:"af-text-sm af-text-muted-foreground",children:"It only takes a few minutes. You'll enter your details with Stripe, who handle the payments, and money from sales goes straight to your own bank."})]})]}),e?qe(N,{onClick:e,children:[Re(_s,{className:"af-h-4 af-w-4 af-mr-1"}),s.stripe_account_connected?"Finish setting up":"Set up payments"]}):Re("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),s.reason==="needs_paid_plan"&&qe("div",{className:"af-space-y-3",children:[qe("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Re(Nr,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),qe("div",{children:[Re("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),Re("p",{className:"af-text-sm af-text-muted-foreground",children:"Your products are saved as drafts. Upgrade to a paid plan to start accepting payments on your site."})]})]}),t?Re(N,{onClick:t,children:"Upgrade plan"}):Re("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),s.reason==="account_disabled"&&qe("div",{className:"af-space-y-3",children:[qe("div",{className:"af-flex af-items-start af-gap-3 af-bg-yellow-50 af-border af-border-yellow-200 af-rounded-lg af-p-4",children:[Re(Nr,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),qe("div",{children:[Re("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),s.stripe_account_connected?Re("p",{className:"af-text-sm af-text-yellow-800",children:"Your Stripe account can't currently accept charges. Check your Stripe account for outstanding requirements or notifications \u2014 once Stripe re-enables charges, payments resume here automatically."}):Re("p",{className:"af-text-sm af-text-yellow-800",children:"Payments are currently paused for this site. If you think this is a mistake, get in touch with support and we'll look into it with you."})]})]}),qe("div",{className:"af-flex af-gap-2",children:[e&&s.stripe_account_connected&&qe(N,{onClick:e,children:[Re(_s,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),qe(N,{variant:"outline",onClick:d,disabled:u,children:[u?Re(Qi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Re(Zi,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as it from"react";function Os(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function Ra({includeStats:e=!1,refreshKey:t}={}){let{api:a}=Y(),[s,r]=it.useState([]),[i,l]=it.useState(!0),[u,f]=it.useState(null),d=it.useRef(0),n=it.useCallback(async()=>{let p=++d.current;try{l(!0),f(null);let S=await a.getProducts(e?{include:"stats"}:{});if(p!==d.current)return;r(S)}catch(S){if(p!==d.current)return;f(S instanceof Error?S:new Error("Failed to fetch products"))}finally{p===d.current&&l(!1)}},[a,e,t]);it.useEffect(()=>{n()},[n]);let m=it.useCallback(async p=>{let S=await a.createProduct(p);return r(R=>[S,...R]),S},[a]),x=it.useCallback(async(p,S)=>{let R=await a.updateProduct(p,S);return r(A=>Os(A,p,R)),R},[a]),h=it.useCallback(async p=>{await a.deleteProduct(p),r(S=>S.filter(R=>R.id!==p))},[a]),b=it.useCallback(async(p,S)=>{let R=await a.attachProductFile(p,S);return r(A=>Os(A,p,R)),R},[a]),v=it.useCallback(async(p,S)=>{let R=await a.attachProductFileFromUrl(p,S);return r(A=>Os(A,p,R)),R},[a]);return{products:s,isLoading:i,error:u,refetch:n,createProduct:m,updateProduct:x,deleteProduct:h,attachProductFile:b,attachProductFileFromUrl:v}}import{jsx as $e,jsxs as wt}from"react/jsx-runtime";function Pr({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:r}){let[i,l]=ns.useState(t),[u,f]=ns.useState("list"),[d,n]=ns.useState(null),m=Ra(),{status:x,error:h}=Sa(),b=x?.currency,v=A=>{n(A),f("edit")},p=()=>{n(null),f("create")},S=()=>{f("list"),n(null)},R=A=>{n(A),f("edit")};return wt("div",{className:e,children:[wt("div",{className:"af-mb-6",children:[$e("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),$e("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),wt(Fa,{value:i,onValueChange:A=>l(A),children:[wt(La,{className:"af-mb-4",children:[wt(qt,{value:"products",className:"af-gap-2",children:[$e(Yi,{className:"af-h-4 af-w-4"}),"Products"]}),wt(qt,{value:"orders",className:"af-gap-2",children:[$e(Xi,{className:"af-h-4 af-w-4"}),"Orders"]}),wt(qt,{value:"customers",className:"af-gap-2",children:[$e(to,{className:"af-h-4 af-w-4"}),"Customers"]}),wt(qt,{value:"setup",className:"af-gap-2",children:[$e(eo,{className:"af-h-4 af-w-4"}),"Setup"]})]}),$e(Gt,{value:"products",children:u==="list"?$e(ja,{productsState:m,onSelectProduct:v,onCreateProduct:p}):wt("div",{children:[wt("div",{className:"af-mb-6",children:[wt(N,{variant:"ghost",size:"sm",onClick:S,className:"af-mb-2 af--ml-2",children:[$e(Ji,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),$e("h3",{className:"af-text-lg af-font-semibold",children:u==="create"?"New Product":d?.name})]}),u==="create"&&!b?$e("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:h?wt("div",{className:"af-text-destructive",children:["Error: ",h.message]}):$e("div",{className:"af-text-muted-foreground",children:"Loading..."})}):$e(Ga,{productsState:m,product:u==="edit"?d:null,currency:b??"usd",onSaved:R},u==="edit"?d?.id??"edit":"new")]})}),$e(Gt,{value:"orders",children:$e(Pa,{onRefund:s})}),$e(Gt,{value:"customers",children:$e(ss,{})}),$e(Gt,{value:"setup",children:$e(rs,{onConnectStripe:a,onUpgradePlan:r})})]})]})}import*as Rr from"react";import*as Mt from"react";function is({refreshKey:e}={}){let{api:t}=Y(),[a,s]=Mt.useState(null),[r,i]=Mt.useState(!0),[l,u]=Mt.useState(null),f=Mt.useRef(0),d=Mt.useCallback(async()=>{let n=++f.current;try{i(!0),u(null);let m=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(n!==f.current)return;s(m)}catch(m){if(n!==f.current)return;u(m instanceof Error?m:new Error("Failed to fetch summary"))}finally{n===f.current&&i(!1)}},[t,e]);return Mt.useEffect(()=>{d()},[d]),{summary:a,isLoading:r,error:l,refetch:d}}import{Fragment as Ls,jsx as Ge,jsxs as Bs}from"react/jsx-runtime";function Sr(e,t){if(e.settled.complete)return{headline:U(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:U(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${U(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:U(0,t),extra:[]}}function Tr({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:r,className:i}){let{summary:l,isLoading:u,error:f,refetch:d}=is({refreshKey:e}),[n,m]=Rr.useState(!1),x=Ge("div",{className:"af-mb-6",children:f&&!l?Ge(pt,{message:"Couldn't load your revenue summary.",onRetry:()=>d()}):Ge("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:u||!l?Bs(Ls,{children:[Ge(rt,{label:"This week",children:Ge(z,{className:"af-h-6 af-w-24"})}),Ge(rt,{label:"Today",children:Ge(z,{className:"af-h-6 af-w-24"})}),Ge(rt,{label:"Needs attention",children:Ge(z,{className:"af-h-6 af-w-10"})})]}):Ge(Ls,{children:(()=>{let h=Sr(l.revenue.d7,l.currency),b=Sr(l.revenue.today,l.currency);return Bs(Ls,{children:[Ge(rt,{label:"This week",detail:h.extra.length>0?Ge("div",{children:h.extra.map(v=>Ge("div",{children:v},v))}):void 0,children:h.headline}),Ge(rt,{label:"Today",detail:b.extra.length>0?Ge("div",{children:b.extra.map(v=>Ge("div",{children:v},v))}):void 0,children:b.headline}),Ge(rt,{label:"Needs attention",valueClassName:l.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:l.needs_attention.count===0?"All clear":l.needs_attention.items[0]?.title??void 0,children:l.needs_attention.count})]})})()})})});return Bs(Vt,{title:"Orders",onBackToWebsite:r,hideBackButton:n,className:i,children:[x,Ge(Pa,{refreshKey:e,initialOrderId:t,onDetailOpenChange:m,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as sa from"react";import{ImageOff as io,Package as oo,Search as lo}from"lucide-react";import*as zt from"react";import{ArrowLeft as ro,ImageOff as no}from"lucide-react";import{jsx as kt,jsxs as Da}from"react/jsx-runtime";var Cr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ua="af-text-xs af-text-muted-foreground",os="af-text-sm af-font-medium af-tabular-nums",ao=3;function so(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let f=e.min_amount??t?.min_amount??null,d=e.max_amount??t?.max_amount??null;return f!==null&&d!==null?{text:`Buyer chooses (${U(f,a)} \u2013 ${U(d,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let r=t?.min_amount??e.unit_amount,i=t?.max_amount??e.unit_amount;if(r===null||i===null)return{text:"Varies by variant",compareAt:null};let l=r===i?U(r,a):`${U(r,a)} \u2013 ${U(i,a)}`,u=t?.compare_at_amount??null;return{text:l,compareAt:u!==null&&u>i?U(u,a):null}}function ls({product:e,className:t}){let a=so(e);return Da("div",{className:t,children:[kt("span",{className:os,children:a.text}),a.compareAt&&kt("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function fs({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?kt(q,{variant:"destructive",children:"Out of stock"}):t.low_stock?Da(q,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?kt(q,{variant:"secondary",children:"Backorder"}):t.available===null?null:Da(q,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?kt(q,{variant:"warning",children:"Low stock"}):null}function cs(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function ds(e){return e.map(t=>U(t.amount,t.currency)).join(" + ")}function kr(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${U(e.min_amount,e.currency)} \u2013 ${U(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":U(e.unit_amount,e.currency)}function _r({variant:e}){let t=e.inventory;if(!t||!t.tracked)return kt("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?Da("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[kt("span",{className:"af-tabular-nums",children:Math.max(0,a)}),kt(q,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?kt(q,{variant:"destructive",children:"Out of stock"}):Da("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[kt("span",{className:"af-tabular-nums",children:a}),a<=ao&&kt(q,{variant:"warning",children:"Low"})]})}import{jsx as H,jsxs as Pe}from"react/jsx-runtime";function Ia({title:e,children:t,className:a}){return Pe("section",{className:D("af-rounded-lg af-border af-p-4",a),children:[H("h4",{className:Cr,children:e}),H("div",{className:"af-mt-3",children:t})]})}function Or({src:e,className:t}){let[a,s]=zt.useState(!1);return zt.useEffect(()=>s(!1),[e]),!e||a?H("div",{"aria-hidden":"true",className:D("af-flex af-items-center af-justify-center af-bg-muted",t),children:H(no,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):H("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:D("af-object-cover",t)})}function Lr({product:e,showStats:t=!1,onBack:a}){let{api:s}=Y(),[r,i]=zt.useState(null),[l,u]=zt.useState(!0),[f,d]=zt.useState(null),[n,m]=zt.useState(0),[x,h]=zt.useState(0);zt.useEffect(()=>{let _=!1;return u(!0),d(null),s.getProduct(e.id).then(F=>{_||i(F)}).catch(F=>{_||d(F instanceof Error?F:new Error("Failed to load product"))}).finally(()=>{_||u(!1)}),()=>{_=!0}},[s,e.id,n]);let b=r?{...e,...r}:e,v=b.images.length>0?b.images:e.images,p=v[x]??v[0],S=cs(b),R=t?b.stats:void 0,A=r?.variants??[],W=A.length>1;return Pe("div",{children:[Pe("div",{className:"af-mb-6",children:[Pe(N,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[H(ro,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),Pe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[H("h3",{className:"af-text-xl af-font-semibold af-break-words",children:b.name}),H(q,{variant:b.active?"success":"secondary",children:b.active?"Active":"Draft"}),H(fs,{product:b})]}),H(ls,{product:b,className:"af-mt-1"}),!b.active&&H("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),Pe("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[Pe("div",{className:"af-space-y-2",children:[H(Or,{src:p,className:"af-h-48 af-w-full af-rounded-md af-border"}),v.length>1&&H("div",{className:"af-flex af-flex-wrap af-gap-2",children:v.map((_,F)=>H("button",{type:"button",onClick:()=>h(F),"aria-label":`Show photo ${F+1} of ${v.length}`,"aria-pressed":F===x,className:D("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",F===x?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:H(Or,{src:_,className:"af-h-12 af-w-12 af-rounded-md"})},`${_}-${F}`))})]}),Pe("div",{className:"af-space-y-6",children:[b.description&&H(Ia,{title:"Description",children:H("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:b.description})}),l?Pe(Ia,{title:"Variants",children:[H("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(_=>Pe("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[H(z,{className:"af-h-4 af-w-28"}),H(z,{className:"af-h-4 af-w-20"}),H(z,{className:"af-h-4 af-w-16"})]},_))}),H("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):f?H(pt,{message:"Couldn't load this product's variants.",onRetry:()=>m(_=>_+1)}):W?H(Ia,{title:`Variants \xB7 ${A.length}`,children:H("div",{className:"af-overflow-x-auto",children:Pe(be,{children:[H(ye,{children:Pe(X,{children:[H(C,{children:"Variant"}),H(C,{children:"SKU"}),H(C,{className:"af-text-right",children:"Price"}),H(C,{children:"Stock"})]})}),H(he,{children:A.map(_=>Pe(X,{children:[Pe(k,{className:"af-font-medium",children:[_.title||_.option_values.map(F=>F.value).join(" / ")||"\u2014",!_.active&&H(q,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),H(k,{className:"af-text-muted-foreground",children:_.sku?H("code",{className:"af-font-mono af-text-xs af-break-all",children:_.sku}):"\u2014"}),Pe(k,{className:"af-whitespace-nowrap af-text-right",children:[H("div",{className:os,children:kr(_)}),_.compare_at_amount!==null&&_.unit_amount!==null&&_.compare_at_amount>_.unit_amount&&H("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:U(_.compare_at_amount,_.currency)})]}),H(k,{className:"af-text-sm",children:H(_r,{variant:_})})]},_.id))})]})})}):null,H(Ia,{title:"Details",children:Pe("dl",{className:"af-space-y-2",children:[Pe("div",{children:[H("dt",{className:ua,children:"Delivery"}),H("dd",{className:"af-text-sm",children:S==="Digital download"?b.fulfillment.filename??"Digital download":S??"Nothing to deliver"})]}),b.fulfillment.type==="redirect"&&b.fulfillment.url&&Pe("div",{children:[H("dt",{className:ua,children:"Sends buyers to"}),H("dd",{className:"af-break-all af-text-sm",children:b.fulfillment.url})]}),Pe("div",{children:[H("dt",{className:ua,children:"Shipping address"}),H("dd",{className:"af-text-sm",children:b.collect_shipping_address?"Collected at checkout":"Not collected"})]}),Pe("div",{children:[H("dt",{className:ua,children:"Most one buyer can order"}),H("dd",{className:"af-text-sm af-tabular-nums",children:b.max_quantity})]})]})}),R&&H(Ia,{title:"Last 30 days",children:Pe("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[Pe("div",{children:[H("dt",{className:ua,children:"Units sold"}),H("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:R.units_sold})]}),Pe("div",{children:[H("dt",{className:ua,children:"Orders"}),H("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:R.orders})]}),Pe("div",{children:[H("dt",{className:ua,children:"Gross"}),H("dd",{className:os,children:R.gross.length>0?ds(R.gross):"\u2014"})]})]})}),H("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}import{Fragment as Ta,jsx as $,jsxs as Te}from"react/jsx-runtime";var fo={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},co=["all","active","draft","low_stock","out_of_stock"];function Br(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function Er(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function uo(e){return e.inventory?.out_of_stock??!1}function mo(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Er(e);case"out_of_stock":return uo(e);default:return!0}}function po({product:e,showStats:t,onOpen:a}){let s=e.images[0],r=t?e.stats:void 0,i=cs(e),l=e.variant_count??0;return Te("button",{type:"button",onClick:a,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?$("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):$("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:$(io,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Te("div",{className:"af-space-y-2 af-p-3",children:[Te("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Te("div",{className:"af-min-w-0",children:[$("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),$(ls,{product:e,className:"af-mt-0.5"})]}),!e.active&&$(q,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Te("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[$(fs,{product:e}),l>1&&Te(q,{variant:"outline",children:[l," variants"]}),i&&$(q,{variant:"outline",children:i})]}),r&&Te("div",{className:"af-text-xs af-text-muted-foreground",children:[r.units_sold," sold",r.gross.length>0?` \xB7 ${ds(r.gross)}`:""," ",$("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function go(){return $("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:[0,1,2,3,4,5].map(e=>Te("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[$("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),Te("div",{className:"af-space-y-2 af-p-3",children:[$(z,{className:"af-w-32"}),$(z,{className:"af-w-16"}),$(z,{className:"af-h-5 af-w-24"})]})]},e))})}function Dr({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:r,isLoading:i,error:l,refetch:u}=Ra({includeStats:t,refreshKey:e}),[f,d]=sa.useState(null),[n,m]=sa.useState("all"),[x,h]=sa.useState(""),[b,v]=sa.useState("newest"),p=sa.useMemo(()=>{if(!t)return null;let I=null;for(let pe of r)!pe.stats||pe.stats.units_sold===0||(!I||pe.stats.units_sold>(I.stats?.units_sold??0))&&(I=pe);return I},[r,t]),S=sa.useMemo(()=>r.filter(Er).length,[r]),R=x.trim().toLowerCase(),A=sa.useMemo(()=>{let pe=[...r.filter(g=>mo(g,n)&&(!R||g.name.toLowerCase().includes(R)))];return b==="name"?pe.sort((g,te)=>g.name.localeCompare(te.name)):b==="best_selling"?pe.sort((g,te)=>(te.stats?.units_sold??0)-(g.stats?.units_sold??0)):pe.sort((g,te)=>Br(te.created_at)-Br(g.created_at)),pe},[r,n,R,b]),W=n!=="all"||!!R,_=()=>{m("all"),h("")},F=i||l!==null&&r.length===0,M=$("div",{className:"af-mb-6",children:$("div",{className:D("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:F?Te(Ta,{children:[$(rt,{label:"Products",children:$(z,{className:"af-h-6 af-w-10"})}),t?Te(Ta,{children:[$(rt,{label:"Best seller",children:$(z,{className:"af-h-6 af-w-28"})}),$(rt,{label:"Low stock",children:$(z,{className:"af-h-6 af-w-10"})})]}):$(rt,{label:"Active",children:$(z,{className:"af-h-6 af-w-10"})})]}):Te(Ta,{children:[$(rt,{label:"Products",children:r.length}),t?Te(Ta,{children:[$(rt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:p?`${p.stats?.units_sold??0} sold, last 30 days`:void 0,children:p?$("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:p.name}):$("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),$(rt,{label:"Low stock",children:S})]}):$(rt,{label:"Active",children:r.filter(I=>I.active).length})]})})}),Z=Te("div",{className:"af-mb-4 af-space-y-3",children:[Te("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[$("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:co.map(I=>$("button",{type:"button","aria-pressed":n===I,onClick:()=>m(I),className:D("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",n===I?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:fo[I]},I))}),Te("div",{className:"af-relative af-w-full af-max-w-xs",children:[$(lo,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),$(ie,{type:"text",value:x,onChange:I=>h(I.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Te(ht,{value:b,onValueChange:I=>v(I),children:[$(dt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:$(xt,{})}),Te(ut,{children:[$(xe,{value:"newest",children:"Newest"}),$(xe,{value:"name",children:"Name A\u2013Z"}),t&&$(xe,{value:"best_selling",children:"Best selling"})]})]}),W&&$(N,{type:"button",variant:"ghost",size:"sm",onClick:_,children:"Clear filters"})]}),i&&r.length===0?$(z,{className:"af-h-4 af-w-28"}):$("p",{className:"af-text-sm af-text-muted-foreground",children:W?`${A.length} of ${r.length} products`:`${r.length} ${r.length===1?"product":"products"}${S>0?` \xB7 ${S} low stock`:""}`})]}),j;return f?j=$(Lr,{product:f,showStats:t,onBack:()=>{d(null),u()}},f.id):i&&r.length===0?j=Te(Ta,{children:[Z,$(go,{}),$("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):l&&r.length===0?j=$("div",{className:"af-flex af-justify-center af-py-8",children:$(pt,{message:"Couldn't load your products.",onRetry:()=>u()})}):r.length===0?j=Te(Ht,{icon:$(oo,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",$("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):j=Te(Ta,{children:[Z,l&&$("div",{className:"af-mb-4",children:$(pt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>u()})}),A.length===0?Te(Ht,{children:["No products match these filters.",$("br",{}),$(N,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:_,children:"Show all products"})]}):$("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:A.map(I=>$(po,{product:I,showStats:t,onOpen:()=>d(I)},I.id))})]}),Te(Vt,{title:"Products",onBackToWebsite:a,hideBackButton:!!f,className:s,children:[!f&&M,j]})}import*as _t from"react";import{ArrowLeft as Vr,Check as vo,ChevronLeft as Ir,ChevronRight as Ar,ClipboardCopy as bo,Mail as Ds,Search as yo,Users as ho}from"lucide-react";import*as gt from"react";function us({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=Y(),[s,r]=gt.useState([]),[i,l]=gt.useState(!0),[u,f]=gt.useState(null),[d,n]=gt.useState(0),[m]=gt.useState(e),[x,h]=gt.useState(""),b=gt.useRef(0),v=gt.useCallback(async()=>{let p=++b.current;try{l(!0),f(null);let S={limit:m,offset:d*m};x.trim()&&(S.q=x.trim());let R=await a.getPeople(S);if(p!==b.current)return;r(R.people)}catch(S){if(p!==b.current)return;f(S instanceof Error?S:new Error("Failed to fetch people"))}finally{p===b.current&&l(!1)}},[a,d,m,x,t]);return gt.useEffect(()=>{v()},[v]),{people:s,isLoading:i,error:u,page:d,pageSize:m,hasNextPage:s.length===m,hasPreviousPage:d>0,setPage:n,q:x,setQ:p=>{h(p),n(0)},refetch:v}}import*as jt from"react";function ms(e,{refreshKey:t}={}){let{api:a}=Y(),[s,r]=jt.useState(null),[i,l]=jt.useState(e!==null),[u,f]=jt.useState(null),d=jt.useRef(0),n=jt.useCallback(async()=>{if(e===null){r(null),l(!1),f(null);return}let m=++d.current;try{l(!0),f(null);let x=await a.getPerson(e);if(m!==d.current)return;r(x)}catch(x){if(m!==d.current)return;f(x instanceof Error?x:new Error("Failed to fetch person"))}finally{m===d.current&&l(!1)}},[a,e,t]);return jt.useEffect(()=>{n()},[n]),{person:s,isLoading:i,error:u,refetch:n}}import{jsx as o,jsxs as V}from"react/jsx-runtime";var Es="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",xo="af-text-xs af-text-muted-foreground";function Ca(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Is(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function No(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function wo({value:e,label:t}){let[a,s]=_t.useState(!1);return No()?V(N,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[a?o(vo,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):o(bo,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function Fr(e){return V("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&V(q,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&o(q,{variant:"secondary",children:"Contact form"})]})}function Ur(e){return e.name?e.name:e.email?e.email:o("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Po=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,So=40;function Ro(e){let t=Object.entries(e).filter(([r])=>!r.startsWith("_")),s=t.find(([r,i])=>Po.test(r)&&typeof i=="string"&&i.trim())??t.filter(([,r])=>typeof r=="string"&&r.trim().length>=So).sort((r,i)=>String(i[1]).trim().length-String(r[1]).trim().length)[0];return s?{message:String(s[1]),rest:t.filter(([r])=>r!==s[0])}:{message:null,rest:t}}function To(e){return e.replace(/_/g," ")}function Co(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function ko({data:e}){let{message:t,rest:a}=Ro(e);return t===null&&a.length===0?o("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):V("div",{className:"af-space-y-3",children:[t!==null&&o("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),a.length>0&&o("dl",{className:"af-space-y-1",children:a.map(([s,r])=>V("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[o("dt",{className:D(xo,"af-w-28 af-shrink-0 af-capitalize"),children:To(s)}),o("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Co(r)})]},s))})]})}function Hr({formName:e,createdAt:t,data:a}){return V("div",{className:"af-rounded-md af-border af-p-3",children:[V("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[o(q,{variant:"outline",children:"Form submission (unverified)"}),e&&o("span",{className:"af-text-xs af-text-muted-foreground",children:e}),o("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Ca(t)})]}),o(ko,{data:a})]})}function _o(e){return e.charged_total??e.amount_total}function Oo({email:e,refreshKey:t,onBack:a}){let{person:s,isLoading:r,error:i,refetch:l}=ms(e,{refreshKey:t}),u=Is(e,s?.submissions[0]?.form_name);return V("div",{children:[V("div",{className:"af-mb-6",children:[V(N,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[o(Vr,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),V("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[V("div",{className:"af-min-w-0",children:[r?o(z,{className:"af-h-7 af-w-48"}):o("h3",{className:"af-text-xl af-font-semibold af-break-all",children:s?.name||e}),V("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[o("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),o(wo,{value:e,label:"Copy email address"})]})]}),o(N,{asChild:!0,children:V("a",{href:u,children:[o(Ds,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),r?V("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(f=>V("div",{className:"af-rounded-md af-border af-p-3",children:[o(z,{className:"af-w-40"}),o(z,{className:"af-mt-2 af-w-64"})]},f)),o("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!s?o("div",{className:"af-flex af-justify-center af-py-8",children:o(pt,{message:"Couldn't load this person.",onRetry:()=>l()})}):V("div",{className:"af-space-y-6",children:[s.customer&&V("div",{children:[o("h4",{className:D(Es,"af-mb-3"),children:"Customer"}),V("dl",{className:"af-space-y-1 af-text-sm",children:[s.customer.name&&V("div",{className:"af-flex af-gap-2",children:[o("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),o("dd",{children:s.customer.name})]}),s.customer.phone&&V("div",{className:"af-flex af-gap-2",children:[o("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),o("dd",{children:s.customer.phone})]}),V("div",{className:"af-flex af-gap-2",children:[o("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),o("dd",{children:Ca(s.customer.created_at)})]})]})]}),s.orders.length>0&&V("div",{children:[o("h4",{className:D(Es,"af-mb-3"),children:"Purchases"}),o("div",{className:"af-overflow-x-auto",children:V(be,{children:[o(ye,{children:V(X,{children:[o(C,{children:"Order"}),o(C,{children:"Date"}),o(C,{className:"af-text-right",children:"Total"}),o(C,{children:"Status"})]})}),o(he,{children:s.orders.map(f=>V(X,{children:[o(k,{className:"af-whitespace-nowrap af-font-medium",children:aa(f)}),o(k,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ca(f.created_at)}),o(k,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:U(_o(f),f.currency)}),o(k,{children:o(pa,{status:f.status})})]},f.id))})]})}),o("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),s.submissions.length>0&&V("div",{children:[o("h4",{className:D(Es,"af-mb-3"),children:"Messages"}),o("div",{className:"af-space-y-3",children:s.submissions.map(f=>o(Hr,{formName:f.form_name,createdAt:f.created_at,data:f.data},f.id))})]})]})]})}function Lo({submissionId:e,onBack:t}){let{api:a}=Y(),[s,r]=_t.useState(null),[i,l]=_t.useState(!0),[u,f]=_t.useState(null),[d,n]=_t.useState(0);return _t.useEffect(()=>{let m=!1;return l(!0),f(null),a.getSubmission(e).then(x=>{m||r(x)}).catch(x=>{m||f(x instanceof Error?x:new Error("Failed to load submission"))}).finally(()=>{m||l(!1)}),()=>{m=!0}},[a,e,d]),V("div",{children:[V("div",{className:"af-mb-6",children:[V(N,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[o(Vr,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),o("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?o(z,{className:"af-mt-1 af-h-4 af-w-32"}):s&&o("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Ca(s.metadata.submitted_at)})]}),i?V("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[o(z,{className:"af-w-40"}),o(z,{className:"af-mt-2 af-w-64"}),o(z,{className:"af-mt-2 af-w-52"}),o("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):u||!s?o("div",{className:"af-flex af-justify-center af-py-8",children:o(pt,{message:"Couldn't load this submission.",onRetry:()=>n(m=>m+1)})}):V("div",{className:"af-space-y-3",children:[o(Hr,{formName:null,createdAt:s.metadata.submitted_at,data:s.data}),o("p",{className:"af-text-xs af-text-muted-foreground",children:"No email address came with this submission, so there is nobody to reply to."})]})]})}var Bo={all:"All",customers:"Customers",leads:"Leads"},Eo=["all","customers","leads"];function Do(e,t){return t==="customers"?e.sources.includes("customer"):t==="leads"?e.sources.includes("lead"):!0}function $r({refreshKey:e,onBackToWebsite:t,className:a}){let{people:s,isLoading:r,error:i,page:l,pageSize:u,hasNextPage:f,hasPreviousPage:d,setPage:n,q:m,setQ:x,refetch:h}=us({refreshKey:e}),[b,v]=_t.useState({kind:"list"}),[p,S]=_t.useState(""),[R,A]=_t.useState("all"),W=j=>{j.email?v({kind:"person",email:j.email}):j.submission_id&&v({kind:"submission",submissionId:j.submission_id})},_=()=>{v({kind:"list"}),h()},F=j=>{let I=j.trim();I!==m&&x(I)},M=s.filter(j=>Do(j,R)),Z;if(b.kind==="person")Z=o(Oo,{email:b.email,refreshKey:e,onBack:_});else if(b.kind==="submission")Z=o(Lo,{submissionId:b.submissionId,onBack:_});else{let j=V("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[o("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Eo.map(I=>o("button",{type:"button","aria-pressed":R===I,onClick:()=>A(I),className:D("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",R===I?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Bo[I]},I))}),V("div",{className:"af-relative af-w-full af-max-w-xs",children:[o(yo,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),o(ie,{type:"text",value:p,onChange:I=>S(I.target.value),onBlur:()=>F(p),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),F(p))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),m&&o(N,{type:"button",variant:"ghost",size:"sm",onClick:()=>{S(""),x("")},children:"Clear search"})]});if(r)Z=V("div",{children:[j,o("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(I=>V("div",{className:"af-rounded-md af-border af-p-3",children:[V("div",{className:"af-flex af-items-center af-justify-between",children:[o(z,{className:"af-h-4 af-w-32"}),o(z,{className:"af-h-4 af-w-16"})]}),o(z,{className:"af-mt-2 af-h-5 af-w-28"}),o(z,{className:"af-mt-2 af-h-3 af-w-56"})]},I))}),o("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:V(be,{children:[o(ye,{children:V(X,{children:[o(C,{children:"Person"}),o(C,{children:"Came from"}),o(C,{children:"Latest message"}),o(C,{children:"Last activity"}),o(C,{className:"af-w-8"}),o(C,{className:"af-w-8"})]})}),o(he,{"aria-hidden":"true",children:[0,1,2,3,4].map(I=>V(X,{children:[o(k,{children:o(z,{className:"af-h-4 af-w-40"})}),o(k,{children:o(z,{className:"af-h-5 af-w-24"})}),o(k,{children:o(z,{className:"af-h-4 af-w-56"})}),o(k,{children:o(z,{className:"af-h-4 af-w-24"})}),o(k,{}),o(k,{})]},I))})]})}),o("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)Z=V("div",{children:[j,o("div",{className:"af-flex af-justify-center af-py-8",children:o(pt,{message:"Couldn't load your leads.",onRetry:()=>h()})})]});else if(M.length===0&&l===0){let I=!!m||R!=="all";Z=V("div",{children:[I&&j,I?o(Ht,{children:m?"Nobody matches that search.":R==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):o(Ht,{icon:o(ho,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Form submissions and customers will show up here."})]})}else if(s.length===0)Z=V("div",{children:[j,o(Ht,{children:"No more results."}),o("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:V(N,{variant:"outline",size:"sm",onClick:()=>n(l-1),children:[o(Ir,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let I=l*u+1,pe=l*u+s.length;Z=V("div",{children:[j,o("div",{className:"af-space-y-3 lg:af-hidden",children:M.map((g,te)=>V("div",{onClick:()=>W(g),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[V("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[V("div",{className:"af-min-w-0",children:[o("button",{type:"button",onClick:Se=>{Se.stopPropagation(),W(g)},"aria-label":`Open ${g.name||g.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Ur(g)}),g.name&&g.email&&o("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:g.email})]}),V("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[o("span",{className:"af-text-xs af-text-muted-foreground",children:Ca(g.last_activity_at)}),g.email&&o(N,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:o("a",{href:Is(g.email),onClick:Se=>Se.stopPropagation(),"aria-label":`Email ${g.email}`,children:o(Ds,{className:"af-h-4 af-w-4"})})})]})]}),o("div",{className:"af-mt-2",children:Fr(g)}),g.latest_message_excerpt&&o("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:g.latest_message_excerpt})]},g.email??g.submission_id??te))}),o("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:V(be,{children:[o(ye,{children:V(X,{children:[o(C,{children:"Person"}),o(C,{children:"Came from"}),o(C,{children:"Latest message"}),o(C,{children:"Last activity"}),o(C,{className:"af-w-8",children:o("span",{className:"af-sr-only",children:"Reply"})}),o(C,{className:"af-w-8"})]})}),o(he,{children:M.map((g,te)=>V(X,{onClick:()=>W(g),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[V(k,{className:"af-max-w-[260px] af-font-medium",children:[o("button",{type:"button",onClick:Se=>{Se.stopPropagation(),W(g)},"aria-label":`Open ${g.name||g.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Ur(g)}),g.name&&g.email&&o("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:g.email})]}),o(k,{children:Fr(g)}),o(k,{className:"af-max-w-[320px]",children:g.latest_message_excerpt?o("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:g.latest_message_excerpt}):o("span",{className:"af-text-muted-foreground",children:"\u2014"})}),o(k,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ca(g.last_activity_at)}),o(k,{className:"af-w-8",children:g.email&&o(N,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:o("a",{href:Is(g.email),onClick:Se=>Se.stopPropagation(),"aria-label":`Email ${g.email}`,children:o(Ds,{className:"af-h-4 af-w-4"})})})}),o(k,{className:"af-w-8 af-text-right",children:o(Ar,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},g.email??g.submission_id??te))})]})}),V("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[o("span",{className:"af-text-sm af-text-muted-foreground",children:R==="all"?`Showing ${I}-${pe}`:`${M.length} of ${s.length} on this page`}),V("div",{className:"af-flex af-items-center af-gap-2",children:[V(N,{variant:"outline",size:"sm",onClick:()=>n(l-1),disabled:!d,children:[o(Ir,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),V(N,{variant:"outline",size:"sm",onClick:()=>n(l+1),disabled:!f,children:["Next",o(Ar,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return o(Vt,{title:"Leads",onBackToWebsite:t,hideBackButton:b.kind!=="list",className:a,children:Z})}import{ChevronLeft as Mr,ChevronRight as Io,Repeat as Ao}from"lucide-react";import*as ct from"react";function ps({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=Y(),[s,r]=ct.useState([]),[i,l]=ct.useState(0),[u,f]=ct.useState(!0),[d,n]=ct.useState(null),[m,x]=ct.useState(0),[h,b]=ct.useState(e),[v,p]=ct.useState(void 0),S=ct.useRef(0),R=ct.useCallback(async()=>{let W=++S.current;try{f(!0),n(null);let _={limit:h,offset:m*h};v&&(_.status=v);let F=await a.getSubscriptions(_);if(W!==S.current)return;r(F.subscriptions),l(F.total)}catch(_){if(W!==S.current)return;n(_ instanceof Error?_:new Error("Failed to fetch subscriptions"))}finally{W===S.current&&f(!1)}},[a,m,h,v,t]);ct.useEffect(()=>{R()},[R]);let A=Math.ceil(i/h);return{subscriptions:s,total:i,isLoading:u,error:d,page:m,pageSize:h,hasNextPage:m<A-1,hasPreviousPage:m>0,setPage:x,setPageSize:W=>{b(W),x(0)},status:v,setStatus:W=>{p(W),x(0)},refetch:R}}import{jsx as E,jsxs as Ce}from"react/jsx-runtime";function zr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function jr({sub:e}){return e.status==="canceled"?E(q,{variant:"outline",children:"Canceled"}):e.status==="past_due"?E(q,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?E(q,{variant:"warning",children:"Scheduled to cancel"}):E(q,{variant:"success",children:"Active"}):E(q,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Fo(e,t){let a=U(t,e.currency);return e.plan_interval_count===1?`${a} / ${e.plan_interval}`:`${a} every ${e.plan_interval_count} ${e.plan_interval}s`}function qr({sub:e}){let t=e.current_amount!==e.plan_amount;return Ce("div",{children:[E("div",{className:"af-font-medium af-tabular-nums",children:Fo(e,e.current_amount)}),t&&Ce("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",U(e.plan_amount,e.currency)]})]})}function Gr(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${zr(e.current_period_end)}`:"Ends at period end":e.current_period_end?zr(e.current_period_end):"\u2014"}function Wr({refreshKey:e,onBackToWebsite:t,className:a}){let{subscriptions:s,total:r,isLoading:i,error:l,page:u,pageSize:f,hasNextPage:d,hasPreviousPage:n,setPage:m,refetch:x}=ps({refreshKey:e}),h;if(i)h=Ce("div",{children:[E("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(b=>Ce("div",{className:"af-rounded-md af-border af-p-3",children:[Ce("div",{className:"af-flex af-items-center af-justify-between",children:[E(z,{className:"af-h-4 af-w-40"}),E(z,{className:"af-h-4 af-w-20"})]}),E(z,{className:"af-mt-2 af-h-3 af-w-32"}),E(z,{className:"af-mt-2 af-h-5 af-w-24"})]},b))}),E("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ce(be,{children:[E(ye,{children:Ce(X,{children:[E(C,{children:"Subscriber"}),E(C,{children:"Plan"}),E(C,{className:"af-text-right",children:"Amount"}),E(C,{children:"Renews"}),E(C,{children:"Status"})]})}),E(he,{"aria-hidden":"true",children:[0,1,2,3,4].map(b=>Ce(X,{children:[E(k,{children:E(z,{className:"af-h-4 af-w-44"})}),E(k,{children:E(z,{className:"af-h-4 af-w-32"})}),E(k,{className:"af-text-right",children:E(z,{className:"af-ml-auto af-h-4 af-w-24"})}),E(k,{children:E(z,{className:"af-h-4 af-w-24"})}),E(k,{children:E(z,{className:"af-h-5 af-w-20"})})]},b))})]})}),E("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(l)h=E("div",{className:"af-flex af-justify-center af-py-8",children:E(pt,{message:"Couldn't load your subscriptions.",onRetry:()=>x()})});else if(s.length===0&&u===0)h=E(Ht,{icon:E(Ao,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(s.length===0)h=Ce("div",{children:[E(Ht,{children:"No more results."}),E("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Ce(N,{variant:"outline",size:"sm",onClick:()=>m(u-1),children:[E(Mr,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let b=u*f+1,v=u*f+s.length;h=Ce("div",{children:[E("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(p=>Ce("div",{className:"af-rounded-md af-border af-p-3",children:[Ce("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ce("div",{className:"af-min-w-0",children:[E("div",{className:"af-truncate af-text-sm af-font-medium",children:p.customer_email||E("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),E("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:p.plan_title||"Untitled plan"})]}),E("div",{className:"af-shrink-0 af-text-right",children:E(qr,{sub:p})})]}),Ce("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[E(jr,{sub:p}),p.is_test&&E(q,{variant:"outline",children:"Test"}),E("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Gr(p)})]})]},p.id))}),E("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ce(be,{children:[E(ye,{children:Ce(X,{children:[E(C,{children:"Subscriber"}),E(C,{children:"Plan"}),E(C,{className:"af-text-right",children:"Amount"}),E(C,{children:"Renews"}),E(C,{children:"Status"})]})}),E(he,{children:s.map(p=>Ce(X,{children:[E(k,{className:"af-max-w-[240px]",children:E("div",{className:"af-truncate af-font-medium",children:p.customer_email||E("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),E(k,{className:"af-max-w-[220px]",children:E("div",{className:"af-truncate",children:p.plan_title||E("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),E(k,{className:"af-whitespace-nowrap af-text-right",children:E(qr,{sub:p})}),E(k,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Gr(p)}),E(k,{children:Ce("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[E(jr,{sub:p}),p.is_test&&E(q,{variant:"outline",children:"Test"})]})})]},p.id))})]})}),Ce("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[E("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${b}-${v} of ${r}`}),Ce("div",{className:"af-flex af-items-center af-gap-2",children:[Ce(N,{variant:"outline",size:"sm",onClick:()=>m(u-1),disabled:!n,children:[E(Mr,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ce(N,{variant:"outline",size:"sm",onClick:()=>m(u+1),disabled:!d,children:["Next",E(Io,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return E(Vt,{title:"Subscriptions",onBackToWebsite:t,className:a,children:h})}export{na as AifeaturesApiError,Xr as AifeaturesProvider,ts as CustomerDetail,ss as CustomersList,Ma as FormSettings,$a as FormSubmissions,Ys as FormsDashboard,Ua as FormsList,$r as LeadsView,Ja as OrderDetail,pa as OrderStatusBadge,Pa as OrdersList,Tr as OrdersView,Pr as PaymentsDashboard,rs as PaymentsSetup,Ga as ProductSettings,ja as ProductsList,Dr as ProductsView,Ha as SubmissionDetail,Wr as SubscriptionsView,qa as VariantsEditor,Vt as ViewShell,Tt as chargedTotal,vs as createApiClient,U as formatPrice,At as isZeroDecimalCurrency,Je as toMajorUnits,Ct as toMinorUnits,Y as useAifeatures,Y as useAifeaturesContext,is as useBusinessSummary,es as useCustomers,Na as useForms,Wa as useOrders,Sa as usePaymentsStatus,us as usePeople,ms as usePerson,Ra as useProducts,Va as useSubmissions,ps as useSubscriptions};
2
+ import*as ma from"react";var ua=class extends Error{constructor(s,a,r){super(s);this.status=a;this.details=r;this.name="AifeaturesApiError"}};function Rs(e,t){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${t}`}function Cs(e,t="https://aifeatures.dev"){async function s(a,r={}){let i=`${t}${a}`,l=await fetch(i,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!l.ok){let p;try{p=await l.json()}catch{}throw new ua(Rs(p?.error,l.status),l.status,p)}if(l.status!==204)return l.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(a){return s(`/api/v1/forms/${a}`)},async createForm(a){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,r){return s(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(a){await s(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,r={}){let i=new URLSearchParams;r.limit!==void 0&&i.set("limit",String(r.limit)),r.offset!==void 0&&i.set("offset",String(r.offset));let l=i.toString(),p=`/api/v1/forms/${a}/submissions${l?`?${l}`:""}`;return s(p)},async getSubmission(a){return s(`/api/v1/submissions/${a}`)},async deleteSubmission(a){await s(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,r){let i=typeof r=="string"?{name:r}:r,l=i.name,p=i.id??i.name,c=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(p)}`,d=await fetch(c,{headers:{Authorization:`Bearer ${e}`}});if(!d.ok){let m;try{m=await d.json()}catch{}throw new ua(Rs(m?.error,d.status),d.status,m)}let n=await d.blob(),g=URL.createObjectURL(n),x=document.createElement("a");x.href=g,x.download=l,document.body.appendChild(x),x.click(),document.body.removeChild(x),URL.revokeObjectURL(g)},async getPaymentsStatus(){return s("/api/v1/payments/status")},async getProducts(a={}){let r=new URLSearchParams;a.include&&r.set("include",a.include);let i=r.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(a){return s(`/api/v1/products/${a}`)},async createProduct(a){return s("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,r){return s(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(a){await s(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,r){let i=new FormData;i.append("file",r);let l=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!l.ok){let p;try{p=await l.json()}catch{}throw new ua(Rs(p?.error,l.status),l.status,p)}return l.json()},async attachProductFileFromUrl(a,r){return s(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(a,r){return s(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(a,r){return s(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(a){await s(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,r){return s(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(a,r){return s(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(a){await s(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,r){return s(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(a,r){return s(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(a={}){let r=new URLSearchParams;a.email&&r.set("email",a.email),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let i=r.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(a){return s(`/api/v1/customers/${a}`)},async getOrders(a={}){let r=new URLSearchParams;a.status&&r.set("status",a.status),a.excludeStatus?.length&&r.set("exclude_status",a.excludeStatus.join(",")),a.customerEmail&&r.set("customer_email",a.customerEmail),a.from&&r.set("from",a.from),a.to&&r.set("to",a.to),a.unfulfilledOnly&&r.set("unfulfilled_only","true"),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let i=r.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(a){return s(`/api/v1/orders/${a}`)},async resendOrderReceipt(a){await s(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return s(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,r){return s(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(a={}){let r=new URLSearchParams;a.status&&r.set("status",a.status),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let i=r.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getBusinessSummary(a){let r=new URLSearchParams;return r.set("tz_offset_minutes",String(a.tzOffsetMinutes)),s(`/api/v1/summary?${r.toString()}`)},async getPeople(a={}){let r=new URLSearchParams;a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let i=r.toString();return s(`/api/v1/people${i?`?${i}`:""}`)},async getPerson(a){return s(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(a){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,r){return s(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(a){await s(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return s(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await s(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,r){let i=r===void 0?"":`?limit=${r}`;return(await s(`/api/v1/event-destinations/${a}/deliveries${i}`)).deliveries},async retryEventDelivery(a,r){return s(`/api/v1/event-destinations/${a}/deliveries/${r}/retry`,{method:"POST"})}}}import{jsx as Aa,jsxs as mn}from"react/jsx-runtime";var Xs=ma.createContext(null);function dn(e){return e?e.startsWith("sk_")?"Invalid token type: You passed an organization API key (sk_xxx) but AifeaturesProvider requires a site token (st_xxx). Site tokens are returned when you create a site via the API.":e.startsWith("st_")?null:`Invalid token format: Expected a site token starting with "st_" but got "${e.slice(0,10)}...". Site tokens are returned when you create a site via the API.`:"No siteToken provided to AifeaturesProvider"}function un({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:s=!1,className:a,children:r}){let i=ma.useMemo(()=>dn(e),[e]),l=ma.useMemo(()=>Cs(e,t),[e,t]),p=ma.useMemo(()=>({siteToken:e,apiUrl:t,api:l}),[e,t,l]);return i?Aa("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:mn("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[Aa("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),Aa("p",{className:"af-text-sm af-text-destructive",children:i})]})}):Aa(Xs.Provider,{value:p,children:Aa("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:r})})}function Y(){let e=ma.useContext(Xs);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as ga from"react";import{ArrowLeft as ci,Settings as di,Inbox as ui}from"lucide-react";import*as za from"react";import*as kt from"@radix-ui/react-tabs";import{clsx as pn}from"clsx";import{twMerge as gn}from"tailwind-merge";function F(...e){return gn(pn(e))}import{jsx as Ts}from"react/jsx-runtime";var ja=kt.Root,Fa=za.forwardRef(({className:e,...t},s)=>Ts(kt.List,{ref:s,className:F("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));Fa.displayName=kt.List.displayName;var aa=za.forwardRef(({className:e,...t},s)=>Ts(kt.Trigger,{ref:s,className:F("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));aa.displayName=kt.Trigger.displayName;var sa=za.forwardRef(({className:e,...t},s)=>Ts(kt.Content,{ref:s,className:F("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));sa.displayName=kt.Content.displayName;import*as er from"react";import{Slot as vn}from"@radix-ui/react-slot";import{cva as bn}from"class-variance-authority";import{jsx as hn}from"react/jsx-runtime";var yn=bn("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),h=er.forwardRef(({className:e,variant:t,size:s,asChild:a=!1,...r},i)=>hn(a?vn:"button",{className:F(yn({variant:t,size:s,className:e})),ref:i,...r}));h.displayName="Button";import{Inbox as tr,Settings as wn}from"lucide-react";import*as na from"react";import{jsx as ra}from"react/jsx-runtime";var we=na.forwardRef(({className:e,...t},s)=>ra("div",{className:"af-relative af-w-full af-overflow-auto",children:ra("table",{ref:s,className:F("af-w-full af-caption-bottom af-text-sm",e),...t})}));we.displayName="Table";var Se=na.forwardRef(({className:e,...t},s)=>ra("thead",{ref:s,className:F("[&_tr]:af-border-b",e),...t}));Se.displayName="TableHeader";var Pe=na.forwardRef(({className:e,...t},s)=>ra("tbody",{ref:s,className:F("[&_tr:last-child]:af-border-0",e),...t}));Pe.displayName="TableBody";var xn=na.forwardRef(({className:e,...t},s)=>ra("tfoot",{ref:s,className:F("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));xn.displayName="TableFooter";var ee=na.forwardRef(({className:e,...t},s)=>ra("tr",{ref:s,className:F("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));ee.displayName="TableRow";var k=na.forwardRef(({className:e,...t},s)=>ra("th",{ref:s,className:F("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));k.displayName="TableHead";var _=na.forwardRef(({className:e,...t},s)=>ra("td",{ref:s,className:F("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));_.displayName="TableCell";var Nn=na.forwardRef(({className:e,...t},s)=>ra("caption",{ref:s,className:F("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Nn.displayName="TableCaption";import*as _t from"react";function Ta(){let{api:e}=Y(),[t,s]=_t.useState([]),[a,r]=_t.useState(!0),[i,l]=_t.useState(null),p=_t.useCallback(async()=>{try{r(!0),l(null);let g=await e.getForms();s(g)}catch(g){l(g instanceof Error?g:new Error("Failed to fetch forms"))}finally{r(!1)}},[e]);_t.useEffect(()=>{p()},[p]);let c=_t.useCallback(async g=>{let x=await e.createForm(g);return s(m=>[...m,x]),x},[e]),d=_t.useCallback(async(g,x)=>{let m=await e.updateForm(g,x);return s(o=>o.map(u=>u.id===g?m:u)),m},[e]),n=_t.useCallback(async g=>{await e.deleteForm(g),s(x=>x.filter(m=>m.id!==g))},[e]);return{forms:t,isLoading:a,error:i,refetch:p,createForm:c,updateForm:d,deleteForm:n}}import{jsx as Qe,jsxs as ia}from"react/jsx-runtime";function qa({onSelectForm:e,className:t}){let{forms:s,isLoading:a,error:r}=Ta();return a?Qe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Qe("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):r?Qe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:ia("div",{className:"af-text-destructive",children:["Error: ",r.message]})}):s.length===0?ia("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Qe(tr,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),ia("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",Qe("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):Qe("div",{className:t,children:ia(we,{children:[Qe(Se,{children:ia(ee,{children:[Qe(k,{children:"Name"}),Qe(k,{children:"Endpoint"}),Qe(k,{className:"af-text-right",children:"Actions"})]})}),Qe(Pe,{children:s.map(i=>ia(ee,{children:[Qe(_,{className:"af-font-medium",children:i.name}),Qe(_,{children:Qe("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url.replace("https://aifeatures.dev","")})}),Qe(_,{className:"af-text-right",children:ia("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[ia(h,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[Qe(tr,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),ia(h,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[Qe(wn,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import*as Ua from"react";import{ChevronLeft as An,ChevronRight as Fn,Eye as Un,Inbox as Vn,Paperclip as Hn}from"lucide-react";import*as pa from"react";import*as ne from"@radix-ui/react-select";import{Check as Sn,ChevronDown as ar,ChevronUp as Pn}from"lucide-react";import{jsx as rt,jsxs as ks}from"react/jsx-runtime";var wt=ne.Root;var St=ne.Value,mt=pa.forwardRef(({className:e,children:t,...s},a)=>ks(ne.Trigger,{ref:a,className:F("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[t,rt(ne.Icon,{asChild:!0,children:rt(ar,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));mt.displayName=ne.Trigger.displayName;var sr=pa.forwardRef(({className:e,...t},s)=>rt(ne.ScrollUpButton,{ref:s,className:F("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:rt(Pn,{className:"af-h-4 af-w-4"})}));sr.displayName=ne.ScrollUpButton.displayName;var rr=pa.forwardRef(({className:e,...t},s)=>rt(ne.ScrollDownButton,{ref:s,className:F("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:rt(ar,{className:"af-h-4 af-w-4"})}));rr.displayName=ne.ScrollDownButton.displayName;var pt=pa.forwardRef(({className:e,children:t,position:s="popper",...a},r)=>rt(ne.Portal,{children:ks(ne.Content,{ref:r,className:F("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...a,children:[rt(sr,{}),rt(ne.Viewport,{className:F("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),rt(rr,{})]})}));pt.displayName=ne.Content.displayName;var Rn=pa.forwardRef(({className:e,...t},s)=>rt(ne.Label,{ref:s,className:F("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));Rn.displayName=ne.Label.displayName;var Re=pa.forwardRef(({className:e,children:t,...s},a)=>ks(ne.Item,{ref:a,className:F("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...s,children:[rt("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:rt(ne.ItemIndicator,{children:rt(Sn,{className:"af-h-4 af-w-4"})})}),rt(ne.ItemText,{children:t})]}));Re.displayName=ne.Item.displayName;var Cn=pa.forwardRef(({className:e,...t},s)=>rt(ne.Separator,{ref:s,className:F("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));Cn.displayName=ne.Separator.displayName;import*as Pt from"react";function Wa({formId:e,initialPageSize:t=25}){let{api:s}=Y(),[a,r]=Pt.useState([]),[i,l]=Pt.useState(0),[p,c]=Pt.useState(!0),[d,n]=Pt.useState(null),[g,x]=Pt.useState(0),[m,o]=Pt.useState(t),u=Pt.useCallback(async()=>{if(e)try{c(!0),n(null);let R={limit:m,offset:g*m},A=await s.getSubmissions(e,R);r(A.submissions),l(A.total)}catch(R){n(R instanceof Error?R:new Error("Failed to fetch submissions"))}finally{c(!1)}},[s,e,g,m]);Pt.useEffect(()=>{u()},[u]);let b=Pt.useCallback(async R=>{await s.deleteSubmission(R),r(A=>A.filter(j=>j.id!==R)),l(A=>A-1)},[s]),N=Math.ceil(i/m);return{submissions:a,total:i,isLoading:p,error:d,page:g,pageSize:m,hasNextPage:g<N-1,hasPreviousPage:g>0,setPage:x,setPageSize:R=>{o(R),x(0)},refetch:u,deleteSubmission:b}}import*as ir from"react";import{ArrowLeft as Tn,Download as kn,Globe as _n,Clock as Dn,FileText as En,Loader2 as On,Monitor as Ln,Mail as Bn}from"lucide-react";import{jsx as He,jsxs as Fe}from"react/jsx-runtime";function nr(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function In(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,a)).toFixed(1))} ${s[a]}`}function Ga({submission:e,onBack:t}){let{api:s}=Y(),[a,r]=ir.useState(null),i=c=>c.id??c.name,l=async c=>{r(i(c));try{await s.downloadAttachment(e.id,c)}catch(d){console.error("Download failed:",d)}finally{r(null)}},p=Object.entries(e.data).filter(([c])=>!c.startsWith("_"));return Fe("div",{children:[Fe("div",{className:"af-mb-6",children:[Fe(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[He(Tn,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),He("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),Fe("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",nr(e.metadata.submitted_at)]})]}),Fe("div",{className:"af-space-y-6",children:[Fe("div",{children:[He("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),Fe("div",{className:"af-space-y-3",children:[p.map(([c,d])=>Fe("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[He("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:c.replace(/_/g," ")}),He("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof d=="string"&&d.includes(`
3
+ `)?He("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:d}):String(d)})]},c)),p.length===0&&He("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&Fe("div",{children:[He("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),He("div",{className:"af-space-y-2",children:e.attachments.map((c,d)=>Fe("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[Fe("div",{className:"af-flex af-items-center af-gap-2",children:[He(En,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),He("span",{className:"af-text-sm",children:c.name}),Fe("span",{className:"af-text-xs af-text-muted-foreground",children:["(",In(c.size),")"]})]}),Fe(h,{variant:"ghost",size:"sm",onClick:()=>l(c),disabled:a===i(c),children:[a===i(c)?He(On,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):He(kn,{className:"af-h-4 af-w-4 af-mr-1"}),a===i(c)?"Downloading...":"Download"]})]},d))})]}),Fe("div",{children:[He("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),Fe("div",{className:"af-space-y-2 af-text-sm",children:[Fe("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[He(Dn,{className:"af-h-4 af-w-4"}),He("span",{children:nr(e.metadata.submitted_at)})]}),e.metadata.ip_address&&Fe("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[He(_n,{className:"af-h-4 af-w-4"}),Fe("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&Fe("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[He(Ln,{className:"af-h-4 af-w-4 af-mt-0.5"}),He("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&Fe("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[He(Bn,{className:"af-h-4 af-w-4"}),Fe("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as de,jsxs as Ye}from"react/jsx-runtime";function $n(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Mn(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let s of t)if(typeof e[s]=="string")return e[s];return null}function zn(e){let t=Object.entries(e).filter(([r])=>!r.startsWith("_")&&!r.toLowerCase().includes("email"));if(t.length===0)return"";let[,s]=t[0],a=String(s);return a.length>50?a.slice(0,50)+"...":a}function Ka({formId:e,className:t,defaultSubmissionId:s}){let{submissions:a,total:r,isLoading:i,error:l,page:p,pageSize:c,hasNextPage:d,hasPreviousPage:n,setPage:g,setPageSize:x}=Wa({formId:e}),[m,o]=Ua.useState("list"),[u,b]=Ua.useState(null);Ua.useEffect(()=>{if(s&&a.length>0){let C=a.find(U=>U.id===s);C&&(b(C),o("detail"))}},[s,a]);let N=C=>{b(C),o("detail")},R=()=>{o("list"),b(null)};if(m==="detail"&&u)return de("div",{className:t,children:de(Ga,{submission:u,onBack:R})});if(i)return de("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:de("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(l)return de("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ye("div",{className:"af-text-destructive",children:["Error: ",l.message]})});if(a.length===0&&p===0)return Ye("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[de(Vn,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ye("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",de("br",{}),"Submissions will appear here when visitors use your form."]})]});let A=p*c+1,j=Math.min((p+1)*c,r);return Ye("div",{className:t,children:[Ye(we,{children:[de(Se,{children:Ye(ee,{children:[de(k,{children:"Email"}),de(k,{children:"Preview"}),de(k,{children:"Date"}),de(k,{className:"af-text-right",children:"Actions"})]})}),de(Pe,{children:a.map(C=>{let U=Mn(C.data),H=zn(C.data);return Ye(ee,{children:[de(_,{className:"af-font-medium",children:Ye("div",{className:"af-flex af-items-center af-gap-2",children:[U||de("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),C.attachments.length>0&&Ye("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${C.attachments.length} attachment(s)`,children:[de(Hn,{className:"af-h-3 af-w-3"}),de("span",{className:"af-text-xs",children:C.attachments.length})]})]})}),de(_,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:H||de("span",{className:"af-italic",children:"No preview available"})}),de(_,{className:"af-text-muted-foreground",children:$n(C.metadata.submitted_at)}),de(_,{className:"af-text-right",children:de(h,{variant:"ghost",size:"icon",onClick:()=>N(C),title:"View details",children:de(Un,{className:"af-h-4 af-w-4"})})})]},C.id)})})]}),Ye("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Ye("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ye("span",{children:["Showing ",A,"-",j," of ",r]}),Ye(wt,{value:String(c),onValueChange:C=>x(Number(C)),children:[de(mt,{className:"af-w-[70px] af-h-8",children:de(St,{})}),Ye(pt,{children:[de(Re,{value:"10",children:"10"}),de(Re,{value:"25",children:"25"}),de(Re,{value:"50",children:"50"}),de(Re,{value:"100",children:"100"})]})]}),de("span",{children:"per page"})]}),Ye("div",{className:"af-flex af-items-center af-gap-2",children:[Ye(h,{variant:"outline",size:"sm",onClick:()=>g(p-1),disabled:!n,children:[de(An,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ye(h,{variant:"outline",size:"sm",onClick:()=>g(p+1),disabled:!d,children:["Next",de(Fn,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as vt from"react";import{Plus as ii,X as oi,Loader2 as li,Check as fi}from"lucide-react";import*as or from"react";import{jsx as jn}from"react/jsx-runtime";var re=or.forwardRef(({className:e,type:t,...s},a)=>jn("input",{type:t,className:F("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:a,...s}));re.displayName="Input";import*as lr from"react";import{cva as qn}from"class-variance-authority";import{jsx as Gn}from"react/jsx-runtime";var Wn=qn("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),se=lr.forwardRef(({className:e,...t},s)=>Gn("label",{ref:s,className:F(Wn(),e),...t}));se.displayName="Label";import{cva as Kn}from"class-variance-authority";import{jsx as Zn}from"react/jsx-runtime";var Jn=Kn("af-inline-flex af-items-center af-rounded-md af-border af-px-2.5 af-py-0.5 af-text-xs af-font-semibold af-transition-colors focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2",{variants:{variant:{default:"af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",secondary:"af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",destructive:"af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",outline:"af-text-foreground",success:"af-border-transparent af-bg-green-100 af-text-green-800",warning:"af-border-transparent af-bg-yellow-100 af-text-yellow-800"}},defaultVariants:{variant:"default"}});function V({className:e,variant:t,...s}){return Zn("div",{className:F(Jn({variant:t}),e),...s})}import*as Ct from"react";import{Plus as ei,Loader2 as Ds,Copy as ti,Check as ai,Trash2 as si,RefreshCw as ri,AlertTriangle as ni}from"lucide-react";import*as Va from"react";import*as je from"@radix-ui/react-dialog";import{X as Qn}from"lucide-react";import{jsx as oa,jsxs as _s}from"react/jsx-runtime";var qt=je.Root;var Yn=je.Portal;var fr=Va.forwardRef(({className:e,...t},s)=>oa(je.Overlay,{ref:s,className:F("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));fr.displayName=je.Overlay.displayName;var Dt=Va.forwardRef(({className:e,children:t,...s},a)=>oa(Yn,{children:_s("div",{className:"aifeatures-admin",children:[oa(fr,{}),_s(je.Content,{ref:a,className:F("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[t,_s(je.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[oa(Qn,{className:"af-h-4 af-w-4"}),oa("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Dt.displayName=je.Content.displayName;var Et=({className:e,...t})=>oa("div",{className:F("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Et.displayName="DialogHeader";var Ot=({className:e,...t})=>oa("div",{className:F("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ot.displayName="DialogFooter";var Lt=Va.forwardRef(({className:e,...t},s)=>oa(je.Title,{ref:s,className:F("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Lt.displayName=je.Title.displayName;var Bt=Va.forwardRef(({className:e,...t},s)=>oa(je.Description,{ref:s,className:F("af-text-sm af-text-muted-foreground",e),...t}));Bt.displayName=je.Description.displayName;import*as gt from"react";function Ja(){let{api:e}=Y(),[t,s]=gt.useState([]),[a,r]=gt.useState(!0),[i,l]=gt.useState(null),p=gt.useCallback(async()=>{try{r(!0),l(null),s(await e.getEventDestinations())}catch(m){l(m instanceof Error?m:new Error("Failed to fetch webhooks"))}finally{r(!1)}},[e]);gt.useEffect(()=>{p()},[p]);let c=gt.useCallback(async m=>{let o=await e.createEventDestination(m);return s(u=>[o,...u]),o},[e]),d=gt.useCallback(async(m,o)=>{let u=await e.updateEventDestination(m,o);return s(b=>b.map(N=>N.id===m?u:N)),u},[e]),n=gt.useCallback(async m=>{await e.deleteEventDestination(m),s(o=>o.filter(u=>u.id!==m))},[e]),g=gt.useCallback(async m=>{let o=await e.rotateEventDestinationSecret(m);return s(u=>u.map(b=>b.id===m?o:b)),o},[e]),x=gt.useCallback(m=>e.getEventDestinationSecret(m),[e]);return{destinations:t,isLoading:a,error:i,refetch:p,createDestination:c,updateDestination:d,deleteDestination:n,rotateSecret:g,getSecret:x}}import*as la from"react";import{Loader2 as cr,RotateCw as Xn}from"lucide-react";import{jsx as Rt,jsxs as Ha}from"react/jsx-runtime";function Za({destinationId:e,limit:t=25,className:s}){let{api:a}=Y(),[r,i]=la.useState([]),[l,p]=la.useState(!0),[c,d]=la.useState(null),[n,g]=la.useState(null),x=la.useCallback(async()=>{try{p(!0),d(null),i(await a.getEventDeliveries(e,t))}catch(o){d(o instanceof Error?o.message:"Failed to load deliveries")}finally{p(!1)}},[a,e,t]);la.useEffect(()=>{x()},[x]);let m=async o=>{try{g(o.id),d(null);let u=await a.retryEventDelivery(e,o.id);i(b=>b.map(N=>N.id===o.id?u:N))}catch(u){d(u instanceof Error?u.message:"Retry failed")}finally{g(null)}};return l?Ha("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[Rt(cr,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):c?Rt("div",{className:"af-text-sm af-text-destructive af-py-2",children:c}):r.length===0?Rt("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):Rt("div",{className:s,children:Rt("div",{className:"af-divide-y af-border af-rounded",children:r.map(o=>{let u=o.delivered_at!==null;return Ha("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[Ha("div",{className:"af-min-w-0",children:[Ha("div",{className:"af-flex af-items-center af-gap-2",children:[u?Rt(V,{variant:"secondary",children:o.last_status??200}):Rt(V,{variant:"destructive",children:o.last_status??"failed"}),Rt("span",{className:"af-text-sm af-truncate",children:o.type})]}),Ha("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[o.event_id," \xB7 ",o.created_at,o.attempts>0&&` \xB7 ${o.attempts} failed ${o.attempts===1?"attempt":"attempts"}`]}),!u&&o.last_error&&Rt("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:o.last_error})]}),Rt(h,{variant:"ghost",size:"sm",title:"Send this event again",disabled:n===o.id,onClick:()=>m(o),children:n===o.id?Rt(cr,{className:"af-h-4 af-w-4 af-animate-spin"}):Rt(Xn,{className:"af-h-4 af-w-4"})})]},o.id)})})})}import{jsx as ue,jsxs as $e}from"react/jsx-runtime";function Qa({formId:e,topics:t,description:s,className:a}){let{destinations:r,isLoading:i,error:l,createDestination:p,updateDestination:c,deleteDestination:d,rotateSecret:n,getSecret:g}=Ja(),[x,m]=Ct.useState(""),[o,u]=Ct.useState(!1),[b,N]=Ct.useState(null),[R,A]=Ct.useState(null),[j,C]=Ct.useState(null),[U,H]=Ct.useState(!1),[J,$]=Ct.useState(null),[O,ie]=Ct.useState(null),[y,ae]=Ct.useState(null),he=Ct.useMemo(()=>r.filter(I=>I.form_id===e),[r,e]),ye=async()=>{let I=x.trim();if(I){if(!I.startsWith("https://")){N("Webhook URLs must start with https://");return}try{u(!0),N(null),await p({url:I,form_id:e,...t&&t.length>0?{topics:t}:{}}),m("")}catch(pe){N(pe instanceof Error?pe.message:"Failed to add webhook")}finally{u(!1)}}},ce=async I=>{try{ie(I.id),N(null),await n(I.id),H(!1),C(await g(I.id))}catch(pe){N(pe instanceof Error?pe.message:"Failed to rotate secret")}finally{ie(null)}},Be=async I=>{try{ie(I.id),N(null),await c(I.id,{status:"active"})}catch(pe){N(pe instanceof Error?pe.message:"Failed to re-enable")}finally{ie(null)}},X=async()=>{if(J)try{ie(J.id),await d(J.id),$(null)}catch(I){N(I instanceof Error?I.message:"Failed to delete")}finally{ie(null)}},me=async I=>{if(R===I.id){A(null),C(null);return}try{ie(I.id),N(null),H(!1),A(I.id),C(await g(I.id))}catch(pe){A(null),N(pe instanceof Error?pe.message:"Failed to read secret")}finally{ie(null)}},Ce=async()=>{if(j)try{await navigator.clipboard.writeText(j),H(!0)}catch{}};return $e("div",{className:a,children:[$e("div",{className:"af-space-y-1",children:[ue(se,{children:"Webhooks"}),ue("p",{className:"af-text-sm af-text-muted-foreground",children:s??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),$e("div",{className:"af-flex af-gap-2 af-mt-4",children:[ue(re,{value:x,placeholder:"https://hooks.zapier.com/...",onChange:I=>m(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),ye())},disabled:o}),$e(h,{onClick:ye,disabled:o||!x.trim(),children:[o?ue(Ds,{className:"af-h-4 af-w-4 af-animate-spin"}):ue(ei,{className:"af-h-4 af-w-4"}),ue("span",{className:"af-ml-1",children:"Add"})]})]}),(b||l)&&ue("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:b||l?.message}),$e("div",{className:"af-mt-4 af-space-y-2",children:[i&&$e("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[ue(Ds,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&he.length===0&&ue("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),he.map(I=>$e("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[$e("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[$e("div",{className:"af-min-w-0",children:[$e("div",{className:"af-flex af-items-center af-gap-2",children:[ue("span",{className:"af-font-mono af-text-sm af-truncate",children:I.url}),I.status==="disabled"?ue(V,{variant:"destructive",children:"Disabled"}):ue(V,{variant:"secondary",children:"Active"})]}),ue("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:I.topics.includes("*")?"All events":I.topics.join(", ")})]}),$e("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[ue(h,{variant:"ghost",size:"sm",onClick:()=>ae(y===I.id?null:I.id),children:y===I.id?"Hide log":"Deliveries"}),ue(h,{variant:"ghost",size:"sm",onClick:()=>me(I),disabled:O===I.id,children:R===I.id?"Hide secret":"Show secret"}),ue(h,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:O===I.id,onClick:()=>$(I),children:ue(si,{className:"af-h-4 af-w-4"})})]})]}),I.status==="disabled"&&$e("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[ue(ni,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),$e("div",{className:"af-text-sm",children:[$e("p",{children:["We stopped sending after repeated failures."," ",I.disabled_reason]}),ue(h,{variant:"outline",size:"sm",className:"af-mt-2",disabled:O===I.id,onClick:()=>Be(I),children:"Re-enable"})]})]}),R===I.id&&j&&$e("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[ue("p",{className:"af-text-xs af-text-muted-foreground",children:"Optional. Use this if you want your endpoint to check that a delivery really came from us. Rotating replaces it."}),$e("div",{className:"af-flex af-gap-2",children:[ue(re,{readOnly:!0,value:j,className:"af-font-mono"}),ue(h,{variant:"outline",title:"Copy signing secret",onClick:Ce,children:U?ue(ai,{className:"af-h-4 af-w-4"}):ue(ti,{className:"af-h-4 af-w-4"})}),ue(h,{variant:"outline",title:"Rotate signing secret",disabled:O===I.id,onClick:()=>ce(I),children:O===I.id?ue(Ds,{className:"af-h-4 af-w-4 af-animate-spin"}):ue(ri,{className:"af-h-4 af-w-4"})})]})]}),y===I.id&&ue(Za,{destinationId:I.id})]},I.id))]}),ue(qt,{open:!!J,onOpenChange:I=>{!I&&!O&&$(null)},children:$e(Dt,{children:[$e(Et,{children:[ue(Lt,{children:"Delete this webhook?"}),$e(Bt,{children:["New submissions will stop being sent to ",J?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),$e(Ot,{children:[ue(h,{variant:"outline",onClick:()=>$(null),disabled:!!O,children:"Cancel"}),ue(h,{variant:"destructive",onClick:X,disabled:!!O,children:O?"Deleting...":"Delete"})]})]})})]})}import{jsx as ge,jsxs as It}from"react/jsx-runtime";function Ya({form:e,onSaved:t,className:s}){let{updateForm:a}=Ta(),[r,i]=vt.useState(!1),[l,p]=vt.useState(null),[c,d]=vt.useState(null),[n,g]=vt.useState(e.name),[x,m]=vt.useState(e.redirect_url||""),[o,u]=vt.useState(e.email_recipients),[b,N]=vt.useState("");vt.useEffect(()=>{g(e.name),m(e.redirect_url||""),u(e.email_recipients),d(null)},[e]);let R=vt.useCallback(async H=>{try{i(!0),d(null);let J=await a(e.id,H);p(new Date),t?.(J)}catch(J){d(J instanceof Error?J.message:"Failed to save")}finally{i(!1)}},[e.id,a,t]);vt.useEffect(()=>{if(l){let H=setTimeout(()=>p(null),2e3);return()=>clearTimeout(H)}},[l]);let A=async()=>{let H=b.trim().toLowerCase();if(!H)return;if(!H.includes("@")){d("Please enter a valid email address");return}if(o.includes(H)){d("This email is already added");return}let J=[...o,H];u(J),N(""),d(null),await R({email_recipients:J})},j=async H=>{let J=o.filter($=>$!==H);u(J),await R({email_recipients:J})},C=async()=>{n!==e.name&&await R({name:n})},U=async()=>{let H=x||null;H!==e.redirect_url&&await R({redirect_url:H})};return It("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(r||l)&&ge("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:r?It("div",{className:"af-flex af-items-center af-gap-2 af-bg-background af-border af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[ge(li,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),ge("span",{className:"af-text-sm",children:"Saving..."})]}):It("div",{className:"af-flex af-items-center af-gap-2 af-bg-green-50 af-border af-border-green-200 af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[ge(fi,{className:"af-h-4 af-w-4 af-text-green-600"}),ge("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),It("div",{className:"af-space-y-2",children:[ge(se,{htmlFor:"form-name",children:"Form Name"}),ge(re,{id:"form-name",value:n,onChange:H=>g(H.target.value),onBlur:C,placeholder:"Contact Form"}),ge("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),It("div",{className:"af-space-y-2",children:[ge(se,{children:"Email Recipients"}),ge("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),It("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[o.map(H=>It(V,{variant:"secondary",className:"af-gap-1",children:[H,ge("button",{type:"button",onClick:()=>j(H),className:"af-ml-1 hover:af-text-destructive",disabled:r,children:ge(oi,{className:"af-h-3 af-w-3"})})]},H)),o.length===0&&ge("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),It("div",{className:"af-flex af-gap-2",children:[ge(re,{type:"email",value:b,onChange:H=>N(H.target.value),placeholder:"Add email address",onKeyDown:H=>{H.key==="Enter"&&(H.preventDefault(),A())},disabled:r}),ge(h,{type:"button",variant:"outline",onClick:A,disabled:!b.trim()||r,children:ge(ii,{className:"af-h-4 af-w-4"})})]})]}),It("div",{className:"af-space-y-2",children:[ge(se,{htmlFor:"redirect-url",children:"Redirect URL"}),ge(re,{id:"redirect-url",value:x,onChange:H=>m(H.target.value),onBlur:U,placeholder:"/thank-you"}),ge("p",{className:"af-text-xs af-text-muted-foreground",children:"Where to send visitors after a successful submission. Use a site path (/thank-you) or a full URL (https://example.com/thank-you). Leave empty for a default success page."})]}),It("div",{className:"af-space-y-2",children:[ge(se,{children:"Form Endpoint"}),ge("div",{className:"af-flex af-items-center af-gap-2",children:ge("code",{className:"af-flex-1 af-text-xs af-bg-muted af-px-3 af-py-2 af-rounded af-border",children:e.endpoint_url})}),ge("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),It("div",{className:"af-space-y-2",children:[ge(se,{children:"Captcha Protection"}),ge("div",{className:"af-flex af-items-center af-gap-2",children:ge(V,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),ge("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),ge(Qa,{formId:e.id}),c&&ge("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c})]})}import{jsx as ot,jsxs as Wt}from"react/jsx-runtime";function dr({className:e,submissionId:t}){let{api:s}=Y(),[a,r]=ga.useState("list"),[i,l]=ga.useState(null),[p,c]=ga.useState("submissions"),[d,n]=ga.useState(t),[g,x]=ga.useState(!!t);ga.useEffect(()=>{if(!t)return;async function b(){try{let N=await s.getSubmission(t),R=await s.getForm(N.form_id);l(R),r("detail"),c("submissions"),n(t)}catch(N){console.error("Failed to load submission for deep link:",N)}finally{x(!1)}}b()},[t,s]);let m=(b,N)=>{l(b),r("detail"),c(N),n(void 0)},o=()=>{r("list"),l(null),n(void 0)},u=b=>{l(b)};return g?ot("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:ot("div",{className:"af-text-muted-foreground",children:"Loading..."})}):Wt("div",{className:e,children:[a==="list"&&Wt("div",{children:[Wt("div",{className:"af-mb-6",children:[ot("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),ot("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),ot(qa,{onSelectForm:m})]}),a==="detail"&&i&&Wt("div",{children:[Wt("div",{className:"af-mb-6",children:[Wt(h,{variant:"ghost",size:"sm",onClick:o,className:"af-mb-2 af--ml-2",children:[ot(ci,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),ot("h2",{className:"af-text-lg af-font-semibold",children:i.name}),ot("p",{className:"af-text-sm af-text-muted-foreground",children:ot("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),Wt(ja,{value:p,onValueChange:b=>c(b),children:[Wt(Fa,{className:"af-mb-4",children:[Wt(aa,{value:"submissions",className:"af-gap-2",children:[ot(ui,{className:"af-h-4 af-w-4"}),"Submissions"]}),Wt(aa,{value:"settings",className:"af-gap-2",children:[ot(di,{className:"af-h-4 af-w-4"}),"Settings"]})]}),ot(sa,{value:"submissions",children:ot(Ka,{formId:i.id,defaultSubmissionId:d})}),ot(sa,{value:"settings",children:ot(Ya,{form:i,onSaved:u})})]})]})]})}import*as gs from"react";import{ArrowLeft as bo,Package as yo,Receipt as ho,Settings as xo,Users as No}from"lucide-react";import*as Xa from"react";import{Package as pi,Pencil as gi,Plus as ur,Trash2 as vi}from"lucide-react";var mi=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Gt(e){return mi.has(e.toLowerCase())}function M(e,t,s){let a=Gt(t)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:t.toUpperCase()}).format(a)}catch{return`${a} ${t.toUpperCase()}`}}function At(e){let t=e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0;return e.amount_total+(e.shipping_total??0)+t}function Ft(e,t){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let a=Gt(t)?s:s*100;return Math.round(a)}function Xe(e,t){return Gt(t)?e:e/100}import{jsx as be,jsxs as nt}from"react/jsx-runtime";function bi(e){if(e.allow_custom_amount){let t=e.min_amount!==null?M(e.min_amount,e.currency):"?",s=e.max_amount!==null?M(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${s})`}return e.unit_amount===null?"Varies by variant":M(e.unit_amount,e.currency)}function yi(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function es({productsState:e,onSelectProduct:t,onCreateProduct:s,className:a}){let{products:r,isLoading:i,error:l,deleteProduct:p}=e,[c,d]=Xa.useState(null),[n,g]=Xa.useState(!1),[x,m]=Xa.useState(null),o=async()=>{if(c)try{g(!0),m(null),await p(c.id),d(null)}catch(u){m(u instanceof Error?u.message:"Failed to delete product")}finally{g(!1)}};return i?be("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:be("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):l?be("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:nt("div",{className:"af-text-destructive",children:["Error: ",l.message]})}):r.length===0?nt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[be(pi,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),nt("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",be("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),nt(h,{variant:"outline",onClick:()=>s?.(),children:[be(ur,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):nt("div",{className:a,children:[be("div",{className:"af-flex af-justify-end af-mb-4",children:nt(h,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[be(ur,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),nt(we,{children:[be(Se,{children:nt(ee,{children:[be(k,{children:"Name"}),be(k,{children:"Price"}),be(k,{children:"Fulfillment"}),be(k,{children:"Status"}),be(k,{className:"af-text-right",children:"Actions"})]})}),be(Pe,{children:r.map(u=>nt(ee,{children:[be(_,{className:"af-font-medium",children:u.name}),be(_,{children:bi(u)}),be(_,{className:"af-text-muted-foreground",children:yi(u)}),be(_,{children:be(V,{variant:u.active?"success":"secondary",children:u.active?"Active":"Inactive"})}),be(_,{className:"af-text-right",children:nt("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[nt(h,{variant:"ghost",size:"sm",onClick:()=>t?.(u),children:[be(gi,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),nt(h,{variant:"ghost",size:"sm",onClick:()=>{m(null),d(u)},children:[be(vi,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},u.id))})]}),be(qt,{open:!!c,onOpenChange:u=>{!u&&!n&&d(null)},children:nt(Dt,{children:[nt(Et,{children:[be(Lt,{children:"Delete product?"}),nt(Bt,{children:['"',c?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),x&&be("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:x}),nt(Ot,{children:[be(h,{variant:"outline",onClick:()=>d(null),disabled:n,children:"Cancel"}),be(h,{variant:"destructive",onClick:o,disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}import*as Te from"react";import{FileText as xi,Link2 as Ni,Loader2 as gr,Plus as wi,Upload as Si,X as Pi}from"lucide-react";import*as Me from"react";import{Loader2 as mr,Plus as Es,Trash2 as pr,X as hi}from"lucide-react";import{jsx as E,jsxs as Z}from"react/jsx-runtime";function Os(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function ts({productId:e,currency:t,className:s}){let{api:a}=Y(),r=Gt(t)?"1":"0.01",[i,l]=Me.useState(null),[p,c]=Me.useState(!0),[d,n]=Me.useState(null),[g,x]=Me.useState(null),[m,o]=Me.useState(!1),u=Me.useRef(!0);Me.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);let b=Me.useCallback(async()=>{try{let w=await a.getProduct(e);if(!u.current)return;l(w)}catch(w){if(!u.current)return;n(w instanceof Error?w.message:"Failed to load product")}finally{u.current&&c(!1)}},[a,e]);Me.useEffect(()=>{b()},[b]);let N=async w=>{x(null),o(!0);try{await w(),await b()}catch(T){u.current&&x(T instanceof Error?T.message:"Something went wrong")}finally{u.current&&o(!1)}},[R,A]=Me.useState(""),[j,C]=Me.useState(""),[U,H]=Me.useState({}),J=()=>N(async()=>{let w=R.trim(),T=j.split(",").map(le=>le.trim()).filter(Boolean);if(!w)throw new Error("Option name is required");if(T.length===0)throw new Error("Add at least one value");await a.createOption(e,{title:w,values:T}),u.current&&(A(""),C(""))}),$=w=>N(async()=>{let T=(U[w.id]??"").trim();if(!T)throw new Error("Enter a value");await a.updateOption(w.id,{add_values:[T]}),u.current&&H(le=>({...le,[w.id]:""}))}),O=(w,T)=>N(()=>a.updateOption(w.id,{remove_values:[T]})),ie=w=>N(()=>a.deleteOption(w.id)),[y,ae]=Me.useState(null),[he,ye]=Me.useState(null),[ce,Be]=Me.useState(!1),[X,me]=Me.useState(null),Ce=i?.options??[],I=i?.variants??[],pe=()=>{ye(null),ae({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(Ce.map(w=>[w.id,w.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Ht=w=>{ye(null);let T=w.inventory?.on_hand??0,le=T<0?"":String(T);ae({variant:w,title:w.title??"",sku:w.sku??"",unitAmount:w.unit_amount!=null?String(Xe(w.unit_amount,t)):"",compareAt:w.compare_at_amount!=null?String(Xe(w.compare_at_amount,t)):"",active:w.active,optionValues:{},tracked:w.inventory?.tracked??!1,onHand:le,initialOnHand:le,allowBackorder:w.inventory?.allow_backorder??!1})},$t=async()=>{if(!y)return;ye(null);let w=y.variant?.allow_custom_amount??!1,T=null,le=null;if(!w){if(T=Ft(y.unitAmount,t),T===null||T<=0){ye("Enter a valid price");return}if(y.compareAt.trim()&&(le=Ft(y.compareAt,t),le===null||le<=T)){ye("Compare-at price must be greater than the price");return}}let tt=y.onHand.trim()!==y.initialOnHand.trim(),at=parseInt(y.onHand,10);if(y.tracked&&tt&&(!Number.isFinite(at)||at<0)){ye("On-hand quantity must be zero or more");return}try{if(Be(!0),y.variant)await a.updateVariant(y.variant.id,{title:y.title.trim()||null,sku:y.sku.trim()||null,...w?{}:{unit_amount:T,compare_at_amount:le},active:y.active}),await a.setVariantInventory(y.variant.id,{tracked:y.tracked,on_hand:y.tracked&&tt?at:void 0,allow_backorder:y.allowBackorder});else{let st={};for(let Ze of Ce){let zt=y.optionValues[Ze.id];if(!zt){ye(`Choose a ${Ze.title}`),Be(!1);return}st[Ze.title]=zt}await a.createVariant(e,{title:y.title.trim()||null,sku:y.sku.trim()||null,unit_amount:T,compare_at_amount:le,active:y.active,option_values:Ce.length>0?st:void 0,inventory:y.tracked?{tracked:!0,on_hand:at,allow_backorder:y.allowBackorder}:{tracked:!1,allow_backorder:y.allowBackorder}})}await b(),u.current&&ae(null)}catch(st){if(u.current&&ye(st instanceof Error?st.message:"Failed to save variant"),y.variant)try{let Ze=await a.getProduct(e);u.current&&l(Ze)}catch{}}finally{u.current&&Be(!1)}},Ie=()=>N(async()=>{X&&(await a.deleteVariant(X.id),u.current&&me(null))}),ht=y?.variant?.allow_custom_amount??!1,xt=y?.variant!=null&&y.variant.option_values.length===0&&Ce.length>0&&!y.variant.active,Ve=y?.variant?.inventory!=null&&y.variant.inventory.on_hand<0?-y.variant.inventory.on_hand:null;function Mt(w){let T=w.inventory;if(!T||!T.tracked)return E("span",{className:"af-text-muted-foreground",children:"Unlimited"});let le=T.available??T.on_hand;return le<0?Z("span",{children:[-le," backordered"]}):Z("span",{children:[le," in stock",T.allow_backorder&&E("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return p?E("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:E(mr,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):d?E("div",{className:s,children:E("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})}):Z("div",{className:`af-space-y-6 ${s||""}`,children:[Z("div",{className:"af-space-y-3",children:[Z("div",{children:[E(se,{children:"Options"}),E("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),Ce.length>0&&E("div",{className:"af-space-y-3",children:Ce.map(w=>Z("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[Z("div",{className:"af-flex af-items-center af-justify-between",children:[E("span",{className:"af-text-sm af-font-medium",children:w.title}),E(h,{variant:"ghost",size:"sm",onClick:()=>ie(w),disabled:m,children:E(pr,{className:"af-h-4 af-w-4"})})]}),E("div",{className:"af-flex af-flex-wrap af-gap-2",children:w.values.map(T=>Z(V,{variant:"secondary",className:"af-gap-1",children:[T.value,E("button",{type:"button",onClick:()=>O(w,T.value),className:"af-ml-1 hover:af-text-destructive",disabled:m,title:"Remove value",children:E(hi,{className:"af-h-3 af-w-3"})})]},T.id))}),Z("div",{className:"af-flex af-gap-2",children:[E(re,{value:U[w.id]??"",onChange:T=>H(le=>({...le,[w.id]:T.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),$(w))},disabled:m}),E(h,{type:"button",variant:"outline",size:"sm",onClick:()=>$(w),disabled:m||!(U[w.id]??"").trim(),children:E(Es,{className:"af-h-4 af-w-4"})})]})]},w.id))}),Z("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[Z("div",{className:"af-space-y-1",children:[E(se,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),E(re,{id:"new-option-title",value:R,onChange:w=>A(w.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:m})]}),Z("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[E(se,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),E(re,{id:"new-option-values",value:j,onChange:w=>C(w.target.value),placeholder:"S, M, L",disabled:m})]}),Z(h,{type:"button",variant:"outline",onClick:J,disabled:m||!R.trim()||!j.trim(),children:[E(Es,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),Z("div",{className:"af-space-y-3",children:[Z("div",{className:"af-flex af-items-center af-justify-between",children:[E(se,{children:"Variants"}),Z(h,{type:"button",variant:"outline",size:"sm",onClick:pe,disabled:m||Ce.length===0,children:[E(Es,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),Ce.length===0&&E("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),I.length===0?E("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):Z(we,{children:[E(Se,{children:Z(ee,{children:[E(k,{children:"Variant"}),E(k,{children:"SKU"}),E(k,{children:"Price"}),E(k,{children:"Stock"}),E(k,{children:"Status"}),E(k,{className:"af-text-right",children:"Actions"})]})}),E(Pe,{children:I.map(w=>Z(ee,{children:[E(_,{className:"af-font-medium",children:Os(w)}),E(_,{className:"af-text-muted-foreground",children:w.sku||"-"}),E(_,{children:w.unit_amount!=null?Z("span",{children:[w.compare_at_amount!=null&&E("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:M(w.compare_at_amount,w.currency)}),M(w.unit_amount,w.currency)]}):w.allow_custom_amount?E("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),E(_,{children:Mt(w)}),E(_,{children:E(V,{variant:w.active?"success":"secondary",children:w.active?"Active":"Inactive"})}),E(_,{className:"af-text-right",children:Z("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[E(h,{variant:"ghost",size:"sm",onClick:()=>Ht(w),disabled:m,children:"Edit"}),E(h,{variant:"ghost",size:"icon",onClick:()=>me(w),disabled:m,title:"Delete variant",children:E(pr,{className:"af-h-4 af-w-4"})})]})})]},w.id))})]})]}),g&&E("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g}),E(qt,{open:y!==null,onOpenChange:w=>{!w&&!ce&&ae(null)},children:Z(Dt,{children:[Z(Et,{children:[E(Lt,{children:y?.variant?"Edit variant":"Add variant"}),E(Bt,{children:"Price, markdown, and stock live on the variant."})]}),y&&Z("div",{className:"af-space-y-3",children:[y.variant?y.variant.option_values.length>0&&Z("div",{className:"af-text-sm",children:[E("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Os(y.variant)]}):Ce.map(w=>Z("div",{className:"af-space-y-1",children:[E(se,{className:"af-text-xs af-text-muted-foreground",children:w.title}),Z(wt,{value:y.optionValues[w.id]??"",onValueChange:T=>ae(le=>le&&{...le,optionValues:{...le.optionValues,[w.id]:T}}),children:[E(mt,{children:E(St,{placeholder:`Choose ${w.title}`})}),E(pt,{children:w.values.map(T=>E(Re,{value:T.value,children:T.value},T.id))})]})]},w.id)),ht?Z("div",{className:"af-space-y-1",children:[E(se,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),E("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):Z("div",{className:"af-flex af-gap-3",children:[Z("div",{className:"af-space-y-1",children:[Z(se,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),E(re,{id:"variant-price",type:"number",min:"0",step:r,value:y.unitAmount,onChange:w=>ae(T=>T&&{...T,unitAmount:w.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),Z("div",{className:"af-space-y-1",children:[E(se,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),E(re,{id:"variant-compare",type:"number",min:"0",step:r,value:y.compareAt,onChange:w=>ae(T=>T&&{...T,compareAt:w.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),Z("div",{className:"af-space-y-1",children:[E(se,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),E(re,{id:"variant-sku",value:y.sku,onChange:w=>ae(T=>T&&{...T,sku:w.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),Z("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[Z("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[E("input",{type:"checkbox",checked:y.tracked,onChange:w=>ae(T=>T&&{...T,tracked:w.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),y.tracked&&Z("div",{className:"af-space-y-1 af-pl-6",children:[Z("div",{className:"af-flex af-items-end af-gap-3",children:[Z("div",{className:"af-space-y-1",children:[E(se,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),E(re,{id:"variant-onhand",type:"number",min:"0",step:"1",value:y.onHand,onChange:w=>ae(T=>T&&{...T,onHand:w.target.value}),placeholder:Ve!=null?"0":void 0,className:"af-w-[100px]"})]}),Z("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[E("input",{type:"checkbox",checked:y.allowBackorder,onChange:w=>ae(T=>T&&{...T,allowBackorder:w.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Ve!=null&&Z("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Ve," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),Z("div",{className:"af-space-y-1",children:[Z("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[E("input",{type:"checkbox",checked:y.active,onChange:w=>ae(T=>T&&{...T,active:w.target.checked}),className:"af-h-4 af-w-4",disabled:xt}),"Active (buyers can purchase this variant)"]}),xt&&E("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),he&&E("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:he})]}),Z(Ot,{children:[E(h,{variant:"outline",onClick:()=>ae(null),disabled:ce,children:"Cancel"}),Z(h,{onClick:$t,disabled:ce,children:[ce?E(mr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,y?.variant?"Save":"Add variant"]})]})]})}),E(qt,{open:X!==null,onOpenChange:w=>{!w&&!m&&me(null)},children:Z(Dt,{children:[Z(Et,{children:[E(Lt,{children:"Delete variant?"}),E(Bt,{children:X&&`"${Os(X)}" will no longer be purchasable. Past orders are unaffected.`})]}),Z(Ot,{children:[E(h,{variant:"outline",onClick:()=>me(null),disabled:m,children:"Cancel"}),E(h,{variant:"destructive",onClick:Ie,disabled:m,children:"Delete"})]})]})})]})}import{Fragment as Ci,jsx as Q,jsxs as oe}from"react/jsx-runtime";function Ri(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,a)).toFixed(1))} ${s[a]}`}function as({productsState:e,product:t,currency:s,onSaved:a,className:r}){let{createProduct:i,updateProduct:l,attachProductFile:p,attachProductFileFromUrl:c}=e,d=!!t,n=t?.currency??s,g=Gt(n)?"1":"0.01",x=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[m,o]=Te.useState(!1),[u,b]=Te.useState(null),N=Te.useRef(!0);Te.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]);let[R,A]=Te.useState(t?.name??""),[j,C]=Te.useState(t?.description??""),[U,H]=Te.useState(t?.allow_custom_amount?"custom":"fixed"),[J,$]=Te.useState(t?.unit_amount!=null?String(Xe(t.unit_amount,n)):""),[O,ie]=Te.useState(t?.min_amount!=null?String(Xe(t.min_amount,n)):""),[y,ae]=Te.useState(t?.max_amount!=null?String(Xe(t.max_amount,n)):""),[he,ye]=Te.useState(String(t?.max_quantity??10)),ce=Te.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(Xe(t.unit_amount,n)):"",minAmount:t?.min_amount!=null?String(Xe(t.min_amount,n)):"",maxAmount:t?.max_amount!=null?String(Xe(t.max_amount,n)):"",maxQuantity:String(t?.max_quantity??10)}).current,[Be,X]=Te.useState(t?.collect_shipping_address??!1),[me,Ce]=Te.useState(t?.active??!0),[I,pe]=Te.useState(t?.images??[]),[Ht,$t]=Te.useState(""),[Ie,ht]=Te.useState(t?.fulfillment??null),[xt,Ve]=Te.useState(!1),[Mt,w]=Te.useState(""),[T,le]=Te.useState(null),tt=Te.useRef(null),at=m||xt,st=()=>{let K=Ht.trim();if(K){if(I.includes(K)){b("This image URL is already added");return}pe(Ne=>[...Ne,K]),$t(""),b(null)}},Ze=K=>{pe(Ne=>Ne.filter(Oe=>Oe!==K))},zt=async()=>{if(b(null),!R.trim()){b("Product name is required");return}let K=null,Ne=null,Oe=null,da=!d||U!==ce.pricingMode||(U==="fixed"?J!==ce.unitAmount:O!==ce.minAmount||y!==ce.maxAmount),jt=!d||he!==ce.maxQuantity,Ca=x||U==="fixed";if(!(x||!da))if(U==="fixed"){if(K=Ft(J,n),K===null||K<=0){b("Enter a valid price");return}}else{if(Ne=Ft(O,n),Oe=Ft(y,n),Ne===null||Oe===null){b("Enter valid minimum and maximum amounts");return}if(Oe<Ne){b("Maximum amount must be at least the minimum amount");return}}let Nt=parseInt(he,10);if(Ca&&jt&&(!Number.isFinite(Nt)||Nt<1)){b("Max quantity must be at least 1");return}try{o(!0);let Ae;if(d&&t){let We={name:R.trim(),description:j.trim()||null,images:I,collect_shipping_address:Be,active:me};!x&&da&&(We.allow_custom_amount=U==="custom",U==="fixed"?We.unit_amount=K:(We.min_amount=Ne,We.max_amount=Oe)),Ca&&jt&&(We.max_quantity=Nt),Ae=await l(t.id,We),ce.pricingMode=Ae.allow_custom_amount?"custom":"fixed",ce.unitAmount=Ae.unit_amount!=null?String(Xe(Ae.unit_amount,n)):"",ce.minAmount=Ae.min_amount!=null?String(Xe(Ae.min_amount,n)):"",ce.maxAmount=Ae.max_amount!=null?String(Xe(Ae.max_amount,n)):"",ce.maxQuantity=String(Ae.max_quantity)}else{let We={name:R.trim(),allow_custom_amount:U==="custom",collect_shipping_address:Be,active:me};j.trim()&&(We.description=j.trim()),I.length>0&&(We.images=I),U==="fixed"?(We.unit_amount=K,We.max_quantity=Nt):(We.min_amount=Ne,We.max_amount=Oe),Ae=await i(We)}if(!N.current)return;ht(Ae.fulfillment),a?.(Ae)}catch(Ae){if(!N.current)return;b(Ae instanceof Error?Ae.message:"Failed to save product")}finally{N.current&&o(!1)}},Pa=async K=>{let Ne=K.target.files?.[0];if(!(!Ne||!t))try{Ve(!0),le(null);let Oe=await p(t.id,Ne);if(!N.current)return;ht(Oe.fulfillment),a?.(Oe)}catch(Oe){if(!N.current)return;le(Oe instanceof Error?Oe.message:"Failed to upload file")}finally{N.current&&(Ve(!1),tt.current&&(tt.current.value=""))}},Ra=async()=>{let K=Mt.trim();if(!(!K||!t))try{Ve(!0),le(null);let Ne=await c(t.id,K);if(!N.current)return;ht(Ne.fulfillment),w(""),a?.(Ne)}catch(Ne){if(!N.current)return;le(Ne instanceof Error?Ne.message:"Failed to fetch file")}finally{N.current&&Ve(!1)}};return oe("div",{className:`af-space-y-6 ${r||""}`,children:[oe("div",{className:"af-space-y-2",children:[Q(se,{htmlFor:"product-name",children:"Name"}),Q(re,{id:"product-name",value:R,onChange:K=>A(K.target.value),placeholder:"My product"})]}),oe("div",{className:"af-space-y-2",children:[Q(se,{htmlFor:"product-description",children:"Description"}),Q("textarea",{id:"product-description",value:j,onChange:K=>C(K.target.value),rows:3,placeholder:"Shown on the Stripe checkout page.",className:"af-flex af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring"})]}),oe("div",{className:"af-space-y-2",children:[Q(se,{children:"Pricing"}),x?Q("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):oe(Ci,{children:[oe(wt,{value:U,onValueChange:K=>H(K),children:[Q(mt,{className:"af-w-[260px]",children:Q(St,{})}),oe(pt,{children:[Q(Re,{value:"fixed",children:"Fixed price"}),Q(Re,{value:"custom",children:"Buyer chooses the amount"})]})]}),U==="fixed"?Q("div",{className:"af-flex af-items-end af-gap-3",children:oe("div",{className:"af-space-y-1",children:[oe(se,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",n.toUpperCase(),")"]}),Q(re,{id:"product-price",type:"number",min:"0",step:g,value:J,onChange:K=>$(K.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):oe("div",{className:"af-space-y-1",children:[oe("div",{className:"af-flex af-items-end af-gap-3",children:[oe("div",{className:"af-space-y-1",children:[oe(se,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",n.toUpperCase(),")"]}),Q(re,{id:"product-min-amount",type:"number",min:"0",step:g,value:O,onChange:K=>ie(K.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),oe("div",{className:"af-space-y-1",children:[oe(se,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",n.toUpperCase(),")"]}),Q(re,{id:"product-max-amount",type:"number",min:"0",step:g,value:y,onChange:K=>ae(K.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),Q("p",{className:"af-text-xs af-text-muted-foreground",children:"Buyers pick their own amount within these bounds (tip jar, pay-what-you-want). Quantity is always 1."})]}),oe("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",n.toUpperCase(),"), which follows the country of your payment account."]})]}),(x||U==="fixed")&&oe("div",{className:"af-space-y-1",children:[Q(se,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),Q(re,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:he,onChange:K=>ye(K.target.value),className:"af-w-[140px]"})]})]}),oe("div",{className:"af-space-y-2",children:[Q(se,{children:"Images"}),Q("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),oe("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[I.map(K=>oe(V,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[Q("span",{className:"af-truncate",children:K}),Q("button",{type:"button",onClick:()=>Ze(K),className:"af-ml-1 hover:af-text-destructive",disabled:m,children:Q(Pi,{className:"af-h-3 af-w-3"})})]},K)),I.length===0&&Q("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),oe("div",{className:"af-flex af-gap-2",children:[Q(re,{type:"url",value:Ht,onChange:K=>$t(K.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:K=>{K.key==="Enter"&&(K.preventDefault(),st())},disabled:m}),Q(h,{type:"button",variant:"outline",onClick:st,disabled:!Ht.trim()||m,children:Q(wi,{className:"af-h-4 af-w-4"})})]})]}),oe("div",{className:"af-space-y-2",children:[Q(se,{children:"Digital File"}),Q("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),d?oe("div",{className:"af-space-y-3",children:[Ie?.type==="download"&&oe("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Q(xi,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Q("span",{className:"af-text-sm",children:Ie.filename}),Ie.size!=null&&oe("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Ri(Ie.size),")"]})]}),Ie?.type==="redirect"&&Ie.url&&oe("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Q(Ni,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),oe("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Ie.url]})]}),oe("div",{className:"af-flex af-items-center af-gap-2",children:[Q("input",{ref:tt,type:"file",onChange:Pa,className:"af-hidden",disabled:at}),oe(h,{type:"button",variant:"outline",size:"sm",onClick:()=>tt.current?.click(),disabled:at,children:[xt?Q(gr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Q(Si,{className:"af-h-4 af-w-4 af-mr-1"}),Ie?.type==="download"?"Replace file":"Upload file"]}),Q("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),Q(re,{type:"url",value:Mt,onChange:K=>w(K.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:xt}),Q(h,{type:"button",variant:"outline",size:"sm",onClick:Ra,disabled:!Mt.trim()||at,children:"Fetch from URL"})]}),T&&Q("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:T})]}):Q("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),oe("div",{className:"af-space-y-2",children:[Q(se,{children:"Settings"}),oe("div",{className:"af-space-y-2",children:[oe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Q("input",{type:"checkbox",checked:Be,onChange:K=>X(K.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),oe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Q("input",{type:"checkbox",checked:me,onChange:K=>Ce(K.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),d&&t&&oe("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[Q(se,{children:"Options & Variants"}),Q(ts,{productId:t.id,currency:n})]}),u&&Q("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u}),Q("div",{className:"af-flex af-items-center af-gap-2",children:oe(h,{type:"button",onClick:zt,disabled:at,children:[m?Q(gr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?"Save changes":"Create product"]})})]})}import*as Ge from"react";import{ChevronLeft as Zi,ChevronRight as kr,Loader2 as Qi,Receipt as Yi,Search as Xi,SlidersHorizontal as eo}from"lucide-react";import*as Le from"react";var Ti=["pending","paid","failed","expired","refunded","partially_refunded","disputed"];function ss({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=Y(),[a,r]=Le.useState([]),[i,l]=Le.useState(0),[p,c]=Le.useState(!0),[d,n]=Le.useState(null),[g,x]=Le.useState(0),[m,o]=Le.useState(e),[u,b]=Le.useState(void 0),[N,R]=Le.useState(""),[A,j]=Le.useState(""),[C,U]=Le.useState(""),[H,J]=Le.useState(!1),[$,O]=Le.useState(!1),[ie,y]=Le.useState(void 0),ae=ie?ie.join(","):"",he=Le.useMemo(()=>{if(!ae)return;let X=new Set(ae.split(","));return Ti.filter(me=>!X.has(me))},[ae]),ye=Le.useRef(0),ce=Le.useCallback(async()=>{let X=++ye.current;try{c(!0),n(null);let me={limit:m,offset:g*m};u?me.status=u:he?me.excludeStatus=he:H||(me.excludeStatus=["pending","expired"]),N.trim()&&(me.customerEmail=N.trim()),A.trim()&&(me.from=A.trim()),C.trim()&&(me.to=C.trim()),$&&(me.unfulfilledOnly=!0);let Ce=await s.getOrders(me);if(X!==ye.current)return;r(Ce.orders),l(Ce.total)}catch(me){if(X!==ye.current)return;n(me instanceof Error?me:new Error("Failed to fetch orders"))}finally{X===ye.current&&c(!1)}},[s,g,m,u,he,H,$,N,A,C,t]);Le.useEffect(()=>{ce()},[ce]);let Be=Math.ceil(i/m);return{orders:a,total:i,isLoading:p,error:d,page:g,pageSize:m,hasNextPage:g<Be-1,hasPreviousPage:g>0,setPage:x,setPageSize:X=>{o(X),x(0)},status:u,setStatus:X=>{b(X),x(0)},statusIn:ie,setStatusIn:X=>{y(X&&X.length>0?X:void 0),x(0)},customerEmail:N,setCustomerEmail:X=>{R(X),x(0)},from:A,setFrom:X=>{j(X),x(0)},to:C,setTo:X=>{U(X),x(0)},showAbandoned:H,setShowAbandoned:X=>{J(X),x(0)},unfulfilledOnly:$,setUnfulfilledOnly:X=>{O(X),x(0)},clearFilters:()=>{b(void 0),y(void 0),J(!1),O(!1),R(""),j(""),U(""),x(0)},refetch:ce}}import*as Ue from"react";import{ArrowLeft as Di,Check as xr,ChevronLeft as Ei,ChevronRight as Oi,ClipboardCopy as Li,Copy as Bi,Download as Ii,Loader2 as ns,Mail as Nr,MoreHorizontal as Ai,Package as Fi,RotateCcw as Ui,Truck as Vi,Undo2 as wr}from"lucide-react";import*as vr from"react";import*as Kt from"@radix-ui/react-popover";import{jsx as Ls}from"react/jsx-runtime";var br=Kt.Root,yr=Kt.Trigger;var Bs=vr.forwardRef(({className:e,align:t="end",sideOffset:s=4,...a},r)=>Ls(Kt.Portal,{children:Ls("div",{className:"aifeatures-admin",children:Ls(Kt.Content,{ref:r,align:t,sideOffset:s,className:F("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...a})})}));Bs.displayName=Kt.Content.displayName;import{jsx as rs}from"react/jsx-runtime";var ki={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed"};function _i(e){return ki[e]??e}function hr(e){switch(e){case"paid":return"success";case"pending":return"secondary";case"refunded":case"partially_refunded":return"warning";case"disputed":return"destructive";default:return"outline"}}function ha({status:e,className:t}){return rs(V,{variant:hr(e),className:t,children:_i(e)})}function xa({status:e}){return rs(ha,{status:e})}function ka({order:e,className:t}){return e.shipping_address?typeof e.merchant_fulfilled_at=="string"?rs(V,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?rs(V,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function fa(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as Gi,jsx as v,jsxs as L}from"react/jsx-runtime";var Cr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Na="af-text-xs af-text-muted-foreground";function Is(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tr(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var is=24,$i=["paid","partially_refunded"],Mi=["paid","partially_refunded","disputed"],zi=/^[A-Za-z0-9 _-]*$/,Sr=100;function Us(e,t,s,a,r){let i=$i.includes(a);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${is} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${is} tries used). Nothing is being retried while the order is ${a.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?s<is&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:s<is&&e==="buyer"&&!r?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${s} attempt${s===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${a==="refunded"?"because the order was refunded":a==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function Pr({title:e,recipient:t,status:s,attempts:a,side:r,orderStatus:i,action:l}){let p=Us(r,s,a,i,t);return L("div",{children:[L("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[L("div",{className:"af-min-w-0",children:[v("div",{className:"af-text-sm",children:e}),t&&v("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),v(V,{variant:p.variant,className:"af-shrink-0",children:p.label})]}),p.detail&&v("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:p.detail}),l&&v("div",{className:"af-mt-2",children:l})]})}function Rr(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let s=Hi(e.address)?e.address:null;if(s){for(let r of["line1","line2"]){let i=s[r];typeof i=="string"&&i&&t.push(i)}let a=["city","state","postal_code"].map(r=>s[r]).filter(r=>typeof r=="string"&&!!r).join(", ");a&&t.push(a),typeof s.country=="string"&&s.country&&t.push(s.country)}return t.length>0?t:Object.entries(e).map(([a,r])=>`${a}: ${Tr(r)}`)}function ji(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Vs({value:e,label:t,children:s,className:a,size:r="icon"}){let[i,l]=Ue.useState(!1);if(!ji())return null;let p=async()=>{try{await navigator.clipboard.writeText(e),l(!0),setTimeout(()=>l(!1),1500)}catch{}},c=i?v(xr,{className:"af-h-3 af-w-3"}):v(Bi,{className:"af-h-3 af-w-3"});return r==="icon"?v(h,{variant:"ghost",size:"icon",className:F("af-h-6 af-w-6 af-shrink-0",a),onClick:p,title:t,"aria-label":t,children:c}):L(h,{variant:"outline",size:"sm",className:a,onClick:p,"aria-label":t,children:[i?v(xr,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):v(Li,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function As({label:e,value:t}){return L("div",{children:[v("div",{className:Na,children:e}),L("div",{className:"af-flex af-items-center af-gap-1",children:[v("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),v(Vs,{value:t,label:`Copy ${e}`})]})]})}function qi({src:e}){let[t,s]=Ue.useState(!1);return!e||t?v("div",{"aria-hidden":"true",className:"af-flex af-h-10 af-w-10 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-muted",children:v(Fi,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):v("img",{src:e,alt:"","aria-hidden":"true",onError:()=>s(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function va({title:e,action:t,children:s,className:a}){return L("section",{className:F("af-rounded-lg af-border af-p-4",a),children:[L("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[v("h4",{className:Cr,children:e}),t]}),v("div",{className:"af-mt-3",children:s})]})}function ba({label:e,emphasis:t,children:s}){return L("div",{className:F("af-flex af-items-baseline af-justify-between af-gap-6",t&&"af-mt-2 af-border-t af-pt-2"),children:[v("span",{className:t?"af-text-base af-font-semibold":Na,children:e}),v("span",{className:F("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function Fs({onSelect:e,disabled:t,icon:s,children:a}){return L(h,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[v("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),a]})}function Wi(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${M(At(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=Us("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=Us("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"?"You were notified of this sale":`Sale alert to you \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${M(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function os({order:e,onBack:t,onRefund:s,onOrderUpdated:a,allowFulfillment:r=!1,onPrevOrder:i,onNextOrder:l,hasPrevOrder:p=!1,hasNextOrder:c=!1}){let{api:d}=Y(),[n,g]=Ue.useState(e),[x,m]=Ue.useState(null),[o,u]=Ue.useState(null),[b,N]=Ue.useState(!1),[R,A]=Ue.useState(!1),[j,C]=Ue.useState(!1),[U,H]=Ue.useState(!1),[J,$]=Ue.useState(""),[O,ie]=Ue.useState(!1),[y,ae]=Ue.useState(null),[he,ye]=Ue.useState(!1),[ce,Be]=Ue.useState(""),[X,me]=Ue.useState([]),[Ce,I]=Ue.useState(!1),[pe,Ht]=Ue.useState(!1),[$t,Ie]=Ue.useState(null);Ue.useEffect(()=>{g(e)},[e]);let ht=P=>{g(P),a?.(P)},xt=Object.entries(n.metadata??{}),Ve=At(n)-n.amount_refunded,Mt=(n.status==="paid"||n.status==="partially_refunded")&&Ve>0,w=P=>(typeof P.unitAmount=="number"?P.unitAmount:0)*(typeof P.quantity=="number"&&P.quantity>0?P.quantity:1),T=Math.max(0,(n.shipping_total??0)-(n.shipping_refunded??0)),le=X.reduce((P,xe)=>P+w(n.line_items[xe]??{}),0)+(Ce?T:0),tt=n.tax_total??0,at=n.automatic_tax&&n.tax_behavior==="exclusive"&&tt>0&&n.amount_total+(n.shipping_total??0)>0?Math.min(Math.max(0,tt-(n.tax_refunded??0)),Math.round(tt*le/(n.amount_total+(n.shipping_total??0)))):0,st=le+at,Ze=X.length>0||Ce,zt=Ze?st:Ft(ce,n.currency),Pa=Gt(n.currency)?"1":"0.01",Ra=async()=>{try{N(!0),m(null),u(null),await d.resendOrderReceipt(n.id);let P=await d.getOrder(n.id);ht(P),u("Receipt email queued.")}catch(P){m(P instanceof Error?P.message:"Failed to resend receipt")}finally{N(!1)}},K=async()=>{try{A(!0),m(null),u(null);let P=await d.resetOrderDownloads(n.id);ht(P),C(!1),u("Download count reset.")}catch(P){m(P instanceof Error?P.message:"Failed to reset downloads")}finally{A(!1)}},Ne=!!n.shipping_address,Oe=typeof n.merchant_fulfilled_at=="string",da=Mi.includes(n.status),jt=J.trim(),Ca=zi.test(jt)&&jt.length<=Sr,Nt=async P=>{try{ie(!0),ae(null),u(null);let xe=await d.setOrderFulfillment(n.id,{fulfilled:P,...P&&jt?{trackingNumber:jt}:{}});ht(xe),$(""),u(P?"Marked as shipped.":"Marked as not shipped.")}catch(xe){xe instanceof ua&&xe.status===409?ae(`This order is ${n.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):ae(xe instanceof Error?xe.message:"Failed to update the order")}finally{ie(!1)}},Ae=()=>{Ie(null),Be(String(Xe(Ve,n.currency))),me([]),I(!1),ye(!0)},We=P=>me(xe=>xe.includes(P)?xe.filter(ct=>ct!==P):[...xe,P]),Ba=async(P,xe)=>{if(s)try{Ht(!0),Ie(null),await s(n,P,xe);let ct=await d.getOrder(n.id);ht(ct),ye(!1),u("Refund issued.")}catch(ct){Ie(ct instanceof Error?ct.message:"Refund failed")}finally{Ht(!1)}},D=async()=>{if(Ze){if(st<=0){Ie("The lines you picked were charged nothing");return}if(st>Ve){Ie(`That selection exceeds the refundable remainder (${M(Ve,n.currency)})`);return}await Ba(st,{...X.length>0?{line_items:[...X].sort((xe,ct)=>xe-ct)}:{},...Ce?{shipping:!0}:{}});return}let P=Ft(ce,n.currency);if(P===null||P<=0){Ie("Enter a valid refund amount");return}if(P>Ve){Ie(`Amount exceeds the refundable remainder (${M(Ve,n.currency)})`);return}await Ba(P,{amount:P})},ft=()=>Ba(Ve,{full:!0}),Gs=n.fulfillment_type==="download",Ks=r&&Ne,on=Wi(n),ln=n.shipping_address?Rr(n.shipping_address).join(`
4
+ `):"",Js=n.shipping_total!=null,Zs=!!n.automatic_tax&&n.tax_behavior==="exclusive"&&(n.tax_total??0)>0,fn=!(n.automatic_tax&&n.tax_behavior==="exclusive")&&(n.tax_total??0)>0,cn=Js||Zs,Ia=[];return Ia.push(v(Fs,{icon:b?v(ns,{className:"af-h-4 af-w-4 af-animate-spin"}):v(Nr,{className:"af-h-4 af-w-4"}),disabled:b||n.fulfillment_status!=="fulfilled",onSelect:()=>{H(!1),Ra()},children:"Resend receipt"},"resend")),Gs&&Ia.push(v(Fs,{icon:v(Ui,{className:"af-h-4 af-w-4"}),disabled:R,onSelect:()=>{H(!1),C(!0)},children:"Reset download count"},"reset")),Mt&&Ia.push(L("div",{children:[v(Fs,{icon:v(wr,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{H(!1),Ae()},children:"Refund\u2026"}),!s&&v("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),L("div",{children:[L("div",{className:"af-mb-6",children:[L(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[v(Di,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),L("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[L("div",{className:"af-min-w-0",children:[L("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[v("h3",{className:"af-text-xl af-font-semibold",children:fa(n)}),v(ha,{status:n.status}),r&&v(ka,{order:n}),n.is_test&&v(V,{variant:"outline",children:"Test"})]}),L("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Is(n.created_at)]}),n.is_test&&v("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),L("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||l)&&L("div",{className:"af-flex af-items-center",children:[v(h,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!p,"aria-label":"Previous order",children:v(Ei,{className:"af-h-4 af-w-4"})}),v(h,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:l,disabled:!c,"aria-label":"Next order",children:v(Oi,{className:"af-h-4 af-w-4"})})]}),Ks&&(Oe?L("div",{className:"af-flex af-items-center af-gap-1",children:[L("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",n.merchant_fulfilled_at?` \xB7 ${Is(n.merchant_fulfilled_at)}`:""]}),da&&L(h,{variant:"ghost",size:"sm",onClick:()=>Nt(!1),disabled:O,children:[O?v(ns,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):v(wr,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):da?L("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[v(re,{value:J,onChange:P=>$(P.target.value),placeholder:"Tracking number (optional)",maxLength:Sr,className:"af-w-[200px]","aria-label":"Tracking number (optional)",disabled:O}),L(h,{variant:"default",onClick:()=>Nt(!0),disabled:O||!Ca,children:[O?v(ns,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):v(Vi,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Ia.length>0&&L(br,{open:U,onOpenChange:H,children:[v(yr,{asChild:!0,children:v(h,{variant:"outline",size:"icon","aria-label":"More actions",children:v(Ai,{className:"af-h-4 af-w-4"})})}),v(Bs,{children:v("div",{className:"af-space-y-0.5",children:Ia})})]})]})]}),Ks&&!Oe&&!Ca&&v("p",{className:"af-mt-2 af-text-xs af-text-destructive",children:"Tracking numbers can use letters, numbers, spaces, dashes and underscores \u2014 up to 100 characters."}),y&&v("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:y}),o&&v("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:o}),x&&v("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:x})]}),L("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[L("div",{className:"af-space-y-6",children:[n.line_items.length>0&&v(va,{title:"Items",children:v("ul",{className:"af-space-y-3",children:n.line_items.map((P,xe)=>{let ct=typeof P.name=="string"&&P.name?P.name:"Item",Qs=typeof P.quantity=="number"&&P.quantity>0?P.quantity:1,Ys=typeof P.unitAmount=="number";return L("li",{className:"af-flex af-items-start af-gap-3",children:[v(qi,{src:typeof P.imageUrl=="string"&&P.imageUrl?P.imageUrl:void 0}),L("div",{className:"af-min-w-0 af-flex-1",children:[L("div",{className:"af-text-sm af-font-medium",children:[ct,typeof P.variantTitle=="string"&&P.variantTitle&&L("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",P.variantTitle]})]}),L("div",{className:Na,children:[Qs," \xD7"," ",Ys?M(P.unitAmount,n.currency):"\u2014"]}),P.refunded===!0&&v(V,{variant:"secondary",className:"af-mt-1",children:P.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),v("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:Ys?M(P.unitAmount*Qs,n.currency):"\u2014"})]},xe)})})}),xt.length>0&&v(va,{title:"Order details",children:v("dl",{className:"af-space-y-2",children:xt.map(([P,xe])=>L("div",{children:[v("dt",{className:F(Na,"af-capitalize"),children:P.replace(/_/g," ")}),v("dd",{className:"af-text-sm af-break-words",children:Tr(xe)})]},P))})}),v(va,{title:"Payment",children:L("div",{className:"af-ml-auto af-w-full sm:af-max-w-xs",children:[cn&&v(ba,{label:"Subtotal",children:M(n.amount_total,n.currency)}),Js&&v(ba,{label:"Shipping",children:n.shipping_total===0?"Free":M(n.shipping_total??0,n.currency)}),Zs&&v(ba,{label:"Tax",children:M(n.tax_total??0,n.currency)}),v(ba,{label:"Total",emphasis:!0,children:M(At(n),n.currency)}),fn&&v(ba,{label:"incl. tax",children:M(n.tax_total??0,n.currency)}),n.base_currency!=null&&n.base_amount_total!=null&&L(ba,{label:"Your price",children:[M(n.base_amount_total,n.base_currency),L("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",n.currency.toUpperCase()]})]}),n.amount_refunded>0&&L(Gi,{children:[L(ba,{label:"Refunded",children:["\u2212",M(n.amount_refunded,n.currency),(n.shipping_refunded??0)>0&&L("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",M(n.shipping_refunded??0,n.currency)," ","shipping"]})]}),v(ba,{label:"Net",children:v("span",{className:"af-font-medium",children:M(Math.max(0,At(n)-n.amount_refunded),n.currency)})})]})]})}),v(va,{title:"Timeline",children:v("ol",{className:"af-space-y-3",children:on.map(P=>L("li",{className:"af-flex af-gap-3",children:[v("span",{"aria-hidden":"true",className:F("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",P.tone==="destructive"?"af-bg-destructive":P.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),L("div",{className:"af-min-w-0",children:[v("div",{className:"af-text-sm af-break-words",children:P.text}),P.at&&v("div",{className:"af-text-xs af-text-muted-foreground",children:Is(P.at)})]})]},P.key))})})]}),L("div",{className:"af-space-y-6",children:[v(va,{title:"Customer",children:L("div",{className:"af-space-y-2",children:[L("div",{children:[v("div",{className:Na,children:"Email"}),L("div",{className:"af-flex af-items-center af-gap-1",children:[v("span",{className:"af-min-w-0 af-break-all af-text-sm",children:n.customer_email||v("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),n.customer_email&&v(Vs,{value:n.customer_email,label:"Copy email"})]})]}),n.customer_name&&L("div",{children:[v("div",{className:Na,children:"Name"}),v("div",{className:"af-text-sm",children:n.customer_name})]}),n.customer&&L("div",{children:[v("div",{className:Na,children:"Customer record"}),L("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[v("span",{className:"af-break-all af-text-sm",children:n.customer.name||n.customer.email}),v(V,{variant:"secondary",children:"Linked"})]})]})]})}),n.shipping_address&&v(va,{title:"Ship to",action:v(Vs,{value:ln,label:"Copy address",size:"sm",children:"Copy address"}),children:v("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Rr(n.shipping_address).map((P,xe)=>v("div",{children:P},xe))})}),v(va,{title:"Emails",children:L("div",{className:"af-space-y-4",children:[v(Pr,{side:"buyer",title:"Receipt to buyer",recipient:n.customer_email,status:n.buyer_email_status,attempts:n.buyer_email_attempts,orderStatus:n.status,action:L(h,{variant:"outline",size:"sm",onClick:Ra,disabled:b||n.fulfillment_status!=="fulfilled",children:[b?v(ns,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):v(Nr,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),v(Pr,{side:"merchant",title:"Sale alert to you",recipient:null,status:n.merchant_email_status,attempts:n.merchant_email_attempts,orderStatus:n.status})]})}),Gs&&v(va,{title:"Download",children:L("div",{className:"af-space-y-2",children:[L("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[v(Ii,{className:"af-h-4 af-w-4"}),L("span",{children:["Downloaded ",n.download_count," time",n.download_count===1?"":"s"]})]}),n.download_url&&v("a",{href:n.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),L("details",{className:"af-rounded-lg af-border af-p-4",children:[v("summary",{className:F(Cr,"af-cursor-pointer af-select-none"),children:"Technical details"}),L("div",{className:"af-mt-3 af-space-y-2",children:[v(As,{label:"Order ID",value:n.id}),n.stripe_checkout_session_id&&v(As,{label:"Checkout session",value:n.stripe_checkout_session_id}),n.stripe_payment_intent_id&&v(As,{label:"Payment",value:n.stripe_payment_intent_id})]})]})]})]}),v(qt,{open:j,onOpenChange:P=>{!P&&!R&&C(!1)},children:L(Dt,{children:[L(Et,{children:[v(Lt,{children:"Reset download count?"}),v(Bt,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),L(Ot,{children:[v(h,{variant:"outline",onClick:()=>C(!1),disabled:R,children:"Cancel"}),v(h,{onClick:K,disabled:R,children:R?"Resetting...":"Reset"})]})]})}),v(qt,{open:he,onOpenChange:P=>{!P&&!pe&&ye(!1)},children:L(Dt,{children:[L(Et,{children:[v(Lt,{children:"Refund order"}),L(Bt,{children:["Refund up to ",M(Ve,n.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),L("div",{className:"af-space-y-4",children:[(n.line_items.length>0||T>0)&&L("div",{className:"af-space-y-2",children:[v(se,{children:"Items"}),L("div",{className:"af-space-y-2",children:[n.line_items.map((P,xe)=>{let ct=P.refunded===!0;return L("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[v("input",{type:"checkbox",checked:X.includes(xe),onChange:()=>We(xe),disabled:pe||ct,className:"af-h-4 af-w-4"}),L("span",{className:ct?"af-text-muted-foreground af-line-through":void 0,children:[typeof P.name=="string"&&P.name?P.name:"Item",typeof P.variantTitle=="string"&&P.variantTitle?` \u2014 ${P.variantTitle}`:"",typeof P.quantity=="number"&&P.quantity>1?` \xD7 ${P.quantity}`:""]}),v("span",{className:"af-ml-auto af-text-muted-foreground",children:ct?"Refunded":M(w(P),n.currency)})]},xe)}),T>0&&L("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[v("input",{type:"checkbox",checked:Ce,onChange:P=>I(P.target.checked),disabled:pe,className:"af-h-4 af-w-4"}),v("span",{children:"Shipping"}),v("span",{className:"af-ml-auto af-text-muted-foreground",children:M(T,n.currency)})]})]})]}),L("div",{className:"af-space-y-2",children:[L(se,{htmlFor:"refund-amount",children:["Amount (",n.currency.toUpperCase(),")"]}),v(re,{id:"refund-amount",type:"number",min:"0",step:Pa,value:Ze?String(Xe(st,n.currency)):ce,onChange:P=>Be(P.target.value),disabled:pe||Ze}),Ze&&v("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),$t&&v("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:$t}),L(Ot,{children:[v(h,{variant:"outline",onClick:()=>ye(!1),disabled:pe,children:"Cancel"}),v(h,{variant:"outline",onClick:ft,disabled:pe,children:"Refund everything"}),v(h,{variant:"destructive",onClick:D,disabled:pe,children:pe?"Refunding...":zt!==null&&zt>0?`Refund ${M(zt,n.currency)}`:"Refund"})]})]})})]})}import*as ls from"react";import{ArrowLeft as Ki,RefreshCw as Ji}from"lucide-react";import{jsx as Jt,jsxs as wa}from"react/jsx-runtime";function Zt({title:e,onBackToWebsite:t,hideBackButton:s=!1,children:a,className:r}){let i=ls.useRef(null);return ls.useEffect(()=>{i.current?.focus()},[]),wa("div",{className:F("af-bg-background",r),children:[wa("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-justify-between af-gap-2 af-border-b af-bg-background af-px-4 af-py-2",children:[Jt("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!s&&wa(h,{type:"button",variant:"outline",size:"sm",onClick:t,children:[Jt(Ki,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Jt("div",{className:"af-p-4",children:a})]})}function G({className:e}){return Jt("div",{"aria-hidden":"true",className:F("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function it({label:e,children:t,detail:s,valueClassName:a}){return wa("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Jt("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Jt("div",{className:F("af-mt-1 af-text-lg af-font-semibold",a),children:t}),s&&Jt("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function bt({message:e,onRetry:t}){return wa("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Jt("span",{children:e}),wa(h,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[Jt(Ji,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Qt({icon:e,children:t}){return wa("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Jt("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}import{Fragment as ao,jsx as S,jsxs as te}from"react/jsx-runtime";var to={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},_r={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Dr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Er(e){let t=Array.isArray(e.line_items)?e.line_items:[],s=t[0];if(!s)return"\u2014";let a=typeof s.name=="string"&&s.name?s.name:"Item",r=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,i=r>1?`${a} \xD7${r}`:a;return t.length>1?`${i} +${t.length-1} more`:i}function fs(e){return e.customer?.name||e.customer_name||null}function _a({onRefund:e,className:t,refreshKey:s,initialOrderId:a,showFulfillment:r=!1,emptyMessage:i,onDetailOpenChange:l}){let{api:p}=Y(),c=ss({refreshKey:s}),{orders:d,total:n,isLoading:g,error:x,page:m,pageSize:o,hasNextPage:u,hasPreviousPage:b,setPage:N,setPageSize:R,customerEmail:A,setCustomerEmail:j,setStatusIn:C,from:U,setFrom:H,to:J,setTo:$,showAbandoned:O,setShowAbandoned:ie,setUnfulfilledOnly:y,refetch:ae}=c,[he,ye]=Ge.useState("list"),[ce,Be]=Ge.useState(null),[X,me]=Ge.useState(""),[Ce,I]=Ge.useState(""),[pe,Ht]=Ge.useState(r?"needs_shipping":"all"),[$t,Ie]=Ge.useState(!1),[ht,xt]=Ge.useState(!!a),[Ve,Mt]=Ge.useState(null);Ge.useEffect(()=>{if(!a)return;let D=!1;return xt(!0),Mt(null),p.getOrder(a).then(ft=>{D||(Be(ft),ye("detail"))}).catch(()=>{D||Mt("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{D||xt(!1)}),()=>{D=!0}},[p,a]);let w=Ge.useCallback(D=>{Ht(D);let ft=_r[D];C(ft.statusIn),y(ft.unfulfilledOnly)},[C,y]);Ge.useEffect(()=>{r&&y(!0)},[]);let T=Ge.useRef(!r);Ge.useEffect(()=>{T.current||g||(T.current=!0,d.length===0&&w("all"))},[g,d.length,w]);let le=he==="detail"&&!!ce;Ge.useEffect(()=>{l?.(le)},[le,l]);let tt=(U?1:0)+(J?1:0)+(O?1:0),at=tt>0||!!A||!!Ce,st=!!U&&!!J&&U>J,Ze=D=>{Be(D),ye("detail")},zt=()=>{ye("list"),Be(null),ae()},Pa=D=>{let ft=D.trim();if(!ft){I(""),A&&j("");return}if(ft.startsWith("#")||/^\d+$/.test(ft)){I(ft),A&&j("");return}I(""),j(ft)},Ra=()=>{me(""),I(""),j(""),H(""),$(""),ie(!1),Ie(!1)},K=Ce.replace(/^#/,"").toLowerCase(),Ne=K?d.filter(D=>String(D.order_number??"")===K||D.id.toLowerCase().startsWith(K)):d,Oe=ce?d.findIndex(D=>D.id===ce.id):-1,da=Oe>0,jt=Oe>=0&&Oe<d.length-1;if(ht)return S("div",{className:t,children:S("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:S(Qi,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(he==="detail"&&ce)return S("div",{className:t,children:S(os,{order:ce,onBack:zt,onRefund:e,onOrderUpdated:D=>Be(D),allowFulfillment:r,onPrevOrder:da?()=>Be(d[Oe-1]):void 0,onNextOrder:jt?()=>Be(d[Oe+1]):void 0,hasPrevOrder:da,hasNextOrder:jt},ce.id)});let Nt=te("div",{className:"af-mb-4 af-space-y-3",children:[Ve&&S("p",{className:"af-text-xs af-text-muted-foreground",children:Ve}),te("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[S("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(r?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(D=>S("button",{type:"button","aria-pressed":pe===D,onClick:()=>w(D),className:F("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",pe===D?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:to[D]},D))}),te("div",{className:"af-relative af-w-full af-max-w-xs",children:[S(Xi,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),S(re,{type:"text",value:X,onChange:D=>me(D.target.value),onBlur:()=>Pa(X),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),Pa(X))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),te(h,{type:"button",variant:tt>0?"secondary":"ghost",size:"sm",onClick:()=>Ie(D=>!D),"aria-expanded":$t,children:[S(eo,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",tt>0&&S(V,{variant:"secondary",className:"af-ml-2",children:tt})]}),at&&S(h,{type:"button",variant:"ghost",size:"sm",onClick:Ra,children:"Clear filters"})]}),($t||!!U||!!J)&&te("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2",children:[S(se,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),S(re,{id:"orders-from",type:"date",value:U,max:J||void 0,onChange:D=>H(D.target.value),className:"af-w-[170px]"}),S(se,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),S(re,{id:"orders-to",type:"date",value:J,min:U||void 0,onChange:D=>$(D.target.value),className:"af-w-[170px]"}),!_r[pe].statusIn&&S(h,{type:"button",variant:O?"secondary":"ghost",size:"sm",onClick:()=>ie(!O),"aria-pressed":O,children:O?"Hide abandoned":"Show abandoned"})]}),st&&S("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(g)return te("div",{className:t,children:[Nt,S("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(D=>te("div",{className:"af-rounded-md af-border af-p-3",children:[te("div",{className:"af-flex af-items-center af-justify-between",children:[S(G,{className:"af-h-4 af-w-16"}),S(G,{className:"af-h-4 af-w-14"})]}),S(G,{className:"af-mt-2 af-h-3 af-w-40"}),S(G,{className:"af-mt-2 af-h-3 af-w-24"})]},D))}),S("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:te(we,{children:[S(Se,{children:te(ee,{children:[S(k,{children:"Order"}),S(k,{children:"Date"}),S(k,{children:"Customer"}),S(k,{children:"Items"}),S(k,{className:"af-text-right",children:"Total"}),S(k,{children:"Status"}),S(k,{className:"af-w-8"})]})}),S(Pe,{"aria-hidden":"true",children:[0,1,2,3,4].map(D=>te(ee,{children:[S(_,{children:S(G,{className:"af-h-4 af-w-14"})}),S(_,{children:S(G,{className:"af-h-4 af-w-24"})}),S(_,{children:S(G,{className:"af-h-4 af-w-40"})}),S(_,{children:S(G,{className:"af-h-4 af-w-32"})}),S(_,{children:S(G,{className:"af-ml-auto af-h-4 af-w-16"})}),S(_,{children:S(G,{className:"af-h-5 af-w-16"})}),S(_,{})]},D))})]})}),S("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(x)return te("div",{className:t,children:[Nt,te("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[S("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),S(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>ae(),children:"Try again"})]})]});let Ae=pe!=="all";if(Ne.length===0&&m===0)return te("div",{className:t,children:[(at||Ae)&&Nt,te("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[S(Yi,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),S("p",{className:"af-text-muted-foreground af-text-center",children:at||Ae?"No orders match these filters.":i??te(ao,{children:["No orders yet.",S("br",{}),"Orders will appear here when someone buys from your website."]})}),!at&&!Ae&&S(h,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>ie(!0),children:"Show abandoned checkouts"})]})]});let We=m*o+1,Ba=Math.min((m+1)*o,n);return te("div",{className:t,children:[Nt,S("div",{className:"af-space-y-3 lg:af-hidden",children:Ne.map(D=>te("button",{type:"button",onClick:()=>Ze(D),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[te("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[S("span",{className:"af-font-medium",children:fa(D)}),S("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:M(At(D),D.currency)})]}),te("div",{className:"af-mt-1 af-min-w-0",children:[te("div",{className:"af-truncate af-text-sm",children:[D.customer_email||S("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),fs(D)&&te("span",{className:"af-text-muted-foreground",children:[" \xB7 ",fs(D)]})]}),S("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Er(D)}),D.amount_refunded>0&&te("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",M(D.amount_refunded,D.currency)," refunded"]})]}),te("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[S(ha,{status:D.status}),D.is_test&&S(V,{variant:"outline",children:"Test"}),r&&S(ka,{order:D}),S("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Dr(D.created_at)})]})]},D.id))}),S("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:te(we,{children:[S(Se,{children:te(ee,{children:[S(k,{children:"Order"}),S(k,{children:"Date"}),S(k,{children:"Customer"}),S(k,{children:"Items"}),S(k,{className:"af-text-right",children:"Total"}),S(k,{children:"Status"}),S(k,{className:"af-w-8"})]})}),S(Pe,{children:Ne.map(D=>te(ee,{onClick:()=>Ze(D),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[te(_,{className:"af-whitespace-nowrap af-font-medium",children:[S("button",{type:"button",onClick:ft=>{ft.stopPropagation(),Ze(D)},"aria-label":`Open order ${fa(D)}`,className:"af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:fa(D)}),D.is_test&&S(V,{variant:"outline",className:"af-ml-2",children:"Test"})]}),S(_,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Dr(D.created_at)}),te(_,{className:"af-max-w-[220px]",children:[S("div",{className:"af-truncate",children:D.customer_email||S("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),fs(D)&&S("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:fs(D)})]}),S(_,{className:"af-max-w-[220px]",children:S("div",{className:"af-truncate af-text-muted-foreground",children:Er(D)})}),te(_,{className:"af-whitespace-nowrap af-text-right",children:[S("div",{className:"af-font-medium af-tabular-nums",children:M(At(D),D.currency)}),D.amount_refunded>0&&te("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",M(D.amount_refunded,D.currency)," ","refunded"]})]}),S(_,{children:te("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[S(ha,{status:D.status}),r&&S(ka,{order:D})]})}),S(_,{className:"af-w-8 af-text-right",children:S(kr,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},D.id))})]})}),te("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[te("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[S("span",{children:K?`${Ne.length} matching this page`:`Showing ${We}-${Ba} of ${n}`}),te(wt,{value:String(o),onValueChange:D=>R(Number(D)),children:[S(mt,{className:"af-w-[70px] af-h-8",children:S(St,{})}),te(pt,{children:[S(Re,{value:"10",children:"10"}),S(Re,{value:"25",children:"25"}),S(Re,{value:"50",children:"50"}),S(Re,{value:"100",children:"100"})]})]}),S("span",{children:"per page"})]}),te("div",{className:"af-flex af-items-center af-gap-2",children:[te(h,{variant:"outline",size:"sm",onClick:()=>N(m-1),disabled:!b,children:[S(Zi,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),te(h,{variant:"outline",size:"sm",onClick:()=>N(m+1),disabled:!u,children:["Next",S(kr,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as us from"react";import{ChevronLeft as io,ChevronRight as oo,Eye as lo,Search as fo,Users as co}from"lucide-react";import*as dt from"react";function cs({initialPageSize:e=25}={}){let{api:t}=Y(),[s,a]=dt.useState([]),[r,i]=dt.useState(0),[l,p]=dt.useState(!0),[c,d]=dt.useState(null),[n,g]=dt.useState(0),[x,m]=dt.useState(e),[o,u]=dt.useState(""),b=dt.useRef(0),N=dt.useCallback(async()=>{let A=++b.current;try{p(!0),d(null);let j={limit:x,offset:n*x};o.trim()&&(j.email=o.trim());let C=await t.getCustomers(j);if(A!==b.current)return;a(C.customers),i(C.total)}catch(j){if(A!==b.current)return;d(j instanceof Error?j:new Error("Failed to fetch customers"))}finally{A===b.current&&p(!1)}},[t,n,x,o]);dt.useEffect(()=>{N()},[N]);let R=Math.ceil(r/x);return{customers:s,total:r,isLoading:l,error:c,page:n,pageSize:x,hasNextPage:n<R-1,hasPreviousPage:n>0,setPage:g,setPageSize:A=>{m(A),g(0)},email:o,setEmail:A=>{u(A),g(0)},refetch:N}}import*as Sa from"react";import{ArrowLeft as so,Loader2 as ro}from"lucide-react";import{jsx as ve,jsxs as et}from"react/jsx-runtime";function Or(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function no(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&t.push(s),e.country&&t.push(e.country),t}function ds({customer:e,onBack:t,className:s}){let{api:a}=Y(),[r,i]=Sa.useState(null),[l,p]=Sa.useState([]),[c,d]=Sa.useState(!0),[n,g]=Sa.useState(null);Sa.useEffect(()=>{let o=!1;return d(!0),g(null),Promise.all([a.getCustomer(e.id),a.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([u,b])=>{o||(i(u),p(b.orders))}).catch(u=>{o||g(u instanceof Error?u.message:"Failed to load customer")}).finally(()=>{o||d(!1)}),()=>{o=!0}},[a,e.id,e.email]);let x=r?.addresses??[],m=r?.order_count??l.length;return et("div",{className:s,children:[et("div",{className:"af-mb-6",children:[et(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[ve(so,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),ve("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),et("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Or(e.created_at)]})]}),c?ve("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:ve(ro,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):n?ve("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:n}):et("div",{className:"af-space-y-6",children:[et("div",{children:[ve("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),et("div",{className:"af-space-y-1 af-text-sm",children:[et("div",{className:"af-flex af-gap-2",children:[ve("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),ve("span",{children:e.email})]}),e.name&&et("div",{className:"af-flex af-gap-2",children:[ve("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),ve("span",{children:e.name})]}),e.phone&&et("div",{className:"af-flex af-gap-2",children:[ve("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),ve("span",{children:e.phone})]}),et("div",{className:"af-flex af-gap-2",children:[ve("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),ve("span",{children:m})]})]})]}),x.length>0&&et("div",{children:[ve("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),ve("div",{className:"af-flex af-flex-wrap af-gap-3",children:x.map(o=>et("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[o.is_default&&ve(V,{variant:"secondary",className:"af-mb-1",children:"Default"}),no(o).map((u,b)=>ve("div",{children:u},b))]},o.id))})]}),et("div",{children:[ve("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),l.length===0?ve("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):et(we,{children:[ve(Se,{children:et(ee,{children:[ve(k,{children:"Date"}),ve(k,{children:"Amount"}),ve(k,{children:"Status"})]})}),ve(Pe,{children:l.map(o=>et(ee,{children:[ve(_,{className:"af-text-muted-foreground",children:Or(o.created_at)}),ve(_,{children:M(At(o),o.currency)}),ve(_,{children:ve(xa,{status:o.status})})]},o.id))})]})]})]})]})}import{Fragment as mo,jsx as fe,jsxs as ze}from"react/jsx-runtime";function uo(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function ms({className:e}){let{customers:t,total:s,isLoading:a,error:r,page:i,pageSize:l,hasNextPage:p,hasPreviousPage:c,setPage:d,setPageSize:n,email:g,setEmail:x,refetch:m}=cs(),[o,u]=us.useState("list"),[b,N]=us.useState(null),[R,A]=us.useState(""),j=$=>{N($),u("detail")},C=()=>{u("list"),N(null),m()};if(o==="detail"&&b)return fe("div",{className:e,children:fe(ds,{customer:b,onBack:C})});let U=ze("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[fe(re,{type:"email",value:R,onChange:$=>A($.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),x(R.trim()))}}),ze(h,{type:"button",variant:"outline",size:"sm",onClick:()=>x(R.trim()),children:[fe(fo,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),g&&fe(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>{A(""),x("")},children:"Clear"})]});if(a)return ze("div",{className:e,children:[U,fe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:fe("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(r)return ze("div",{className:e,children:[U,fe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:ze("div",{className:"af-text-destructive",children:["Error: ",r.message]})})]});if(t.length===0&&i===0)return ze("div",{className:e,children:[g&&U,ze("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[fe(co,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),fe("p",{className:"af-text-muted-foreground af-text-center",children:g?"No customers match that email.":ze(mo,{children:["No customers yet.",fe("br",{}),"Customers appear here after their first purchase."]})})]})]});let H=i*l+1,J=Math.min((i+1)*l,s);return ze("div",{className:e,children:[U,ze(we,{children:[fe(Se,{children:ze(ee,{children:[fe(k,{children:"Email"}),fe(k,{children:"Name"}),fe(k,{children:"Customer since"}),fe(k,{className:"af-text-right",children:"Actions"})]})}),fe(Pe,{children:t.map($=>ze(ee,{children:[fe(_,{className:"af-font-medium",children:$.email}),fe(_,{children:$.name||fe("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),fe(_,{className:"af-text-muted-foreground",children:uo($.created_at)}),fe(_,{className:"af-text-right",children:fe(h,{variant:"ghost",size:"icon",onClick:()=>j($),title:"View customer",children:fe(lo,{className:"af-h-4 af-w-4"})})})]},$.id))})]}),ze("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[ze("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[ze("span",{children:["Showing ",H,"-",J," of ",s]}),ze(wt,{value:String(l),onValueChange:$=>n(Number($)),children:[fe(mt,{className:"af-w-[70px] af-h-8",children:fe(St,{})}),ze(pt,{children:[fe(Re,{value:"10",children:"10"}),fe(Re,{value:"25",children:"25"}),fe(Re,{value:"50",children:"50"}),fe(Re,{value:"100",children:"100"})]})]}),fe("span",{children:"per page"})]}),ze("div",{className:"af-flex af-items-center af-gap-2",children:[ze(h,{variant:"outline",size:"sm",onClick:()=>d(i-1),disabled:!c,children:[fe(io,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ze(h,{variant:"outline",size:"sm",onClick:()=>d(i+1),disabled:!p,children:["Next",fe(oo,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Br from"react";import{AlertTriangle as Lr,CheckCircle2 as po,CreditCard as Hs,Loader2 as go,RefreshCw as vo}from"lucide-react";import*as Yt from"react";function Da(){let{api:e}=Y(),[t,s]=Yt.useState(null),[a,r]=Yt.useState(!0),[i,l]=Yt.useState(null),p=Yt.useRef(0),c=Yt.useCallback(async()=>{let d=++p.current;try{r(!0),l(null);let n=await e.getPaymentsStatus();if(d!==p.current)return;s(n)}catch(n){if(d!==p.current)return;l(n instanceof Error?n:new Error("Failed to fetch payments status"))}finally{d===p.current&&r(!1)}},[e]);return Yt.useEffect(()=>{c()},[c]),{status:t,isLoading:a,error:i,refetch:c}}import{jsx as _e,jsxs as Ke}from"react/jsx-runtime";function ps({onConnectStripe:e,onUpgradePlan:t,className:s}){let{status:a,isLoading:r,error:i,refetch:l}=Da(),[p,c]=Br.useState(!1),d=async()=>{c(!0);try{await l()}finally{c(!1)}};return r&&!a?_e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:_e("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!a?_e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Ke("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):a.status==="active"?_e("div",{className:s,children:Ke("div",{className:"af-flex af-items-start af-gap-3 af-bg-green-50 af-border af-border-green-200 af-rounded-lg af-p-4",children:[_e(po,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),Ke("div",{children:[_e("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),Ke("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",a.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):Ke("div",{className:`af-space-y-4 ${s||""}`,children:[a.reason==="needs_stripe"&&Ke("div",{className:"af-space-y-3",children:[Ke("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[_e(Hs,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Ke("div",{children:[_e("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),_e("p",{className:"af-text-sm af-text-muted-foreground",children:"It only takes a few minutes. You'll enter your details with Stripe, who handle the payments, and money from sales goes straight to your own bank."})]})]}),e?Ke(h,{onClick:e,children:[_e(Hs,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):_e("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),a.reason==="needs_paid_plan"&&Ke("div",{className:"af-space-y-3",children:[Ke("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[_e(Lr,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Ke("div",{children:[_e("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),_e("p",{className:"af-text-sm af-text-muted-foreground",children:"Your products are saved as drafts. Upgrade to a paid plan to start accepting payments on your site."})]})]}),t?_e(h,{onClick:t,children:"Upgrade plan"}):_e("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),a.reason==="account_disabled"&&Ke("div",{className:"af-space-y-3",children:[Ke("div",{className:"af-flex af-items-start af-gap-3 af-bg-yellow-50 af-border af-border-yellow-200 af-rounded-lg af-p-4",children:[_e(Lr,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),Ke("div",{children:[_e("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?_e("p",{className:"af-text-sm af-text-yellow-800",children:"Your Stripe account can't currently accept charges. Check your Stripe account for outstanding requirements or notifications \u2014 once Stripe re-enables charges, payments resume here automatically."}):_e("p",{className:"af-text-sm af-text-yellow-800",children:"Payments are currently paused for this site. If you think this is a mistake, get in touch with support and we'll look into it with you."})]})]}),Ke("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&Ke(h,{onClick:e,children:[_e(Hs,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),Ke(h,{variant:"outline",onClick:d,disabled:p,children:[p?_e(go,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):_e(vo,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as lt from"react";function $s(e,t,s){return e.map(a=>a.id===t?{...a,...s}:a)}function Ea({includeStats:e=!1,refreshKey:t}={}){let{api:s}=Y(),[a,r]=lt.useState([]),[i,l]=lt.useState(!0),[p,c]=lt.useState(null),d=lt.useRef(0),n=lt.useCallback(async()=>{let b=++d.current;try{l(!0),c(null);let N=await s.getProducts(e?{include:"stats"}:{});if(b!==d.current)return;r(N)}catch(N){if(b!==d.current)return;c(N instanceof Error?N:new Error("Failed to fetch products"))}finally{b===d.current&&l(!1)}},[s,e,t]);lt.useEffect(()=>{n()},[n]);let g=lt.useCallback(async b=>{let N=await s.createProduct(b);return r(R=>[N,...R]),N},[s]),x=lt.useCallback(async(b,N)=>{let R=await s.updateProduct(b,N);return r(A=>$s(A,b,R)),R},[s]),m=lt.useCallback(async b=>{await s.deleteProduct(b),r(N=>N.filter(R=>R.id!==b))},[s]),o=lt.useCallback(async(b,N)=>{let R=await s.attachProductFile(b,N);return r(A=>$s(A,b,R)),R},[s]),u=lt.useCallback(async(b,N)=>{let R=await s.attachProductFileFromUrl(b,N);return r(A=>$s(A,b,R)),R},[s]);return{products:a,isLoading:i,error:p,refetch:n,createProduct:g,updateProduct:x,deleteProduct:m,attachProductFile:o,attachProductFileFromUrl:u}}import{jsx as qe,jsxs as Tt}from"react/jsx-runtime";function Ir({className:e,defaultTab:t="products",onConnectStripe:s,onRefund:a,onUpgradePlan:r}){let[i,l]=gs.useState(t),[p,c]=gs.useState("list"),[d,n]=gs.useState(null),g=Ea(),{status:x,error:m}=Da(),o=x?.currency,u=A=>{n(A),c("edit")},b=()=>{n(null),c("create")},N=()=>{c("list"),n(null)},R=A=>{n(A),c("edit")};return Tt("div",{className:e,children:[Tt("div",{className:"af-mb-6",children:[qe("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),qe("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Tt(ja,{value:i,onValueChange:A=>l(A),children:[Tt(Fa,{className:"af-mb-4",children:[Tt(aa,{value:"products",className:"af-gap-2",children:[qe(yo,{className:"af-h-4 af-w-4"}),"Products"]}),Tt(aa,{value:"orders",className:"af-gap-2",children:[qe(ho,{className:"af-h-4 af-w-4"}),"Orders"]}),Tt(aa,{value:"customers",className:"af-gap-2",children:[qe(No,{className:"af-h-4 af-w-4"}),"Customers"]}),Tt(aa,{value:"setup",className:"af-gap-2",children:[qe(xo,{className:"af-h-4 af-w-4"}),"Setup"]})]}),qe(sa,{value:"products",children:p==="list"?qe(es,{productsState:g,onSelectProduct:u,onCreateProduct:b}):Tt("div",{children:[Tt("div",{className:"af-mb-6",children:[Tt(h,{variant:"ghost",size:"sm",onClick:N,className:"af-mb-2 af--ml-2",children:[qe(bo,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),qe("h3",{className:"af-text-lg af-font-semibold",children:p==="create"?"New Product":d?.name})]}),p==="create"&&!o?qe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:m?Tt("div",{className:"af-text-destructive",children:["Error: ",m.message]}):qe("div",{className:"af-text-muted-foreground",children:"Loading..."})}):qe(as,{productsState:g,product:p==="edit"?d:null,currency:o??"usd",onSaved:R},p==="edit"?d?.id??"edit":"new")]})}),qe(sa,{value:"orders",children:qe(_a,{onRefund:a})}),qe(sa,{value:"customers",children:qe(ms,{})}),qe(sa,{value:"setup",children:qe(ps,{onConnectStripe:s,onUpgradePlan:r})})]})]})}import*as Fr from"react";import*as Xt from"react";function vs({refreshKey:e}={}){let{api:t}=Y(),[s,a]=Xt.useState(null),[r,i]=Xt.useState(!0),[l,p]=Xt.useState(null),c=Xt.useRef(0),d=Xt.useCallback(async()=>{let n=++c.current;try{i(!0),p(null);let g=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(n!==c.current)return;a(g)}catch(g){if(n!==c.current)return;p(g instanceof Error?g:new Error("Failed to fetch summary"))}finally{n===c.current&&i(!1)}},[t,e]);return Xt.useEffect(()=>{d()},[d]),{summary:s,isLoading:r,error:l,refetch:d}}import{Fragment as Ms,jsx as Je,jsxs as zs}from"react/jsx-runtime";function Ar(e,t){if(e.settled.complete)return{headline:M(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:M(s.gross,s.currency),extra:e.totals.slice(1).map(a=>`+ ${M(a.gross,a.currency)} in ${a.currency.toUpperCase()}`)}:{headline:M(0,t),extra:[]}}function Ur({refreshKey:e,initialOrderId:t,isOwner:s=!1,onRefund:a,onBackToWebsite:r,className:i}){let{summary:l,isLoading:p,error:c,refetch:d}=vs({refreshKey:e}),[n,g]=Fr.useState(!1),x=Je("div",{className:"af-mb-6",children:c&&!l?Je(bt,{message:"Couldn't load your revenue summary.",onRetry:()=>d()}):Je("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:p||!l?zs(Ms,{children:[Je(it,{label:"This week",children:Je(G,{className:"af-h-6 af-w-24"})}),Je(it,{label:"Today",children:Je(G,{className:"af-h-6 af-w-24"})}),Je(it,{label:"Needs attention",children:Je(G,{className:"af-h-6 af-w-10"})})]}):Je(Ms,{children:(()=>{let m=Ar(l.revenue.d7,l.currency),o=Ar(l.revenue.today,l.currency);return zs(Ms,{children:[Je(it,{label:"This week",detail:m.extra.length>0?Je("div",{children:m.extra.map(u=>Je("div",{children:u},u))}):void 0,children:m.headline}),Je(it,{label:"Today",detail:o.extra.length>0?Je("div",{children:o.extra.map(u=>Je("div",{children:u},u))}):void 0,children:o.headline}),Je(it,{label:"Needs attention",valueClassName:l.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:l.needs_attention.count===0?"All clear":l.needs_attention.items[0]?.title??void 0,children:l.needs_attention.count})]})})()})})});return zs(Zt,{title:"Orders",onBackToWebsite:r,hideBackButton:n,className:i,children:[x,Je(_a,{refreshKey:e,initialOrderId:t,onDetailOpenChange:g,showFulfillment:!0,onRefund:s?a:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as ca from"react";import{ImageOff as Co,Package as To,Search as ko}from"lucide-react";import*as ea from"react";import{ArrowLeft as Po,ImageOff as Ro}from"lucide-react";import{jsx as Ut,jsxs as $a}from"react/jsx-runtime";var Vr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ya="af-text-xs af-text-muted-foreground",bs="af-text-sm af-font-medium af-tabular-nums",wo=3;function So(e){let t=e.pricing,s=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let c=e.min_amount??t?.min_amount??null,d=e.max_amount??t?.max_amount??null;return c!==null&&d!==null?{text:`Buyer chooses (${M(c,s)} \u2013 ${M(d,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let r=t?.min_amount??e.unit_amount,i=t?.max_amount??e.unit_amount;if(r===null||i===null)return{text:"Varies by variant",compareAt:null};let l=r===i?M(r,s):`${M(r,s)} \u2013 ${M(i,s)}`,p=t?.compare_at_amount??null;return{text:l,compareAt:p!==null&&p>i?M(p,s):null}}function ys({product:e,className:t}){let s=So(e);return $a("div",{className:t,children:[Ut("span",{className:bs,children:s.text}),s.compareAt&&Ut("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function hs({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?Ut(V,{variant:"destructive",children:"Out of stock"}):t.low_stock?$a(V,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?Ut(V,{variant:"secondary",children:"Backorder"}):t.available===null?null:$a(V,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?Ut(V,{variant:"warning",children:"Low stock"}):null}function xs(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Ns(e){return e.map(t=>M(t.amount,t.currency)).join(" + ")}function Hr(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${M(e.min_amount,e.currency)} \u2013 ${M(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":M(e.unit_amount,e.currency)}function $r({variant:e}){let t=e.inventory;if(!t||!t.tracked)return Ut("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=t.available??0;return t.allow_backorder?$a("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Ut("span",{className:"af-tabular-nums",children:Math.max(0,s)}),Ut(V,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?Ut(V,{variant:"destructive",children:"Out of stock"}):$a("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Ut("span",{className:"af-tabular-nums",children:s}),s<=wo&&Ut(V,{variant:"warning",children:"Low"})]})}import{jsx as q,jsxs as ke}from"react/jsx-runtime";function Ma({title:e,children:t,className:s}){return ke("section",{className:F("af-rounded-lg af-border af-p-4",s),children:[q("h4",{className:Vr,children:e}),q("div",{className:"af-mt-3",children:t})]})}function Mr({src:e,className:t}){let[s,a]=ea.useState(!1);return ea.useEffect(()=>a(!1),[e]),!e||s?q("div",{"aria-hidden":"true",className:F("af-flex af-items-center af-justify-center af-bg-muted",t),children:q(Ro,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):q("img",{src:e,alt:"",loading:"lazy",onError:()=>a(!0),className:F("af-object-cover",t)})}function zr({product:e,showStats:t=!1,onBack:s}){let{api:a}=Y(),[r,i]=ea.useState(null),[l,p]=ea.useState(!0),[c,d]=ea.useState(null),[n,g]=ea.useState(0),[x,m]=ea.useState(0);ea.useEffect(()=>{let C=!1;return p(!0),d(null),a.getProduct(e.id).then(U=>{C||i(U)}).catch(U=>{C||d(U instanceof Error?U:new Error("Failed to load product"))}).finally(()=>{C||p(!1)}),()=>{C=!0}},[a,e.id,n]);let o=r?{...e,...r}:e,u=o.images.length>0?o.images:e.images,b=u[x]??u[0],N=xs(o),R=t?o.stats:void 0,A=r?.variants??[],j=A.length>1;return ke("div",{children:[ke("div",{className:"af-mb-6",children:[ke(h,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[q(Po,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),ke("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[q("h3",{className:"af-text-xl af-font-semibold af-break-words",children:o.name}),q(V,{variant:o.active?"success":"secondary",children:o.active?"Active":"Draft"}),q(hs,{product:o})]}),q(ys,{product:o,className:"af-mt-1"}),!o.active&&q("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),ke("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[ke("div",{className:"af-space-y-2",children:[q(Mr,{src:b,className:"af-h-48 af-w-full af-rounded-md af-border"}),u.length>1&&q("div",{className:"af-flex af-flex-wrap af-gap-2",children:u.map((C,U)=>q("button",{type:"button",onClick:()=>m(U),"aria-label":`Show photo ${U+1} of ${u.length}`,"aria-pressed":U===x,className:F("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",U===x?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:q(Mr,{src:C,className:"af-h-12 af-w-12 af-rounded-md"})},`${C}-${U}`))})]}),ke("div",{className:"af-space-y-6",children:[o.description&&q(Ma,{title:"Description",children:q("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:o.description})}),l?ke(Ma,{title:"Variants",children:[q("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(C=>ke("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[q(G,{className:"af-h-4 af-w-28"}),q(G,{className:"af-h-4 af-w-20"}),q(G,{className:"af-h-4 af-w-16"})]},C))}),q("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):c?q(bt,{message:"Couldn't load this product's variants.",onRetry:()=>g(C=>C+1)}):j?q(Ma,{title:`Variants \xB7 ${A.length}`,children:q("div",{className:"af-overflow-x-auto",children:ke(we,{children:[q(Se,{children:ke(ee,{children:[q(k,{children:"Variant"}),q(k,{children:"SKU"}),q(k,{className:"af-text-right",children:"Price"}),q(k,{children:"Stock"})]})}),q(Pe,{children:A.map(C=>ke(ee,{children:[ke(_,{className:"af-font-medium",children:[C.title||C.option_values.map(U=>U.value).join(" / ")||"\u2014",!C.active&&q(V,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),q(_,{className:"af-text-muted-foreground",children:C.sku?q("code",{className:"af-font-mono af-text-xs af-break-all",children:C.sku}):"\u2014"}),ke(_,{className:"af-whitespace-nowrap af-text-right",children:[q("div",{className:bs,children:Hr(C)}),C.compare_at_amount!==null&&C.unit_amount!==null&&C.compare_at_amount>C.unit_amount&&q("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:M(C.compare_at_amount,C.currency)})]}),q(_,{className:"af-text-sm",children:q($r,{variant:C})})]},C.id))})]})})}):null,q(Ma,{title:"Details",children:ke("dl",{className:"af-space-y-2",children:[ke("div",{children:[q("dt",{className:ya,children:"Delivery"}),q("dd",{className:"af-text-sm",children:N==="Digital download"?o.fulfillment.filename??"Digital download":N??"Nothing to deliver"})]}),o.fulfillment.type==="redirect"&&o.fulfillment.url&&ke("div",{children:[q("dt",{className:ya,children:"Sends buyers to"}),q("dd",{className:"af-break-all af-text-sm",children:o.fulfillment.url})]}),ke("div",{children:[q("dt",{className:ya,children:"Shipping address"}),q("dd",{className:"af-text-sm",children:o.collect_shipping_address?"Collected at checkout":"Not collected"})]}),ke("div",{children:[q("dt",{className:ya,children:"Most one buyer can order"}),q("dd",{className:"af-text-sm af-tabular-nums",children:o.max_quantity})]})]})}),R&&q(Ma,{title:"Last 30 days",children:ke("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[ke("div",{children:[q("dt",{className:ya,children:"Units sold"}),q("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:R.units_sold})]}),ke("div",{children:[q("dt",{className:ya,children:"Orders"}),q("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:R.orders})]}),ke("div",{children:[q("dt",{className:ya,children:"Gross"}),q("dd",{className:bs,children:R.gross.length>0?Ns(R.gross):"\u2014"})]})]})}),q("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}import{Fragment as Oa,jsx as W,jsxs as De}from"react/jsx-runtime";var _o={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Do=["all","active","draft","low_stock","out_of_stock"];function jr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t).getTime();return Number.isNaN(s)?0:s}function qr(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Eo(e){return e.inventory?.out_of_stock??!1}function Oo(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return qr(e);case"out_of_stock":return Eo(e);default:return!0}}function Lo({product:e,showStats:t,onOpen:s}){let a=e.images[0],r=t?e.stats:void 0,i=xs(e),l=e.variant_count??0;return De("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[a?W("img",{src:a,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):W("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:W(Co,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),De("div",{className:"af-space-y-2 af-p-3",children:[De("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[De("div",{className:"af-min-w-0",children:[W("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),W(ys,{product:e,className:"af-mt-0.5"})]}),!e.active&&W(V,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),De("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[W(hs,{product:e}),l>1&&De(V,{variant:"outline",children:[l," variants"]}),i&&W(V,{variant:"outline",children:i})]}),r&&De("div",{className:"af-text-xs af-text-muted-foreground",children:[r.units_sold," sold",r.gross.length>0?` \xB7 ${Ns(r.gross)}`:""," ",W("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Bo(){return W("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:[0,1,2,3,4,5].map(e=>De("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[W("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),De("div",{className:"af-space-y-2 af-p-3",children:[W(G,{className:"af-w-32"}),W(G,{className:"af-w-16"}),W(G,{className:"af-h-5 af-w-24"})]})]},e))})}function Wr({refreshKey:e,showStats:t=!1,onBackToWebsite:s,className:a}){let{products:r,isLoading:i,error:l,refetch:p}=Ea({includeStats:t,refreshKey:e}),[c,d]=ca.useState(null),[n,g]=ca.useState("all"),[x,m]=ca.useState(""),[o,u]=ca.useState("newest"),b=ca.useMemo(()=>{if(!t)return null;let O=null;for(let ie of r)!ie.stats||ie.stats.units_sold===0||(!O||ie.stats.units_sold>(O.stats?.units_sold??0))&&(O=ie);return O},[r,t]),N=ca.useMemo(()=>r.filter(qr).length,[r]),R=x.trim().toLowerCase(),A=ca.useMemo(()=>{let ie=[...r.filter(y=>Oo(y,n)&&(!R||y.name.toLowerCase().includes(R)))];return o==="name"?ie.sort((y,ae)=>y.name.localeCompare(ae.name)):o==="best_selling"?ie.sort((y,ae)=>(ae.stats?.units_sold??0)-(y.stats?.units_sold??0)):ie.sort((y,ae)=>jr(ae.created_at)-jr(y.created_at)),ie},[r,n,R,o]),j=n!=="all"||!!R,C=()=>{g("all"),m("")},U=i||l!==null&&r.length===0,H=W("div",{className:"af-mb-6",children:W("div",{className:F("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:U?De(Oa,{children:[W(it,{label:"Products",children:W(G,{className:"af-h-6 af-w-10"})}),t?De(Oa,{children:[W(it,{label:"Best seller",children:W(G,{className:"af-h-6 af-w-28"})}),W(it,{label:"Low stock",children:W(G,{className:"af-h-6 af-w-10"})})]}):W(it,{label:"Active",children:W(G,{className:"af-h-6 af-w-10"})})]}):De(Oa,{children:[W(it,{label:"Products",children:r.length}),t?De(Oa,{children:[W(it,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:b?`${b.stats?.units_sold??0} sold, last 30 days`:void 0,children:b?W("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:b.name}):W("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),W(it,{label:"Low stock",children:N})]}):W(it,{label:"Active",children:r.filter(O=>O.active).length})]})})}),J=De("div",{className:"af-mb-4 af-space-y-3",children:[De("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[W("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Do.map(O=>W("button",{type:"button","aria-pressed":n===O,onClick:()=>g(O),className:F("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",n===O?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:_o[O]},O))}),De("div",{className:"af-relative af-w-full af-max-w-xs",children:[W(ko,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),W(re,{type:"text",value:x,onChange:O=>m(O.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),De(wt,{value:o,onValueChange:O=>u(O),children:[W(mt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:W(St,{})}),De(pt,{children:[W(Re,{value:"newest",children:"Newest"}),W(Re,{value:"name",children:"Name A\u2013Z"}),t&&W(Re,{value:"best_selling",children:"Best selling"})]})]}),j&&W(h,{type:"button",variant:"ghost",size:"sm",onClick:C,children:"Clear filters"})]}),i&&r.length===0?W(G,{className:"af-h-4 af-w-28"}):W("p",{className:"af-text-sm af-text-muted-foreground",children:j?`${A.length} of ${r.length} products`:`${r.length} ${r.length===1?"product":"products"}${N>0?` \xB7 ${N} low stock`:""}`})]}),$;return c?$=W(zr,{product:c,showStats:t,onBack:()=>{d(null),p()}},c.id):i&&r.length===0?$=De(Oa,{children:[J,W(Bo,{}),W("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):l&&r.length===0?$=W("div",{className:"af-flex af-justify-center af-py-8",children:W(bt,{message:"Couldn't load your products.",onRetry:()=>p()})}):r.length===0?$=De(Qt,{icon:W(To,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",W("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):$=De(Oa,{children:[J,l&&W("div",{className:"af-mb-4",children:W(bt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>p()})}),A.length===0?De(Qt,{children:["No products match these filters.",W("br",{}),W(h,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:C,children:"Show all products"})]}):W("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:A.map(O=>W(Lo,{product:O,showStats:t,onOpen:()=>d(O)},O.id))})]}),De(Zt,{title:"Products",onBackToWebsite:s,hideBackButton:!!c,className:a,children:[!c&&H,$]})}import*as Vt from"react";import{ArrowLeft as Qr,Check as Io,ChevronLeft as Gr,ChevronRight as Kr,ClipboardCopy as Ao,Mail as qs,Search as Fo,Users as Uo}from"lucide-react";import*as yt from"react";function ws({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=Y(),[a,r]=yt.useState([]),[i,l]=yt.useState(!0),[p,c]=yt.useState(null),[d,n]=yt.useState(0),[g]=yt.useState(e),[x,m]=yt.useState(""),o=yt.useRef(0),u=yt.useCallback(async()=>{let b=++o.current;try{l(!0),c(null);let N={limit:g,offset:d*g};x.trim()&&(N.q=x.trim());let R=await s.getPeople(N);if(b!==o.current)return;r(R.people)}catch(N){if(b!==o.current)return;c(N instanceof Error?N:new Error("Failed to fetch people"))}finally{b===o.current&&l(!1)}},[s,d,g,x,t]);return yt.useEffect(()=>{u()},[u]),{people:a,isLoading:i,error:p,page:d,pageSize:g,hasNextPage:a.length===g,hasPreviousPage:d>0,setPage:n,q:x,setQ:b=>{m(b),n(0)},refetch:u}}import*as ta from"react";function Ss(e,{refreshKey:t}={}){let{api:s}=Y(),[a,r]=ta.useState(null),[i,l]=ta.useState(e!==null),[p,c]=ta.useState(null),d=ta.useRef(0),n=ta.useCallback(async()=>{if(e===null){r(null),l(!1),c(null);return}let g=++d.current;try{l(!0),c(null);let x=await s.getPerson(e);if(g!==d.current)return;r(x)}catch(x){if(g!==d.current)return;c(x instanceof Error?x:new Error("Failed to fetch person"))}finally{g===d.current&&l(!1)}},[s,e,t]);return ta.useEffect(()=>{n()},[n]),{person:a,isLoading:i,error:p,refetch:n}}import{jsx as f,jsxs as z}from"react/jsx-runtime";var js="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Vo="af-text-xs af-text-muted-foreground";function La(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Ws(e,t){let s=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function Ho(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function $o({value:e,label:t}){let[s,a]=Vt.useState(!1);return Ho()?z(h,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),a(!0),setTimeout(()=>a(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[s?f(Io,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):f(Ao,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function Jr(e){return z("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&z(V,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&f(V,{variant:"secondary",children:"Contact form"})]})}function Zr(e){return e.name?e.name:e.email?e.email:f("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Mo=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,zo=40;function jo(e){let t=Object.entries(e).filter(([r])=>!r.startsWith("_")),a=t.find(([r,i])=>Mo.test(r)&&typeof i=="string"&&i.trim())??t.filter(([,r])=>typeof r=="string"&&r.trim().length>=zo).sort((r,i)=>String(i[1]).trim().length-String(r[1]).trim().length)[0];return a?{message:String(a[1]),rest:t.filter(([r])=>r!==a[0])}:{message:null,rest:t}}function qo(e){return e.replace(/_/g," ")}function Wo(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Go({data:e}){let{message:t,rest:s}=jo(e);return t===null&&s.length===0?f("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):z("div",{className:"af-space-y-3",children:[t!==null&&f("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),s.length>0&&f("dl",{className:"af-space-y-1",children:s.map(([a,r])=>z("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[f("dt",{className:F(Vo,"af-w-28 af-shrink-0 af-capitalize"),children:qo(a)}),f("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Wo(r)})]},a))})]})}function Yr({formName:e,createdAt:t,data:s}){return z("div",{className:"af-rounded-md af-border af-p-3",children:[z("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[f(V,{variant:"outline",children:"Form submission (unverified)"}),e&&f("span",{className:"af-text-xs af-text-muted-foreground",children:e}),f("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:La(t)})]}),f(Go,{data:s})]})}function Ko(e){return e.charged_total??e.amount_total}function Jo({email:e,refreshKey:t,onBack:s}){let{person:a,isLoading:r,error:i,refetch:l}=Ss(e,{refreshKey:t}),p=Ws(e,a?.submissions[0]?.form_name);return z("div",{children:[z("div",{className:"af-mb-6",children:[z(h,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[f(Qr,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),z("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[z("div",{className:"af-min-w-0",children:[r?f(G,{className:"af-h-7 af-w-48"}):f("h3",{className:"af-text-xl af-font-semibold af-break-all",children:a?.name||e}),z("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[f("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),f($o,{value:e,label:"Copy email address"})]})]}),f(h,{asChild:!0,children:z("a",{href:p,children:[f(qs,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),r?z("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(c=>z("div",{className:"af-rounded-md af-border af-p-3",children:[f(G,{className:"af-w-40"}),f(G,{className:"af-mt-2 af-w-64"})]},c)),f("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!a?f("div",{className:"af-flex af-justify-center af-py-8",children:f(bt,{message:"Couldn't load this person.",onRetry:()=>l()})}):z("div",{className:"af-space-y-6",children:[a.customer&&z("div",{children:[f("h4",{className:F(js,"af-mb-3"),children:"Customer"}),z("dl",{className:"af-space-y-1 af-text-sm",children:[a.customer.name&&z("div",{className:"af-flex af-gap-2",children:[f("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),f("dd",{children:a.customer.name})]}),a.customer.phone&&z("div",{className:"af-flex af-gap-2",children:[f("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),f("dd",{children:a.customer.phone})]}),z("div",{className:"af-flex af-gap-2",children:[f("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),f("dd",{children:La(a.customer.created_at)})]})]})]}),a.orders.length>0&&z("div",{children:[f("h4",{className:F(js,"af-mb-3"),children:"Purchases"}),f("div",{className:"af-overflow-x-auto",children:z(we,{children:[f(Se,{children:z(ee,{children:[f(k,{children:"Order"}),f(k,{children:"Date"}),f(k,{className:"af-text-right",children:"Total"}),f(k,{children:"Status"})]})}),f(Pe,{children:a.orders.map(c=>z(ee,{children:[f(_,{className:"af-whitespace-nowrap af-font-medium",children:fa(c)}),f(_,{className:"af-whitespace-nowrap af-text-muted-foreground",children:La(c.created_at)}),f(_,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:M(Ko(c),c.currency)}),f(_,{children:f(xa,{status:c.status})})]},c.id))})]})}),f("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),a.submissions.length>0&&z("div",{children:[f("h4",{className:F(js,"af-mb-3"),children:"Messages"}),f("div",{className:"af-space-y-3",children:a.submissions.map(c=>f(Yr,{formName:c.form_name,createdAt:c.created_at,data:c.data},c.id))})]})]})]})}function Zo({submissionId:e,onBack:t}){let{api:s}=Y(),[a,r]=Vt.useState(null),[i,l]=Vt.useState(!0),[p,c]=Vt.useState(null),[d,n]=Vt.useState(0);return Vt.useEffect(()=>{let g=!1;return l(!0),c(null),s.getSubmission(e).then(x=>{g||r(x)}).catch(x=>{g||c(x instanceof Error?x:new Error("Failed to load submission"))}).finally(()=>{g||l(!1)}),()=>{g=!0}},[s,e,d]),z("div",{children:[z("div",{className:"af-mb-6",children:[z(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[f(Qr,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),f("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?f(G,{className:"af-mt-1 af-h-4 af-w-32"}):a&&f("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:La(a.metadata.submitted_at)})]}),i?z("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[f(G,{className:"af-w-40"}),f(G,{className:"af-mt-2 af-w-64"}),f(G,{className:"af-mt-2 af-w-52"}),f("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):p||!a?f("div",{className:"af-flex af-justify-center af-py-8",children:f(bt,{message:"Couldn't load this submission.",onRetry:()=>n(g=>g+1)})}):z("div",{className:"af-space-y-3",children:[f(Yr,{formName:null,createdAt:a.metadata.submitted_at,data:a.data}),f("p",{className:"af-text-xs af-text-muted-foreground",children:"No email address came with this submission, so there is nobody to reply to."})]})]})}var Qo={all:"All",customers:"Customers",leads:"Leads"},Yo=["all","customers","leads"];function Xo(e,t){return t==="customers"?e.sources.includes("customer"):t==="leads"?e.sources.includes("lead"):!0}function Xr({refreshKey:e,onBackToWebsite:t,className:s}){let{people:a,isLoading:r,error:i,page:l,pageSize:p,hasNextPage:c,hasPreviousPage:d,setPage:n,q:g,setQ:x,refetch:m}=ws({refreshKey:e}),[o,u]=Vt.useState({kind:"list"}),[b,N]=Vt.useState(""),[R,A]=Vt.useState("all"),j=$=>{$.email?u({kind:"person",email:$.email}):$.submission_id&&u({kind:"submission",submissionId:$.submission_id})},C=()=>{u({kind:"list"}),m()},U=$=>{let O=$.trim();O!==g&&x(O)},H=a.filter($=>Xo($,R)),J;if(o.kind==="person")J=f(Jo,{email:o.email,refreshKey:e,onBack:C});else if(o.kind==="submission")J=f(Zo,{submissionId:o.submissionId,onBack:C});else{let $=z("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[f("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Yo.map(O=>f("button",{type:"button","aria-pressed":R===O,onClick:()=>A(O),className:F("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",R===O?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Qo[O]},O))}),z("div",{className:"af-relative af-w-full af-max-w-xs",children:[f(Fo,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),f(re,{type:"text",value:b,onChange:O=>N(O.target.value),onBlur:()=>U(b),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),U(b))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),g&&f(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>{N(""),x("")},children:"Clear search"})]});if(r)J=z("div",{children:[$,f("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(O=>z("div",{className:"af-rounded-md af-border af-p-3",children:[z("div",{className:"af-flex af-items-center af-justify-between",children:[f(G,{className:"af-h-4 af-w-32"}),f(G,{className:"af-h-4 af-w-16"})]}),f(G,{className:"af-mt-2 af-h-5 af-w-28"}),f(G,{className:"af-mt-2 af-h-3 af-w-56"})]},O))}),f("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:z(we,{children:[f(Se,{children:z(ee,{children:[f(k,{children:"Person"}),f(k,{children:"Came from"}),f(k,{children:"Latest message"}),f(k,{children:"Last activity"}),f(k,{className:"af-w-8"}),f(k,{className:"af-w-8"})]})}),f(Pe,{"aria-hidden":"true",children:[0,1,2,3,4].map(O=>z(ee,{children:[f(_,{children:f(G,{className:"af-h-4 af-w-40"})}),f(_,{children:f(G,{className:"af-h-5 af-w-24"})}),f(_,{children:f(G,{className:"af-h-4 af-w-56"})}),f(_,{children:f(G,{className:"af-h-4 af-w-24"})}),f(_,{}),f(_,{})]},O))})]})}),f("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)J=z("div",{children:[$,f("div",{className:"af-flex af-justify-center af-py-8",children:f(bt,{message:"Couldn't load your leads.",onRetry:()=>m()})})]});else if(H.length===0&&l===0){let O=!!g||R!=="all";J=z("div",{children:[O&&$,O?f(Qt,{children:g?"Nobody matches that search.":R==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):f(Qt,{icon:f(Uo,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Form submissions and customers will show up here."})]})}else if(a.length===0)J=z("div",{children:[$,f(Qt,{children:"No more results."}),f("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:z(h,{variant:"outline",size:"sm",onClick:()=>n(l-1),children:[f(Gr,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let O=l*p+1,ie=l*p+a.length;J=z("div",{children:[$,f("div",{className:"af-space-y-3 lg:af-hidden",children:H.map((y,ae)=>z("div",{onClick:()=>j(y),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[z("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[z("div",{className:"af-min-w-0",children:[f("button",{type:"button",onClick:he=>{he.stopPropagation(),j(y)},"aria-label":`Open ${y.name||y.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Zr(y)}),y.name&&y.email&&f("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:y.email})]}),z("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[f("span",{className:"af-text-xs af-text-muted-foreground",children:La(y.last_activity_at)}),y.email&&f(h,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:f("a",{href:Ws(y.email),onClick:he=>he.stopPropagation(),"aria-label":`Email ${y.email}`,children:f(qs,{className:"af-h-4 af-w-4"})})})]})]}),f("div",{className:"af-mt-2",children:Jr(y)}),y.latest_message_excerpt&&f("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:y.latest_message_excerpt})]},y.email??y.submission_id??ae))}),f("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:z(we,{children:[f(Se,{children:z(ee,{children:[f(k,{children:"Person"}),f(k,{children:"Came from"}),f(k,{children:"Latest message"}),f(k,{children:"Last activity"}),f(k,{className:"af-w-8",children:f("span",{className:"af-sr-only",children:"Reply"})}),f(k,{className:"af-w-8"})]})}),f(Pe,{children:H.map((y,ae)=>z(ee,{onClick:()=>j(y),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[z(_,{className:"af-max-w-[260px] af-font-medium",children:[f("button",{type:"button",onClick:he=>{he.stopPropagation(),j(y)},"aria-label":`Open ${y.name||y.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Zr(y)}),y.name&&y.email&&f("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:y.email})]}),f(_,{children:Jr(y)}),f(_,{className:"af-max-w-[320px]",children:y.latest_message_excerpt?f("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:y.latest_message_excerpt}):f("span",{className:"af-text-muted-foreground",children:"\u2014"})}),f(_,{className:"af-whitespace-nowrap af-text-muted-foreground",children:La(y.last_activity_at)}),f(_,{className:"af-w-8",children:y.email&&f(h,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:f("a",{href:Ws(y.email),onClick:he=>he.stopPropagation(),"aria-label":`Email ${y.email}`,children:f(qs,{className:"af-h-4 af-w-4"})})})}),f(_,{className:"af-w-8 af-text-right",children:f(Kr,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},y.email??y.submission_id??ae))})]})}),z("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[f("span",{className:"af-text-sm af-text-muted-foreground",children:R==="all"?`Showing ${O}-${ie}`:`${H.length} of ${a.length} on this page`}),z("div",{className:"af-flex af-items-center af-gap-2",children:[z(h,{variant:"outline",size:"sm",onClick:()=>n(l-1),disabled:!d,children:[f(Gr,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),z(h,{variant:"outline",size:"sm",onClick:()=>n(l+1),disabled:!c,children:["Next",f(Kr,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return f(Zt,{title:"Leads",onBackToWebsite:t,hideBackButton:o.kind!=="list",className:s,children:J})}import{ChevronLeft as en,ChevronRight as el,Repeat as tl}from"lucide-react";import*as ut from"react";function Ps({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=Y(),[a,r]=ut.useState([]),[i,l]=ut.useState(0),[p,c]=ut.useState(!0),[d,n]=ut.useState(null),[g,x]=ut.useState(0),[m,o]=ut.useState(e),[u,b]=ut.useState(void 0),N=ut.useRef(0),R=ut.useCallback(async()=>{let j=++N.current;try{c(!0),n(null);let C={limit:m,offset:g*m};u&&(C.status=u);let U=await s.getSubscriptions(C);if(j!==N.current)return;r(U.subscriptions),l(U.total)}catch(C){if(j!==N.current)return;n(C instanceof Error?C:new Error("Failed to fetch subscriptions"))}finally{j===N.current&&c(!1)}},[s,g,m,u,t]);ut.useEffect(()=>{R()},[R]);let A=Math.ceil(i/m);return{subscriptions:a,total:i,isLoading:p,error:d,page:g,pageSize:m,hasNextPage:g<A-1,hasPreviousPage:g>0,setPage:x,setPageSize:j=>{o(j),x(0)},status:u,setStatus:j=>{b(j),x(0)},refetch:R}}import{jsx as B,jsxs as Ee}from"react/jsx-runtime";function tn(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function an({sub:e}){return e.status==="canceled"?B(V,{variant:"outline",children:"Canceled"}):e.status==="past_due"?B(V,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?B(V,{variant:"warning",children:"Scheduled to cancel"}):B(V,{variant:"success",children:"Active"}):B(V,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function al(e,t){let s=M(t,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function sn({sub:e}){let t=e.current_amount!==e.plan_amount;return Ee("div",{children:[B("div",{className:"af-font-medium af-tabular-nums",children:al(e,e.current_amount)}),t&&Ee("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",M(e.plan_amount,e.currency)]})]})}function rn(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${tn(e.current_period_end)}`:"Ends at period end":e.current_period_end?tn(e.current_period_end):"\u2014"}function nn({refreshKey:e,onBackToWebsite:t,className:s}){let{subscriptions:a,total:r,isLoading:i,error:l,page:p,pageSize:c,hasNextPage:d,hasPreviousPage:n,setPage:g,refetch:x}=Ps({refreshKey:e}),m;if(i)m=Ee("div",{children:[B("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(o=>Ee("div",{className:"af-rounded-md af-border af-p-3",children:[Ee("div",{className:"af-flex af-items-center af-justify-between",children:[B(G,{className:"af-h-4 af-w-40"}),B(G,{className:"af-h-4 af-w-20"})]}),B(G,{className:"af-mt-2 af-h-3 af-w-32"}),B(G,{className:"af-mt-2 af-h-5 af-w-24"})]},o))}),B("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ee(we,{children:[B(Se,{children:Ee(ee,{children:[B(k,{children:"Subscriber"}),B(k,{children:"Plan"}),B(k,{className:"af-text-right",children:"Amount"}),B(k,{children:"Renews"}),B(k,{children:"Status"})]})}),B(Pe,{"aria-hidden":"true",children:[0,1,2,3,4].map(o=>Ee(ee,{children:[B(_,{children:B(G,{className:"af-h-4 af-w-44"})}),B(_,{children:B(G,{className:"af-h-4 af-w-32"})}),B(_,{className:"af-text-right",children:B(G,{className:"af-ml-auto af-h-4 af-w-24"})}),B(_,{children:B(G,{className:"af-h-4 af-w-24"})}),B(_,{children:B(G,{className:"af-h-5 af-w-20"})})]},o))})]})}),B("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(l)m=B("div",{className:"af-flex af-justify-center af-py-8",children:B(bt,{message:"Couldn't load your subscriptions.",onRetry:()=>x()})});else if(a.length===0&&p===0)m=B(Qt,{icon:B(tl,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(a.length===0)m=Ee("div",{children:[B(Qt,{children:"No more results."}),B("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Ee(h,{variant:"outline",size:"sm",onClick:()=>g(p-1),children:[B(en,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let o=p*c+1,u=p*c+a.length;m=Ee("div",{children:[B("div",{className:"af-space-y-3 lg:af-hidden",children:a.map(b=>Ee("div",{className:"af-rounded-md af-border af-p-3",children:[Ee("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ee("div",{className:"af-min-w-0",children:[B("div",{className:"af-truncate af-text-sm af-font-medium",children:b.customer_email||B("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),B("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:b.plan_title||"Untitled plan"})]}),B("div",{className:"af-shrink-0 af-text-right",children:B(sn,{sub:b})})]}),Ee("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[B(an,{sub:b}),b.is_test&&B(V,{variant:"outline",children:"Test"}),B("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:rn(b)})]})]},b.id))}),B("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ee(we,{children:[B(Se,{children:Ee(ee,{children:[B(k,{children:"Subscriber"}),B(k,{children:"Plan"}),B(k,{className:"af-text-right",children:"Amount"}),B(k,{children:"Renews"}),B(k,{children:"Status"})]})}),B(Pe,{children:a.map(b=>Ee(ee,{children:[B(_,{className:"af-max-w-[240px]",children:B("div",{className:"af-truncate af-font-medium",children:b.customer_email||B("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),B(_,{className:"af-max-w-[220px]",children:B("div",{className:"af-truncate",children:b.plan_title||B("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),B(_,{className:"af-whitespace-nowrap af-text-right",children:B(sn,{sub:b})}),B(_,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rn(b)}),B(_,{children:Ee("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[B(an,{sub:b}),b.is_test&&B(V,{variant:"outline",children:"Test"})]})})]},b.id))})]})}),Ee("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[B("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${o}-${u} of ${r}`}),Ee("div",{className:"af-flex af-items-center af-gap-2",children:[Ee(h,{variant:"outline",size:"sm",onClick:()=>g(p-1),disabled:!n,children:[B(en,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ee(h,{variant:"outline",size:"sm",onClick:()=>g(p+1),disabled:!d,children:["Next",B(el,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return B(Zt,{title:"Subscriptions",onBackToWebsite:t,className:s,children:m})}export{ua as AifeaturesApiError,un as AifeaturesProvider,ds as CustomerDetail,ms as CustomersList,Ya as FormSettings,Ka as FormSubmissions,dr as FormsDashboard,qa as FormsList,Xr as LeadsView,os as OrderDetail,xa as OrderStatusBadge,_a as OrdersList,Ur as OrdersView,Ir as PaymentsDashboard,ps as PaymentsSetup,as as ProductSettings,es as ProductsList,Wr as ProductsView,Ga as SubmissionDetail,nn as SubscriptionsView,ts as VariantsEditor,Zt as ViewShell,Za as WebhookDeliveries,Qa as WebhookSettings,At as chargedTotal,Cs as createApiClient,M as formatPrice,Gt as isZeroDecimalCurrency,Xe as toMajorUnits,Ft as toMinorUnits,Y as useAifeatures,Y as useAifeaturesContext,vs as useBusinessSummary,cs as useCustomers,Ja as useEventDestinations,Ta as useForms,ss as useOrders,Da as usePaymentsStatus,ws as usePeople,Ss as usePerson,Ea as useProducts,Wa as useSubmissions,Ps as useSubscriptions};