@aifeatures/admin-react 0.3.0 → 0.4.0

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 ta from"react";var ea=class extends Error{constructor(a,s,r){super(a);this.status=s;this.details=r;this.name="AifeaturesApiError"}};function cs(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 us(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 m;try{m=await l.json()}catch{}throw new ea(cs(m?.error,l.status),l.status,m)}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(),m=`/api/v1/forms/${s}/submissions${l?`?${l}`:""}`;return a(m)},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,m=i.id??i.name,d=`${t}/api/v1/submissions/${s}/attachments/${encodeURIComponent(m)}`,c=await fetch(d,{headers:{Authorization:`Bearer ${e}`}});if(!c.ok){let w;try{w=await c.json()}catch{}throw new ea(cs(w?.error,c.status),c.status,w)}let n=await c.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 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 m;try{m=await l.json()}catch{}throw new ea(cs(m?.error,l.status),l.status,m)}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 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 Ta,jsxs as jr}from"react/jsx-runtime";var Us=ta.createContext(null);function $r(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 zr({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:r}){let i=ta.useMemo(()=>$r(e),[e]),l=ta.useMemo(()=>us(e,t),[e,t]),m=ta.useMemo(()=>({siteToken:e,apiUrl:t,api:l}),[e,t,l]);return i?Ta("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:jr("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[Ta("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),Ta("p",{className:"af-text-sm af-text-destructive",children:i})]})}):Ta(Us.Provider,{value:m,children:Ta("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:r})})}function Y(){let e=ta.useContext(Us);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as sa from"react";import{ArrowLeft as En,Settings as Dn,Inbox as In}from"lucide-react";import*as Ea from"react";import*as ht from"@radix-ui/react-tabs";import{clsx as qr}from"clsx";import{twMerge as Gr}from"tailwind-merge";function E(...e){return Gr(qr(e))}import{jsx as ms}from"react/jsx-runtime";var Da=ht.Root,ka=Ea.forwardRef(({className:e,...t},a)=>ms(ht.List,{ref:a,className:E("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}));ka.displayName=ht.List.displayName;var Ht=Ea.forwardRef(({className:e,...t},a)=>ms(ht.Trigger,{ref:a,className:E("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}));Ht.displayName=ht.Trigger.displayName;var Mt=Ea.forwardRef(({className:e,...t},a)=>ms(ht.Content,{ref:a,className:E("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}));Mt.displayName=ht.Content.displayName;import*as Vs from"react";import{Slot as Wr}from"@radix-ui/react-slot";import{cva as Kr}from"class-variance-authority";import{jsx as Jr}from"react/jsx-runtime";var Qr=Kr("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=Vs.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...r},i)=>Jr(s?Wr:"button",{className:E(Qr({variant:t,size:a,className:e})),ref:i,...r}));h.displayName="Button";import{Inbox as Hs,Settings as Xr}from"lucide-react";import*as zt from"react";import{jsx as $t}from"react/jsx-runtime";var Re=zt.forwardRef(({className:e,...t},a)=>$t("div",{className:"af-relative af-w-full af-overflow-auto",children:$t("table",{ref:a,className:E("af-w-full af-caption-bottom af-text-sm",e),...t})}));Re.displayName="Table";var Ce=zt.forwardRef(({className:e,...t},a)=>$t("thead",{ref:a,className:E("[&_tr]:af-border-b",e),...t}));Ce.displayName="TableHeader";var Te=zt.forwardRef(({className:e,...t},a)=>$t("tbody",{ref:a,className:E("[&_tr:last-child]:af-border-0",e),...t}));Te.displayName="TableBody";var Zr=zt.forwardRef(({className:e,...t},a)=>$t("tfoot",{ref:a,className:E("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Zr.displayName="TableFooter";var re=zt.forwardRef(({className:e,...t},a)=>$t("tr",{ref:a,className:E("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));re.displayName="TableRow";var L=zt.forwardRef(({className:e,...t},a)=>$t("th",{ref:a,className:E("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}));L.displayName="TableHead";var B=zt.forwardRef(({className:e,...t},a)=>$t("td",{ref:a,className:E("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));B.displayName="TableCell";var Yr=zt.forwardRef(({className:e,...t},a)=>$t("caption",{ref:a,className:E("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Yr.displayName="TableCaption";import*as xt from"react";function ya(){let{api:e}=Y(),[t,a]=xt.useState([]),[s,r]=xt.useState(!0),[i,l]=xt.useState(null),m=xt.useCallback(async()=>{try{r(!0),l(null);let g=await e.getForms();a(g)}catch(g){l(g instanceof Error?g:new Error("Failed to fetch forms"))}finally{r(!1)}},[e]);xt.useEffect(()=>{m()},[m]);let d=xt.useCallback(async g=>{let x=await e.createForm(g);return a(w=>[...w,x]),x},[e]),c=xt.useCallback(async(g,x)=>{let w=await e.updateForm(g,x);return a(b=>b.map(v=>v.id===g?w:v)),w},[e]),n=xt.useCallback(async g=>{await e.deleteForm(g),a(x=>x.filter(w=>w.id!==g))},[e]);return{forms:t,isLoading:s,error:i,refetch:m,createForm:d,updateForm:c,deleteForm:n}}import{jsx as We,jsxs as jt}from"react/jsx-runtime";function Ia({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:r}=ya();return s?We("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:We("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):r?We("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:jt("div",{className:"af-text-destructive",children:["Error: ",r.message]})}):a.length===0?jt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[We(Hs,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),jt("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",We("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):We("div",{className:t,children:jt(Re,{children:[We(Ce,{children:jt(re,{children:[We(L,{children:"Name"}),We(L,{children:"Endpoint"}),We(L,{className:"af-text-right",children:"Actions"})]})}),We(Te,{children:a.map(i=>jt(re,{children:[We(B,{className:"af-font-medium",children:i.name}),We(B,{children:We("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","")})}),We(B,{className:"af-text-right",children:jt("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[jt(h,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[We(Hs,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),jt(h,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[We(Xr,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import*as _a from"react";import{ChevronLeft as pn,ChevronRight as gn,Eye as vn,Inbox as bn,Paperclip as yn}from"lucide-react";import*as aa from"react";import*as ee from"@radix-ui/react-select";import{Check as en,ChevronDown as Ms,ChevronUp as tn}from"lucide-react";import{jsx as et,jsxs as ps}from"react/jsx-runtime";var gt=ee.Root;var vt=ee.Value,lt=aa.forwardRef(({className:e,children:t,...a},s)=>ps(ee.Trigger,{ref:s,className:E("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,et(ee.Icon,{asChild:!0,children:et(Ms,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));lt.displayName=ee.Trigger.displayName;var $s=aa.forwardRef(({className:e,...t},a)=>et(ee.ScrollUpButton,{ref:a,className:E("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:et(tn,{className:"af-h-4 af-w-4"})}));$s.displayName=ee.ScrollUpButton.displayName;var zs=aa.forwardRef(({className:e,...t},a)=>et(ee.ScrollDownButton,{ref:a,className:E("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:et(Ms,{className:"af-h-4 af-w-4"})}));zs.displayName=ee.ScrollDownButton.displayName;var ft=aa.forwardRef(({className:e,children:t,position:a="popper",...s},r)=>et(ee.Portal,{children:ps(ee.Content,{ref:r,className:E("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:[et($s,{}),et(ee.Viewport,{className:E("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}),et(zs,{})]})}));ft.displayName=ee.Content.displayName;var an=aa.forwardRef(({className:e,...t},a)=>et(ee.Label,{ref:a,className:E("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));an.displayName=ee.Label.displayName;var ve=aa.forwardRef(({className:e,children:t,...a},s)=>ps(ee.Item,{ref:s,className:E("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:[et("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:et(ee.ItemIndicator,{children:et(en,{className:"af-h-4 af-w-4"})})}),et(ee.ItemText,{children:t})]}));ve.displayName=ee.Item.displayName;var sn=aa.forwardRef(({className:e,...t},a)=>et(ee.Separator,{ref:a,className:E("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));sn.displayName=ee.Separator.displayName;import*as bt from"react";function Aa({formId:e,initialPageSize:t=25}){let{api:a}=Y(),[s,r]=bt.useState([]),[i,l]=bt.useState(0),[m,d]=bt.useState(!0),[c,n]=bt.useState(null),[g,x]=bt.useState(0),[w,b]=bt.useState(t),v=bt.useCallback(async()=>{if(e)try{d(!0),n(null);let C={limit:w,offset:g*w},I=await a.getSubmissions(e,C);r(I.submissions),l(I.total)}catch(C){n(C instanceof Error?C:new Error("Failed to fetch submissions"))}finally{d(!1)}},[a,e,g,w]);bt.useEffect(()=>{v()},[v]);let N=bt.useCallback(async C=>{await a.deleteSubmission(C),r(I=>I.filter(Q=>Q.id!==C)),l(I=>I-1)},[a]),S=Math.ceil(i/w);return{submissions:s,total:i,isLoading:m,error:c,page:g,pageSize:w,hasNextPage:g<S-1,hasPreviousPage:g>0,setPage:x,setPageSize:C=>{b(C),x(0)},refetch:v,deleteSubmission:N}}import*as qs from"react";import{ArrowLeft as rn,Download as nn,Globe as on,Clock as ln,FileText as fn,Loader2 as dn,Monitor as cn,Mail as un}from"lucide-react";import{jsx as De,jsxs as Le}from"react/jsx-runtime";function js(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function mn(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 Fa({submission:e,onBack:t}){let{api:a}=Y(),[s,r]=qs.useState(null),i=d=>d.id??d.name,l=async d=>{r(i(d));try{await a.downloadAttachment(e.id,d)}catch(c){console.error("Download failed:",c)}finally{r(null)}},m=Object.entries(e.data).filter(([d])=>!d.startsWith("_"));return Le("div",{children:[Le("div",{className:"af-mb-6",children:[Le(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[De(rn,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),De("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),Le("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",js(e.metadata.submitted_at)]})]}),Le("div",{className:"af-space-y-6",children:[Le("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),Le("div",{className:"af-space-y-3",children:[m.map(([d,c])=>Le("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[De("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:d.replace(/_/g," ")}),De("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof c=="string"&&c.includes(`
3
- `)?De("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:c}):String(c)})]},d)),m.length===0&&De("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&Le("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),De("div",{className:"af-space-y-2",children:e.attachments.map((d,c)=>Le("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[Le("div",{className:"af-flex af-items-center af-gap-2",children:[De(fn,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),De("span",{className:"af-text-sm",children:d.name}),Le("span",{className:"af-text-xs af-text-muted-foreground",children:["(",mn(d.size),")"]})]}),Le(h,{variant:"ghost",size:"sm",onClick:()=>l(d),disabled:s===i(d),children:[s===i(d)?De(dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):De(nn,{className:"af-h-4 af-w-4 af-mr-1"}),s===i(d)?"Downloading...":"Download"]})]},c))})]}),Le("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),Le("div",{className:"af-space-y-2 af-text-sm",children:[Le("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[De(ln,{className:"af-h-4 af-w-4"}),De("span",{children:js(e.metadata.submitted_at)})]}),e.metadata.ip_address&&Le("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[De(on,{className:"af-h-4 af-w-4"}),Le("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&Le("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[De(cn,{className:"af-h-4 af-w-4 af-mt-0.5"}),De("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&Le("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[De(un,{className:"af-h-4 af-w-4"}),Le("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as oe,jsxs as Ke}from"react/jsx-runtime";function hn(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function xn(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 Nn(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 Ua({formId:e,className:t,defaultSubmissionId:a}){let{submissions:s,total:r,isLoading:i,error:l,page:m,pageSize:d,hasNextPage:c,hasPreviousPage:n,setPage:g,setPageSize:x}=Aa({formId:e}),[w,b]=_a.useState("list"),[v,N]=_a.useState(null);_a.useEffect(()=>{if(a&&s.length>0){let _=s.find(F=>F.id===a);_&&(N(_),b("detail"))}},[a,s]);let S=_=>{N(_),b("detail")},C=()=>{b("list"),N(null)};if(w==="detail"&&v)return oe("div",{className:t,children:oe(Fa,{submission:v,onBack:C})});if(i)return oe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:oe("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(l)return oe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ke("div",{className:"af-text-destructive",children:["Error: ",l.message]})});if(s.length===0&&m===0)return Ke("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[oe(bn,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ke("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",oe("br",{}),"Submissions will appear here when visitors use your form."]})]});let I=m*d+1,Q=Math.min((m+1)*d,r);return Ke("div",{className:t,children:[Ke(Re,{children:[oe(Ce,{children:Ke(re,{children:[oe(L,{children:"Email"}),oe(L,{children:"Preview"}),oe(L,{children:"Date"}),oe(L,{className:"af-text-right",children:"Actions"})]})}),oe(Te,{children:s.map(_=>{let F=xn(_.data),M=Nn(_.data);return Ke(re,{children:[oe(B,{className:"af-font-medium",children:Ke("div",{className:"af-flex af-items-center af-gap-2",children:[F||oe("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),_.attachments.length>0&&Ke("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${_.attachments.length} attachment(s)`,children:[oe(yn,{className:"af-h-3 af-w-3"}),oe("span",{className:"af-text-xs",children:_.attachments.length})]})]})}),oe(B,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:M||oe("span",{className:"af-italic",children:"No preview available"})}),oe(B,{className:"af-text-muted-foreground",children:hn(_.metadata.submitted_at)}),oe(B,{className:"af-text-right",children:oe(h,{variant:"ghost",size:"icon",onClick:()=>S(_),title:"View details",children:oe(vn,{className:"af-h-4 af-w-4"})})})]},_.id)})})]}),Ke("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Ke("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ke("span",{children:["Showing ",I,"-",Q," of ",r]}),Ke(gt,{value:String(d),onValueChange:_=>x(Number(_)),children:[oe(lt,{className:"af-w-[70px] af-h-8",children:oe(vt,{})}),Ke(ft,{children:[oe(ve,{value:"10",children:"10"}),oe(ve,{value:"25",children:"25"}),oe(ve,{value:"50",children:"50"}),oe(ve,{value:"100",children:"100"})]})]}),oe("span",{children:"per page"})]}),Ke("div",{className:"af-flex af-items-center af-gap-2",children:[Ke(h,{variant:"outline",size:"sm",onClick:()=>g(m-1),disabled:!n,children:[oe(pn,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ke(h,{variant:"outline",size:"sm",onClick:()=>g(m+1),disabled:!c,children:["Next",oe(gn,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as dt from"react";import{Plus as _n,X as On,Loader2 as Ln,Check as Bn}from"lucide-react";import*as Gs from"react";import{jsx as wn}from"react/jsx-runtime";var ne=Gs.forwardRef(({className:e,type:t,...a},s)=>wn("input",{type:t,className:E("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}));ne.displayName="Input";import*as Ws from"react";import{cva as Pn}from"class-variance-authority";import{jsx as Rn}from"react/jsx-runtime";var Sn=Pn("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),te=Ws.forwardRef(({className:e,...t},a)=>Rn("label",{ref:a,className:E(Sn(),e),...t}));te.displayName="Label";import{cva as Cn}from"class-variance-authority";import{jsx as kn}from"react/jsx-runtime";var Tn=Cn("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 G({className:e,variant:t,...a}){return kn("div",{className:E(Tn({variant:t}),e),...a})}import{jsx as ce,jsxs as Nt}from"react/jsx-runtime";function Va({form:e,onSaved:t,className:a}){let{updateForm:s}=ya(),[r,i]=dt.useState(!1),[l,m]=dt.useState(null),[d,c]=dt.useState(null),[n,g]=dt.useState(e.name),[x,w]=dt.useState(e.redirect_url||""),[b,v]=dt.useState(e.email_recipients),[N,S]=dt.useState("");dt.useEffect(()=>{g(e.name),w(e.redirect_url||""),v(e.email_recipients),c(null)},[e]);let C=dt.useCallback(async M=>{try{i(!0),c(null);let K=await s(e.id,M);m(new Date),t?.(K)}catch(K){c(K instanceof Error?K.message:"Failed to save")}finally{i(!1)}},[e.id,s,t]);dt.useEffect(()=>{if(l){let M=setTimeout(()=>m(null),2e3);return()=>clearTimeout(M)}},[l]);let I=async()=>{let M=N.trim().toLowerCase();if(!M)return;if(!M.includes("@")){c("Please enter a valid email address");return}if(b.includes(M)){c("This email is already added");return}let K=[...b,M];v(K),S(""),c(null),await C({email_recipients:K})},Q=async M=>{let K=b.filter($=>$!==M);v(K),await C({email_recipients:K})},_=async()=>{n!==e.name&&await C({name:n})},F=async()=>{let M=x||null;M!==e.redirect_url&&await C({redirect_url:M})};return Nt("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(r||l)&&ce("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:r?Nt("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:[ce(Ln,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),ce("span",{className:"af-text-sm",children:"Saving..."})]}):Nt("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:[ce(Bn,{className:"af-h-4 af-w-4 af-text-green-600"}),ce("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Nt("div",{className:"af-space-y-2",children:[ce(te,{htmlFor:"form-name",children:"Form Name"}),ce(ne,{id:"form-name",value:n,onChange:M=>g(M.target.value),onBlur:_,placeholder:"Contact Form"}),ce("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),Nt("div",{className:"af-space-y-2",children:[ce(te,{children:"Email Recipients"}),ce("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),Nt("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[b.map(M=>Nt(G,{variant:"secondary",className:"af-gap-1",children:[M,ce("button",{type:"button",onClick:()=>Q(M),className:"af-ml-1 hover:af-text-destructive",disabled:r,children:ce(On,{className:"af-h-3 af-w-3"})})]},M)),b.length===0&&ce("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Nt("div",{className:"af-flex af-gap-2",children:[ce(ne,{type:"email",value:N,onChange:M=>S(M.target.value),placeholder:"Add email address",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),I())},disabled:r}),ce(h,{type:"button",variant:"outline",onClick:I,disabled:!N.trim()||r,children:ce(_n,{className:"af-h-4 af-w-4"})})]})]}),Nt("div",{className:"af-space-y-2",children:[ce(te,{htmlFor:"redirect-url",children:"Redirect URL"}),ce(ne,{id:"redirect-url",value:x,onChange:M=>w(M.target.value),onBlur:F,placeholder:"/thank-you"}),ce("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."})]}),Nt("div",{className:"af-space-y-2",children:[ce(te,{children:"Form Endpoint"}),ce("div",{className:"af-flex af-items-center af-gap-2",children:ce("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})}),ce("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),Nt("div",{className:"af-space-y-2",children:[ce(te,{children:"Captcha Protection"}),ce("div",{className:"af-flex af-items-center af-gap-2",children:ce(G,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),ce("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),d&&ce("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})]})}import{jsx as st,jsxs as Bt}from"react/jsx-runtime";function Ks({className:e,submissionId:t}){let{api:a}=Y(),[s,r]=sa.useState("list"),[i,l]=sa.useState(null),[m,d]=sa.useState("submissions"),[c,n]=sa.useState(t),[g,x]=sa.useState(!!t);sa.useEffect(()=>{if(!t)return;async function N(){try{let S=await a.getSubmission(t),C=await a.getForm(S.form_id);l(C),r("detail"),d("submissions"),n(t)}catch(S){console.error("Failed to load submission for deep link:",S)}finally{x(!1)}}N()},[t,a]);let w=(N,S)=>{l(N),r("detail"),d(S),n(void 0)},b=()=>{r("list"),l(null),n(void 0)},v=N=>{l(N)};return g?st("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:st("div",{className:"af-text-muted-foreground",children:"Loading..."})}):Bt("div",{className:e,children:[s==="list"&&Bt("div",{children:[Bt("div",{className:"af-mb-6",children:[st("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),st("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),st(Ia,{onSelectForm:w})]}),s==="detail"&&i&&Bt("div",{children:[Bt("div",{className:"af-mb-6",children:[Bt(h,{variant:"ghost",size:"sm",onClick:b,className:"af-mb-2 af--ml-2",children:[st(En,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),st("h2",{className:"af-text-lg af-font-semibold",children:i.name}),st("p",{className:"af-text-sm af-text-muted-foreground",children:st("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),Bt(Da,{value:m,onValueChange:N=>d(N),children:[Bt(ka,{className:"af-mb-4",children:[Bt(Ht,{value:"submissions",className:"af-gap-2",children:[st(In,{className:"af-h-4 af-w-4"}),"Submissions"]}),Bt(Ht,{value:"settings",className:"af-gap-2",children:[st(Dn,{className:"af-h-4 af-w-4"}),"Settings"]})]}),st(Mt,{value:"submissions",children:st(Ua,{formId:i.id,defaultSubmissionId:c})}),st(Mt,{value:"settings",children:st(Va,{form:i,onSaved:v})})]})]})]})}import*as as from"react";import{ArrowLeft as Mi,Package as $i,Receipt as zi,Settings as ji,Users as qi}from"lucide-react";import*as Ha from"react";import{Package as Vn,Pencil as Hn,Plus as Js,Trash2 as Mn}from"lucide-react";import*as Oa from"react";import*as Ue from"@radix-ui/react-dialog";import{X as An}from"lucide-react";import{jsx as qt,jsxs as gs}from"react/jsx-runtime";var ra=Ue.Root;var Fn=Ue.Portal;var Qs=Oa.forwardRef(({className:e,...t},a)=>qt(Ue.Overlay,{ref:a,className:E("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Qs.displayName=Ue.Overlay.displayName;var Gt=Oa.forwardRef(({className:e,children:t,...a},s)=>qt(Fn,{children:gs("div",{className:"aifeatures-admin",children:[qt(Qs,{}),gs(Ue.Content,{ref:s,className:E("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,gs(Ue.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:[qt(An,{className:"af-h-4 af-w-4"}),qt("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Gt.displayName=Ue.Content.displayName;var Wt=({className:e,...t})=>qt("div",{className:E("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Wt.displayName="DialogHeader";var Kt=({className:e,...t})=>qt("div",{className:E("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Kt.displayName="DialogFooter";var Qt=Oa.forwardRef(({className:e,...t},a)=>qt(Ue.Title,{ref:a,className:E("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Qt.displayName=Ue.Title.displayName;var Jt=Oa.forwardRef(({className:e,...t},a)=>qt(Ue.Description,{ref:a,className:E("af-text-sm af-text-muted-foreground",e),...t}));Jt.displayName=Ue.Description.displayName;var Un=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Et(e){return Un.has(e.toLowerCase())}function U(e,t,a){let s=Et(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function wt(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 Pt(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=Et(t)?a:a*100;return Math.round(s)}function Qe(e,t){return Et(t)?e:e/100}import{jsx as ue,jsxs as tt}from"react/jsx-runtime";function $n(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 zn(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Ma({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:r,isLoading:i,error:l,deleteProduct:m}=e,[d,c]=Ha.useState(null),[n,g]=Ha.useState(!1),[x,w]=Ha.useState(null),b=async()=>{if(d)try{g(!0),w(null),await m(d.id),c(null)}catch(v){w(v instanceof Error?v.message:"Failed to delete product")}finally{g(!1)}};return i?ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ue("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):l?ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:tt("div",{className:"af-text-destructive",children:["Error: ",l.message]})}):r.length===0?tt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[ue(Vn,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),tt("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",ue("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),tt(h,{variant:"outline",onClick:()=>a?.(),children:[ue(Js,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):tt("div",{className:s,children:[ue("div",{className:"af-flex af-justify-end af-mb-4",children:tt(h,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[ue(Js,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),tt(Re,{children:[ue(Ce,{children:tt(re,{children:[ue(L,{children:"Name"}),ue(L,{children:"Price"}),ue(L,{children:"Fulfillment"}),ue(L,{children:"Status"}),ue(L,{className:"af-text-right",children:"Actions"})]})}),ue(Te,{children:r.map(v=>tt(re,{children:[ue(B,{className:"af-font-medium",children:v.name}),ue(B,{children:$n(v)}),ue(B,{className:"af-text-muted-foreground",children:zn(v)}),ue(B,{children:ue(G,{variant:v.active?"success":"secondary",children:v.active?"Active":"Inactive"})}),ue(B,{className:"af-text-right",children:tt("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[tt(h,{variant:"ghost",size:"sm",onClick:()=>t?.(v),children:[ue(Hn,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),tt(h,{variant:"ghost",size:"sm",onClick:()=>{w(null),c(v)},children:[ue(Mn,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},v.id))})]}),ue(ra,{open:!!d,onOpenChange:v=>{!v&&!n&&c(null)},children:tt(Gt,{children:[tt(Wt,{children:[ue(Qt,{children:"Delete product?"}),tt(Jt,{children:['"',d?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),x&&ue("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:x}),tt(Kt,{children:[ue(h,{variant:"outline",onClick:()=>c(null),disabled:n,children:"Cancel"}),ue(h,{variant:"destructive",onClick:b,disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}import*as ye from"react";import{FileText as qn,Link2 as Gn,Loader2 as Xs,Plus as Wn,Upload as Kn,X as Qn}from"lucide-react";import*as Ie from"react";import{Loader2 as Zs,Plus as vs,Trash2 as Ys,X as jn}from"lucide-react";import{jsx as k,jsxs as j}from"react/jsx-runtime";function bs(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function $a({productId:e,currency:t,className:a}){let{api:s}=Y(),r=Et(t)?"1":"0.01",[i,l]=Ie.useState(null),[m,d]=Ie.useState(!0),[c,n]=Ie.useState(null),[g,x]=Ie.useState(null),[w,b]=Ie.useState(!1),v=Ie.useRef(!0);Ie.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);let N=Ie.useCallback(async()=>{try{let p=await s.getProduct(e);if(!v.current)return;l(p)}catch(p){if(!v.current)return;n(p instanceof Error?p.message:"Failed to load product")}finally{v.current&&d(!1)}},[s,e]);Ie.useEffect(()=>{N()},[N]);let S=async p=>{x(null),b(!0);try{await p(),await N()}catch(R){v.current&&x(R instanceof Error?R.message:"Something went wrong")}finally{v.current&&b(!1)}},[C,I]=Ie.useState(""),[Q,_]=Ie.useState(""),[F,M]=Ie.useState({}),K=()=>S(async()=>{let p=C.trim(),R=Q.split(",").map(se=>se.trim()).filter(Boolean);if(!p)throw new Error("Option name is required");if(R.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:p,values:R}),v.current&&(I(""),_(""))}),$=p=>S(async()=>{let R=(F[p.id]??"").trim();if(!R)throw new Error("Enter a value");await s.updateOption(p.id,{add_values:[R]}),v.current&&M(se=>({...se,[p.id]:""}))}),D=(p,R)=>S(()=>s.updateOption(p.id,{remove_values:[R]})),me=p=>S(()=>s.deleteOption(p.id)),[u,X]=Ie.useState(null),[xe,be]=Ie.useState(null),[le,Fe]=Ie.useState(!1),[J,de]=Ie.useState(null),Pe=i?.options??[],qe=i?.variants??[],He=()=>{be(null),X({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(Pe.map(p=>[p.id,p.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Tt=p=>{be(null);let R=p.inventory?.on_hand??0,se=R<0?"":String(R);X({variant:p,title:p.title??"",sku:p.sku??"",unitAmount:p.unit_amount!=null?String(Qe(p.unit_amount,t)):"",compareAt:p.compare_at_amount!=null?String(Qe(p.compare_at_amount,t)):"",active:p.active,optionValues:{},tracked:p.inventory?.tracked??!1,onHand:se,initialOnHand:se,allowBackorder:p.inventory?.allow_backorder??!1})},kt=async()=>{if(!u)return;be(null);let p=u.variant?.allow_custom_amount??!1,R=null,se=null;if(!p){if(R=Pt(u.unitAmount,t),R===null||R<=0){be("Enter a valid price");return}if(u.compareAt.trim()&&(se=Pt(u.compareAt,t),se===null||se<=R)){be("Compare-at price must be greater than the price");return}}let Ze=u.onHand.trim()!==u.initialOnHand.trim(),Ye=parseInt(u.onHand,10);if(u.tracked&&Ze&&(!Number.isFinite(Ye)||Ye<0)){be("On-hand quantity must be zero or more");return}try{if(Fe(!0),u.variant)await s.updateVariant(u.variant.id,{title:u.title.trim()||null,sku:u.sku.trim()||null,...p?{}:{unit_amount:R,compare_at_amount:se},active:u.active}),await s.setVariantInventory(u.variant.id,{tracked:u.tracked,on_hand:u.tracked&&Ze?Ye:void 0,allow_backorder:u.allowBackorder});else{let Xe={};for(let Ge of Pe){let Ot=u.optionValues[Ge.id];if(!Ot){be(`Choose a ${Ge.title}`),Fe(!1);return}Xe[Ge.title]=Ot}await s.createVariant(e,{title:u.title.trim()||null,sku:u.sku.trim()||null,unit_amount:R,compare_at_amount:se,active:u.active,option_values:Pe.length>0?Xe:void 0,inventory:u.tracked?{tracked:!0,on_hand:Ye,allow_backorder:u.allowBackorder}:{tracked:!1,allow_backorder:u.allowBackorder}})}await N(),v.current&&X(null)}catch(Xe){if(v.current&&be(Xe instanceof Error?Xe.message:"Failed to save variant"),u.variant)try{let Ge=await s.getProduct(e);v.current&&l(Ge)}catch{}}finally{v.current&&Fe(!1)}},_e=()=>S(async()=>{J&&(await s.deleteVariant(J.id),v.current&&de(null))}),ut=u?.variant?.allow_custom_amount??!1,mt=u?.variant!=null&&u.variant.option_values.length===0&&Pe.length>0&&!u.variant.active,Ee=u?.variant?.inventory!=null&&u.variant.inventory.on_hand<0?-u.variant.inventory.on_hand:null;function _t(p){let R=p.inventory;if(!R||!R.tracked)return k("span",{className:"af-text-muted-foreground",children:"Unlimited"});let se=R.available??R.on_hand;return se<0?j("span",{children:[-se," backordered"]}):j("span",{children:[se," in stock",R.allow_backorder&&k("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return m?k("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:k(Zs,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):c?k("div",{className:a,children:k("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c})}):j("div",{className:`af-space-y-6 ${a||""}`,children:[j("div",{className:"af-space-y-3",children:[j("div",{children:[k(te,{children:"Options"}),k("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."})]}),Pe.length>0&&k("div",{className:"af-space-y-3",children:Pe.map(p=>j("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[j("div",{className:"af-flex af-items-center af-justify-between",children:[k("span",{className:"af-text-sm af-font-medium",children:p.title}),k(h,{variant:"ghost",size:"sm",onClick:()=>me(p),disabled:w,children:k(Ys,{className:"af-h-4 af-w-4"})})]}),k("div",{className:"af-flex af-flex-wrap af-gap-2",children:p.values.map(R=>j(G,{variant:"secondary",className:"af-gap-1",children:[R.value,k("button",{type:"button",onClick:()=>D(p,R.value),className:"af-ml-1 hover:af-text-destructive",disabled:w,title:"Remove value",children:k(jn,{className:"af-h-3 af-w-3"})})]},R.id))}),j("div",{className:"af-flex af-gap-2",children:[k(ne,{value:F[p.id]??"",onChange:R=>M(se=>({...se,[p.id]:R.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),$(p))},disabled:w}),k(h,{type:"button",variant:"outline",size:"sm",onClick:()=>$(p),disabled:w||!(F[p.id]??"").trim(),children:k(vs,{className:"af-h-4 af-w-4"})})]})]},p.id))}),j("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[j("div",{className:"af-space-y-1",children:[k(te,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),k(ne,{id:"new-option-title",value:C,onChange:p=>I(p.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:w})]}),j("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[k(te,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),k(ne,{id:"new-option-values",value:Q,onChange:p=>_(p.target.value),placeholder:"S, M, L",disabled:w})]}),j(h,{type:"button",variant:"outline",onClick:K,disabled:w||!C.trim()||!Q.trim(),children:[k(vs,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),j("div",{className:"af-space-y-3",children:[j("div",{className:"af-flex af-items-center af-justify-between",children:[k(te,{children:"Variants"}),j(h,{type:"button",variant:"outline",size:"sm",onClick:He,disabled:w||Pe.length===0,children:[k(vs,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),Pe.length===0&&k("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),qe.length===0?k("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):j(Re,{children:[k(Ce,{children:j(re,{children:[k(L,{children:"Variant"}),k(L,{children:"SKU"}),k(L,{children:"Price"}),k(L,{children:"Stock"}),k(L,{children:"Status"}),k(L,{className:"af-text-right",children:"Actions"})]})}),k(Te,{children:qe.map(p=>j(re,{children:[k(B,{className:"af-font-medium",children:bs(p)}),k(B,{className:"af-text-muted-foreground",children:p.sku||"-"}),k(B,{children:p.unit_amount!=null?j("span",{children:[p.compare_at_amount!=null&&k("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:U(p.compare_at_amount,p.currency)}),U(p.unit_amount,p.currency)]}):p.allow_custom_amount?k("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),k(B,{children:_t(p)}),k(B,{children:k(G,{variant:p.active?"success":"secondary",children:p.active?"Active":"Inactive"})}),k(B,{className:"af-text-right",children:j("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[k(h,{variant:"ghost",size:"sm",onClick:()=>Tt(p),disabled:w,children:"Edit"}),k(h,{variant:"ghost",size:"icon",onClick:()=>de(p),disabled:w,title:"Delete variant",children:k(Ys,{className:"af-h-4 af-w-4"})})]})})]},p.id))})]})]}),g&&k("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g}),k(ra,{open:u!==null,onOpenChange:p=>{!p&&!le&&X(null)},children:j(Gt,{children:[j(Wt,{children:[k(Qt,{children:u?.variant?"Edit variant":"Add variant"}),k(Jt,{children:"Price, markdown, and stock live on the variant."})]}),u&&j("div",{className:"af-space-y-3",children:[u.variant?u.variant.option_values.length>0&&j("div",{className:"af-text-sm",children:[k("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),bs(u.variant)]}):Pe.map(p=>j("div",{className:"af-space-y-1",children:[k(te,{className:"af-text-xs af-text-muted-foreground",children:p.title}),j(gt,{value:u.optionValues[p.id]??"",onValueChange:R=>X(se=>se&&{...se,optionValues:{...se.optionValues,[p.id]:R}}),children:[k(lt,{children:k(vt,{placeholder:`Choose ${p.title}`})}),k(ft,{children:p.values.map(R=>k(ve,{value:R.value,children:R.value},R.id))})]})]},p.id)),ut?j("div",{className:"af-space-y-1",children:[k(te,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),k("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):j("div",{className:"af-flex af-gap-3",children:[j("div",{className:"af-space-y-1",children:[j(te,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),k(ne,{id:"variant-price",type:"number",min:"0",step:r,value:u.unitAmount,onChange:p=>X(R=>R&&{...R,unitAmount:p.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),j("div",{className:"af-space-y-1",children:[k(te,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),k(ne,{id:"variant-compare",type:"number",min:"0",step:r,value:u.compareAt,onChange:p=>X(R=>R&&{...R,compareAt:p.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),j("div",{className:"af-space-y-1",children:[k(te,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),k(ne,{id:"variant-sku",value:u.sku,onChange:p=>X(R=>R&&{...R,sku:p.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),j("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[j("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[k("input",{type:"checkbox",checked:u.tracked,onChange:p=>X(R=>R&&{...R,tracked:p.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),u.tracked&&j("div",{className:"af-space-y-1 af-pl-6",children:[j("div",{className:"af-flex af-items-end af-gap-3",children:[j("div",{className:"af-space-y-1",children:[k(te,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),k(ne,{id:"variant-onhand",type:"number",min:"0",step:"1",value:u.onHand,onChange:p=>X(R=>R&&{...R,onHand:p.target.value}),placeholder:Ee!=null?"0":void 0,className:"af-w-[100px]"})]}),j("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[k("input",{type:"checkbox",checked:u.allowBackorder,onChange:p=>X(R=>R&&{...R,allowBackorder:p.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Ee!=null&&j("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Ee," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),j("div",{className:"af-space-y-1",children:[j("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[k("input",{type:"checkbox",checked:u.active,onChange:p=>X(R=>R&&{...R,active:p.target.checked}),className:"af-h-4 af-w-4",disabled:mt}),"Active (buyers can purchase this variant)"]}),mt&&k("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."})]}),xe&&k("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:xe})]}),j(Kt,{children:[k(h,{variant:"outline",onClick:()=>X(null),disabled:le,children:"Cancel"}),j(h,{onClick:kt,disabled:le,children:[le?k(Zs,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,u?.variant?"Save":"Add variant"]})]})]})}),k(ra,{open:J!==null,onOpenChange:p=>{!p&&!w&&de(null)},children:j(Gt,{children:[j(Wt,{children:[k(Qt,{children:"Delete variant?"}),k(Jt,{children:J&&`"${bs(J)}" will no longer be purchasable. Past orders are unaffected.`})]}),j(Kt,{children:[k(h,{variant:"outline",onClick:()=>de(null),disabled:w,children:"Cancel"}),k(h,{variant:"destructive",onClick:_e,disabled:w,children:"Delete"})]})]})})]})}import{Fragment as Zn,jsx as q,jsxs as ae}from"react/jsx-runtime";function Jn(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 za({productsState:e,product:t,currency:a,onSaved:s,className:r}){let{createProduct:i,updateProduct:l,attachProductFile:m,attachProductFileFromUrl:d}=e,c=!!t,n=t?.currency??a,g=Et(n)?"1":"0.01",x=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[w,b]=ye.useState(!1),[v,N]=ye.useState(null),S=ye.useRef(!0);ye.useEffect(()=>(S.current=!0,()=>{S.current=!1}),[]);let[C,I]=ye.useState(t?.name??""),[Q,_]=ye.useState(t?.description??""),[F,M]=ye.useState(t?.allow_custom_amount?"custom":"fixed"),[K,$]=ye.useState(t?.unit_amount!=null?String(Qe(t.unit_amount,n)):""),[D,me]=ye.useState(t?.min_amount!=null?String(Qe(t.min_amount,n)):""),[u,X]=ye.useState(t?.max_amount!=null?String(Qe(t.max_amount,n)):""),[xe,be]=ye.useState(String(t?.max_quantity??10)),le=ye.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(Qe(t.unit_amount,n)):"",minAmount:t?.min_amount!=null?String(Qe(t.min_amount,n)):"",maxAmount:t?.max_amount!=null?String(Qe(t.max_amount,n)):"",maxQuantity:String(t?.max_quantity??10)}).current,[Fe,J]=ye.useState(t?.collect_shipping_address??!1),[de,Pe]=ye.useState(t?.active??!0),[qe,He]=ye.useState(t?.images??[]),[Tt,kt]=ye.useState(""),[_e,ut]=ye.useState(t?.fulfillment??null),[mt,Ee]=ye.useState(!1),[_t,p]=ye.useState(""),[R,se]=ye.useState(null),Ze=ye.useRef(null),Ye=w||mt,Xe=()=>{let z=Tt.trim();if(z){if(qe.includes(z)){N("This image URL is already added");return}He(ge=>[...ge,z]),kt(""),N(null)}},Ge=z=>{He(ge=>ge.filter(Se=>Se!==z))},Ot=async()=>{if(N(null),!C.trim()){N("Product name is required");return}let z=null,ge=null,Se=null,Xt=!c||F!==le.pricingMode||(F==="fixed"?K!==le.unitAmount:D!==le.minAmount||u!==le.maxAmount),Lt=!c||xe!==le.maxQuantity,ba=x||F==="fixed";if(!(x||!Xt))if(F==="fixed"){if(z=Pt(K,n),z===null||z<=0){N("Enter a valid price");return}}else{if(ge=Pt(D,n),Se=Pt(u,n),ge===null||Se===null){N("Enter valid minimum and maximum amounts");return}if(Se<ge){N("Maximum amount must be at least the minimum amount");return}}let pt=parseInt(xe,10);if(ba&&Lt&&(!Number.isFinite(pt)||pt<1)){N("Max quantity must be at least 1");return}try{b(!0);let Oe;if(c&&t){let Me={name:C.trim(),description:Q.trim()||null,images:qe,collect_shipping_address:Fe,active:de};!x&&Xt&&(Me.allow_custom_amount=F==="custom",F==="fixed"?Me.unit_amount=z:(Me.min_amount=ge,Me.max_amount=Se)),ba&&Lt&&(Me.max_quantity=pt),Oe=await l(t.id,Me),le.pricingMode=Oe.allow_custom_amount?"custom":"fixed",le.unitAmount=Oe.unit_amount!=null?String(Qe(Oe.unit_amount,n)):"",le.minAmount=Oe.min_amount!=null?String(Qe(Oe.min_amount,n)):"",le.maxAmount=Oe.max_amount!=null?String(Qe(Oe.max_amount,n)):"",le.maxQuantity=String(Oe.max_quantity)}else{let Me={name:C.trim(),allow_custom_amount:F==="custom",collect_shipping_address:Fe,active:de};Q.trim()&&(Me.description=Q.trim()),qe.length>0&&(Me.images=qe),F==="fixed"?(Me.unit_amount=z,Me.max_quantity=pt):(Me.min_amount=ge,Me.max_amount=Se),Oe=await i(Me)}if(!S.current)return;ut(Oe.fulfillment),s?.(Oe)}catch(Oe){if(!S.current)return;N(Oe instanceof Error?Oe.message:"Failed to save product")}finally{S.current&&b(!1)}},ga=async z=>{let ge=z.target.files?.[0];if(!(!ge||!t))try{Ee(!0),se(null);let Se=await m(t.id,ge);if(!S.current)return;ut(Se.fulfillment),s?.(Se)}catch(Se){if(!S.current)return;se(Se instanceof Error?Se.message:"Failed to upload file")}finally{S.current&&(Ee(!1),Ze.current&&(Ze.current.value=""))}},va=async()=>{let z=_t.trim();if(!(!z||!t))try{Ee(!0),se(null);let ge=await d(t.id,z);if(!S.current)return;ut(ge.fulfillment),p(""),s?.(ge)}catch(ge){if(!S.current)return;se(ge instanceof Error?ge.message:"Failed to fetch file")}finally{S.current&&Ee(!1)}};return ae("div",{className:`af-space-y-6 ${r||""}`,children:[ae("div",{className:"af-space-y-2",children:[q(te,{htmlFor:"product-name",children:"Name"}),q(ne,{id:"product-name",value:C,onChange:z=>I(z.target.value),placeholder:"My product"})]}),ae("div",{className:"af-space-y-2",children:[q(te,{htmlFor:"product-description",children:"Description"}),q("textarea",{id:"product-description",value:Q,onChange:z=>_(z.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"})]}),ae("div",{className:"af-space-y-2",children:[q(te,{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."}):ae(Zn,{children:[ae(gt,{value:F,onValueChange:z=>M(z),children:[q(lt,{className:"af-w-[260px]",children:q(vt,{})}),ae(ft,{children:[q(ve,{value:"fixed",children:"Fixed price"}),q(ve,{value:"custom",children:"Buyer chooses the amount"})]})]}),F==="fixed"?q("div",{className:"af-flex af-items-end af-gap-3",children:ae("div",{className:"af-space-y-1",children:[ae(te,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",n.toUpperCase(),")"]}),q(ne,{id:"product-price",type:"number",min:"0",step:g,value:K,onChange:z=>$(z.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):ae("div",{className:"af-space-y-1",children:[ae("div",{className:"af-flex af-items-end af-gap-3",children:[ae("div",{className:"af-space-y-1",children:[ae(te,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",n.toUpperCase(),")"]}),q(ne,{id:"product-min-amount",type:"number",min:"0",step:g,value:D,onChange:z=>me(z.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),ae("div",{className:"af-space-y-1",children:[ae(te,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",n.toUpperCase(),")"]}),q(ne,{id:"product-max-amount",type:"number",min:"0",step:g,value:u,onChange:z=>X(z.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."})]}),ae("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")&&ae("div",{className:"af-space-y-1",children:[q(te,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),q(ne,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:xe,onChange:z=>be(z.target.value),className:"af-w-[140px]"})]})]}),ae("div",{className:"af-space-y-2",children:[q(te,{children:"Images"}),q("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),ae("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[qe.map(z=>ae(G,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[q("span",{className:"af-truncate",children:z}),q("button",{type:"button",onClick:()=>Ge(z),className:"af-ml-1 hover:af-text-destructive",disabled:w,children:q(Qn,{className:"af-h-3 af-w-3"})})]},z)),qe.length===0&&q("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),ae("div",{className:"af-flex af-gap-2",children:[q(ne,{type:"url",value:Tt,onChange:z=>kt(z.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),Xe())},disabled:w}),q(h,{type:"button",variant:"outline",onClick:Xe,disabled:!Tt.trim()||w,children:q(Wn,{className:"af-h-4 af-w-4"})})]})]}),ae("div",{className:"af-space-y-2",children:[q(te,{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."}),c?ae("div",{className:"af-space-y-3",children:[_e?.type==="download"&&ae("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[q(qn,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),q("span",{className:"af-text-sm",children:_e.filename}),_e.size!=null&&ae("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Jn(_e.size),")"]})]}),_e?.type==="redirect"&&_e.url&&ae("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[q(Gn,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),ae("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",_e.url]})]}),ae("div",{className:"af-flex af-items-center af-gap-2",children:[q("input",{ref:Ze,type:"file",onChange:ga,className:"af-hidden",disabled:Ye}),ae(h,{type:"button",variant:"outline",size:"sm",onClick:()=>Ze.current?.click(),disabled:Ye,children:[mt?q(Xs,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):q(Kn,{className:"af-h-4 af-w-4 af-mr-1"}),_e?.type==="download"?"Replace file":"Upload file"]}),q("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),q(ne,{type:"url",value:_t,onChange:z=>p(z.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:mt}),q(h,{type:"button",variant:"outline",size:"sm",onClick:va,disabled:!_t.trim()||Ye,children:"Fetch from URL"})]}),R&&q("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:R})]}):q("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),ae("div",{className:"af-space-y-2",children:[q(te,{children:"Settings"}),ae("div",{className:"af-space-y-2",children:[ae("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[q("input",{type:"checkbox",checked:Fe,onChange:z=>J(z.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),ae("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[q("input",{type:"checkbox",checked:de,onChange:z=>Pe(z.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),c&&t&&ae("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[q(te,{children:"Options & Variants"}),q($a,{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:ae(h,{type:"button",onClick:Ot,disabled:Ye,children:[w?q(Xs,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,c?"Save changes":"Create product"]})})]})}import*as $e from"react";import{ChevronLeft as Ni,ChevronRight as ur,Loader2 as wi,Receipt as Pi,Search as Si,SlidersHorizontal as Ri}from"lucide-react";import*as ke from"react";var Yn=["pending","paid","failed","expired","refunded","partially_refunded","disputed"];function ja({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=Y(),[s,r]=ke.useState([]),[i,l]=ke.useState(0),[m,d]=ke.useState(!0),[c,n]=ke.useState(null),[g,x]=ke.useState(0),[w,b]=ke.useState(e),[v,N]=ke.useState(void 0),[S,C]=ke.useState(""),[I,Q]=ke.useState(""),[_,F]=ke.useState(""),[M,K]=ke.useState(!1),[$,D]=ke.useState(!1),[me,u]=ke.useState(void 0),X=me?me.join(","):"",xe=ke.useMemo(()=>{if(!X)return;let J=new Set(X.split(","));return Yn.filter(de=>!J.has(de))},[X]),be=ke.useRef(0),le=ke.useCallback(async()=>{let J=++be.current;try{d(!0),n(null);let de={limit:w,offset:g*w};v?de.status=v:xe?de.excludeStatus=xe:M||(de.excludeStatus=["pending","expired"]),S.trim()&&(de.customerEmail=S.trim()),I.trim()&&(de.from=I.trim()),_.trim()&&(de.to=_.trim()),$&&(de.unfulfilledOnly=!0);let Pe=await a.getOrders(de);if(J!==be.current)return;r(Pe.orders),l(Pe.total)}catch(de){if(J!==be.current)return;n(de instanceof Error?de:new Error("Failed to fetch orders"))}finally{J===be.current&&d(!1)}},[a,g,w,v,xe,M,$,S,I,_,t]);ke.useEffect(()=>{le()},[le]);let Fe=Math.ceil(i/w);return{orders:s,total:i,isLoading:m,error:c,page:g,pageSize:w,hasNextPage:g<Fe-1,hasPreviousPage:g>0,setPage:x,setPageSize:J=>{b(J),x(0)},status:v,setStatus:J=>{N(J),x(0)},statusIn:me,setStatusIn:J=>{u(J&&J.length>0?J:void 0),x(0)},customerEmail:S,setCustomerEmail:J=>{C(J),x(0)},from:I,setFrom:J=>{Q(J),x(0)},to:_,setTo:J=>{F(J),x(0)},showAbandoned:M,setShowAbandoned:J=>{K(J),x(0)},unfulfilledOnly:$,setUnfulfilledOnly:J=>{D(J),x(0)},clearFilters:()=>{N(void 0),u(void 0),K(!1),D(!1),C(""),Q(""),F(""),x(0)},refetch:le}}import*as Be from"react";import{ArrowLeft as ti,Check as rr,ChevronLeft as ai,ChevronRight as si,ClipboardCopy as ri,Copy as ni,Download as ii,Loader2 as Ga,Mail as nr,MoreHorizontal as oi,Package as li,RotateCcw as fi,Truck as di,Undo2 as ir}from"lucide-react";import*as er from"react";import*as Dt from"@radix-ui/react-popover";import{jsx as ys}from"react/jsx-runtime";var tr=Dt.Root,ar=Dt.Trigger;var hs=er.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},r)=>ys(Dt.Portal,{children:ys("div",{className:"aifeatures-admin",children:ys(Dt.Content,{ref:r,align:t,sideOffset:a,className:E("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})})}));hs.displayName=Dt.Content.displayName;import{jsx as qa}from"react/jsx-runtime";var Xn={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed"};function ei(e){return Xn[e]??e}function sr(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 fa({status:e,className:t}){return qa(G,{variant:sr(e),className:t,children:ei(e)})}function da({status:e}){return qa(fa,{status:e})}function ha({order:e,className:t}){return e.shipping_address?typeof e.merchant_fulfilled_at=="string"?qa(G,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?qa(G,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Zt(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as yi,jsx as f,jsxs as O}from"react/jsx-runtime";var dr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ca="af-text-xs af-text-muted-foreground";function xs(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 ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cr(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 Wa=24,ui=["paid","partially_refunded"],mi=["paid","partially_refunded","disputed"],pi=/^[A-Za-z0-9 _-]*$/,or=100;function Ps(e,t,a,s,r){let i=ui.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 ${Wa} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${Wa} 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<Wa&&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<Wa&&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 lr({title:e,recipient:t,status:a,attempts:s,side:r,orderStatus:i,action:l}){let m=Ps(r,a,s,i,t);return O("div",{children:[O("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[O("div",{className:"af-min-w-0",children:[f("div",{className:"af-text-sm",children:e}),t&&f("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),f(G,{variant:m.variant,className:"af-shrink-0",children:m.label})]}),m.detail&&f("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:m.detail}),l&&f("div",{className:"af-mt-2",children:l})]})}function fr(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=ci(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}: ${cr(r)}`)}function gi(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Ss({value:e,label:t,children:a,className:s,size:r="icon"}){let[i,l]=Be.useState(!1);if(!gi())return null;let m=async()=>{try{await navigator.clipboard.writeText(e),l(!0),setTimeout(()=>l(!1),1500)}catch{}},d=i?f(rr,{className:"af-h-3 af-w-3"}):f(ni,{className:"af-h-3 af-w-3"});return r==="icon"?f(h,{variant:"ghost",size:"icon",className:E("af-h-6 af-w-6 af-shrink-0",s),onClick:m,title:t,"aria-label":t,children:d}):O(h,{variant:"outline",size:"sm",className:s,onClick:m,"aria-label":t,children:[i?f(rr,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):f(ri,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":a]})}function Ns({label:e,value:t}){return O("div",{children:[f("div",{className:ca,children:e}),O("div",{className:"af-flex af-items-center af-gap-1",children:[f("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),f(Ss,{value:t,label:`Copy ${e}`})]})]})}function vi({src:e}){let[t,a]=Be.useState(!1);return!e||t?f("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:f(li,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):f("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 na({title:e,action:t,children:a,className:s}){return O("section",{className:E("af-rounded-lg af-border af-p-4",s),children:[O("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[f("h4",{className:dr,children:e}),t]}),f("div",{className:"af-mt-3",children:a})]})}function ia({label:e,emphasis:t,children:a}){return O("div",{className:E("af-flex af-items-baseline af-justify-between af-gap-6",t&&"af-mt-2 af-border-t af-pt-2"),children:[f("span",{className:t?"af-text-base af-font-semibold":ca,children:e}),f("span",{className:E("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:a})]})}function ws({onSelect:e,disabled:t,icon:a,children:s}){return O(h,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[f("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function bi(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(wt(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let a=Ps("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=Ps("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 Ka({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:r=!1,onPrevOrder:i,onNextOrder:l,hasPrevOrder:m=!1,hasNextOrder:d=!1}){let{api:c}=Y(),[n,g]=Be.useState(e),[x,w]=Be.useState(null),[b,v]=Be.useState(null),[N,S]=Be.useState(!1),[C,I]=Be.useState(!1),[Q,_]=Be.useState(!1),[F,M]=Be.useState(!1),[K,$]=Be.useState(""),[D,me]=Be.useState(!1),[u,X]=Be.useState(null),[xe,be]=Be.useState(!1),[le,Fe]=Be.useState(""),[J,de]=Be.useState([]),[Pe,qe]=Be.useState(!1),[He,Tt]=Be.useState(!1),[kt,_e]=Be.useState(null);Be.useEffect(()=>{g(e)},[e]);let ut=P=>{g(P),s?.(P)},mt=Object.entries(n.metadata??{}),Ee=wt(n)-n.amount_refunded,_t=(n.status==="paid"||n.status==="partially_refunded")&&Ee>0,p=P=>(typeof P.unitAmount=="number"?P.unitAmount:0)*(typeof P.quantity=="number"&&P.quantity>0?P.quantity:1),R=Math.max(0,(n.shipping_total??0)-(n.shipping_refunded??0)),se=J.reduce((P,pe)=>P+p(n.line_items[pe]??{}),0)+(Pe?R:0),Ze=n.tax_total??0,Ye=n.automatic_tax&&n.tax_behavior==="exclusive"&&Ze>0&&n.amount_total+(n.shipping_total??0)>0?Math.min(Math.max(0,Ze-(n.tax_refunded??0)),Math.round(Ze*se/(n.amount_total+(n.shipping_total??0)))):0,Xe=se+Ye,Ge=J.length>0||Pe,Ot=Ge?Xe:Pt(le,n.currency),ga=Et(n.currency)?"1":"0.01",va=async()=>{try{S(!0),w(null),v(null),await c.resendOrderReceipt(n.id);let P=await c.getOrder(n.id);ut(P),v("Receipt email queued.")}catch(P){w(P instanceof Error?P.message:"Failed to resend receipt")}finally{S(!1)}},z=async()=>{try{I(!0),w(null),v(null);let P=await c.resetOrderDownloads(n.id);ut(P),_(!1),v("Download count reset.")}catch(P){w(P instanceof Error?P.message:"Failed to reset downloads")}finally{I(!1)}},ge=!!n.shipping_address,Se=typeof n.merchant_fulfilled_at=="string",Xt=mi.includes(n.status),Lt=K.trim(),ba=pi.test(Lt)&&Lt.length<=or,pt=async P=>{try{me(!0),X(null),v(null);let pe=await c.setOrderFulfillment(n.id,{fulfilled:P,...P&&Lt?{trackingNumber:Lt}:{}});ut(pe),$(""),v(P?"Marked as shipped.":"Marked as not shipped.")}catch(pe){pe instanceof ea&&pe.status===409?X(`This order is ${n.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):X(pe instanceof Error?pe.message:"Failed to update the order")}finally{me(!1)}},Oe=()=>{_e(null),Fe(String(Qe(Ee,n.currency))),de([]),qe(!1),be(!0)},Me=P=>de(pe=>pe.includes(P)?pe.filter(it=>it!==P):[...pe,P]),Ra=async(P,pe)=>{if(a)try{Tt(!0),_e(null),await a(n,P,pe);let it=await c.getOrder(n.id);ut(it),be(!1),v("Refund issued.")}catch(it){_e(it instanceof Error?it.message:"Refund failed")}finally{Tt(!1)}},T=async()=>{if(Ge){if(Xe<=0){_e("The lines you picked were charged nothing");return}if(Xe>Ee){_e(`That selection exceeds the refundable remainder (${U(Ee,n.currency)})`);return}await Ra(Xe,{...J.length>0?{line_items:[...J].sort((pe,it)=>pe-it)}:{},...Pe?{shipping:!0}:{}});return}let P=Pt(le,n.currency);if(P===null||P<=0){_e("Enter a valid refund amount");return}if(P>Ee){_e(`Amount exceeds the refundable remainder (${U(Ee,n.currency)})`);return}await Ra(P,{amount:P})},nt=()=>Ra(Ee,{full:!0}),Bs=n.fulfillment_type==="download",Es=r&&ge,Ur=bi(n),Vr=n.shipping_address?fr(n.shipping_address).join(`
4
- `):"",Ds=n.shipping_total!=null,Is=!!n.automatic_tax&&n.tax_behavior==="exclusive"&&(n.tax_total??0)>0,Hr=!(n.automatic_tax&&n.tax_behavior==="exclusive")&&(n.tax_total??0)>0,Mr=Ds||Is,Ca=[];return Ca.push(f(ws,{icon:N?f(Ga,{className:"af-h-4 af-w-4 af-animate-spin"}):f(nr,{className:"af-h-4 af-w-4"}),disabled:N||n.fulfillment_status!=="fulfilled",onSelect:()=>{M(!1),va()},children:"Resend receipt"},"resend")),Bs&&Ca.push(f(ws,{icon:f(fi,{className:"af-h-4 af-w-4"}),disabled:C,onSelect:()=>{M(!1),_(!0)},children:"Reset download count"},"reset")),_t&&Ca.push(O("div",{children:[f(ws,{icon:f(ir,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{M(!1),Oe()},children:"Refund\u2026"}),!a&&f("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),O("div",{children:[O("div",{className:"af-mb-6",children:[O(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[f(ti,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),O("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[O("div",{className:"af-min-w-0",children:[O("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[f("h3",{className:"af-text-xl af-font-semibold",children:Zt(n)}),f(fa,{status:n.status}),r&&f(ha,{order:n}),n.is_test&&f(G,{variant:"outline",children:"Test"})]}),O("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",xs(n.created_at)]}),n.is_test&&f("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),O("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||l)&&O("div",{className:"af-flex af-items-center",children:[f(h,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!m,"aria-label":"Previous order",children:f(ai,{className:"af-h-4 af-w-4"})}),f(h,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:l,disabled:!d,"aria-label":"Next order",children:f(si,{className:"af-h-4 af-w-4"})})]}),Es&&(Se?O("div",{className:"af-flex af-items-center af-gap-1",children:[O("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",n.merchant_fulfilled_at?` \xB7 ${xs(n.merchant_fulfilled_at)}`:""]}),Xt&&O(h,{variant:"ghost",size:"sm",onClick:()=>pt(!1),disabled:D,children:[D?f(Ga,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):f(ir,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Xt?O("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[f(ne,{value:K,onChange:P=>$(P.target.value),placeholder:"Tracking number (optional)",maxLength:or,className:"af-w-[200px]","aria-label":"Tracking number (optional)",disabled:D}),O(h,{variant:"default",onClick:()=>pt(!0),disabled:D||!ba,children:[D?f(Ga,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):f(di,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Ca.length>0&&O(tr,{open:F,onOpenChange:M,children:[f(ar,{asChild:!0,children:f(h,{variant:"outline",size:"icon","aria-label":"More actions",children:f(oi,{className:"af-h-4 af-w-4"})})}),f(hs,{children:f("div",{className:"af-space-y-0.5",children:Ca})})]})]})]}),Es&&!Se&&!ba&&f("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."}),u&&f("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:u}),b&&f("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&&f("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})]}),O("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[O("div",{className:"af-space-y-6",children:[n.line_items.length>0&&f(na,{title:"Items",children:f("ul",{className:"af-space-y-3",children:n.line_items.map((P,pe)=>{let it=typeof P.name=="string"&&P.name?P.name:"Item",As=typeof P.quantity=="number"&&P.quantity>0?P.quantity:1,Fs=typeof P.unitAmount=="number";return O("li",{className:"af-flex af-items-start af-gap-3",children:[f(vi,{src:typeof P.imageUrl=="string"&&P.imageUrl?P.imageUrl:void 0}),O("div",{className:"af-min-w-0 af-flex-1",children:[O("div",{className:"af-text-sm af-font-medium",children:[it,typeof P.variantTitle=="string"&&P.variantTitle&&O("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",P.variantTitle]})]}),O("div",{className:ca,children:[As," \xD7"," ",Fs?U(P.unitAmount,n.currency):"\u2014"]}),P.refunded===!0&&f(G,{variant:"secondary",className:"af-mt-1",children:P.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),f("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:Fs?U(P.unitAmount*As,n.currency):"\u2014"})]},pe)})})}),mt.length>0&&f(na,{title:"Order details",children:f("dl",{className:"af-space-y-2",children:mt.map(([P,pe])=>O("div",{children:[f("dt",{className:E(ca,"af-capitalize"),children:P.replace(/_/g," ")}),f("dd",{className:"af-text-sm af-break-words",children:cr(pe)})]},P))})}),f(na,{title:"Payment",children:O("div",{className:"af-ml-auto af-w-full sm:af-max-w-xs",children:[Mr&&f(ia,{label:"Subtotal",children:U(n.amount_total,n.currency)}),Ds&&f(ia,{label:"Shipping",children:n.shipping_total===0?"Free":U(n.shipping_total??0,n.currency)}),Is&&f(ia,{label:"Tax",children:U(n.tax_total??0,n.currency)}),f(ia,{label:"Total",emphasis:!0,children:U(wt(n),n.currency)}),Hr&&f(ia,{label:"incl. tax",children:U(n.tax_total??0,n.currency)}),n.base_currency!=null&&n.base_amount_total!=null&&O(ia,{label:"Your price",children:[U(n.base_amount_total,n.base_currency),O("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",n.currency.toUpperCase()]})]}),n.amount_refunded>0&&O(yi,{children:[O(ia,{label:"Refunded",children:["\u2212",U(n.amount_refunded,n.currency),(n.shipping_refunded??0)>0&&O("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",U(n.shipping_refunded??0,n.currency)," ","shipping"]})]}),f(ia,{label:"Net",children:f("span",{className:"af-font-medium",children:U(Math.max(0,wt(n)-n.amount_refunded),n.currency)})})]})]})}),f(na,{title:"Timeline",children:f("ol",{className:"af-space-y-3",children:Ur.map(P=>O("li",{className:"af-flex af-gap-3",children:[f("span",{"aria-hidden":"true",className:E("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")}),O("div",{className:"af-min-w-0",children:[f("div",{className:"af-text-sm af-break-words",children:P.text}),P.at&&f("div",{className:"af-text-xs af-text-muted-foreground",children:xs(P.at)})]})]},P.key))})})]}),O("div",{className:"af-space-y-6",children:[f(na,{title:"Customer",children:O("div",{className:"af-space-y-2",children:[O("div",{children:[f("div",{className:ca,children:"Email"}),O("div",{className:"af-flex af-items-center af-gap-1",children:[f("span",{className:"af-min-w-0 af-break-all af-text-sm",children:n.customer_email||f("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),n.customer_email&&f(Ss,{value:n.customer_email,label:"Copy email"})]})]}),n.customer_name&&O("div",{children:[f("div",{className:ca,children:"Name"}),f("div",{className:"af-text-sm",children:n.customer_name})]}),n.customer&&O("div",{children:[f("div",{className:ca,children:"Customer record"}),O("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[f("span",{className:"af-break-all af-text-sm",children:n.customer.name||n.customer.email}),f(G,{variant:"secondary",children:"Linked"})]})]})]})}),n.shipping_address&&f(na,{title:"Ship to",action:f(Ss,{value:Vr,label:"Copy address",size:"sm",children:"Copy address"}),children:f("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:fr(n.shipping_address).map((P,pe)=>f("div",{children:P},pe))})}),f(na,{title:"Emails",children:O("div",{className:"af-space-y-4",children:[f(lr,{side:"buyer",title:"Receipt to buyer",recipient:n.customer_email,status:n.buyer_email_status,attempts:n.buyer_email_attempts,orderStatus:n.status,action:O(h,{variant:"outline",size:"sm",onClick:va,disabled:N||n.fulfillment_status!=="fulfilled",children:[N?f(Ga,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):f(nr,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),f(lr,{side:"merchant",title:"Sale alert to you",recipient:null,status:n.merchant_email_status,attempts:n.merchant_email_attempts,orderStatus:n.status})]})}),Bs&&f(na,{title:"Download",children:O("div",{className:"af-space-y-2",children:[O("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[f(ii,{className:"af-h-4 af-w-4"}),O("span",{children:["Downloaded ",n.download_count," time",n.download_count===1?"":"s"]})]}),n.download_url&&f("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"})]})}),O("details",{className:"af-rounded-lg af-border af-p-4",children:[f("summary",{className:E(dr,"af-cursor-pointer af-select-none"),children:"Technical details"}),O("div",{className:"af-mt-3 af-space-y-2",children:[f(Ns,{label:"Order ID",value:n.id}),n.stripe_checkout_session_id&&f(Ns,{label:"Checkout session",value:n.stripe_checkout_session_id}),n.stripe_payment_intent_id&&f(Ns,{label:"Payment",value:n.stripe_payment_intent_id})]})]})]})]}),f(ra,{open:Q,onOpenChange:P=>{!P&&!C&&_(!1)},children:O(Gt,{children:[O(Wt,{children:[f(Qt,{children:"Reset download count?"}),f(Jt,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),O(Kt,{children:[f(h,{variant:"outline",onClick:()=>_(!1),disabled:C,children:"Cancel"}),f(h,{onClick:z,disabled:C,children:C?"Resetting...":"Reset"})]})]})}),f(ra,{open:xe,onOpenChange:P=>{!P&&!He&&be(!1)},children:O(Gt,{children:[O(Wt,{children:[f(Qt,{children:"Refund order"}),O(Jt,{children:["Refund up to ",U(Ee,n.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),O("div",{className:"af-space-y-4",children:[(n.line_items.length>0||R>0)&&O("div",{className:"af-space-y-2",children:[f(te,{children:"Items"}),O("div",{className:"af-space-y-2",children:[n.line_items.map((P,pe)=>{let it=P.refunded===!0;return O("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[f("input",{type:"checkbox",checked:J.includes(pe),onChange:()=>Me(pe),disabled:He||it,className:"af-h-4 af-w-4"}),O("span",{className:it?"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}`:""]}),f("span",{className:"af-ml-auto af-text-muted-foreground",children:it?"Refunded":U(p(P),n.currency)})]},pe)}),R>0&&O("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[f("input",{type:"checkbox",checked:Pe,onChange:P=>qe(P.target.checked),disabled:He,className:"af-h-4 af-w-4"}),f("span",{children:"Shipping"}),f("span",{className:"af-ml-auto af-text-muted-foreground",children:U(R,n.currency)})]})]})]}),O("div",{className:"af-space-y-2",children:[O(te,{htmlFor:"refund-amount",children:["Amount (",n.currency.toUpperCase(),")"]}),f(ne,{id:"refund-amount",type:"number",min:"0",step:ga,value:Ge?String(Qe(Xe,n.currency)):le,onChange:P=>Fe(P.target.value),disabled:He||Ge}),Ge&&f("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),kt&&f("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:kt}),O(Kt,{children:[f(h,{variant:"outline",onClick:()=>be(!1),disabled:He,children:"Cancel"}),f(h,{variant:"outline",onClick:nt,disabled:He,children:"Refund everything"}),f(h,{variant:"destructive",onClick:T,disabled:He,children:He?"Refunding...":Ot!==null&&Ot>0?`Refund ${U(Ot,n.currency)}`:"Refund"})]})]})})]})}import*as Qa from"react";import{ArrowLeft as hi,RefreshCw as xi}from"lucide-react";import{jsx as It,jsxs as ua}from"react/jsx-runtime";function oa({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:r}){let i=Qa.useRef(null);return Qa.useEffect(()=>{i.current?.focus()},[]),ua("div",{className:E("af-bg-background",r),children:[ua("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:[It("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!a&&ua(h,{type:"button",variant:"outline",size:"sm",onClick:t,children:[It(hi,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),It("div",{className:"af-p-4",children:s})]})}function W({className:e}){return It("div",{"aria-hidden":"true",className:E("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function at({label:e,children:t,detail:a,valueClassName:s}){return ua("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[It("div",{className:"af-text-xs af-text-muted-foreground",children:e}),It("div",{className:E("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&It("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function St({message:e,onRetry:t}){return ua("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[It("span",{children:e}),ua(h,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[It(xi,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function ma({icon:e,children:t}){return ua("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,It("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}import{Fragment as Ti,jsx as y,jsxs as Z}from"react/jsx-runtime";var Ci={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},mr={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function pr(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 gr(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 Ja(e){return e.customer?.name||e.customer_name||null}function xa({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:r=!1,emptyMessage:i,onDetailOpenChange:l}){let{api:m}=Y(),d=ja({refreshKey:a}),{orders:c,total:n,isLoading:g,error:x,page:w,pageSize:b,hasNextPage:v,hasPreviousPage:N,setPage:S,setPageSize:C,customerEmail:I,setCustomerEmail:Q,setStatusIn:_,from:F,setFrom:M,to:K,setTo:$,showAbandoned:D,setShowAbandoned:me,setUnfulfilledOnly:u,refetch:X}=d,[xe,be]=$e.useState("list"),[le,Fe]=$e.useState(null),[J,de]=$e.useState(""),[Pe,qe]=$e.useState(""),[He,Tt]=$e.useState(r?"needs_shipping":"all"),[kt,_e]=$e.useState(!1),[ut,mt]=$e.useState(!!s),[Ee,_t]=$e.useState(null);$e.useEffect(()=>{if(!s)return;let T=!1;return mt(!0),_t(null),m.getOrder(s).then(nt=>{T||(Fe(nt),be("detail"))}).catch(()=>{T||_t("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{T||mt(!1)}),()=>{T=!0}},[m,s]);let p=$e.useCallback(T=>{Tt(T);let nt=mr[T];_(nt.statusIn),u(nt.unfulfilledOnly)},[_,u]);$e.useEffect(()=>{r&&u(!0)},[]);let R=$e.useRef(!r);$e.useEffect(()=>{R.current||g||(R.current=!0,c.length===0&&p("all"))},[g,c.length,p]);let se=xe==="detail"&&!!le;$e.useEffect(()=>{l?.(se)},[se,l]);let Ze=(F?1:0)+(K?1:0)+(D?1:0),Ye=Ze>0||!!I||!!Pe,Xe=!!F&&!!K&&F>K,Ge=T=>{Fe(T),be("detail")},Ot=()=>{be("list"),Fe(null),X()},ga=T=>{let nt=T.trim();if(!nt){qe(""),I&&Q("");return}if(nt.startsWith("#")||/^\d+$/.test(nt)){qe(nt),I&&Q("");return}qe(""),Q(nt)},va=()=>{de(""),qe(""),Q(""),M(""),$(""),me(!1),_e(!1)},z=Pe.replace(/^#/,"").toLowerCase(),ge=z?c.filter(T=>String(T.order_number??"")===z||T.id.toLowerCase().startsWith(z)):c,Se=le?c.findIndex(T=>T.id===le.id):-1,Xt=Se>0,Lt=Se>=0&&Se<c.length-1;if(ut)return y("div",{className:t,children:y("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:y(wi,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(xe==="detail"&&le)return y("div",{className:t,children:y(Ka,{order:le,onBack:Ot,onRefund:e,onOrderUpdated:T=>Fe(T),allowFulfillment:r,onPrevOrder:Xt?()=>Fe(c[Se-1]):void 0,onNextOrder:Lt?()=>Fe(c[Se+1]):void 0,hasPrevOrder:Xt,hasNextOrder:Lt},le.id)});let pt=Z("div",{className:"af-mb-4 af-space-y-3",children:[Ee&&y("p",{className:"af-text-xs af-text-muted-foreground",children:Ee}),Z("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[y("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(T=>y("button",{type:"button","aria-pressed":He===T,onClick:()=>p(T),className:E("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",He===T?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ci[T]},T))}),Z("div",{className:"af-relative af-w-full af-max-w-xs",children:[y(Si,{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"}),y(ne,{type:"text",value:J,onChange:T=>de(T.target.value),onBlur:()=>ga(J),onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),ga(J))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),Z(h,{type:"button",variant:Ze>0?"secondary":"ghost",size:"sm",onClick:()=>_e(T=>!T),"aria-expanded":kt,children:[y(Ri,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ze>0&&y(G,{variant:"secondary",className:"af-ml-2",children:Ze})]}),Ye&&y(h,{type:"button",variant:"ghost",size:"sm",onClick:va,children:"Clear filters"})]}),(kt||!!F||!!K)&&Z("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:[y(te,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),y(ne,{id:"orders-from",type:"date",value:F,max:K||void 0,onChange:T=>M(T.target.value),className:"af-w-[170px]"}),y(te,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),y(ne,{id:"orders-to",type:"date",value:K,min:F||void 0,onChange:T=>$(T.target.value),className:"af-w-[170px]"}),!mr[He].statusIn&&y(h,{type:"button",variant:D?"secondary":"ghost",size:"sm",onClick:()=>me(!D),"aria-pressed":D,children:D?"Hide abandoned":"Show abandoned"})]}),Xe&&y("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(g)return Z("div",{className:t,children:[pt,y("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(T=>Z("div",{className:"af-rounded-md af-border af-p-3",children:[Z("div",{className:"af-flex af-items-center af-justify-between",children:[y(W,{className:"af-h-4 af-w-16"}),y(W,{className:"af-h-4 af-w-14"})]}),y(W,{className:"af-mt-2 af-h-3 af-w-40"}),y(W,{className:"af-mt-2 af-h-3 af-w-24"})]},T))}),y("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Z(Re,{children:[y(Ce,{children:Z(re,{children:[y(L,{children:"Order"}),y(L,{children:"Date"}),y(L,{children:"Customer"}),y(L,{children:"Items"}),y(L,{className:"af-text-right",children:"Total"}),y(L,{children:"Status"}),y(L,{className:"af-w-8"})]})}),y(Te,{"aria-hidden":"true",children:[0,1,2,3,4].map(T=>Z(re,{children:[y(B,{children:y(W,{className:"af-h-4 af-w-14"})}),y(B,{children:y(W,{className:"af-h-4 af-w-24"})}),y(B,{children:y(W,{className:"af-h-4 af-w-40"})}),y(B,{children:y(W,{className:"af-h-4 af-w-32"})}),y(B,{children:y(W,{className:"af-ml-auto af-h-4 af-w-16"})}),y(B,{children:y(W,{className:"af-h-5 af-w-16"})}),y(B,{})]},T))})]})}),y("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(x)return Z("div",{className:t,children:[pt,Z("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[y("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),y(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>X(),children:"Try again"})]})]});let Oe=He!=="all";if(ge.length===0&&w===0)return Z("div",{className:t,children:[(Ye||Oe)&&pt,Z("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[y(Pi,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),y("p",{className:"af-text-muted-foreground af-text-center",children:Ye||Oe?"No orders match these filters.":i??Z(Ti,{children:["No orders yet.",y("br",{}),"Orders will appear here when someone buys from your website."]})}),!Ye&&!Oe&&y(h,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>me(!0),children:"Show abandoned checkouts"})]})]});let Me=w*b+1,Ra=Math.min((w+1)*b,n);return Z("div",{className:t,children:[pt,y("div",{className:"af-space-y-3 lg:af-hidden",children:ge.map(T=>Z("button",{type:"button",onClick:()=>Ge(T),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[Z("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[y("span",{className:"af-font-medium",children:Zt(T)}),y("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:U(wt(T),T.currency)})]}),Z("div",{className:"af-mt-1 af-min-w-0",children:[Z("div",{className:"af-truncate af-text-sm",children:[T.customer_email||y("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Ja(T)&&Z("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Ja(T)]})]}),y("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:gr(T)}),T.amount_refunded>0&&Z("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",U(T.amount_refunded,T.currency)," refunded"]})]}),Z("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[y(fa,{status:T.status}),T.is_test&&y(G,{variant:"outline",children:"Test"}),r&&y(ha,{order:T}),y("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:pr(T.created_at)})]})]},T.id))}),y("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Z(Re,{children:[y(Ce,{children:Z(re,{children:[y(L,{children:"Order"}),y(L,{children:"Date"}),y(L,{children:"Customer"}),y(L,{children:"Items"}),y(L,{className:"af-text-right",children:"Total"}),y(L,{children:"Status"}),y(L,{className:"af-w-8"})]})}),y(Te,{children:ge.map(T=>Z(re,{onClick:()=>Ge(T),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[Z(B,{className:"af-whitespace-nowrap af-font-medium",children:[y("button",{type:"button",onClick:nt=>{nt.stopPropagation(),Ge(T)},"aria-label":`Open order ${Zt(T)}`,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:Zt(T)}),T.is_test&&y(G,{variant:"outline",className:"af-ml-2",children:"Test"})]}),y(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:pr(T.created_at)}),Z(B,{className:"af-max-w-[220px]",children:[y("div",{className:"af-truncate",children:T.customer_email||y("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Ja(T)&&y("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Ja(T)})]}),y(B,{className:"af-max-w-[220px]",children:y("div",{className:"af-truncate af-text-muted-foreground",children:gr(T)})}),Z(B,{className:"af-whitespace-nowrap af-text-right",children:[y("div",{className:"af-font-medium af-tabular-nums",children:U(wt(T),T.currency)}),T.amount_refunded>0&&Z("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",U(T.amount_refunded,T.currency)," ","refunded"]})]}),y(B,{children:Z("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[y(fa,{status:T.status}),r&&y(ha,{order:T})]})}),y(B,{className:"af-w-8 af-text-right",children:y(ur,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},T.id))})]})}),Z("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Z("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[y("span",{children:z?`${ge.length} matching this page`:`Showing ${Me}-${Ra} of ${n}`}),Z(gt,{value:String(b),onValueChange:T=>C(Number(T)),children:[y(lt,{className:"af-w-[70px] af-h-8",children:y(vt,{})}),Z(ft,{children:[y(ve,{value:"10",children:"10"}),y(ve,{value:"25",children:"25"}),y(ve,{value:"50",children:"50"}),y(ve,{value:"100",children:"100"})]})]}),y("span",{children:"per page"})]}),Z("div",{className:"af-flex af-items-center af-gap-2",children:[Z(h,{variant:"outline",size:"sm",onClick:()=>S(w-1),disabled:!N,children:[y(Ni,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Z(h,{variant:"outline",size:"sm",onClick:()=>S(w+1),disabled:!v,children:["Next",y(ur,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Xa from"react";import{ChevronLeft as Li,ChevronRight as Bi,Eye as Ei,Search as Di,Users as Ii}from"lucide-react";import*as ot from"react";function Za({initialPageSize:e=25}={}){let{api:t}=Y(),[a,s]=ot.useState([]),[r,i]=ot.useState(0),[l,m]=ot.useState(!0),[d,c]=ot.useState(null),[n,g]=ot.useState(0),[x,w]=ot.useState(e),[b,v]=ot.useState(""),N=ot.useRef(0),S=ot.useCallback(async()=>{let I=++N.current;try{m(!0),c(null);let Q={limit:x,offset:n*x};b.trim()&&(Q.email=b.trim());let _=await t.getCustomers(Q);if(I!==N.current)return;s(_.customers),i(_.total)}catch(Q){if(I!==N.current)return;c(Q instanceof Error?Q:new Error("Failed to fetch customers"))}finally{I===N.current&&m(!1)}},[t,n,x,b]);ot.useEffect(()=>{S()},[S]);let C=Math.ceil(r/x);return{customers:a,total:r,isLoading:l,error:d,page:n,pageSize:x,hasNextPage:n<C-1,hasPreviousPage:n>0,setPage:g,setPageSize:I=>{w(I),g(0)},email:b,setEmail:I=>{v(I),g(0)},refetch:S}}import*as pa from"react";import{ArrowLeft as ki,Loader2 as _i}from"lucide-react";import{jsx as fe,jsxs as Je}from"react/jsx-runtime";function vr(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 Oi(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 Ya({customer:e,onBack:t,className:a}){let{api:s}=Y(),[r,i]=pa.useState(null),[l,m]=pa.useState([]),[d,c]=pa.useState(!0),[n,g]=pa.useState(null);pa.useEffect(()=>{let b=!1;return c(!0),g(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([v,N])=>{b||(i(v),m(N.orders))}).catch(v=>{b||g(v instanceof Error?v.message:"Failed to load customer")}).finally(()=>{b||c(!1)}),()=>{b=!0}},[s,e.id,e.email]);let x=r?.addresses??[],w=r?.order_count??l.length;return Je("div",{className:a,children:[Je("div",{className:"af-mb-6",children:[Je(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[fe(ki,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),fe("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),Je("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",vr(e.created_at)]})]}),d?fe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:fe(_i,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):n?fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:n}):Je("div",{className:"af-space-y-6",children:[Je("div",{children:[fe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),Je("div",{className:"af-space-y-1 af-text-sm",children:[Je("div",{className:"af-flex af-gap-2",children:[fe("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),fe("span",{children:e.email})]}),e.name&&Je("div",{className:"af-flex af-gap-2",children:[fe("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),fe("span",{children:e.name})]}),e.phone&&Je("div",{className:"af-flex af-gap-2",children:[fe("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),fe("span",{children:e.phone})]}),Je("div",{className:"af-flex af-gap-2",children:[fe("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),fe("span",{children:w})]})]})]}),x.length>0&&Je("div",{children:[fe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),fe("div",{className:"af-flex af-flex-wrap af-gap-3",children:x.map(b=>Je("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[b.is_default&&fe(G,{variant:"secondary",className:"af-mb-1",children:"Default"}),Oi(b).map((v,N)=>fe("div",{children:v},N))]},b.id))})]}),Je("div",{children:[fe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),l.length===0?fe("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):Je(Re,{children:[fe(Ce,{children:Je(re,{children:[fe(L,{children:"Date"}),fe(L,{children:"Amount"}),fe(L,{children:"Status"})]})}),fe(Te,{children:l.map(b=>Je(re,{children:[fe(B,{className:"af-text-muted-foreground",children:vr(b.created_at)}),fe(B,{children:U(wt(b),b.currency)}),fe(B,{children:fe(da,{status:b.status})})]},b.id))})]})]})]})]})}import{Fragment as Fi,jsx as ie,jsxs as Ae}from"react/jsx-runtime";function Ai(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 es({className:e}){let{customers:t,total:a,isLoading:s,error:r,page:i,pageSize:l,hasNextPage:m,hasPreviousPage:d,setPage:c,setPageSize:n,email:g,setEmail:x,refetch:w}=Za(),[b,v]=Xa.useState("list"),[N,S]=Xa.useState(null),[C,I]=Xa.useState(""),Q=$=>{S($),v("detail")},_=()=>{v("list"),S(null),w()};if(b==="detail"&&N)return ie("div",{className:e,children:ie(Ya,{customer:N,onBack:_})});let F=Ae("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[ie(ne,{type:"email",value:C,onChange:$=>I($.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),x(C.trim()))}}),Ae(h,{type:"button",variant:"outline",size:"sm",onClick:()=>x(C.trim()),children:[ie(Di,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),g&&ie(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>{I(""),x("")},children:"Clear"})]});if(s)return Ae("div",{className:e,children:[F,ie("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:ie("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(r)return Ae("div",{className:e,children:[F,ie("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ae("div",{className:"af-text-destructive",children:["Error: ",r.message]})})]});if(t.length===0&&i===0)return Ae("div",{className:e,children:[g&&F,Ae("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[ie(Ii,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),ie("p",{className:"af-text-muted-foreground af-text-center",children:g?"No customers match that email.":Ae(Fi,{children:["No customers yet.",ie("br",{}),"Customers appear here after their first purchase."]})})]})]});let M=i*l+1,K=Math.min((i+1)*l,a);return Ae("div",{className:e,children:[F,Ae(Re,{children:[ie(Ce,{children:Ae(re,{children:[ie(L,{children:"Email"}),ie(L,{children:"Name"}),ie(L,{children:"Customer since"}),ie(L,{className:"af-text-right",children:"Actions"})]})}),ie(Te,{children:t.map($=>Ae(re,{children:[ie(B,{className:"af-font-medium",children:$.email}),ie(B,{children:$.name||ie("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),ie(B,{className:"af-text-muted-foreground",children:Ai($.created_at)}),ie(B,{className:"af-text-right",children:ie(h,{variant:"ghost",size:"icon",onClick:()=>Q($),title:"View customer",children:ie(Ei,{className:"af-h-4 af-w-4"})})})]},$.id))})]}),Ae("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Ae("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ae("span",{children:["Showing ",M,"-",K," of ",a]}),Ae(gt,{value:String(l),onValueChange:$=>n(Number($)),children:[ie(lt,{className:"af-w-[70px] af-h-8",children:ie(vt,{})}),Ae(ft,{children:[ie(ve,{value:"10",children:"10"}),ie(ve,{value:"25",children:"25"}),ie(ve,{value:"50",children:"50"}),ie(ve,{value:"100",children:"100"})]})]}),ie("span",{children:"per page"})]}),Ae("div",{className:"af-flex af-items-center af-gap-2",children:[Ae(h,{variant:"outline",size:"sm",onClick:()=>c(i-1),disabled:!d,children:[ie(Li,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ae(h,{variant:"outline",size:"sm",onClick:()=>c(i+1),disabled:!m,children:["Next",ie(Bi,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as yr from"react";import{AlertTriangle as br,CheckCircle2 as Ui,CreditCard as Rs,Loader2 as Vi,RefreshCw as Hi}from"lucide-react";import*as At from"react";function Na(){let{api:e}=Y(),[t,a]=At.useState(null),[s,r]=At.useState(!0),[i,l]=At.useState(null),m=At.useRef(0),d=At.useCallback(async()=>{let c=++m.current;try{r(!0),l(null);let n=await e.getPaymentsStatus();if(c!==m.current)return;a(n)}catch(n){if(c!==m.current)return;l(n instanceof Error?n:new Error("Failed to fetch payments status"))}finally{c===m.current&&r(!1)}},[e]);return At.useEffect(()=>{d()},[d]),{status:t,isLoading:s,error:i,refetch:d}}import{jsx as Ne,jsxs as ze}from"react/jsx-runtime";function ts({onConnectStripe:e,onUpgradePlan:t,className:a}){let{status:s,isLoading:r,error:i,refetch:l}=Na(),[m,d]=yr.useState(!1),c=async()=>{d(!0);try{await l()}finally{d(!1)}};return r&&!s?Ne("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Ne("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!s?Ne("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:ze("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):s.status==="active"?Ne("div",{className:a,children:ze("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:[Ne(Ui,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),ze("div",{children:[Ne("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),ze("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."]})]})]})}):ze("div",{className:`af-space-y-4 ${a||""}`,children:[s.reason==="needs_stripe"&&ze("div",{className:"af-space-y-3",children:[ze("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Ne(Rs,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),ze("div",{children:[Ne("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),Ne("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?ze(h,{onClick:e,children:[Ne(Rs,{className:"af-h-4 af-w-4 af-mr-1"}),s.stripe_account_connected?"Finish setting up":"Set up payments"]}):Ne("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"&&ze("div",{className:"af-space-y-3",children:[ze("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Ne(br,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),ze("div",{children:[Ne("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),Ne("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?Ne(h,{onClick:t,children:"Upgrade plan"}):Ne("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),s.reason==="account_disabled"&&ze("div",{className:"af-space-y-3",children:[ze("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:[Ne(br,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),ze("div",{children:[Ne("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),s.stripe_account_connected?Ne("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."}):Ne("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."})]})]}),ze("div",{className:"af-flex af-gap-2",children:[e&&s.stripe_account_connected&&ze(h,{onClick:e,children:[Ne(Rs,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),ze(h,{variant:"outline",onClick:c,disabled:m,children:[m?Ne(Vi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Ne(Hi,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as rt from"react";function Cs(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function wa({includeStats:e=!1,refreshKey:t}={}){let{api:a}=Y(),[s,r]=rt.useState([]),[i,l]=rt.useState(!0),[m,d]=rt.useState(null),c=rt.useRef(0),n=rt.useCallback(async()=>{let N=++c.current;try{l(!0),d(null);let S=await a.getProducts(e?{include:"stats"}:{});if(N!==c.current)return;r(S)}catch(S){if(N!==c.current)return;d(S instanceof Error?S:new Error("Failed to fetch products"))}finally{N===c.current&&l(!1)}},[a,e,t]);rt.useEffect(()=>{n()},[n]);let g=rt.useCallback(async N=>{let S=await a.createProduct(N);return r(C=>[S,...C]),S},[a]),x=rt.useCallback(async(N,S)=>{let C=await a.updateProduct(N,S);return r(I=>Cs(I,N,C)),C},[a]),w=rt.useCallback(async N=>{await a.deleteProduct(N),r(S=>S.filter(C=>C.id!==N))},[a]),b=rt.useCallback(async(N,S)=>{let C=await a.attachProductFile(N,S);return r(I=>Cs(I,N,C)),C},[a]),v=rt.useCallback(async(N,S)=>{let C=await a.attachProductFileFromUrl(N,S);return r(I=>Cs(I,N,C)),C},[a]);return{products:s,isLoading:i,error:m,refetch:n,createProduct:g,updateProduct:x,deleteProduct:w,attachProductFile:b,attachProductFileFromUrl:v}}import{jsx as Ve,jsxs as yt}from"react/jsx-runtime";function hr({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:r}){let[i,l]=as.useState(t),[m,d]=as.useState("list"),[c,n]=as.useState(null),g=wa(),{status:x,error:w}=Na(),b=x?.currency,v=I=>{n(I),d("edit")},N=()=>{n(null),d("create")},S=()=>{d("list"),n(null)},C=I=>{n(I),d("edit")};return yt("div",{className:e,children:[yt("div",{className:"af-mb-6",children:[Ve("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),Ve("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),yt(Da,{value:i,onValueChange:I=>l(I),children:[yt(ka,{className:"af-mb-4",children:[yt(Ht,{value:"products",className:"af-gap-2",children:[Ve($i,{className:"af-h-4 af-w-4"}),"Products"]}),yt(Ht,{value:"orders",className:"af-gap-2",children:[Ve(zi,{className:"af-h-4 af-w-4"}),"Orders"]}),yt(Ht,{value:"customers",className:"af-gap-2",children:[Ve(qi,{className:"af-h-4 af-w-4"}),"Customers"]}),yt(Ht,{value:"setup",className:"af-gap-2",children:[Ve(ji,{className:"af-h-4 af-w-4"}),"Setup"]})]}),Ve(Mt,{value:"products",children:m==="list"?Ve(Ma,{productsState:g,onSelectProduct:v,onCreateProduct:N}):yt("div",{children:[yt("div",{className:"af-mb-6",children:[yt(h,{variant:"ghost",size:"sm",onClick:S,className:"af-mb-2 af--ml-2",children:[Ve(Mi,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),Ve("h3",{className:"af-text-lg af-font-semibold",children:m==="create"?"New Product":c?.name})]}),m==="create"&&!b?Ve("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:w?yt("div",{className:"af-text-destructive",children:["Error: ",w.message]}):Ve("div",{className:"af-text-muted-foreground",children:"Loading..."})}):Ve(za,{productsState:g,product:m==="edit"?c:null,currency:b??"usd",onSaved:C},m==="edit"?c?.id??"edit":"new")]})}),Ve(Mt,{value:"orders",children:Ve(xa,{onRefund:s})}),Ve(Mt,{value:"customers",children:Ve(es,{})}),Ve(Mt,{value:"setup",children:Ve(ts,{onConnectStripe:a,onUpgradePlan:r})})]})]})}import*as Nr from"react";import*as Ft from"react";function ss({refreshKey:e}={}){let{api:t}=Y(),[a,s]=Ft.useState(null),[r,i]=Ft.useState(!0),[l,m]=Ft.useState(null),d=Ft.useRef(0),c=Ft.useCallback(async()=>{let n=++d.current;try{i(!0),m(null);let g=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(n!==d.current)return;s(g)}catch(g){if(n!==d.current)return;m(g instanceof Error?g:new Error("Failed to fetch summary"))}finally{n===d.current&&i(!1)}},[t,e]);return Ft.useEffect(()=>{c()},[c]),{summary:a,isLoading:r,error:l,refetch:c}}import{Fragment as Ts,jsx as je,jsxs as ks}from"react/jsx-runtime";function xr(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 wr({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:r,className:i}){let{summary:l,isLoading:m,error:d,refetch:c}=ss({refreshKey:e}),[n,g]=Nr.useState(!1),x=je("div",{className:"af-mb-6",children:d&&!l?je(St,{message:"Couldn't load your revenue summary.",onRetry:()=>c()}):je("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:m||!l?ks(Ts,{children:[je(at,{label:"This week",children:je(W,{className:"af-h-6 af-w-24"})}),je(at,{label:"Today",children:je(W,{className:"af-h-6 af-w-24"})}),je(at,{label:"Needs attention",children:je(W,{className:"af-h-6 af-w-10"})})]}):je(Ts,{children:(()=>{let w=xr(l.revenue.d7,l.currency),b=xr(l.revenue.today,l.currency);return ks(Ts,{children:[je(at,{label:"This week",detail:w.extra.length>0?je("div",{children:w.extra.map(v=>je("div",{children:v},v))}):void 0,children:w.headline}),je(at,{label:"Today",detail:b.extra.length>0?je("div",{children:b.extra.map(v=>je("div",{children:v},v))}):void 0,children:b.headline}),je(at,{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 ks(oa,{title:"Orders",onBackToWebsite:r,hideBackButton:n,className:i,children:[x,je(xa,{refreshKey:e,initialOrderId:t,onDetailOpenChange:g,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as Yt from"react";import{ImageOff as Ji,Package as Zi,Search as Yi}from"lucide-react";import*as Ut from"react";import{ArrowLeft as Ki,ImageOff as Qi}from"lucide-react";import{jsx as Rt,jsxs as La}from"react/jsx-runtime";var Pr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",la="af-text-xs af-text-muted-foreground",rs="af-text-sm af-font-medium af-tabular-nums",Gi=3;function Wi(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let d=e.min_amount??t?.min_amount??null,c=e.max_amount??t?.max_amount??null;return d!==null&&c!==null?{text:`Buyer chooses (${U(d,a)} \u2013 ${U(c,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)}`,m=t?.compare_at_amount??null;return{text:l,compareAt:m!==null&&m>i?U(m,a):null}}function ns({product:e,className:t}){let a=Wi(e);return La("div",{className:t,children:[Rt("span",{className:rs,children:a.text}),a.compareAt&&Rt("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function is({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?Rt(G,{variant:"destructive",children:"Out of stock"}):t.low_stock?La(G,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?Rt(G,{variant:"secondary",children:"Backorder"}):t.available===null?null:La(G,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?Rt(G,{variant:"warning",children:"Low stock"}):null}function os(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function ls(e){return e.map(t=>U(t.amount,t.currency)).join(" + ")}function Sr(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 Rr({variant:e}){let t=e.inventory;if(!t||!t.tracked)return Rt("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?La("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Rt("span",{className:"af-tabular-nums",children:Math.max(0,a)}),Rt(G,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?Rt(G,{variant:"destructive",children:"Out of stock"}):La("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Rt("span",{className:"af-tabular-nums",children:a}),a<=Gi&&Rt(G,{variant:"warning",children:"Low"})]})}import{jsx as V,jsxs as he}from"react/jsx-runtime";function Ba({title:e,children:t,className:a}){return he("section",{className:E("af-rounded-lg af-border af-p-4",a),children:[V("h4",{className:Pr,children:e}),V("div",{className:"af-mt-3",children:t})]})}function Cr({src:e,className:t}){let[a,s]=Ut.useState(!1);return Ut.useEffect(()=>s(!1),[e]),!e||a?V("div",{"aria-hidden":"true",className:E("af-flex af-items-center af-justify-center af-bg-muted",t),children:V(Qi,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):V("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:E("af-object-cover",t)})}function Tr({product:e,showStats:t=!1,onBack:a}){let{api:s}=Y(),[r,i]=Ut.useState(null),[l,m]=Ut.useState(!0),[d,c]=Ut.useState(null),[n,g]=Ut.useState(0),[x,w]=Ut.useState(0);Ut.useEffect(()=>{let _=!1;return m(!0),c(null),s.getProduct(e.id).then(F=>{_||i(F)}).catch(F=>{_||c(F instanceof Error?F:new Error("Failed to load product"))}).finally(()=>{_||m(!1)}),()=>{_=!0}},[s,e.id,n]);let b=r?{...e,...r}:e,v=b.images.length>0?b.images:e.images,N=v[x]??v[0],S=os(b),C=t?b.stats:void 0,I=r?.variants??[],Q=I.length>1;return he("div",{children:[he("div",{className:"af-mb-6",children:[he(h,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[V(Ki,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),he("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[V("h3",{className:"af-text-xl af-font-semibold af-break-words",children:b.name}),V(G,{variant:b.active?"success":"secondary",children:b.active?"Active":"Draft"}),V(is,{product:b})]}),V(ns,{product:b,className:"af-mt-1"}),!b.active&&V("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),he("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[he("div",{className:"af-space-y-2",children:[V(Cr,{src:N,className:"af-h-48 af-w-full af-rounded-md af-border"}),v.length>1&&V("div",{className:"af-flex af-flex-wrap af-gap-2",children:v.map((_,F)=>V("button",{type:"button",onClick:()=>w(F),"aria-label":`Show photo ${F+1} of ${v.length}`,"aria-pressed":F===x,className:E("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:V(Cr,{src:_,className:"af-h-12 af-w-12 af-rounded-md"})},`${_}-${F}`))})]}),he("div",{className:"af-space-y-6",children:[b.description&&V(Ba,{title:"Description",children:V("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:b.description})}),l?he(Ba,{title:"Variants",children:[V("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(_=>he("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[V(W,{className:"af-h-4 af-w-28"}),V(W,{className:"af-h-4 af-w-20"}),V(W,{className:"af-h-4 af-w-16"})]},_))}),V("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):d?V(St,{message:"Couldn't load this product's variants.",onRetry:()=>g(_=>_+1)}):Q?V(Ba,{title:`Variants \xB7 ${I.length}`,children:V("div",{className:"af-overflow-x-auto",children:he(Re,{children:[V(Ce,{children:he(re,{children:[V(L,{children:"Variant"}),V(L,{children:"SKU"}),V(L,{className:"af-text-right",children:"Price"}),V(L,{children:"Stock"})]})}),V(Te,{children:I.map(_=>he(re,{children:[he(B,{className:"af-font-medium",children:[_.title||_.option_values.map(F=>F.value).join(" / ")||"\u2014",!_.active&&V(G,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),V(B,{className:"af-text-muted-foreground",children:_.sku?V("code",{className:"af-font-mono af-text-xs af-break-all",children:_.sku}):"\u2014"}),he(B,{className:"af-whitespace-nowrap af-text-right",children:[V("div",{className:rs,children:Sr(_)}),_.compare_at_amount!==null&&_.unit_amount!==null&&_.compare_at_amount>_.unit_amount&&V("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:U(_.compare_at_amount,_.currency)})]}),V(B,{className:"af-text-sm",children:V(Rr,{variant:_})})]},_.id))})]})})}):null,V(Ba,{title:"Details",children:he("dl",{className:"af-space-y-2",children:[he("div",{children:[V("dt",{className:la,children:"Delivery"}),V("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&&he("div",{children:[V("dt",{className:la,children:"Sends buyers to"}),V("dd",{className:"af-break-all af-text-sm",children:b.fulfillment.url})]}),he("div",{children:[V("dt",{className:la,children:"Shipping address"}),V("dd",{className:"af-text-sm",children:b.collect_shipping_address?"Collected at checkout":"Not collected"})]}),he("div",{children:[V("dt",{className:la,children:"Most one buyer can order"}),V("dd",{className:"af-text-sm af-tabular-nums",children:b.max_quantity})]})]})}),C&&V(Ba,{title:"Last 30 days",children:he("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[he("div",{children:[V("dt",{className:la,children:"Units sold"}),V("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:C.units_sold})]}),he("div",{children:[V("dt",{className:la,children:"Orders"}),V("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:C.orders})]}),he("div",{children:[V("dt",{className:la,children:"Gross"}),V("dd",{className:rs,children:C.gross.length>0?ls(C.gross):"\u2014"})]})]})}),V("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 Pa,jsx as H,jsxs as we}from"react/jsx-runtime";var Xi={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},eo=["all","active","draft","low_stock","out_of_stock"];function kr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function _r(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function to(e){return e.inventory?.out_of_stock??!1}function ao(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return _r(e);case"out_of_stock":return to(e);default:return!0}}function so({product:e,showStats:t,onOpen:a}){let s=e.images[0],r=t?e.stats:void 0,i=os(e),l=e.variant_count??0;return we("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?H("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):H("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:H(Ji,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),we("div",{className:"af-space-y-2 af-p-3",children:[we("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[we("div",{className:"af-min-w-0",children:[H("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),H(ns,{product:e,className:"af-mt-0.5"})]}),!e.active&&H(G,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),we("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[H(is,{product:e}),l>1&&we(G,{variant:"outline",children:[l," variants"]}),i&&H(G,{variant:"outline",children:i})]}),r&&we("div",{className:"af-text-xs af-text-muted-foreground",children:[r.units_sold," sold",r.gross.length>0?` \xB7 ${ls(r.gross)}`:""," ",H("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function ro(){return H("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=>we("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[H("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),we("div",{className:"af-space-y-2 af-p-3",children:[H(W,{className:"af-w-32"}),H(W,{className:"af-w-16"}),H(W,{className:"af-h-5 af-w-24"})]})]},e))})}function Or({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:r,isLoading:i,error:l,refetch:m}=wa({includeStats:t,refreshKey:e}),[d,c]=Yt.useState(null),[n,g]=Yt.useState("all"),[x,w]=Yt.useState(""),[b,v]=Yt.useState("newest"),N=Yt.useMemo(()=>{if(!t)return null;let D=null;for(let me of r)!me.stats||me.stats.units_sold===0||(!D||me.stats.units_sold>(D.stats?.units_sold??0))&&(D=me);return D},[r,t]),S=Yt.useMemo(()=>r.filter(_r).length,[r]),C=x.trim().toLowerCase(),I=Yt.useMemo(()=>{let me=[...r.filter(u=>ao(u,n)&&(!C||u.name.toLowerCase().includes(C)))];return b==="name"?me.sort((u,X)=>u.name.localeCompare(X.name)):b==="best_selling"?me.sort((u,X)=>(X.stats?.units_sold??0)-(u.stats?.units_sold??0)):me.sort((u,X)=>kr(X.created_at)-kr(u.created_at)),me},[r,n,C,b]),Q=n!=="all"||!!C,_=()=>{g("all"),w("")},F=i||l!==null&&r.length===0,M=H("div",{className:"af-mb-6",children:H("div",{className:E("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:F?we(Pa,{children:[H(at,{label:"Products",children:H(W,{className:"af-h-6 af-w-10"})}),t?we(Pa,{children:[H(at,{label:"Best seller",children:H(W,{className:"af-h-6 af-w-28"})}),H(at,{label:"Low stock",children:H(W,{className:"af-h-6 af-w-10"})})]}):H(at,{label:"Active",children:H(W,{className:"af-h-6 af-w-10"})})]}):we(Pa,{children:[H(at,{label:"Products",children:r.length}),t?we(Pa,{children:[H(at,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:N?`${N.stats?.units_sold??0} sold, last 30 days`:void 0,children:N?H("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:N.name}):H("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),H(at,{label:"Low stock",children:S})]}):H(at,{label:"Active",children:r.filter(D=>D.active).length})]})})}),K=we("div",{className:"af-mb-4 af-space-y-3",children:[we("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[H("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:eo.map(D=>H("button",{type:"button","aria-pressed":n===D,onClick:()=>g(D),className:E("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===D?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Xi[D]},D))}),we("div",{className:"af-relative af-w-full af-max-w-xs",children:[H(Yi,{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"}),H(ne,{type:"text",value:x,onChange:D=>w(D.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),we(gt,{value:b,onValueChange:D=>v(D),children:[H(lt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:H(vt,{})}),we(ft,{children:[H(ve,{value:"newest",children:"Newest"}),H(ve,{value:"name",children:"Name A\u2013Z"}),t&&H(ve,{value:"best_selling",children:"Best selling"})]})]}),Q&&H(h,{type:"button",variant:"ghost",size:"sm",onClick:_,children:"Clear filters"})]}),i&&r.length===0?H(W,{className:"af-h-4 af-w-28"}):H("p",{className:"af-text-sm af-text-muted-foreground",children:Q?`${I.length} of ${r.length} products`:`${r.length} ${r.length===1?"product":"products"}${S>0?` \xB7 ${S} low stock`:""}`})]}),$;return d?$=H(Tr,{product:d,showStats:t,onBack:()=>{c(null),m()}},d.id):i&&r.length===0?$=we(Pa,{children:[K,H(ro,{}),H("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):l&&r.length===0?$=H("div",{className:"af-flex af-justify-center af-py-8",children:H(St,{message:"Couldn't load your products.",onRetry:()=>m()})}):r.length===0?$=we(ma,{icon:H(Zi,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",H("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):$=we(Pa,{children:[K,l&&H("div",{className:"af-mb-4",children:H(St,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>m()})}),I.length===0?we(ma,{children:["No products match these filters.",H("br",{}),H(h,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:_,children:"Show all products"})]}):H("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:I.map(D=>H(so,{product:D,showStats:t,onOpen:()=>c(D)},D.id))})]}),we(oa,{title:"Products",onBackToWebsite:a,hideBackButton:!!d,className:s,children:[!d&&M,$]})}import*as Ct from"react";import{ArrowLeft as Ir,Check as no,ChevronLeft as Lr,ChevronRight as Br,ClipboardCopy as io,Mail as Os,Search as oo,Users as lo}from"lucide-react";import*as ct from"react";function fs({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=Y(),[s,r]=ct.useState([]),[i,l]=ct.useState(!0),[m,d]=ct.useState(null),[c,n]=ct.useState(0),[g]=ct.useState(e),[x,w]=ct.useState(""),b=ct.useRef(0),v=ct.useCallback(async()=>{let N=++b.current;try{l(!0),d(null);let S={limit:g,offset:c*g};x.trim()&&(S.q=x.trim());let C=await a.getPeople(S);if(N!==b.current)return;r(C.people)}catch(S){if(N!==b.current)return;d(S instanceof Error?S:new Error("Failed to fetch people"))}finally{N===b.current&&l(!1)}},[a,c,g,x,t]);return ct.useEffect(()=>{v()},[v]),{people:s,isLoading:i,error:m,page:c,pageSize:g,hasNextPage:s.length===g,hasPreviousPage:c>0,setPage:n,q:x,setQ:N=>{w(N),n(0)},refetch:v}}import*as Vt from"react";function ds(e,{refreshKey:t}={}){let{api:a}=Y(),[s,r]=Vt.useState(null),[i,l]=Vt.useState(e!==null),[m,d]=Vt.useState(null),c=Vt.useRef(0),n=Vt.useCallback(async()=>{if(e===null){r(null),l(!1),d(null);return}let g=++c.current;try{l(!0),d(null);let x=await a.getPerson(e);if(g!==c.current)return;r(x)}catch(x){if(g!==c.current)return;d(x instanceof Error?x:new Error("Failed to fetch person"))}finally{g===c.current&&l(!1)}},[a,e,t]);return Vt.useEffect(()=>{n()},[n]),{person:s,isLoading:i,error:m,refetch:n}}import{jsx as o,jsxs as A}from"react/jsx-runtime";var _s="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",fo="af-text-xs af-text-muted-foreground";function Sa(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 Ls(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function co(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function uo({value:e,label:t}){let[a,s]=Ct.useState(!1);return co()?A(h,{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(no,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):o(io,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function Er(e){return A("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&A(G,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&o(G,{variant:"secondary",children:"Contact form"})]})}function Dr(e){return e.name?e.name:e.email?e.email:o("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,po=40;function go(e){let t=Object.entries(e).filter(([r])=>!r.startsWith("_")),s=t.find(([r,i])=>mo.test(r)&&typeof i=="string"&&i.trim())??t.filter(([,r])=>typeof r=="string"&&r.trim().length>=po).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 vo(e){return e.replace(/_/g," ")}function bo(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function yo({data:e}){let{message:t,rest:a}=go(e);return t===null&&a.length===0?o("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):A("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])=>A("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[o("dt",{className:E(fo,"af-w-28 af-shrink-0 af-capitalize"),children:vo(s)}),o("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:bo(r)})]},s))})]})}function Ar({formName:e,createdAt:t,data:a}){return A("div",{className:"af-rounded-md af-border af-p-3",children:[A("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[o(G,{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:Sa(t)})]}),o(yo,{data:a})]})}function ho(e){return e.charged_total??e.amount_total}function xo({email:e,refreshKey:t,onBack:a}){let{person:s,isLoading:r,error:i,refetch:l}=ds(e,{refreshKey:t}),m=Ls(e,s?.submissions[0]?.form_name);return A("div",{children:[A("div",{className:"af-mb-6",children:[A(h,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[o(Ir,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),A("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[A("div",{className:"af-min-w-0",children:[r?o(W,{className:"af-h-7 af-w-48"}):o("h3",{className:"af-text-xl af-font-semibold af-break-all",children:s?.name||e}),A("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(uo,{value:e,label:"Copy email address"})]})]}),o(h,{asChild:!0,children:A("a",{href:m,children:[o(Os,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),r?A("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(d=>A("div",{className:"af-rounded-md af-border af-p-3",children:[o(W,{className:"af-w-40"}),o(W,{className:"af-mt-2 af-w-64"})]},d)),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(St,{message:"Couldn't load this person.",onRetry:()=>l()})}):A("div",{className:"af-space-y-6",children:[s.customer&&A("div",{children:[o("h4",{className:E(_s,"af-mb-3"),children:"Customer"}),A("dl",{className:"af-space-y-1 af-text-sm",children:[s.customer.name&&A("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&&A("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})]}),A("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:Sa(s.customer.created_at)})]})]})]}),s.orders.length>0&&A("div",{children:[o("h4",{className:E(_s,"af-mb-3"),children:"Purchases"}),o("div",{className:"af-overflow-x-auto",children:A(Re,{children:[o(Ce,{children:A(re,{children:[o(L,{children:"Order"}),o(L,{children:"Date"}),o(L,{className:"af-text-right",children:"Total"}),o(L,{children:"Status"})]})}),o(Te,{children:s.orders.map(d=>A(re,{children:[o(B,{className:"af-whitespace-nowrap af-font-medium",children:Zt(d)}),o(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Sa(d.created_at)}),o(B,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:U(ho(d),d.currency)}),o(B,{children:o(da,{status:d.status})})]},d.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&&A("div",{children:[o("h4",{className:E(_s,"af-mb-3"),children:"Messages"}),o("div",{className:"af-space-y-3",children:s.submissions.map(d=>o(Ar,{formName:d.form_name,createdAt:d.created_at,data:d.data},d.id))})]})]})]})}function No({submissionId:e,onBack:t}){let{api:a}=Y(),[s,r]=Ct.useState(null),[i,l]=Ct.useState(!0),[m,d]=Ct.useState(null),[c,n]=Ct.useState(0);return Ct.useEffect(()=>{let g=!1;return l(!0),d(null),a.getSubmission(e).then(x=>{g||r(x)}).catch(x=>{g||d(x instanceof Error?x:new Error("Failed to load submission"))}).finally(()=>{g||l(!1)}),()=>{g=!0}},[a,e,c]),A("div",{children:[A("div",{className:"af-mb-6",children:[A(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[o(Ir,{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(W,{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:Sa(s.metadata.submitted_at)})]}),i?A("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[o(W,{className:"af-w-40"}),o(W,{className:"af-mt-2 af-w-64"}),o(W,{className:"af-mt-2 af-w-52"}),o("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):m||!s?o("div",{className:"af-flex af-justify-center af-py-8",children:o(St,{message:"Couldn't load this submission.",onRetry:()=>n(g=>g+1)})}):A("div",{className:"af-space-y-3",children:[o(Ar,{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 wo={all:"All",customers:"Customers",leads:"Leads"},Po=["all","customers","leads"];function So(e,t){return t==="customers"?e.sources.includes("customer"):t==="leads"?e.sources.includes("lead"):!0}function Fr({refreshKey:e,onBackToWebsite:t,className:a}){let{people:s,isLoading:r,error:i,page:l,pageSize:m,hasNextPage:d,hasPreviousPage:c,setPage:n,q:g,setQ:x,refetch:w}=fs({refreshKey:e}),[b,v]=Ct.useState({kind:"list"}),[N,S]=Ct.useState(""),[C,I]=Ct.useState("all"),Q=$=>{$.email?v({kind:"person",email:$.email}):$.submission_id&&v({kind:"submission",submissionId:$.submission_id})},_=()=>{v({kind:"list"}),w()},F=$=>{let D=$.trim();D!==g&&x(D)},M=s.filter($=>So($,C)),K;if(b.kind==="person")K=o(xo,{email:b.email,refreshKey:e,onBack:_});else if(b.kind==="submission")K=o(No,{submissionId:b.submissionId,onBack:_});else{let $=A("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:Po.map(D=>o("button",{type:"button","aria-pressed":C===D,onClick:()=>I(D),className:E("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",C===D?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:wo[D]},D))}),A("div",{className:"af-relative af-w-full af-max-w-xs",children:[o(oo,{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(ne,{type:"text",value:N,onChange:D=>S(D.target.value),onBlur:()=>F(N),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),F(N))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),g&&o(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>{S(""),x("")},children:"Clear search"})]});if(r)K=A("div",{children:[$,o("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(D=>A("div",{className:"af-rounded-md af-border af-p-3",children:[A("div",{className:"af-flex af-items-center af-justify-between",children:[o(W,{className:"af-h-4 af-w-32"}),o(W,{className:"af-h-4 af-w-16"})]}),o(W,{className:"af-mt-2 af-h-5 af-w-28"}),o(W,{className:"af-mt-2 af-h-3 af-w-56"})]},D))}),o("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:A(Re,{children:[o(Ce,{children:A(re,{children:[o(L,{children:"Person"}),o(L,{children:"Came from"}),o(L,{children:"Latest message"}),o(L,{children:"Last activity"}),o(L,{className:"af-w-8"}),o(L,{className:"af-w-8"})]})}),o(Te,{"aria-hidden":"true",children:[0,1,2,3,4].map(D=>A(re,{children:[o(B,{children:o(W,{className:"af-h-4 af-w-40"})}),o(B,{children:o(W,{className:"af-h-5 af-w-24"})}),o(B,{children:o(W,{className:"af-h-4 af-w-56"})}),o(B,{children:o(W,{className:"af-h-4 af-w-24"})}),o(B,{}),o(B,{})]},D))})]})}),o("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)K=A("div",{children:[$,o("div",{className:"af-flex af-justify-center af-py-8",children:o(St,{message:"Couldn't load your leads.",onRetry:()=>w()})})]});else if(M.length===0&&l===0){let D=!!g||C!=="all";K=A("div",{children:[D&&$,D?o(ma,{children:g?"Nobody matches that search.":C==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):o(ma,{icon:o(lo,{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)K=A("div",{children:[$,o(ma,{children:"No more results."}),o("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:A(h,{variant:"outline",size:"sm",onClick:()=>n(l-1),children:[o(Lr,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let D=l*m+1,me=l*m+s.length;K=A("div",{children:[$,o("div",{className:"af-space-y-3 lg:af-hidden",children:M.map((u,X)=>A("div",{onClick:()=>Q(u),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[A("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[A("div",{className:"af-min-w-0",children:[o("button",{type:"button",onClick:xe=>{xe.stopPropagation(),Q(u)},"aria-label":`Open ${u.name||u.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:Dr(u)}),u.name&&u.email&&o("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:u.email})]}),A("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:Sa(u.last_activity_at)}),u.email&&o(h,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:o("a",{href:Ls(u.email),onClick:xe=>xe.stopPropagation(),"aria-label":`Email ${u.email}`,children:o(Os,{className:"af-h-4 af-w-4"})})})]})]}),o("div",{className:"af-mt-2",children:Er(u)}),u.latest_message_excerpt&&o("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:u.latest_message_excerpt})]},u.email??u.submission_id??X))}),o("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:A(Re,{children:[o(Ce,{children:A(re,{children:[o(L,{children:"Person"}),o(L,{children:"Came from"}),o(L,{children:"Latest message"}),o(L,{children:"Last activity"}),o(L,{className:"af-w-8",children:o("span",{className:"af-sr-only",children:"Reply"})}),o(L,{className:"af-w-8"})]})}),o(Te,{children:M.map((u,X)=>A(re,{onClick:()=>Q(u),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[A(B,{className:"af-max-w-[260px] af-font-medium",children:[o("button",{type:"button",onClick:xe=>{xe.stopPropagation(),Q(u)},"aria-label":`Open ${u.name||u.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:Dr(u)}),u.name&&u.email&&o("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:u.email})]}),o(B,{children:Er(u)}),o(B,{className:"af-max-w-[320px]",children:u.latest_message_excerpt?o("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:u.latest_message_excerpt}):o("span",{className:"af-text-muted-foreground",children:"\u2014"})}),o(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Sa(u.last_activity_at)}),o(B,{className:"af-w-8",children:u.email&&o(h,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:o("a",{href:Ls(u.email),onClick:xe=>xe.stopPropagation(),"aria-label":`Email ${u.email}`,children:o(Os,{className:"af-h-4 af-w-4"})})})}),o(B,{className:"af-w-8 af-text-right",children:o(Br,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},u.email??u.submission_id??X))})]})}),A("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:C==="all"?`Showing ${D}-${me}`:`${M.length} of ${s.length} on this page`}),A("div",{className:"af-flex af-items-center af-gap-2",children:[A(h,{variant:"outline",size:"sm",onClick:()=>n(l-1),disabled:!c,children:[o(Lr,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),A(h,{variant:"outline",size:"sm",onClick:()=>n(l+1),disabled:!d,children:["Next",o(Br,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return o(oa,{title:"Leads",onBackToWebsite:t,hideBackButton:b.kind!=="list",className:a,children:K})}export{ea as AifeaturesApiError,zr as AifeaturesProvider,Ya as CustomerDetail,es as CustomersList,Va as FormSettings,Ua as FormSubmissions,Ks as FormsDashboard,Ia as FormsList,Fr as LeadsView,Ka as OrderDetail,da as OrderStatusBadge,xa as OrdersList,wr as OrdersView,hr as PaymentsDashboard,ts as PaymentsSetup,za as ProductSettings,Ma as ProductsList,Or as ProductsView,Fa as SubmissionDetail,$a as VariantsEditor,oa as ViewShell,wt as chargedTotal,us as createApiClient,U as formatPrice,Et as isZeroDecimalCurrency,Qe as toMajorUnits,Pt as toMinorUnits,Y as useAifeatures,Y as useAifeaturesContext,ss as useBusinessSummary,Za as useCustomers,ya as useForms,ja as useOrders,Na as usePaymentsStatus,fs as usePeople,ds as usePerson,wa as useProducts,Aa as useSubmissions};
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};