@aifeatures/admin-react 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -4
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var Vi=Object.create;var Xs=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var Hi=Object.getOwnPropertyNames;var zi=Object.getPrototypeOf,qi=Object.prototype.hasOwnProperty;var ji=(e,a)=>{for(var s in a)Xs(e,s,{get:a[s],enumerable:!0})},pr=(e,a,s,t)=>{if(a&&typeof a=="object"||typeof a=="function")for(let n of Hi(a))!qi.call(e,n)&&n!==s&&Xs(e,n,{get:()=>a[n],enumerable:!(t=$i(a,n))||t.enumerable});return e};var ne=(e,a,s)=>(s=e!=null?Vi(zi(e)):{},pr(a||!e||!e.__esModule?Xs(s,"default",{value:e,enumerable:!0}):s,e)),Gi=e=>pr(Xs({},"__esModule",{value:!0}),e);var Cl={};ji(Cl,{AifeaturesApiError:()=>na,AifeaturesProvider:()=>vr,AnalyticsView:()=>Bi,CustomerDetail:()=>Ms,CustomersList:()=>Us,FormSettings:()=>Es,FormSubmissions:()=>Rs,FormsDashboard:()=>An,FormsList:()=>hs,InvoiceDetail:()=>bn,InvoiceLabelBadge:()=>us,InvoicesList:()=>es,InvoicesView:()=>er,LeadsView:()=>Zn,MAX_ANALYTICS_FILTERS:()=>is,MAX_ANALYTICS_FILTER_VALUES:()=>os,OrderDetail:()=>Bs,OrderStatusBadge:()=>$a,OrdersList:()=>Za,OrdersView:()=>Wn,PaymentsDashboard:()=>Gn,PaymentsSetup:()=>Vs,ProductSettings:()=>Ds,ProductsList:()=>Is,ProductsView:()=>Kn,REALTIME_FAILURES_BEFORE_ERROR:()=>Tn,REALTIME_POLL_MS:()=>Pn,RetainerStatusBadge:()=>hn,RetainersPanel:()=>ts,SubmissionDetail:()=>Ns,SubscriptionsView:()=>Qn,VariantsEditor:()=>As,ViewShell:()=>bt,WebhookDeliveries:()=>Cs,WebhookSettings:()=>ks,chargedTotal:()=>Zt,createApiClient:()=>tn,formatPrice:()=>W,isZeroDecimalCurrency:()=>fa,toMajorUnits:()=>vt,toMinorUnits:()=>Qt,useAifeatures:()=>te,useAifeaturesContext:()=>te,useAnalytics:()=>Gs,useBusinessSummary:()=>$s,useCustomers:()=>Fs,useEventDestinations:()=>Ps,useForms:()=>Wa,useInvoices:()=>Xa,useOrders:()=>Ls,usePaymentsStatus:()=>as,usePeople:()=>zs,usePerson:()=>qs,useProducts:()=>ss,useRealtimeVisitors:()=>Ws,useRetainers:()=>ns,useSubmissions:()=>ws,useSubscriptions:()=>js});module.exports=Gi(Cl);var Fa=ne(require("react"),1);function en(e,a){let s=new URLSearchParams({period:String(e)});return a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var na=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function En(e,a){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${a}`}function tn(e,a="https://aifeatures.dev"){async function s(t,n={}){let i=`${a}${t}`,o=await fetch(i,{...n,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...n.headers}});if(!o.ok){let g;try{g=await o.json()}catch{}throw new na(En(g?.error,o.status),o.status,g)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(t){return s(`/api/v1/forms/${t}`)},async createForm(t){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(t)})},async updateForm(t,n){return s(`/api/v1/forms/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteForm(t){await s(`/api/v1/forms/${t}`,{method:"DELETE"})},async getSubmissions(t,n={}){let i=new URLSearchParams;n.limit!==void 0&&i.set("limit",String(n.limit)),n.offset!==void 0&&i.set("offset",String(n.offset));let o=i.toString(),g=`/api/v1/forms/${t}/submissions${o?`?${o}`:""}`;return s(g)},async getSubmission(t){return s(`/api/v1/submissions/${t}`)},async deleteSubmission(t){await s(`/api/v1/submissions/${t}`,{method:"DELETE"})},async downloadAttachment(t,n){let i=typeof n=="string"?{name:n}:n,o=i.name,g=i.id??i.name,v=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(g)}`,h=await fetch(v,{headers:{Authorization:`Bearer ${e}`}});if(!h.ok){let p;try{p=await h.json()}catch{}throw new na(En(p?.error,h.status),h.status,p)}let r=await h.blob(),b=URL.createObjectURL(r),w=document.createElement("a");w.href=b,w.download=o,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(b)},async getPaymentsStatus(){return s("/api/v1/payments/status")},async getProducts(t={}){let n=new URLSearchParams;t.include&&n.set("include",t.include);let i=n.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(t){return s(`/api/v1/products/${t}`)},async createProduct(t){return s("/api/v1/products",{method:"POST",body:JSON.stringify(t)})},async updateProduct(t,n){return s(`/api/v1/products/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteProduct(t){await s(`/api/v1/products/${t}`,{method:"DELETE"})},async attachProductFile(t,n){let i=new FormData;i.append("file",n);let o=await fetch(`${a}/api/v1/products/${t}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!o.ok){let g;try{g=await o.json()}catch{}throw new na(En(g?.error,o.status),o.status,g)}return o.json()},async attachProductFileFromUrl(t,n){return s(`/api/v1/products/${t}/file`,{method:"POST",body:JSON.stringify({source_url:n})})},async createOption(t,n){return s(`/api/v1/products/${t}/options`,{method:"POST",body:JSON.stringify(n)})},async updateOption(t,n){return s(`/api/v1/options/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteOption(t){await s(`/api/v1/options/${t}`,{method:"DELETE"})},async createVariant(t,n){return s(`/api/v1/products/${t}/variants`,{method:"POST",body:JSON.stringify(n)})},async updateVariant(t,n){return s(`/api/v1/variants/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteVariant(t){await s(`/api/v1/variants/${t}`,{method:"DELETE"})},async setVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory`,{method:"PUT",body:JSON.stringify(n)})},async adjustVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory/adjust`,{method:"POST",body:JSON.stringify(n)})},async getCustomers(t={}){let n=new URLSearchParams;t.email?n.set("email",t.email):t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(t){return s(`/api/v1/customers/${t}`)},async getOrders(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.source&&n.set("source",t.source),t.excludeStatus?.length&&n.set("exclude_status",t.excludeStatus.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.unfulfilledOnly&&n.set("unfulfilled_only","true"),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(t){return s(`/api/v1/orders/${t}`)},async getInvoices(t={}){let n=new URLSearchParams;t.labels?.length&&n.set("label",t.labels.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.customerId&&n.set("customer_id",t.customerId),t.q&&n.set("q",t.q),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.includeAggregates&&n.set("include","aggregates"),t.retainerId&&n.set("retainer_id",t.retainerId),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(t){return s(`/api/v1/invoices/${t}`)},async getInvoicePreview(t){return s(`/api/v1/invoices/${t}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(t={}){let n=new URLSearchParams;t.statuses?.length&&n.set("status",t.statuses.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/retainers${i?`?${i}`:""}`)},async getRetainer(t){return s(`/api/v1/retainers/${t}`)},async resendOrderReceipt(t){await s(`/api/v1/orders/${t}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(t){return s(`/api/v1/orders/${t}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(t,n){return s(`/api/v1/orders/${t}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:n.fulfilled,...n.trackingNumber!==void 0?{tracking_number:n.trackingNumber}:{}})})},async getSubscriptions(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getAnalyticsStatus(){return s("/api/v1/analytics/status")},async getAnalyticsSummary(t,n){return s(`/api/v1/analytics/summary?${en(t,n)}`)},async getAnalyticsTimeseries(t,n){return s(`/api/v1/analytics/timeseries?${en(t,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(t,n){return s(`/api/v1/analytics/channels?${en(t,n)}`)},async getAnalyticsBreakdown(t,n,i){let o=t.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${en(n,i)}`)},async getBusinessSummary(t){let n=new URLSearchParams;return n.set("tz_offset_minutes",String(t.tzOffsetMinutes)),s(`/api/v1/summary?${n.toString()}`)},async getPeople(t={}){let n=new URLSearchParams;t.since&&n.set("since",t.since),t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/people${i?`?${i}`:""}`)},async getPerson(t){return s(`/api/v1/people/${encodeURIComponent(t)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(t){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(t)})},async updateEventDestination(t,n){return s(`/api/v1/event-destinations/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteEventDestination(t){await s(`/api/v1/event-destinations/${t}`,{method:"DELETE"})},async rotateEventDestinationSecret(t){return s(`/api/v1/event-destinations/${t}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(t){return(await s(`/api/v1/event-destinations/${t}/secret`)).secret},async getEventDeliveries(t,n){let i=n===void 0?"":`?limit=${n}`;return(await s(`/api/v1/event-destinations/${t}/deliveries${i}`)).deliveries},async retryEventDelivery(t,n){return s(`/api/v1/event-destinations/${t}/deliveries/${n}/retry`,{method:"POST"})}}}var Ba=require("react/jsx-runtime"),gr=Fa.createContext(null);function Wi(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 vr({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=Fa.useMemo(()=>Wi(e),[e]),o=Fa.useMemo(()=>tn(e,a),[e,a]),g=Fa.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?(0,Ba.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:(0,Ba.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Ba.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Ba.jsx)("p",{className:"af-text-sm af-text-destructive",children:i})]})}):(0,Ba.jsx)(gr.Provider,{value:g,children:(0,Ba.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function te(){let e=Fa.useContext(gr);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var Va=ne(require("react"),1),ls=require("lucide-react");var an=ne(require("react"),1),ra=ne(require("@radix-ui/react-tabs"),1);var br=require("clsx"),yr=require("tailwind-merge"),Ki=(0,yr.extendTailwindMerge)({prefix:"af-"});function G(...e){return Ki((0,br.clsx)(e))}var nn=require("react/jsx-runtime"),sn=ra.Root,bs=an.forwardRef(({className:e,...a},s)=>(0,nn.jsx)(ra.List,{ref:s,className:G("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),...a}));bs.displayName=ra.List.displayName;var va=an.forwardRef(({className:e,...a},s)=>(0,nn.jsx)(ra.Trigger,{ref:s,className:G("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),...a}));va.displayName=ra.Trigger.displayName;var ba=an.forwardRef(({className:e,...a},s)=>(0,nn.jsx)(ra.Content,{ref:s,className:G("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),...a}));ba.displayName=ra.Content.displayName;var hr=ne(require("react"),1),xr=require("@radix-ui/react-slot"),wr=require("class-variance-authority");var Nr=require("react/jsx-runtime"),Ji=(0,wr.cva)("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"}}),P=hr.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>(0,Nr.jsx)(t?xr.Slot:"button",{className:G(Ji({variant:a,size:s,className:e})),ref:i,...n}));P.displayName="Button";var ys=require("lucide-react");var Ea=ne(require("react"),1);var ya=require("react/jsx-runtime"),Le=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,ya.jsx)("table",{ref:s,className:G("af-w-full af-caption-bottom af-text-sm",e),...a})}));Le.displayName="Table";var Oe=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("thead",{ref:s,className:G("[&_tr]:af-border-b",e),...a}));Oe.displayName="TableHeader";var Be=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("tbody",{ref:s,className:G("[&_tr:last-child]:af-border-0",e),...a}));Be.displayName="TableBody";var Yi=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("tfoot",{ref:s,className:G("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...a}));Yi.displayName="TableFooter";var be=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("tr",{ref:s,className:G("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));be.displayName="TableRow";var F=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("th",{ref:s,className:G("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),...a}));F.displayName="TableHead";var M=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("td",{ref:s,className:G("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));M.displayName="TableCell";var Zi=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("caption",{ref:s,className:G("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));Zi.displayName="TableCaption";var ia=ne(require("react"),1);function Wa(){let{api:e}=te(),[a,s]=ia.useState([]),[t,n]=ia.useState(!0),[i,o]=ia.useState(null),g=ia.useCallback(async()=>{try{n(!0),o(null);let b=await e.getForms();s(b)}catch(b){o(b instanceof Error?b:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);ia.useEffect(()=>{g()},[g]);let v=ia.useCallback(async b=>{let w=await e.createForm(b);return s(p=>[...p,w]),w},[e]),h=ia.useCallback(async(b,w)=>{let p=await e.updateForm(b,w);return s(u=>u.map(f=>f.id===b?p:f)),p},[e]),r=ia.useCallback(async b=>{await e.deleteForm(b),s(w=>w.filter(p=>p.id!==b))},[e]);return{forms:a,isLoading:t,error:i,refetch:g,createForm:v,updateForm:h,deleteForm:r}}var Fe=require("react/jsx-runtime");function hs({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=Wa();return t?(0,Fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,Fe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,Fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,Fe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?(0,Fe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[(0,Fe.jsx)(ys.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Fe.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Fe.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Fe.jsx)("div",{className:a,children:(0,Fe.jsxs)(Le,{children:[(0,Fe.jsx)(Oe,{children:(0,Fe.jsxs)(be,{children:[(0,Fe.jsx)(F,{children:"Name"}),(0,Fe.jsx)(F,{children:"Endpoint"}),(0,Fe.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,Fe.jsx)(Be,{children:s.map(i=>(0,Fe.jsxs)(be,{children:[(0,Fe.jsx)(M,{className:"af-font-medium",children:i.name}),(0,Fe.jsx)(M,{children:(0,Fe.jsx)("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","")})}),(0,Fe.jsx)(M,{className:"af-text-right",children:(0,Fe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Fe.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[(0,Fe.jsx)(ys.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Fe.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[(0,Fe.jsx)(ys.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}var _r=require("lucide-react");var Sr=require("class-variance-authority");var Rr=require("react/jsx-runtime"),Qi=(0,Sr.cva)("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 Z({className:e,variant:a,...s}){return(0,Rr.jsx)("div",{className:G(Qi({variant:a}),e),...s})}var Ot=require("react/jsx-runtime"),Xi={form_notification:"Form notification",purchase_receipt:"Buyer receipt",merchant_sale:"Sale notification",subscription_payment_failed:"Payment reminder",subscription_cancellation:"Cancellation confirmation",subscription_address_change:"Address change confirmation",merchant_subscription_canceled:"Subscription cancellation notice",account_login:"Sign-in email",oversell_refund:"Refund notification",merchant_oversell:"Stock issue notification",dispute_opened:"Dispute notification"};function rn(e){switch(e.state){case"sending":return{label:"Sending",variant:"secondary",detail:null};case"sent":return{label:"Sent",variant:"secondary",detail:"Accepted for sending. Delivery has not been confirmed yet."};case"delivered":return{label:"Delivered",variant:"success",detail:"Accepted by the recipient\u2019s email server. This does not confirm it was read."};case"delivery_delayed":return{label:"Delayed",variant:"warning",detail:"Delivery is delayed. The email provider is still trying."};case"bounced":return{label:"Bounced",variant:"destructive",detail:"A receiving email server rejected this message."};case"complained":return{label:"Marked as spam",variant:"destructive",detail:"A recipient marked this email as spam. Do not resend it to that recipient."};case"suppressed":return{label:"Delivery blocked",variant:"destructive",detail:"The email provider blocked delivery to a recipient after a previous delivery problem or spam complaint."};case"failed":return{label:"Send failed",variant:"destructive",detail:"The email provider reported a sending failure."};case"unknown":return{label:"Delivery unconfirmed",variant:"warning",detail:"We could not confirm whether the email was sent. Check with the recipient before sending it again."}}}function In(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function eo(e){return["sending","sent","delivered","delivery_delayed","unknown","complained"].includes(e.state)?null:e.kind==="form_notification"?"Check this form\u2019s notification email addresses in its settings. The submission is saved here.":e.kind==="merchant_sale"||e.kind==="merchant_oversell"?"Check your notification email addresses. You can view and fulfill this order here.":e.kind==="dispute_opened"?"Check your notification email addresses and review this dispute in Stripe.":e.kind==="merchant_subscription_canceled"?"Check your notification email addresses. The subscription status is still shown here.":e.kind==="account_login"?"Ask the customer to confirm their email address and request a new sign-in link once the delivery problem is resolved.":e.kind==="purchase_receipt"?"Contact the buyer another way to confirm their email address. Payment and download details are still available on this order.":"Contact the customer another way to confirm their email address. Email delivery does not change their subscription or payment status."}function xs({deliveries:e,label:a="Email needs attention"}){return In(e)?(0,Ot.jsxs)("span",{className:"af-mt-1 af-flex af-items-center af-gap-1 af-text-xs af-font-normal af-text-amber-800 dark:af-text-amber-300",children:[(0,Ot.jsx)(_r.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function ha({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||In([n]));return t.length?(0,Ot.jsx)("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:t.map(n=>{let i=rn(n),o=eo(n);return(0,Ot.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Ot.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Ot.jsx)("span",{className:"af-font-medium",children:Xi[n.kind]??"Email notification"}),(0,Ot.jsx)(Z,{variant:i.variant,children:i.label})]}),(0,Ot.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&In([n])&&(0,Ot.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This status applies to the message sent to this group. It does not mean every recipient had a delivery problem."}),i.detail&&(0,Ot.jsx)("p",{className:"af-mt-1",children:i.detail}),o&&(0,Ot.jsx)("p",{className:"af-mt-1",children:o})]},n.id)})}):null}var Ss=ne(require("react"),1),xa=require("lucide-react");var Ma=ne(require("react"),1),Te=ne(require("@radix-ui/react-select"),1),Ka=require("lucide-react");var nt=require("react/jsx-runtime"),Wt=Te.Root;var Kt=Te.Value,Bt=Ma.forwardRef(({className:e,children:a,...s},t)=>(0,nt.jsxs)(Te.Trigger,{ref:t,className:G("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[a,(0,nt.jsx)(Te.Icon,{asChild:!0,children:(0,nt.jsx)(Ka.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Bt.displayName=Te.Trigger.displayName;var Pr=Ma.forwardRef(({className:e,...a},s)=>(0,nt.jsx)(Te.ScrollUpButton,{ref:s,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:(0,nt.jsx)(Ka.ChevronUp,{className:"af-h-4 af-w-4"})}));Pr.displayName=Te.ScrollUpButton.displayName;var Tr=Ma.forwardRef(({className:e,...a},s)=>(0,nt.jsx)(Te.ScrollDownButton,{ref:s,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:(0,nt.jsx)(Ka.ChevronDown,{className:"af-h-4 af-w-4"})}));Tr.displayName=Te.ScrollDownButton.displayName;var Ft=Ma.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>(0,nt.jsx)(Te.Portal,{children:(0,nt.jsxs)(Te.Content,{ref:n,className:G("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...t,children:[(0,nt.jsx)(Pr,{}),(0,nt.jsx)(Te.Viewport,{className:G("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:a}),(0,nt.jsx)(Tr,{})]})}));Ft.displayName=Te.Content.displayName;var to=Ma.forwardRef(({className:e,...a},s)=>(0,nt.jsx)(Te.Label,{ref:s,className:G("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));to.displayName=Te.Label.displayName;var qe=Ma.forwardRef(({className:e,children:a,...s},t)=>(0,nt.jsxs)(Te.Item,{ref:t,className:G("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...s,children:[(0,nt.jsx)("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:(0,nt.jsx)(Te.ItemIndicator,{children:(0,nt.jsx)(Ka.Check,{className:"af-h-4 af-w-4"})})}),(0,nt.jsx)(Te.ItemText,{children:a})]}));qe.displayName=Te.Item.displayName;var ao=Ma.forwardRef(({className:e,...a},s)=>(0,nt.jsx)(Te.Separator,{ref:s,className:G("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));ao.displayName=Te.Separator.displayName;var Jt=ne(require("react"),1);function ws({formId:e,initialPageSize:a=25}){let{api:s}=te(),[t,n]=Jt.useState([]),[i,o]=Jt.useState(0),[g,v]=Jt.useState(!0),[h,r]=Jt.useState(null),[b,w]=Jt.useState(0),[p,u]=Jt.useState(a),f=Jt.useCallback(async()=>{if(e)try{v(!0),r(null);let C={limit:p,offset:b*p},O=await s.getSubmissions(e,C);n(O.submissions),o(O.total)}catch(C){r(C instanceof Error?C:new Error("Failed to fetch submissions"))}finally{v(!1)}},[s,e,b,p]);Jt.useEffect(()=>{f()},[f]);let x=Jt.useCallback(async C=>{await s.deleteSubmission(C),n(O=>O.filter(z=>z.id!==C)),o(O=>O-1)},[s]),N=Math.ceil(i/p);return{submissions:t,total:i,isLoading:g,error:h,page:b,pageSize:p,hasNextPage:b<N-1,hasPreviousPage:b>0,setPage:w,setPageSize:C=>{u(C),w(0)},refetch:f,deleteSubmission:x}}var kr=ne(require("react"),1),wt=require("lucide-react");var ye=require("react/jsx-runtime");function Cr(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function so(e){if(e===0)return"0 B";let a=1024,s=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(a));return`${parseFloat((e/Math.pow(a,t)).toFixed(1))} ${s[t]}`}function Ns({submission:e,onBack:a}){let{api:s}=te(),[t,n]=kr.useState(null),i=v=>v.id??v.name,o=async v=>{n(i(v));try{await s.downloadAttachment(e.id,v)}catch(h){console.error("Download failed:",h)}finally{n(null)}},g=Object.entries(e.data).filter(([v])=>!v.startsWith("_"));return(0,ye.jsxs)("div",{children:[(0,ye.jsxs)("div",{className:"af-mb-6",children:[(0,ye.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,ye.jsx)(wt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,ye.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,ye.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Cr(e.metadata.submitted_at)]})]}),(0,ye.jsxs)("div",{className:"af-space-y-6",children:[(0,ye.jsx)(ha,{deliveries:e.email_deliveries}),(0,ye.jsxs)("div",{children:[(0,ye.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,ye.jsxs)("div",{className:"af-space-y-3",children:[g.map(([v,h])=>(0,ye.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,ye.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:v.replace(/_/g," ")}),(0,ye.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof h=="string"&&h.includes(`
|
|
3
|
-
`)?(0,ye.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:h}):String(h)})]},v)),g.length===0&&(0,ye.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,ye.jsxs)("div",{children:[(0,ye.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,ye.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((v,h)=>(0,ye.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ye.jsx)(wt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,ye.jsx)("span",{className:"af-text-sm",children:v.name}),(0,ye.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",so(v.size),")"]})]}),(0,ye.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>o(v),disabled:t===i(v),children:[t===i(v)?(0,ye.jsx)(wt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,ye.jsx)(wt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(v)?"Downloading...":"Download"]})]},h))})]}),(0,ye.jsxs)("div",{children:[(0,ye.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,ye.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,ye.jsx)(wt.Clock,{className:"af-h-4 af-w-4"}),(0,ye.jsx)("span",{children:Cr(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,ye.jsx)(wt.Globe,{className:"af-h-4 af-w-4"}),(0,ye.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,ye.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,ye.jsx)(wt.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,ye.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,ye.jsx)(wt.Mail,{className:"af-h-4 af-w-4"}),(0,ye.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var ie=require("react/jsx-runtime");function no(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ro(e){let a=["email","Email","EMAIL","e-mail","mail"];for(let s of a)if(typeof e[s]=="string")return e[s];return null}function io(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")&&!n.toLowerCase().includes("email"));if(a.length===0)return"";let[,s]=a[0],t=String(s);return t.length>50?t.slice(0,50)+"...":t}function Rs({formId:e,className:a,defaultSubmissionId:s}){let{submissions:t,total:n,isLoading:i,error:o,page:g,pageSize:v,hasNextPage:h,hasPreviousPage:r,setPage:b,setPageSize:w}=ws({formId:e}),[p,u]=Ss.useState("list"),[f,x]=Ss.useState(null);Ss.useEffect(()=>{if(s&&t.length>0){let c=t.find(S=>S.id===s);c&&(x(c),u("detail"))}},[s,t]);let N=c=>{x(c),u("detail")},C=()=>{u("list"),x(null)};if(p==="detail"&&f)return(0,ie.jsx)("div",{className:a,children:(0,ie.jsx)(Ns,{submission:f,onBack:C})});if(i)return(0,ie.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,ie.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(o)return(0,ie.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,ie.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(t.length===0&&g===0)return(0,ie.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[(0,ie.jsx)(xa.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ie.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,ie.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let O=g*v+1,z=Math.min((g+1)*v,n);return(0,ie.jsxs)("div",{className:a,children:[(0,ie.jsxs)(Le,{children:[(0,ie.jsx)(Oe,{children:(0,ie.jsxs)(be,{children:[(0,ie.jsx)(F,{children:"Email"}),(0,ie.jsx)(F,{children:"Preview"}),(0,ie.jsx)(F,{children:"Date"}),(0,ie.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,ie.jsx)(Be,{children:t.map(c=>{let S=ro(c.data),E=io(c.data);return(0,ie.jsxs)(be,{children:[(0,ie.jsxs)(M,{className:"af-font-medium",children:[(0,ie.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[S||(0,ie.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),c.attachments.length>0&&(0,ie.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${c.attachments.length} attachment(s)`,children:[(0,ie.jsx)(xa.Paperclip,{className:"af-h-3 af-w-3"}),(0,ie.jsx)("span",{className:"af-text-xs",children:c.attachments.length})]})]}),(0,ie.jsx)(xs,{deliveries:c.email_deliveries,label:"Notification email needs attention"})]}),(0,ie.jsx)(M,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:E||(0,ie.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,ie.jsx)(M,{className:"af-text-muted-foreground",children:no(c.metadata.submitted_at)}),(0,ie.jsx)(M,{className:"af-text-right",children:(0,ie.jsx)(P,{variant:"ghost",size:"icon",onClick:()=>N(c),title:"View details",children:(0,ie.jsx)(xa.Eye,{className:"af-h-4 af-w-4"})})})]},c.id)})})]}),(0,ie.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ie.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ie.jsxs)("span",{children:["Showing ",O,"-",z," of ",n]}),(0,ie.jsxs)(Wt,{value:String(v),onValueChange:c=>w(Number(c)),children:[(0,ie.jsx)(Bt,{className:"af-w-[70px] af-h-8",children:(0,ie.jsx)(Kt,{})}),(0,ie.jsxs)(Ft,{children:[(0,ie.jsx)(qe,{value:"10",children:"10"}),(0,ie.jsx)(qe,{value:"25",children:"25"}),(0,ie.jsx)(qe,{value:"50",children:"50"}),(0,ie.jsx)(qe,{value:"100",children:"100"})]})]}),(0,ie.jsx)("span",{children:"per page"})]}),(0,ie.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ie.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>b(g-1),disabled:!r,children:[(0,ie.jsx)(xa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ie.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>b(g+1),disabled:!h,children:["Next",(0,ie.jsx)(xa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ut=ne(require("react"),1),Ua=require("lucide-react");var Er=ne(require("react"),1);var Ir=require("react/jsx-runtime"),Se=Er.forwardRef(({className:e,type:a,...s},t)=>(0,Ir.jsx)("input",{type:a,className:G("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:t,...s}));Se.displayName="Input";var Ar=ne(require("react"),1),Dr=require("class-variance-authority");var Lr=require("react/jsx-runtime"),oo=(0,Dr.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Re=Ar.forwardRef(({className:e,...a},s)=>(0,Lr.jsx)("label",{ref:s,className:G(oo(),e),...a}));Re.displayName="Label";var Yt=ne(require("react"),1),Nt=require("lucide-react");var _s=ne(require("react"),1),ft=ne(require("@radix-ui/react-dialog"),1),Or=require("lucide-react");var Ct=require("react/jsx-runtime"),wa=ft.Root;var lo=ft.Portal;var Br=_s.forwardRef(({className:e,...a},s)=>(0,Ct.jsx)(ft.Overlay,{ref:s,className:G("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));Br.displayName=ft.Overlay.displayName;var oa=_s.forwardRef(({className:e,children:a,...s},t)=>(0,Ct.jsx)(lo,{children:(0,Ct.jsxs)("div",{className:"aifeatures-admin",children:[(0,Ct.jsx)(Br,{}),(0,Ct.jsxs)(ft.Content,{ref:t,className:G("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[a,(0,Ct.jsxs)(ft.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:[(0,Ct.jsx)(Or.X,{className:"af-h-4 af-w-4"}),(0,Ct.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));oa.displayName=ft.Content.displayName;var la=({className:e,...a})=>(0,Ct.jsx)("div",{className:G("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...a});la.displayName="DialogHeader";var ca=({className:e,...a})=>(0,Ct.jsx)("div",{className:G("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...a});ca.displayName="DialogFooter";var da=_s.forwardRef(({className:e,...a},s)=>(0,Ct.jsx)(ft.Title,{ref:s,className:G("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));da.displayName=ft.Title.displayName;var ua=_s.forwardRef(({className:e,...a},s)=>(0,Ct.jsx)(ft.Description,{ref:s,className:G("af-text-sm af-text-muted-foreground",e),...a}));ua.displayName=ft.Description.displayName;var Mt=ne(require("react"),1);function Ps(){let{api:e}=te(),[a,s]=Mt.useState([]),[t,n]=Mt.useState(!0),[i,o]=Mt.useState(null),g=Mt.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(p){o(p instanceof Error?p:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);Mt.useEffect(()=>{g()},[g]);let v=Mt.useCallback(async p=>{let u=await e.createEventDestination(p);return s(f=>[u,...f]),u},[e]),h=Mt.useCallback(async(p,u)=>{let f=await e.updateEventDestination(p,u);return s(x=>x.map(N=>N.id===p?f:N)),f},[e]),r=Mt.useCallback(async p=>{await e.deleteEventDestination(p),s(u=>u.filter(f=>f.id!==p))},[e]),b=Mt.useCallback(async p=>{let u=await e.rotateEventDestinationSecret(p);return s(f=>f.map(x=>x.id===p?u:x)),u},[e]),w=Mt.useCallback(p=>e.getEventDestinationSecret(p),[e]);return{destinations:a,isLoading:t,error:i,refetch:g,createDestination:v,updateDestination:h,deleteDestination:r,rotateSecret:b,getSecret:w}}var Ia=ne(require("react"),1),Ts=require("lucide-react");var mt=require("react/jsx-runtime");function Cs({destinationId:e,limit:a=25,className:s}){let{api:t}=te(),[n,i]=Ia.useState([]),[o,g]=Ia.useState(!0),[v,h]=Ia.useState(null),[r,b]=Ia.useState(null),w=Ia.useCallback(async()=>{try{g(!0),h(null),i(await t.getEventDeliveries(e,a))}catch(u){h(u instanceof Error?u.message:"Failed to load deliveries")}finally{g(!1)}},[t,e,a]);Ia.useEffect(()=>{w()},[w]);let p=async u=>{try{b(u.id),h(null);let f=await t.retryEventDelivery(e,u.id);i(x=>x.map(N=>N.id===u.id?f:N))}catch(f){h(f instanceof Error?f.message:"Retry failed")}finally{b(null)}};return o?(0,mt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,mt.jsx)(Ts.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):v?(0,mt.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:v}):n.length===0?(0,mt.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):(0,mt.jsx)("div",{className:s,children:(0,mt.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(u=>{let f=u.delivered_at!==null;return(0,mt.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,mt.jsxs)("div",{className:"af-min-w-0",children:[(0,mt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[f?(0,mt.jsx)(Z,{variant:"secondary",children:u.last_status??200}):(0,mt.jsx)(Z,{variant:"destructive",children:u.last_status??"failed"}),(0,mt.jsx)("span",{className:"af-text-sm af-truncate",children:u.type})]}),(0,mt.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[u.event_id," \xB7 ",u.created_at,u.attempts>0&&` \xB7 ${u.attempts} failed ${u.attempts===1?"attempt":"attempts"}`]}),!f&&u.last_error&&(0,mt.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),(0,mt.jsx)(P,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===u.id,onClick:()=>p(u),children:r===u.id?(0,mt.jsx)(Ts.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,mt.jsx)(Ts.RotateCw,{className:"af-h-4 af-w-4"})})]},u.id)})})})}var re=require("react/jsx-runtime");function ks({formId:e,topics:a,description:s,className:t}){let{destinations:n,isLoading:i,error:o,createDestination:g,updateDestination:v,deleteDestination:h,rotateSecret:r,getSecret:b}=Ps(),[w,p]=Yt.useState(""),[u,f]=Yt.useState(!1),[x,N]=Yt.useState(null),[C,O]=Yt.useState(null),[z,c]=Yt.useState(null),[S,E]=Yt.useState(!1),[J,B]=Yt.useState(null),[R,H]=Yt.useState(null),[y,Q]=Yt.useState(null),le=Yt.useMemo(()=>n.filter(K=>K.form_id===e),[n,e]),ce=async()=>{let K=w.trim();if(K){if(!K.startsWith("https://")){N("Webhook URLs must start with https://");return}try{f(!0),N(null),await g({url:K,form_id:e,...a&&a.length>0?{topics:a}:{}}),p("")}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to add webhook")}finally{f(!1)}}},ee=async K=>{try{H(K.id),N(null),await r(K.id),E(!1),c(await b(K.id))}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to rotate secret")}finally{H(null)}},_e=async K=>{try{H(K.id),N(null),await v(K.id,{status:"active"})}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to re-enable")}finally{H(null)}},Y=async()=>{if(J)try{H(J.id),await h(J.id),B(null)}catch(K){N(K instanceof Error?K.message:"Failed to delete")}finally{H(null)}},oe=async K=>{if(C===K.id){O(null),c(null);return}try{H(K.id),N(null),E(!1),O(K.id),c(await b(K.id))}catch(Pe){O(null),N(Pe instanceof Error?Pe.message:"Failed to read secret")}finally{H(null)}},fe=async()=>{if(z)try{await navigator.clipboard.writeText(z),E(!0)}catch{}};return(0,re.jsxs)("div",{className:t,children:[(0,re.jsxs)("div",{className:"af-space-y-1",children:[(0,re.jsx)(Re,{children:"Webhooks"}),(0,re.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:s??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),(0,re.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,re.jsx)(Se,{value:w,placeholder:"https://hooks.zapier.com/...",onChange:K=>p(K.target.value),onKeyDown:K=>{K.key==="Enter"&&(K.preventDefault(),ce())},disabled:u}),(0,re.jsxs)(P,{onClick:ce,disabled:u||!w.trim(),children:[u?(0,re.jsx)(Nt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,re.jsx)(Nt.Plus,{className:"af-h-4 af-w-4"}),(0,re.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(x||o)&&(0,re.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:x||o?.message}),(0,re.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[i&&(0,re.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,re.jsx)(Nt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&le.length===0&&(0,re.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),le.map(K=>(0,re.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,re.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,re.jsxs)("div",{className:"af-min-w-0",children:[(0,re.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,re.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:K.url}),K.status==="disabled"?(0,re.jsx)(Z,{variant:"destructive",children:"Disabled"}):(0,re.jsx)(Z,{variant:"secondary",children:"Active"})]}),(0,re.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:K.topics.includes("*")?"All events":K.topics.join(", ")})]}),(0,re.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,re.jsx)(P,{variant:"ghost",size:"sm",onClick:()=>Q(y===K.id?null:K.id),children:y===K.id?"Hide log":"Deliveries"}),(0,re.jsx)(P,{variant:"ghost",size:"sm",onClick:()=>oe(K),disabled:R===K.id,children:C===K.id?"Hide secret":"Show secret"}),(0,re.jsx)(P,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:R===K.id,onClick:()=>B(K),children:(0,re.jsx)(Nt.Trash2,{className:"af-h-4 af-w-4"})})]})]}),K.status==="disabled"&&(0,re.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[(0,re.jsx)(Nt.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,re.jsxs)("div",{className:"af-text-sm",children:[(0,re.jsxs)("p",{children:["We stopped sending after repeated failures."," ",K.disabled_reason]}),(0,re.jsx)(P,{variant:"outline",size:"sm",className:"af-mt-2",disabled:R===K.id,onClick:()=>_e(K),children:"Re-enable"})]})]}),C===K.id&&z&&(0,re.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,re.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Optional. Use this if you want your endpoint to check that a delivery really came from us. Rotating replaces it."}),(0,re.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,re.jsx)(Se,{readOnly:!0,value:z,className:"af-font-mono"}),(0,re.jsx)(P,{variant:"outline",title:"Copy signing secret",onClick:fe,children:S?(0,re.jsx)(Nt.Check,{className:"af-h-4 af-w-4"}):(0,re.jsx)(Nt.Copy,{className:"af-h-4 af-w-4"})}),(0,re.jsx)(P,{variant:"outline",title:"Rotate signing secret",disabled:R===K.id,onClick:()=>ee(K),children:R===K.id?(0,re.jsx)(Nt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,re.jsx)(Nt.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),y===K.id&&(0,re.jsx)(Cs,{destinationId:K.id})]},K.id))]}),(0,re.jsx)(wa,{open:!!J,onOpenChange:K=>{!K&&!R&&B(null)},children:(0,re.jsxs)(oa,{children:[(0,re.jsxs)(la,{children:[(0,re.jsx)(da,{children:"Delete this webhook?"}),(0,re.jsxs)(ua,{children:["New submissions will stop being sent to ",J?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),(0,re.jsxs)(ca,{children:[(0,re.jsx)(P,{variant:"outline",onClick:()=>B(null),disabled:!!R,children:"Cancel"}),(0,re.jsx)(P,{variant:"destructive",onClick:Y,disabled:!!R,children:R?"Deleting...":"Delete"})]})]})})]})}var we=require("react/jsx-runtime");function Es({form:e,onSaved:a,className:s}){let{updateForm:t}=Wa(),[n,i]=Ut.useState(!1),[o,g]=Ut.useState(null),[v,h]=Ut.useState(null),[r,b]=Ut.useState(e.name),[w,p]=Ut.useState(e.redirect_url||""),[u,f]=Ut.useState(e.email_recipients),[x,N]=Ut.useState("");Ut.useEffect(()=>{b(e.name),p(e.redirect_url||""),f(e.email_recipients),h(null)},[e]);let C=Ut.useCallback(async E=>{try{i(!0),h(null);let J=await t(e.id,E);g(new Date),a?.(J)}catch(J){h(J instanceof Error?J.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);Ut.useEffect(()=>{if(o){let E=setTimeout(()=>g(null),2e3);return()=>clearTimeout(E)}},[o]);let O=async()=>{let E=x.trim().toLowerCase();if(!E)return;if(!E.includes("@")){h("Please enter a valid email address");return}if(u.includes(E)){h("This email is already added");return}let J=[...u,E];f(J),N(""),h(null),await C({email_recipients:J})},z=async E=>{let J=u.filter(B=>B!==E);f(J),await C({email_recipients:J})},c=async()=>{r!==e.name&&await C({name:r})},S=async()=>{let E=w||null;E!==e.redirect_url&&await C({redirect_url:E})};return(0,we.jsxs)("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&(0,we.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,we.jsxs)("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:[(0,we.jsx)(Ua.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,we.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,we.jsxs)("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:[(0,we.jsx)(Ua.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,we.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{htmlFor:"form-name",children:"Form Name"}),(0,we.jsx)(Se,{id:"form-name",value:r,onChange:E=>b(E.target.value),onBlur:c,placeholder:"Contact Form"}),(0,we.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{children:"Email Recipients"}),(0,we.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,we.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(E=>(0,we.jsxs)(Z,{variant:"secondary",className:"af-gap-1",children:[E,(0,we.jsx)("button",{type:"button",onClick:()=>z(E),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,we.jsx)(Ua.X,{className:"af-h-3 af-w-3"})})]},E)),u.length===0&&(0,we.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,we.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,we.jsx)(Se,{type:"email",value:x,onChange:E=>N(E.target.value),placeholder:"Add email address",onKeyDown:E=>{E.key==="Enter"&&(E.preventDefault(),O())},disabled:n}),(0,we.jsx)(P,{type:"button",variant:"outline",onClick:O,disabled:!x.trim()||n,children:(0,we.jsx)(Ua.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,we.jsx)(Se,{id:"redirect-url",value:w,onChange:E=>p(E.target.value),onBlur:S,placeholder:"/thank-you"}),(0,we.jsx)("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."})]}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{children:"Form Endpoint"}),(0,we.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,we.jsx)("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})}),(0,we.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{children:"Captcha Protection"}),(0,we.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,we.jsx)(Z,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,we.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,we.jsx)(ks,{formId:e.id}),v&&(0,we.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v})]})}var Ve=require("react/jsx-runtime");function An({className:e,submissionId:a}){let{api:s}=te(),[t,n]=Va.useState("list"),[i,o]=Va.useState(null),[g,v]=Va.useState("submissions"),[h,r]=Va.useState(a),[b,w]=Va.useState(!!a);Va.useEffect(()=>{if(!a)return;async function x(){try{let N=await s.getSubmission(a),C=await s.getForm(N.form_id);o(C),n("detail"),v("submissions"),r(a)}catch(N){console.error("Failed to load submission for deep link:",N)}finally{w(!1)}}x()},[a,s]);let p=(x,N)=>{o(x),n("detail"),v(N),r(void 0)},u=()=>{n("list"),o(null),r(void 0)},f=x=>{o(x)};return b?(0,Ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,Ve.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Ve.jsxs)("div",{className:e,children:[t==="list"&&(0,Ve.jsxs)("div",{children:[(0,Ve.jsxs)("div",{className:"af-mb-6",children:[(0,Ve.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,Ve.jsx)(hs,{onSelectForm:p})]}),t==="detail"&&i&&(0,Ve.jsxs)("div",{children:[(0,Ve.jsxs)("div",{className:"af-mb-6",children:[(0,Ve.jsxs)(P,{variant:"ghost",size:"sm",onClick:u,className:"af-mb-2 af--ml-2",children:[(0,Ve.jsx)(ls.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),(0,Ve.jsx)("h2",{className:"af-text-lg af-font-semibold",children:i.name}),(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:(0,Ve.jsx)("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),(0,Ve.jsxs)(sn,{value:g,onValueChange:x=>v(x),children:[(0,Ve.jsxs)(bs,{className:"af-mb-4",children:[(0,Ve.jsxs)(va,{value:"submissions",className:"af-gap-2",children:[(0,Ve.jsx)(ls.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,Ve.jsxs)(va,{value:"settings",className:"af-gap-2",children:[(0,Ve.jsx)(ls.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,Ve.jsx)(ba,{value:"submissions",children:(0,Ve.jsx)(Rs,{formId:i.id,defaultSubmissionId:h})}),(0,Ve.jsx)(ba,{value:"settings",children:(0,Ve.jsx)(Es,{form:i,onSaved:f})})]})]})]})}var fs=ne(require("react"),1),aa=require("lucide-react");var on=ne(require("react"),1),Aa=require("lucide-react");var co=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function fa(e){return co.has(e.toLowerCase())}function W(e,a,s){let t=fa(a)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:a.toUpperCase()}).format(t)}catch{return`${t} ${a.toUpperCase()}`}}function Zt(e){let a=e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0;return e.amount_total+(e.shipping_total??0)+a}function Qt(e,a){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let t=fa(a)?s:s*100;return Math.round(t)}function vt(e,a){return fa(a)?e:e/100}var ve=require("react/jsx-runtime");function uo(e){if(e.allow_custom_amount){let a=e.min_amount!==null?W(e.min_amount,e.currency):"?",s=e.max_amount!==null?W(e.max_amount,e.currency):"?";return`Buyer chooses (${a} - ${s})`}return e.unit_amount===null?"Varies by variant":W(e.unit_amount,e.currency)}function fo(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Is({productsState:e,onSelectProduct:a,onCreateProduct:s,className:t}){let{products:n,isLoading:i,error:o,deleteProduct:g}=e,[v,h]=on.useState(null),[r,b]=on.useState(!1),[w,p]=on.useState(null),u=async()=>{if(v)try{b(!0),p(null),await g(v.id),h(null)}catch(f){p(f instanceof Error?f.message:"Failed to delete product")}finally{b(!1)}};return i?(0,ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ve.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ve.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?(0,ve.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,ve.jsx)(Aa.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ve.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,ve.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,ve.jsxs)(P,{variant:"outline",onClick:()=>s?.(),children:[(0,ve.jsx)(Aa.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,ve.jsxs)("div",{className:t,children:[(0,ve.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,ve.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[(0,ve.jsx)(Aa.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,ve.jsxs)(Le,{children:[(0,ve.jsx)(Oe,{children:(0,ve.jsxs)(be,{children:[(0,ve.jsx)(F,{children:"Name"}),(0,ve.jsx)(F,{children:"Price"}),(0,ve.jsx)(F,{children:"Fulfillment"}),(0,ve.jsx)(F,{children:"Status"}),(0,ve.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,ve.jsx)(Be,{children:n.map(f=>(0,ve.jsxs)(be,{children:[(0,ve.jsx)(M,{className:"af-font-medium",children:f.name}),(0,ve.jsx)(M,{children:uo(f)}),(0,ve.jsx)(M,{className:"af-text-muted-foreground",children:fo(f)}),(0,ve.jsx)(M,{children:(0,ve.jsx)(Z,{variant:f.active?"success":"secondary",children:f.active?"Active":"Inactive"})}),(0,ve.jsx)(M,{className:"af-text-right",children:(0,ve.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,ve.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>a?.(f),children:[(0,ve.jsx)(Aa.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,ve.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>{p(null),h(f)},children:[(0,ve.jsx)(Aa.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},f.id))})]}),(0,ve.jsx)(wa,{open:!!v,onOpenChange:f=>{!f&&!r&&h(null)},children:(0,ve.jsxs)(oa,{children:[(0,ve.jsxs)(la,{children:[(0,ve.jsx)(da,{children:"Delete product?"}),(0,ve.jsxs)(ua,{children:['"',v?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),w&&(0,ve.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:w}),(0,ve.jsxs)(ca,{children:[(0,ve.jsx)(P,{variant:"outline",onClick:()=>h(null),disabled:r,children:"Cancel"}),(0,ve.jsx)(P,{variant:"destructive",onClick:u,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}var Ge=ne(require("react"),1),Vt=require("lucide-react");var ct=ne(require("react"),1),Xt=require("lucide-react");var T=require("react/jsx-runtime");function Dn(e){return e.option_values.length>0?e.option_values.map(a=>a.value).join(" / "):e.title||"Default"}function As({productId:e,currency:a,className:s}){let{api:t}=te(),n=fa(a)?"1":"0.01",[i,o]=ct.useState(null),[g,v]=ct.useState(!0),[h,r]=ct.useState(null),[b,w]=ct.useState(null),[p,u]=ct.useState(!1),f=ct.useRef(!0);ct.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]);let x=ct.useCallback(async()=>{try{let k=await t.getProduct(e);if(!f.current)return;o(k)}catch(k){if(!f.current)return;r(k instanceof Error?k.message:"Failed to load product")}finally{f.current&&v(!1)}},[t,e]);ct.useEffect(()=>{x()},[x]);let N=async k=>{w(null),u(!0);try{await k(),await x()}catch(L){f.current&&w(L instanceof Error?L.message:"Something went wrong")}finally{f.current&&u(!1)}},[C,O]=ct.useState(""),[z,c]=ct.useState(""),[S,E]=ct.useState({}),J=()=>N(async()=>{let k=C.trim(),L=z.split(",").map(ge=>ge.trim()).filter(Boolean);if(!k)throw new Error("Option name is required");if(L.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:k,values:L}),f.current&&(O(""),c(""))}),B=k=>N(async()=>{let L=(S[k.id]??"").trim();if(!L)throw new Error("Enter a value");await t.updateOption(k.id,{add_values:[L]}),f.current&&E(ge=>({...ge,[k.id]:""}))}),R=(k,L)=>N(()=>t.updateOption(k.id,{remove_values:[L]})),H=k=>N(()=>t.deleteOption(k.id)),[y,Q]=ct.useState(null),[le,ce]=ct.useState(null),[ee,_e]=ct.useState(!1),[Y,oe]=ct.useState(null),fe=i?.options??[],K=i?.variants??[],Pe=()=>{ce(null),Q({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(fe.map(k=>[k.id,k.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Me=k=>{ce(null);let L=k.inventory?.on_hand??0,ge=L<0?"":String(L);Q({variant:k,title:k.title??"",sku:k.sku??"",unitAmount:k.unit_amount!=null?String(vt(k.unit_amount,a)):"",compareAt:k.compare_at_amount!=null?String(vt(k.compare_at_amount,a)):"",active:k.active,optionValues:{},tracked:k.inventory?.tracked??!1,onHand:ge,initialOnHand:ge,allowBackorder:k.inventory?.allow_backorder??!1})},xt=async()=>{if(!y)return;ce(null);let k=y.variant?.allow_custom_amount??!1,L=null,ge=null;if(!k){if(L=Qt(y.unitAmount,a),L===null||L<=0){ce("Enter a valid price");return}if(y.compareAt.trim()&&(ge=Qt(y.compareAt,a),ge===null||ge<=L)){ce("Compare-at price must be greater than the price");return}}let Ke=y.onHand.trim()!==y.initialOnHand.trim(),ze=parseInt(y.onHand,10);if(y.tracked&&Ke&&(!Number.isFinite(ze)||ze<0)){ce("On-hand quantity must be zero or more");return}try{if(_e(!0),y.variant)await t.updateVariant(y.variant.id,{title:y.title.trim()||null,sku:y.sku.trim()||null,...k?{}:{unit_amount:L,compare_at_amount:ge},active:y.active}),await t.setVariantInventory(y.variant.id,{tracked:y.tracked,on_hand:y.tracked&&Ke?ze:void 0,allow_backorder:y.allowBackorder});else{let at={};for(let Je of fe){let st=y.optionValues[Je.id];if(!st){ce(`Choose a ${Je.title}`),_e(!1);return}at[Je.title]=st}await t.createVariant(e,{title:y.title.trim()||null,sku:y.sku.trim()||null,unit_amount:L,compare_at_amount:ge,active:y.active,option_values:fe.length>0?at:void 0,inventory:y.tracked?{tracked:!0,on_hand:ze,allow_backorder:y.allowBackorder}:{tracked:!1,allow_backorder:y.allowBackorder}})}await x(),f.current&&Q(null)}catch(at){if(f.current&&ce(at instanceof Error?at.message:"Failed to save variant"),y.variant)try{let Je=await t.getProduct(e);f.current&&o(Je)}catch{}}finally{f.current&&_e(!1)}},q=()=>N(async()=>{Y&&(await t.deleteVariant(Y.id),f.current&&oe(null))}),pe=y?.variant?.allow_custom_amount??!1,xe=y?.variant!=null&&y.variant.option_values.length===0&&fe.length>0&&!y.variant.active,de=y?.variant?.inventory!=null&&y.variant.inventory.on_hand<0?-y.variant.inventory.on_hand:null;function Ue(k){let L=k.inventory;if(!L||!L.tracked)return(0,T.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let ge=L.available??L.on_hand;return ge<0?(0,T.jsxs)("span",{children:[-ge," backordered"]}):(0,T.jsxs)("span",{children:[ge," in stock",L.allow_backorder&&(0,T.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return g?(0,T.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:(0,T.jsx)(Xt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):h?(0,T.jsx)("div",{className:s,children:(0,T.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:h})}):(0,T.jsxs)("div",{className:`af-space-y-6 ${s||""}`,children:[(0,T.jsxs)("div",{className:"af-space-y-3",children:[(0,T.jsxs)("div",{children:[(0,T.jsx)(Re,{children:"Options"}),(0,T.jsx)("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."})]}),fe.length>0&&(0,T.jsx)("div",{className:"af-space-y-3",children:fe.map(k=>(0,T.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,T.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,T.jsx)("span",{className:"af-text-sm af-font-medium",children:k.title}),(0,T.jsx)(P,{variant:"ghost",size:"sm",onClick:()=>H(k),disabled:p,children:(0,T.jsx)(Xt.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,T.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:k.values.map(L=>(0,T.jsxs)(Z,{variant:"secondary",className:"af-gap-1",children:[L.value,(0,T.jsx)("button",{type:"button",onClick:()=>R(k,L.value),className:"af-ml-1 hover:af-text-destructive",disabled:p,title:"Remove value",children:(0,T.jsx)(Xt.X,{className:"af-h-3 af-w-3"})})]},L.id))}),(0,T.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,T.jsx)(Se,{value:S[k.id]??"",onChange:L=>E(ge=>({...ge,[k.id]:L.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),B(k))},disabled:p}),(0,T.jsx)(P,{type:"button",variant:"outline",size:"sm",onClick:()=>B(k),disabled:p||!(S[k.id]??"").trim(),children:(0,T.jsx)(Xt.Plus,{className:"af-h-4 af-w-4"})})]})]},k.id))}),(0,T.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(Re,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,T.jsx)(Se,{id:"new-option-title",value:C,onChange:k=>O(k.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:p})]}),(0,T.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,T.jsx)(Re,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,T.jsx)(Se,{id:"new-option-values",value:z,onChange:k=>c(k.target.value),placeholder:"S, M, L",disabled:p})]}),(0,T.jsxs)(P,{type:"button",variant:"outline",onClick:J,disabled:p||!C.trim()||!z.trim(),children:[(0,T.jsx)(Xt.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,T.jsxs)("div",{className:"af-space-y-3",children:[(0,T.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,T.jsx)(Re,{children:"Variants"}),(0,T.jsxs)(P,{type:"button",variant:"outline",size:"sm",onClick:Pe,disabled:p||fe.length===0,children:[(0,T.jsx)(Xt.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),fe.length===0&&(0,T.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),K.length===0?(0,T.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,T.jsxs)(Le,{children:[(0,T.jsx)(Oe,{children:(0,T.jsxs)(be,{children:[(0,T.jsx)(F,{children:"Variant"}),(0,T.jsx)(F,{children:"SKU"}),(0,T.jsx)(F,{children:"Price"}),(0,T.jsx)(F,{children:"Stock"}),(0,T.jsx)(F,{children:"Status"}),(0,T.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,T.jsx)(Be,{children:K.map(k=>(0,T.jsxs)(be,{children:[(0,T.jsx)(M,{className:"af-font-medium",children:Dn(k)}),(0,T.jsx)(M,{className:"af-text-muted-foreground",children:k.sku||"-"}),(0,T.jsx)(M,{children:k.unit_amount!=null?(0,T.jsxs)("span",{children:[k.compare_at_amount!=null&&(0,T.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:W(k.compare_at_amount,k.currency)}),W(k.unit_amount,k.currency)]}):k.allow_custom_amount?(0,T.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,T.jsx)(M,{children:Ue(k)}),(0,T.jsx)(M,{children:(0,T.jsx)(Z,{variant:k.active?"success":"secondary",children:k.active?"Active":"Inactive"})}),(0,T.jsx)(M,{className:"af-text-right",children:(0,T.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,T.jsx)(P,{variant:"ghost",size:"sm",onClick:()=>Me(k),disabled:p,children:"Edit"}),(0,T.jsx)(P,{variant:"ghost",size:"icon",onClick:()=>oe(k),disabled:p,title:"Delete variant",children:(0,T.jsx)(Xt.Trash2,{className:"af-h-4 af-w-4"})})]})})]},k.id))})]})]}),b&&(0,T.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),(0,T.jsx)(wa,{open:y!==null,onOpenChange:k=>{!k&&!ee&&Q(null)},children:(0,T.jsxs)(oa,{children:[(0,T.jsxs)(la,{children:[(0,T.jsx)(da,{children:y?.variant?"Edit variant":"Add variant"}),(0,T.jsx)(ua,{children:"Price, markdown, and stock live on the variant."})]}),y&&(0,T.jsxs)("div",{className:"af-space-y-3",children:[y.variant?y.variant.option_values.length>0&&(0,T.jsxs)("div",{className:"af-text-sm",children:[(0,T.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Dn(y.variant)]}):fe.map(k=>(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:k.title}),(0,T.jsxs)(Wt,{value:y.optionValues[k.id]??"",onValueChange:L=>Q(ge=>ge&&{...ge,optionValues:{...ge.optionValues,[k.id]:L}}),children:[(0,T.jsx)(Bt,{children:(0,T.jsx)(Kt,{placeholder:`Choose ${k.title}`})}),(0,T.jsx)(Ft,{children:k.values.map(L=>(0,T.jsx)(qe,{value:L.value,children:L.value},L.id))})]})]},k.id)),pe?(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,T.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,T.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsxs)(Re,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",a.toUpperCase(),")"]}),(0,T.jsx)(Se,{id:"variant-price",type:"number",min:"0",step:n,value:y.unitAmount,onChange:k=>Q(L=>L&&{...L,unitAmount:k.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(Re,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,T.jsx)(Se,{id:"variant-compare",type:"number",min:"0",step:n,value:y.compareAt,onChange:k=>Q(L=>L&&{...L,compareAt:k.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(Re,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,T.jsx)(Se,{id:"variant-sku",value:y.sku,onChange:k=>Q(L=>L&&{...L,sku:k.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,T.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,T.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,T.jsx)("input",{type:"checkbox",checked:y.tracked,onChange:k=>Q(L=>L&&{...L,tracked:k.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),y.tracked&&(0,T.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,T.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(Re,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,T.jsx)(Se,{id:"variant-onhand",type:"number",min:"0",step:"1",value:y.onHand,onChange:k=>Q(L=>L&&{...L,onHand:k.target.value}),placeholder:de!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,T.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,T.jsx)("input",{type:"checkbox",checked:y.allowBackorder,onChange:k=>Q(L=>L&&{...L,allowBackorder:k.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),de!=null&&(0,T.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",de," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,T.jsx)("input",{type:"checkbox",checked:y.active,onChange:k=>Q(L=>L&&{...L,active:k.target.checked}),className:"af-h-4 af-w-4",disabled:xe}),"Active (buyers can purchase this variant)"]}),xe&&(0,T.jsx)("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."})]}),le&&(0,T.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:le})]}),(0,T.jsxs)(ca,{children:[(0,T.jsx)(P,{variant:"outline",onClick:()=>Q(null),disabled:ee,children:"Cancel"}),(0,T.jsxs)(P,{onClick:xt,disabled:ee,children:[ee?(0,T.jsx)(Xt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,y?.variant?"Save":"Add variant"]})]})]})}),(0,T.jsx)(wa,{open:Y!==null,onOpenChange:k=>{!k&&!p&&oe(null)},children:(0,T.jsxs)(oa,{children:[(0,T.jsxs)(la,{children:[(0,T.jsx)(da,{children:"Delete variant?"}),(0,T.jsx)(ua,{children:Y&&`"${Dn(Y)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,T.jsxs)(ca,{children:[(0,T.jsx)(P,{variant:"outline",onClick:()=>oe(null),disabled:p,children:"Cancel"}),(0,T.jsx)(P,{variant:"destructive",onClick:q,disabled:p,children:"Delete"})]})]})})]})}var $=require("react/jsx-runtime");function mo(e){if(e===0)return"0 B";let a=1024,s=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(a));return`${parseFloat((e/Math.pow(a,t)).toFixed(1))} ${s[t]}`}function Ds({productsState:e,product:a,currency:s,onSaved:t,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:g,attachProductFileFromUrl:v}=e,h=!!a,r=a?.currency??s,b=fa(r)?"1":"0.01",w=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[p,u]=Ge.useState(!1),[f,x]=Ge.useState(null),N=Ge.useRef(!0);Ge.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]);let[C,O]=Ge.useState(a?.name??""),[z,c]=Ge.useState(a?.description??""),[S,E]=Ge.useState(a?.allow_custom_amount?"custom":"fixed"),[J,B]=Ge.useState(a?.unit_amount!=null?String(vt(a.unit_amount,r)):""),[R,H]=Ge.useState(a?.min_amount!=null?String(vt(a.min_amount,r)):""),[y,Q]=Ge.useState(a?.max_amount!=null?String(vt(a.max_amount,r)):""),[le,ce]=Ge.useState(String(a?.max_quantity??10)),ee=Ge.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(vt(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(vt(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(vt(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[_e,Y]=Ge.useState(a?.collect_shipping_address??!1),[oe,fe]=Ge.useState(a?.active??!0),[K,Pe]=Ge.useState(a?.images??[]),[Me,xt]=Ge.useState(""),[q,pe]=Ge.useState(a?.fulfillment??null),[xe,de]=Ge.useState(!1),[Ue,k]=Ge.useState(""),[L,ge]=Ge.useState(null),Ke=Ge.useRef(null),ze=p||xe,at=()=>{let se=Me.trim();if(se){if(K.includes(se)){x("This image URL is already added");return}Pe(De=>[...De,se]),xt(""),x(null)}},Je=se=>{Pe(De=>De.filter(je=>je!==se))},st=async()=>{if(x(null),!C.trim()){x("Product name is required");return}let se=null,De=null,je=null,sa=!h||S!==ee.pricingMode||(S==="fixed"?J!==ee.unitAmount:R!==ee.minAmount||y!==ee.maxAmount),_t=!h||le!==ee.maxQuantity,ka=w||S==="fixed";if(!(w||!sa))if(S==="fixed"){if(se=Qt(J,r),se===null||se<=0){x("Enter a valid price");return}}else{if(De=Qt(R,r),je=Qt(y,r),De===null||je===null){x("Enter valid minimum and maximum amounts");return}if(je<De){x("Maximum amount must be at least the minimum amount");return}}let lt=parseInt(le,10);if(ka&&_t&&(!Number.isFinite(lt)||lt<1)){x("Max quantity must be at least 1");return}try{u(!0);let Qe;if(h&&a){let I={name:C.trim(),description:z.trim()||null,images:K,collect_shipping_address:_e,active:oe};!w&&sa&&(I.allow_custom_amount=S==="custom",S==="fixed"?I.unit_amount=se:(I.min_amount=De,I.max_amount=je)),ka&&_t&&(I.max_quantity=lt),Qe=await o(a.id,I),ee.pricingMode=Qe.allow_custom_amount?"custom":"fixed",ee.unitAmount=Qe.unit_amount!=null?String(vt(Qe.unit_amount,r)):"",ee.minAmount=Qe.min_amount!=null?String(vt(Qe.min_amount,r)):"",ee.maxAmount=Qe.max_amount!=null?String(vt(Qe.max_amount,r)):"",ee.maxQuantity=String(Qe.max_quantity)}else{let I={name:C.trim(),allow_custom_amount:S==="custom",collect_shipping_address:_e,active:oe};z.trim()&&(I.description=z.trim()),K.length>0&&(I.images=K),S==="fixed"?(I.unit_amount=se,I.max_quantity=lt):(I.min_amount=De,I.max_amount=je),Qe=await i(I)}if(!N.current)return;pe(Qe.fulfillment),t?.(Qe)}catch(Qe){if(!N.current)return;x(Qe instanceof Error?Qe.message:"Failed to save product")}finally{N.current&&u(!1)}},Gt=async se=>{let De=se.target.files?.[0];if(!(!De||!a))try{de(!0),ge(null);let je=await g(a.id,De);if(!N.current)return;pe(je.fulfillment),t?.(je)}catch(je){if(!N.current)return;ge(je instanceof Error?je.message:"Failed to upload file")}finally{N.current&&(de(!1),Ke.current&&(Ke.current.value=""))}},ga=async()=>{let se=Ue.trim();if(!(!se||!a))try{de(!0),ge(null);let De=await v(a.id,se);if(!N.current)return;pe(De.fulfillment),k(""),t?.(De)}catch(De){if(!N.current)return;ge(De instanceof Error?De.message:"Failed to fetch file")}finally{N.current&&de(!1)}};return(0,$.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{htmlFor:"product-name",children:"Name"}),(0,$.jsx)(Se,{id:"product-name",value:C,onChange:se=>O(se.target.value),placeholder:"My product"})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{htmlFor:"product-description",children:"Description"}),(0,$.jsx)("textarea",{id:"product-description",value:z,onChange:se=>c(se.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"})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{children:"Pricing"}),w?(0,$.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(Wt,{value:S,onValueChange:se=>E(se),children:[(0,$.jsx)(Bt,{className:"af-w-[260px]",children:(0,$.jsx)(Kt,{})}),(0,$.jsxs)(Ft,{children:[(0,$.jsx)(qe,{value:"fixed",children:"Fixed price"}),(0,$.jsx)(qe,{value:"custom",children:"Buyer chooses the amount"})]})]}),S==="fixed"?(0,$.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsxs)(Re,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),(0,$.jsx)(Se,{id:"product-price",type:"number",min:"0",step:b,value:J,onChange:se=>B(se.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsxs)(Re,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),(0,$.jsx)(Se,{id:"product-min-amount",type:"number",min:"0",step:b,value:R,onChange:se=>H(se.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsxs)(Re,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),(0,$.jsx)(Se,{id:"product-max-amount",type:"number",min:"0",step:b,value:y,onChange:se=>Q(se.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,$.jsx)("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."})]}),(0,$.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",r.toUpperCase(),"), which follows the country of your payment account."]})]}),(w||S==="fixed")&&(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsx)(Re,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,$.jsx)(Se,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:le,onChange:se=>ce(se.target.value),className:"af-w-[140px]"})]})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{children:"Images"}),(0,$.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,$.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[K.map(se=>(0,$.jsxs)(Z,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,$.jsx)("span",{className:"af-truncate",children:se}),(0,$.jsx)("button",{type:"button",onClick:()=>Je(se),className:"af-ml-1 hover:af-text-destructive",disabled:p,children:(0,$.jsx)(Vt.X,{className:"af-h-3 af-w-3"})})]},se)),K.length===0&&(0,$.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,$.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,$.jsx)(Se,{type:"url",value:Me,onChange:se=>xt(se.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:se=>{se.key==="Enter"&&(se.preventDefault(),at())},disabled:p}),(0,$.jsx)(P,{type:"button",variant:"outline",onClick:at,disabled:!Me.trim()||p,children:(0,$.jsx)(Vt.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{children:"Digital File"}),(0,$.jsx)("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."}),h?(0,$.jsxs)("div",{className:"af-space-y-3",children:[q?.type==="download"&&(0,$.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,$.jsx)(Vt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,$.jsx)("span",{className:"af-text-sm",children:q.filename}),q.size!=null&&(0,$.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",mo(q.size),")"]})]}),q?.type==="redirect"&&q.url&&(0,$.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,$.jsx)(Vt.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,$.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",q.url]})]}),(0,$.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,$.jsx)("input",{ref:Ke,type:"file",onChange:Gt,className:"af-hidden",disabled:ze}),(0,$.jsxs)(P,{type:"button",variant:"outline",size:"sm",onClick:()=>Ke.current?.click(),disabled:ze,children:[xe?(0,$.jsx)(Vt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,$.jsx)(Vt.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),q?.type==="download"?"Replace file":"Upload file"]}),(0,$.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,$.jsx)(Se,{type:"url",value:Ue,onChange:se=>k(se.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:xe}),(0,$.jsx)(P,{type:"button",variant:"outline",size:"sm",onClick:ga,disabled:!Ue.trim()||ze,children:"Fetch from URL"})]}),L&&(0,$.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:L})]}):(0,$.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{children:"Settings"}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,$.jsx)("input",{type:"checkbox",checked:_e,onChange:se=>Y(se.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,$.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,$.jsx)("input",{type:"checkbox",checked:oe,onChange:se=>fe(se.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),h&&a&&(0,$.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,$.jsx)(Re,{children:"Options & Variants"}),(0,$.jsx)(As,{productId:a.id,currency:r})]}),f&&(0,$.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f}),(0,$.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,$.jsxs)(P,{type:"button",onClick:st,disabled:ze,children:[p?(0,$.jsx)(Vt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,h?"Save changes":"Create product"]})})]})}var yt=ne(require("react"),1),Ht=require("lucide-react");var Xe=ne(require("react"),1);var po=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Ls({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=te(),[t,n]=Xe.useState([]),[i,o]=Xe.useState(0),[g,v]=Xe.useState(!0),[h,r]=Xe.useState(null),[b,w]=Xe.useState(0),[p,u]=Xe.useState(e),[f,x]=Xe.useState(void 0),[N,C]=Xe.useState(""),[O,z]=Xe.useState(""),[c,S]=Xe.useState(""),[E,J]=Xe.useState(!1),[B,R]=Xe.useState(!1),[H,y]=Xe.useState(void 0),Q=H?H.join(","):"",le=Xe.useMemo(()=>{if(!Q)return;let Y=new Set(Q.split(","));return po.filter(oe=>!Y.has(oe))},[Q]),ce=Xe.useRef(0),ee=Xe.useCallback(async()=>{let Y=++ce.current;try{v(!0),r(null);let oe={limit:p,offset:b*p};f?oe.status=f:le?oe.excludeStatus=le:E||(oe.excludeStatus=["pending","expired"]),N.trim()&&(oe.customerEmail=N.trim()),O.trim()&&(oe.from=O.trim()),c.trim()&&(oe.to=c.trim()),B&&(oe.unfulfilledOnly=!0);let fe=await s.getOrders(oe);if(Y!==ce.current)return;n(fe.orders),o(fe.total)}catch(oe){if(Y!==ce.current)return;r(oe instanceof Error?oe:new Error("Failed to fetch orders"))}finally{Y===ce.current&&v(!1)}},[s,b,p,f,le,E,B,N,O,c,a]);Xe.useEffect(()=>{ee()},[ee]);let _e=Math.ceil(i/p);return{orders:t,total:i,isLoading:g,error:h,page:b,pageSize:p,hasNextPage:b<_e-1,hasPreviousPage:b>0,setPage:w,setPageSize:Y=>{u(Y),w(0)},status:f,setStatus:Y=>{x(Y),w(0)},statusIn:H,setStatusIn:Y=>{y(Y&&Y.length>0?Y:void 0),w(0)},customerEmail:N,setCustomerEmail:Y=>{C(Y),w(0)},from:O,setFrom:Y=>{z(Y),w(0)},to:c,setTo:Y=>{S(Y),w(0)},showAbandoned:E,setShowAbandoned:Y=>{J(Y),w(0)},unfulfilledOnly:B,setUnfulfilledOnly:Y=>{R(Y),w(0)},clearFilters:()=>{x(void 0),y(void 0),J(!1),R(!1),C(""),z(""),S(""),w(0)},refetch:ee}}var rt=ne(require("react"),1),ke=require("lucide-react");var Fr=ne(require("react"),1),Na=ne(require("@radix-ui/react-popover"),1);var ln=require("react/jsx-runtime"),Mr=Na.Root,Ur=Na.Trigger;var Ln=Fr.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>(0,ln.jsx)(Na.Portal,{children:(0,ln.jsx)("div",{className:"aifeatures-admin",children:(0,ln.jsx)(Na.Content,{ref:n,align:a,sideOffset:s,className:G("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),...t})})}));Ln.displayName=Na.Content.displayName;var Os=require("react/jsx-runtime"),go={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function vo(e){return go[e]??e}function Vr(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 Ja({status:e,className:a}){return(0,Os.jsx)(Z,{variant:Vr(e),className:a,children:vo(e)})}function $a({status:e}){return(0,Os.jsx)(Ja,{status:e})}function cs({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,Os.jsx)(Z,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Os.jsx)(Z,{variant:"warning",className:a,children:"Needs shipping"}):null:null}function Da(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var d=require("react/jsx-runtime"),qr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ya="af-text-xs af-text-muted-foreground";function On(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jr(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 cn=24,yo=["paid","partially_refunded"],ho=["paid","partially_refunded","disputed"],xo=/^[A-Za-z0-9 _-]*$/,$r=100;function Mn(e,a,s,t,n){let i=yo.includes(t);return a==="sent"?{label:"Sent",variant:"success",detail:null}:a==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:a==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${cn} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${cn} tries used). Nothing is being retried while the order is ${t.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:a==="failed_final"?s<cn&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:s<cn&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${s} attempt${s===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:a==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${t==="refunded"?"because the order was refunded":t==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:a==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(a),variant:"secondary",detail:null}}function Hr({title:e,recipient:a,status:s,attempts:t,side:n,orderStatus:i,action:o,delivery:g}){if(g)return(0,d.jsxs)("div",{children:[(0,d.jsx)(ha,{deliveries:[g]}),o&&(0,d.jsx)("div",{className:"af-mt-2",children:o})]});let v=Mn(n,s,t,i,a);return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,d.jsxs)("div",{className:"af-min-w-0",children:[(0,d.jsx)("div",{className:"af-text-sm",children:e}),a&&(0,d.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:a})]}),(0,d.jsx)(Z,{variant:v.variant,className:"af-shrink-0",children:v.label})]}),v.detail&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:v.detail}),o&&(0,d.jsx)("div",{className:"af-mt-2",children:o})]})}function zr(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=bo(e.address)?e.address:null;if(s){for(let n of["line1","line2"]){let i=s[n];typeof i=="string"&&i&&a.push(i)}let t=["city","state","postal_code"].map(n=>s[n]).filter(n=>typeof n=="string"&&!!n).join(", ");t&&a.push(t),typeof s.country=="string"&&s.country&&a.push(s.country)}return a.length>0?a:Object.entries(e).map(([t,n])=>`${t}: ${jr(n)}`)}function wo(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Un({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=rt.useState(!1);if(!wo())return null;let g=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},v=i?(0,d.jsx)(ke.Check,{className:"af-h-3 af-w-3"}):(0,d.jsx)(ke.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,d.jsx)(P,{variant:"ghost",size:"icon",className:G("af-h-6 af-w-6 af-shrink-0",t),onClick:g,title:a,"aria-label":a,children:v}):(0,d.jsxs)(P,{variant:"outline",size:"sm",className:t,onClick:g,"aria-label":a,children:[i?(0,d.jsx)(ke.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,d.jsx)(ke.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function Bn({label:e,value:a}){return(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:Ya,children:e}),(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,d.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:a}),(0,d.jsx)(Un,{value:a,label:`Copy ${e}`})]})]})}function No({src:e}){let[a,s]=rt.useState(!1);return!e||a?(0,d.jsx)("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:(0,d.jsx)(ke.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,d.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>s(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Ha({title:e,action:a,children:s,className:t}){return(0,d.jsxs)("section",{className:G("af-rounded-lg af-border af-p-4",t),children:[(0,d.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,d.jsx)("h4",{className:qr,children:e}),a]}),(0,d.jsx)("div",{className:"af-mt-3",children:s})]})}function za({label:e,emphasis:a,divider:s,children:t}){return(0,d.jsxs)("div",{className:G("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[(0,d.jsx)("span",{className:a?"af-text-base af-font-semibold":Ya,children:e}),(0,d.jsx)("span",{className:G("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function Fn({onSelect:e,disabled:a,icon:s,children:t}){return(0,d.jsxs)(P,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:a,children:[(0,d.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),t]})}function So(e){let a=[];if(a.push({key:"placed",text:"Order placed",at:e.created_at}),e.paid_at&&a.push({key:"paid",text:`Payment received \u2014 ${W(Zt(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),t=s?rn(s):Mn("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);a.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${t.label.toLowerCase()}`,at:null,tone:t.variant==="destructive"?"destructive":t.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),t=s?rn(s):Mn("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);a.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${t.label.toLowerCase()}`,at:null,tone:t.variant==="destructive"?"destructive":t.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&a.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&&a.push({key:"refunded",text:`Refunded ${W(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&a.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),a}function Bs({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:g=!1,hasNextOrder:v=!1}){let{api:h}=te(),[r,b]=rt.useState(e),[w,p]=rt.useState(null),[u,f]=rt.useState(null),[x,N]=rt.useState(!1),[C,O]=rt.useState(!1),[z,c]=rt.useState(!1),[S,E]=rt.useState(!1),[J,B]=rt.useState(""),[R,H]=rt.useState(!1),[y,Q]=rt.useState(null),[le,ce]=rt.useState(!1),[ee,_e]=rt.useState(""),[Y,oe]=rt.useState([]),[fe,K]=rt.useState(!1),[Pe,Me]=rt.useState(!1),[xt,q]=rt.useState(null);rt.useEffect(()=>{b(e)},[e]);let pe=A=>{let Ae=A.id===r.id&&A.email_deliveries===void 0?{...A,email_deliveries:r.email_deliveries}:A;b(Ae),t?.(Ae)},xe=Object.entries(r.metadata??{}),de=Zt(r)-r.amount_refunded,Ue=(r.status==="paid"||r.status==="partially_refunded")&&de>0,k=A=>(typeof A.unitAmount=="number"?A.unitAmount:0)*(typeof A.quantity=="number"&&A.quantity>0?A.quantity:1),L=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),ge=Y.reduce((A,Ae)=>A+k(r.line_items[Ae]??{}),0)+(fe?L:0),Ke=r.tax_total??0,ze=r.automatic_tax&&r.tax_behavior==="exclusive"&&Ke>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,Ke-(r.tax_refunded??0)),Math.round(Ke*ge/(r.amount_total+(r.shipping_total??0)))):0,at=ge+ze,Je=Y.length>0||fe,st=Je?at:Qt(ee,r.currency),Gt=fa(r.currency)?"1":"0.01",ga=async()=>{try{N(!0),p(null),f(null),await h.resendOrderReceipt(r.id);let A=await h.getOrder(r.id);pe(A),f("Receipt email queued.")}catch(A){p(A instanceof Error?A.message:"Failed to resend receipt")}finally{N(!1)}},se=async()=>{try{O(!0),p(null),f(null);let A=await h.resetOrderDownloads(r.id);pe(A),c(!1),f("Download count reset.")}catch(A){p(A instanceof Error?A.message:"Failed to reset downloads")}finally{O(!1)}},De=r.line_items.some(A=>A.collectShippingAddress===!0),je=typeof r.merchant_fulfilled_at=="string",sa=ho.includes(r.status),_t=J.trim(),ka=xo.test(_t)&&_t.length<=$r,lt=async A=>{try{H(!0),Q(null),f(null);let Ae=await h.setOrderFulfillment(r.id,{fulfilled:A,...A&&_t?{trackingNumber:_t}:{}});pe(Ae),B(""),f(A?"Marked as shipped.":"Marked as not shipped.")}catch(Ae){Ae instanceof na&&Ae.status===409?Q(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Q(Ae instanceof Error?Ae.message:"Failed to update the order")}finally{H(!1)}},Qe=()=>{q(null),_e(String(vt(de,r.currency))),oe([]),K(!1),ce(!0)},I=A=>oe(Ae=>Ae.includes(A)?Ae.filter(Tt=>Tt!==A):[...Ae,A]),He=async(A,Ae)=>{if(s)try{Me(!0),q(null),await s(r,A,Ae);let Tt=await h.getOrder(r.id);pe(Tt),ce(!1),f("Refund issued.")}catch(Tt){q(Tt instanceof Error?Tt.message:"Refund failed")}finally{Me(!1)}},U=async()=>{if(Je){if(at<=0){q("The lines you picked were charged nothing");return}if(at>de){q(`That selection exceeds the refundable remainder (${W(de,r.currency)})`);return}await He(at,{...Y.length>0?{line_items:[...Y].sort((Ae,Tt)=>Ae-Tt)}:{},...fe?{shipping:!0}:{}});return}let A=Qt(ee,r.currency);if(A===null||A<=0){q("Enter a valid refund amount");return}if(A>de){q(`Amount exceeds the refundable remainder (${W(de,r.currency)})`);return}await He(A,{amount:A})},Pt=()=>He(de,{full:!0}),or=r.fulfillment_type==="download",lr=n&&De,Fi=So(r),Mi=r.shipping_address?zr(r.shipping_address).join(`
|
|
4
|
-
`):"",cr=r.shipping_total!=null,dr=!!r.automatic_tax&&r.tax_behavior==="exclusive"&&(r.tax_total??0)>0,Ui=!(r.automatic_tax&&r.tax_behavior==="exclusive")&&(r.tax_total??0)>0,ur=cr||dr,vs=[];return vs.push((0,d.jsx)(Fn,{icon:x?(0,d.jsx)(ke.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,d.jsx)(ke.Mail,{className:"af-h-4 af-w-4"}),disabled:x||r.fulfillment_status!=="fulfilled",onSelect:()=>{E(!1),ga()},children:"Resend receipt"},"resend")),or&&vs.push((0,d.jsx)(Fn,{icon:(0,d.jsx)(ke.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:C,onSelect:()=>{E(!1),c(!0)},children:"Reset download count"},"reset")),Ue&&vs.push((0,d.jsxs)("div",{children:[(0,d.jsx)(Fn,{icon:(0,d.jsx)(ke.Undo2,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{E(!1),Qe()},children:"Refund\u2026"}),!s&&(0,d.jsx)("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"af-mb-6",children:[(0,d.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,d.jsx)(ke.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,d.jsxs)("div",{className:"af-min-w-0",children:[(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,d.jsx)("h3",{className:"af-text-xl af-font-semibold",children:Da(r)}),(0,d.jsx)(Ja,{status:r.status}),n&&(0,d.jsx)(cs,{order:r}),r.is_test&&(0,d.jsx)(Z,{variant:"outline",children:"Test"})]}),(0,d.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",On(r.created_at)]}),r.is_test&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&(0,d.jsxs)("div",{className:"af-flex af-items-center",children:[(0,d.jsx)(P,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!g,"aria-label":"Previous order",children:(0,d.jsx)(ke.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,d.jsx)(P,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!v,"aria-label":"Next order",children:(0,d.jsx)(ke.ChevronRight,{className:"af-h-4 af-w-4"})})]}),lr&&(je?(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,d.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${On(r.merchant_fulfilled_at)}`:""]}),sa&&(0,d.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>lt(!1),disabled:R,children:[R?(0,d.jsx)(ke.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(ke.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):sa?(0,d.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,d.jsx)(Se,{value:J,onChange:A=>B(A.target.value),placeholder:"Tracking number (optional)",maxLength:$r,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:R}),(0,d.jsxs)(P,{variant:"default",className:"af-shrink-0",onClick:()=>lt(!0),disabled:R||!ka,children:[R?(0,d.jsx)(ke.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(ke.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),vs.length>0&&(0,d.jsxs)(Mr,{open:S,onOpenChange:E,children:[(0,d.jsx)(Ur,{asChild:!0,children:(0,d.jsx)(P,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,d.jsx)(ke.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,d.jsx)(Ln,{children:(0,d.jsx)("div",{className:"af-space-y-0.5",children:vs})})]})]})]}),lr&&!je&&!ka&&(0,d.jsx)("p",{className:"af-mt-2 af-text-xs af-text-destructive",children:"Tracking numbers can use letters, numbers, spaces, dashes and underscores \u2014 up to 100 characters."}),y&&(0,d.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:y}),u&&(0,d.jsx)("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:u}),w&&(0,d.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:w})]}),(0,d.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,d.jsxs)("div",{className:"af-space-y-6",children:[r.line_items.length>0&&(0,d.jsx)(Ha,{title:"Items",children:(0,d.jsx)("ul",{className:"af-space-y-3",children:r.line_items.map((A,Ae)=>{let Tt=typeof A.name=="string"&&A.name?A.name:"Item",fr=typeof A.quantity=="number"&&A.quantity>0?A.quantity:1,mr=typeof A.unitAmount=="number";return(0,d.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,d.jsx)(No,{src:typeof A.imageUrl=="string"&&A.imageUrl?A.imageUrl:void 0}),(0,d.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,d.jsxs)("div",{className:"af-text-sm af-font-medium",children:[Tt,typeof A.variantTitle=="string"&&A.variantTitle&&(0,d.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",A.variantTitle]})]}),(0,d.jsxs)("div",{className:Ya,children:[fr," \xD7"," ",mr?W(A.unitAmount,r.currency):"\u2014"]}),A.refunded===!0&&(0,d.jsx)(Z,{variant:"secondary",className:"af-mt-1",children:A.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,d.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:mr?W(A.unitAmount*fr,r.currency):"\u2014"})]},Ae)})})}),xe.length>0&&(0,d.jsx)(Ha,{title:"Order details",children:(0,d.jsx)("dl",{className:"af-space-y-2",children:xe.map(([A,Ae])=>(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{className:G(Ya,"af-capitalize"),children:A.replace(/_/g," ")}),(0,d.jsx)("dd",{className:"af-text-sm af-break-words",children:jr(Ae)})]},A))})}),(0,d.jsx)(Ha,{title:"Totals",children:(0,d.jsxs)("div",{className:"af-w-full",children:[ur&&(0,d.jsx)(za,{label:"Subtotal",children:W(r.amount_total,r.currency)}),cr&&(0,d.jsx)(za,{label:"Shipping",children:r.shipping_total===0?"Free":W(r.shipping_total??0,r.currency)}),dr&&(0,d.jsx)(za,{label:"Tax",children:W(r.tax_total??0,r.currency)}),(0,d.jsx)(za,{label:"Total",emphasis:!0,divider:ur,children:W(Zt(r),r.currency)}),Ui&&(0,d.jsx)(za,{label:"incl. tax",children:W(r.tax_total??0,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&(0,d.jsxs)(za,{label:"Your price",children:[W(r.base_amount_total,r.base_currency),(0,d.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(za,{label:"Refunded",children:["\u2212",W(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&(0,d.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",W(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),(0,d.jsx)(za,{label:"Net",children:(0,d.jsx)("span",{className:"af-font-medium",children:W(Math.max(0,Zt(r)-r.amount_refunded),r.currency)})})]})]})}),(0,d.jsx)(Ha,{title:"Timeline",children:(0,d.jsx)("ol",{className:"af-space-y-3",children:Fi.map(A=>(0,d.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,d.jsx)("span",{"aria-hidden":"true",className:G("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",A.tone==="destructive"?"af-bg-destructive":A.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,d.jsxs)("div",{className:"af-min-w-0",children:[(0,d.jsx)("div",{className:"af-text-sm af-break-words",children:A.text}),A.at&&(0,d.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:On(A.at)})]})]},A.key))})})]}),(0,d.jsxs)("div",{className:"af-space-y-6",children:[(0,d.jsx)(Ha,{title:"Customer",children:(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:Ya,children:"Email"}),(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,d.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||(0,d.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&(0,d.jsx)(Un,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:Ya,children:"Name"}),(0,d.jsx)("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:Ya,children:"Customer record"}),(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,d.jsx)("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),(0,d.jsx)(Z,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&(0,d.jsx)(Ha,{title:"Ship to",action:(0,d.jsx)(Un,{value:Mi,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,d.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:zr(r.shipping_address).map((A,Ae)=>(0,d.jsx)("div",{children:A},Ae))})}),(0,d.jsxs)(Ha,{title:"Emails",children:[(0,d.jsx)(ha,{deliveries:r.email_deliveries?.filter(A=>!["purchase_receipt","merchant_sale"].includes(A.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,d.jsxs)("div",{className:"af-space-y-4",children:[(0,d.jsx)(Hr,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(A=>A.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:(0,d.jsxs)(P,{variant:"outline",size:"sm",onClick:ga,disabled:x||r.fulfillment_status!=="fulfilled",children:[x?(0,d.jsx)(ke.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(ke.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,d.jsx)(Hr,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(A=>A.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),or&&(0,d.jsx)(Ha,{title:"Download",children:(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,d.jsx)(ke.Download,{className:"af-h-4 af-w-4"}),(0,d.jsxs)("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&(0,d.jsx)("a",{href:r.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,d.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,d.jsx)("summary",{className:G(qr,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,d.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,d.jsx)(Bn,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&(0,d.jsx)(Bn,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&(0,d.jsx)(Bn,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),(0,d.jsx)(wa,{open:z,onOpenChange:A=>{!A&&!C&&c(!1)},children:(0,d.jsxs)(oa,{children:[(0,d.jsxs)(la,{children:[(0,d.jsx)(da,{children:"Reset download count?"}),(0,d.jsx)(ua,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,d.jsxs)(ca,{children:[(0,d.jsx)(P,{variant:"outline",onClick:()=>c(!1),disabled:C,children:"Cancel"}),(0,d.jsx)(P,{onClick:se,disabled:C,children:C?"Resetting...":"Reset"})]})]})}),(0,d.jsx)(wa,{open:le,onOpenChange:A=>{!A&&!Pe&&ce(!1)},children:(0,d.jsxs)(oa,{children:[(0,d.jsxs)(la,{children:[(0,d.jsx)(da,{children:"Refund order"}),(0,d.jsxs)(ua,{children:["Refund up to ",W(de,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,d.jsxs)("div",{className:"af-space-y-4",children:[(r.line_items.length>0||L>0)&&(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsx)(Re,{children:"Items"}),(0,d.jsxs)("div",{className:"af-space-y-2",children:[r.line_items.map((A,Ae)=>{let Tt=A.refunded===!0;return(0,d.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,d.jsx)("input",{type:"checkbox",checked:Y.includes(Ae),onChange:()=>I(Ae),disabled:Pe||Tt,className:"af-h-4 af-w-4"}),(0,d.jsxs)("span",{className:Tt?"af-text-muted-foreground af-line-through":void 0,children:[typeof A.name=="string"&&A.name?A.name:"Item",typeof A.variantTitle=="string"&&A.variantTitle?` \u2014 ${A.variantTitle}`:"",typeof A.quantity=="number"&&A.quantity>1?` \xD7 ${A.quantity}`:""]}),(0,d.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Tt?"Refunded":W(k(A),r.currency)})]},Ae)}),L>0&&(0,d.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,d.jsx)("input",{type:"checkbox",checked:fe,onChange:A=>K(A.target.checked),disabled:Pe,className:"af-h-4 af-w-4"}),(0,d.jsx)("span",{children:"Shipping"}),(0,d.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:W(L,r.currency)})]})]})]}),(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)(Re,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),(0,d.jsx)(Se,{id:"refund-amount",type:"number",min:"0",step:Gt,value:Je?String(vt(at,r.currency)):ee,onChange:A=>_e(A.target.value),disabled:Pe||Je}),Je&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),xt&&(0,d.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:xt}),(0,d.jsxs)(ca,{children:[(0,d.jsx)(P,{variant:"outline",onClick:()=>ce(!1),disabled:Pe,children:"Cancel"}),(0,d.jsx)(P,{variant:"outline",onClick:Pt,disabled:Pe,children:"Refund everything"}),(0,d.jsx)(P,{variant:"destructive",onClick:U,disabled:Pe,children:Pe?"Refunding...":st!==null&&st>0?`Refund ${W(st,r.currency)}`:"Refund"})]})]})})]})}var dn=ne(require("react"),1),un=require("lucide-react");var pt=require("react/jsx-runtime");function bt({title:e,onBackToWebsite:a,hideBackButton:s=!1,children:t,className:n}){let i=dn.useRef(null);return dn.useEffect(()=>{i.current?.focus()},[]),(0,pt.jsxs)("div",{className:G("af-bg-background",n),children:[(0,pt.jsxs)("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:[(0,pt.jsx)("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),a&&!s&&(0,pt.jsxs)(P,{type:"button",variant:"outline",size:"sm",onClick:a,children:[(0,pt.jsx)(un.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,pt.jsx)("div",{className:"af-p-4",children:t})]})}function X({className:e}){return(0,pt.jsx)("div",{"aria-hidden":"true",className:G("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function Ye({label:e,children:a,detail:s,valueClassName:t}){return(0,pt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,pt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,pt.jsx)("div",{className:G("af-mt-1 af-text-lg af-font-semibold",t),children:a}),s&&(0,pt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function $t({message:e,onRetry:a}){return(0,pt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,pt.jsx)("span",{children:e}),(0,pt.jsxs)(P,{type:"button",variant:"ghost",size:"sm",onClick:a,children:[(0,pt.jsx)(un.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Sa({icon:e,children:a}){return(0,pt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,pt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:a})]})}var _=require("react/jsx-runtime"),Ro={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Gr={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Wr(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Kr(e){let a=Array.isArray(e.line_items)?e.line_items:[],s=a[0];if(!s)return"\u2014";let t=typeof s.name=="string"&&s.name?s.name:"Item",n=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,i=n>1?`${t} \xD7${n}`:t;return a.length>1?`${i} +${a.length-1} more`:i}function fn(e){return e.customer?.name||e.customer_name||null}function Za({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o}){let{api:g}=te(),v=Ls({refreshKey:s}),{orders:h,total:r,isLoading:b,error:w,page:p,pageSize:u,hasNextPage:f,hasPreviousPage:x,setPage:N,setPageSize:C,customerEmail:O,setCustomerEmail:z,setStatusIn:c,from:S,setFrom:E,to:J,setTo:B,showAbandoned:R,setShowAbandoned:H,setUnfulfilledOnly:y,refetch:Q}=v,[le,ce]=yt.useState("list"),[ee,_e]=yt.useState(null),[Y,oe]=yt.useState(""),[fe,K]=yt.useState(""),[Pe,Me]=yt.useState(n?"needs_shipping":"all"),[xt,q]=yt.useState(!1),[pe,xe]=yt.useState(!!t),[de,Ue]=yt.useState(null);yt.useEffect(()=>{if(!t)return;let U=!1;return xe(!0),Ue(null),g.getOrder(t).then(Pt=>{U||(_e(Pt),ce("detail"))}).catch(()=>{U||Ue("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{U||xe(!1)}),()=>{U=!0}},[g,t]);let k=yt.useCallback(U=>{Me(U);let Pt=Gr[U];c(Pt.statusIn),y(Pt.unfulfilledOnly)},[c,y]);yt.useEffect(()=>{n&&y(!0)},[]);let L=yt.useRef(!n);yt.useEffect(()=>{L.current||b||(L.current=!0,h.length===0&&k("all"))},[b,h.length,k]);let ge=le==="detail"&&!!ee;yt.useEffect(()=>{o?.(ge)},[ge,o]);let Ke=(S?1:0)+(J?1:0)+(R?1:0),ze=Ke>0||!!O||!!fe,at=!!S&&!!J&&S>J,Je=U=>{_e(U),ce("detail")},st=()=>{ce("list"),_e(null),Q()},Gt=U=>{let Pt=U.trim();if(!Pt){K(""),O&&z("");return}if(Pt.startsWith("#")||/^\d+$/.test(Pt)){K(Pt),O&&z("");return}K(""),z(Pt)},ga=()=>{oe(""),K(""),z(""),E(""),B(""),H(!1),q(!1)},se=fe.replace(/^#/,"").toLowerCase(),De=se?h.filter(U=>String(U.order_number??"")===se||U.id.toLowerCase().startsWith(se)):h,je=ee?h.findIndex(U=>U.id===ee.id):-1,sa=je>0,_t=je>=0&&je<h.length-1;if(pe)return(0,_.jsx)("div",{className:a,children:(0,_.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,_.jsx)(Ht.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(le==="detail"&&ee)return(0,_.jsx)("div",{className:a,children:(0,_.jsx)(Bs,{order:ee,onBack:st,onRefund:e,onOrderUpdated:U=>_e(U),allowFulfillment:n,onPrevOrder:sa?()=>_e(h[je-1]):void 0,onNextOrder:_t?()=>_e(h[je+1]):void 0,hasPrevOrder:sa,hasNextOrder:_t},ee.id)});let lt=(0,_.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[de&&(0,_.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:de}),(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)("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:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(U=>(0,_.jsx)("button",{type:"button","aria-pressed":Pe===U,onClick:()=>k(U),className:G("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Pe===U?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ro[U]},U))}),(0,_.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,_.jsx)(Ht.Search,{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"}),(0,_.jsx)(Se,{type:"text",value:Y,onChange:U=>oe(U.target.value),onBlur:()=>Gt(Y),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),Gt(Y))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,_.jsxs)(P,{type:"button",variant:Ke>0?"secondary":"ghost",size:"sm",onClick:()=>q(U=>!U),"aria-expanded":xt,children:[(0,_.jsx)(Ht.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ke>0&&(0,_.jsx)(Z,{variant:"secondary",className:"af-ml-2",children:Ke})]}),ze&&(0,_.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:ga,children:"Clear filters"})]}),(xt||!!S||!!J)&&(0,_.jsxs)("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:[(0,_.jsx)(Re,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,_.jsx)(Se,{id:"orders-from",type:"date",value:S,max:J||void 0,onChange:U=>E(U.target.value),className:"af-w-[170px]"}),(0,_.jsx)(Re,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,_.jsx)(Se,{id:"orders-to",type:"date",value:J,min:S||void 0,onChange:U=>B(U.target.value),className:"af-w-[170px]"}),!Gr[Pe].statusIn&&(0,_.jsx)(P,{type:"button",variant:R?"secondary":"ghost",size:"sm",onClick:()=>H(!R),"aria-pressed":R,children:R?"Hide abandoned":"Show abandoned"})]}),at&&(0,_.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(b)return(0,_.jsxs)("div",{className:a,children:[lt,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,_.jsx)(X,{className:"af-h-4 af-w-16"}),(0,_.jsx)(X,{className:"af-h-4 af-w-14"})]}),(0,_.jsx)(X,{className:"af-mt-2 af-h-3 af-w-40"}),(0,_.jsx)(X,{className:"af-mt-2 af-h-3 af-w-24"})]},U))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(Le,{children:[(0,_.jsx)(Oe,{children:(0,_.jsxs)(be,{children:[(0,_.jsx)(F,{children:"Order"}),(0,_.jsx)(F,{children:"Date"}),(0,_.jsx)(F,{children:"Customer"}),(0,_.jsx)(F,{children:"Items"}),(0,_.jsx)(F,{className:"af-text-right",children:"Total"}),(0,_.jsx)(F,{children:"Status"}),(0,_.jsx)(F,{className:"af-w-8"})]})}),(0,_.jsx)(Be,{"aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,_.jsxs)(be,{children:[(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-4 af-w-14"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-4 af-w-24"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-4 af-w-40"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-4 af-w-32"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-5 af-w-16"})}),(0,_.jsx)(M,{})]},U))})]})}),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(w)return(0,_.jsxs)("div",{className:a,children:[lt,(0,_.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,_.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,_.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>Q(),children:"Try again"})]})]});let Qe=Pe!=="all";if(De.length===0&&p===0)return(0,_.jsxs)("div",{className:a,children:[(ze||Qe)&<,(0,_.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,_.jsx)(Ht.Receipt,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,_.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:ze||Qe?"No orders match these filters.":i??(0,_.jsxs)(_.Fragment,{children:["No orders yet.",(0,_.jsx)("br",{}),"Orders will appear here when someone buys from your website."]})}),!ze&&!Qe&&(0,_.jsx)(P,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>H(!0),children:"Show abandoned checkouts"})]})]});let I=p*u+1,He=Math.min((p+1)*u,r);return(0,_.jsxs)("div",{className:a,children:[lt,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:De.map(U=>(0,_.jsxs)("button",{type:"button",onClick:()=>Je(U),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[(0,_.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,_.jsx)("span",{className:"af-font-medium",children:Da(U)}),(0,_.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:W(Zt(U),U.currency)})]}),(0,_.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,_.jsxs)("div",{className:"af-truncate af-text-sm",children:[U.customer_email||(0,_.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),fn(U)&&(0,_.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",fn(U)]})]}),(0,_.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Kr(U)}),U.amount_refunded>0&&(0,_.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",W(U.amount_refunded,U.currency)," refunded"]})]}),(0,_.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,_.jsx)(Ja,{status:U.status}),(0,_.jsx)(xs,{deliveries:U.email_deliveries}),U.is_test&&(0,_.jsx)(Z,{variant:"outline",children:"Test"}),n&&(0,_.jsx)(cs,{order:U}),(0,_.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Wr(U.created_at)})]})]},U.id))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(Le,{children:[(0,_.jsx)(Oe,{children:(0,_.jsxs)(be,{children:[(0,_.jsx)(F,{children:"Order"}),(0,_.jsx)(F,{children:"Date"}),(0,_.jsx)(F,{children:"Customer"}),(0,_.jsx)(F,{children:"Items"}),(0,_.jsx)(F,{className:"af-text-right",children:"Total"}),(0,_.jsx)(F,{children:"Status"}),(0,_.jsx)(F,{className:"af-w-8"})]})}),(0,_.jsx)(Be,{children:De.map(U=>(0,_.jsxs)(be,{onClick:()=>Je(U),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,_.jsxs)(M,{className:"af-whitespace-nowrap af-font-medium",children:[(0,_.jsx)("button",{type:"button",onClick:Pt=>{Pt.stopPropagation(),Je(U)},"aria-label":`Open order ${Da(U)}`,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:Da(U)}),U.is_test&&(0,_.jsx)(Z,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,_.jsx)(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Wr(U.created_at)}),(0,_.jsxs)(M,{className:"af-max-w-[220px]",children:[(0,_.jsx)("div",{className:"af-truncate",children:U.customer_email||(0,_.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),fn(U)&&(0,_.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:fn(U)})]}),(0,_.jsx)(M,{className:"af-max-w-[220px]",children:(0,_.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:Kr(U)})}),(0,_.jsxs)(M,{className:"af-whitespace-nowrap af-text-right",children:[(0,_.jsx)("div",{className:"af-font-medium af-tabular-nums",children:W(Zt(U),U.currency)}),U.amount_refunded>0&&(0,_.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",W(U.amount_refunded,U.currency)," ","refunded"]})]}),(0,_.jsx)(M,{children:(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,_.jsx)(Ja,{status:U.status}),(0,_.jsx)(xs,{deliveries:U.email_deliveries}),n&&(0,_.jsx)(cs,{order:U})]})}),(0,_.jsx)(M,{className:"af-w-8 af-text-right",children:(0,_.jsx)(Ht.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},U.id))})]})}),(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,_.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,_.jsx)("span",{children:se?`${De.length} matching this page`:`Showing ${I}-${He} of ${r}`}),(0,_.jsxs)(Wt,{value:String(u),onValueChange:U=>C(Number(U)),children:[(0,_.jsx)(Bt,{className:"af-w-[70px] af-h-8",children:(0,_.jsx)(Kt,{})}),(0,_.jsxs)(Ft,{children:[(0,_.jsx)(qe,{value:"10",children:"10"}),(0,_.jsx)(qe,{value:"25",children:"25"}),(0,_.jsx)(qe,{value:"50",children:"50"}),(0,_.jsx)(qe,{value:"100",children:"100"})]})]}),(0,_.jsx)("span",{children:"per page"})]}),(0,_.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>N(p-1),disabled:!x,children:[(0,_.jsx)(Ht.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,_.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>N(p+1),disabled:!f,children:["Next",(0,_.jsx)(Ht.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var pn=ne(require("react"),1),Ra=require("lucide-react");var kt=ne(require("react"),1);function Fs({initialPageSize:e=25}={}){let{api:a}=te(),[s,t]=kt.useState([]),[n,i]=kt.useState(0),[o,g]=kt.useState(!0),[v,h]=kt.useState(null),[r,b]=kt.useState(0),[w,p]=kt.useState(e),[u,f]=kt.useState(""),x=kt.useRef(0),N=kt.useCallback(async()=>{let O=++x.current;try{g(!0),h(null);let z={limit:w,offset:r*w};u.trim()&&(z.email=u.trim());let c=await a.getCustomers(z);if(O!==x.current)return;t(c.customers),i(c.total)}catch(z){if(O!==x.current)return;h(z instanceof Error?z:new Error("Failed to fetch customers"))}finally{O===x.current&&g(!1)}},[a,r,w,u]);kt.useEffect(()=>{N()},[N]);let C=Math.ceil(n/w);return{customers:s,total:n,isLoading:o,error:v,page:r,pageSize:w,hasNextPage:r<C-1,hasPreviousPage:r>0,setPage:b,setPageSize:O=>{p(O),b(0)},email:u,setEmail:O=>{f(O),b(0)},refetch:N}}var Qa=ne(require("react"),1),mn=require("lucide-react");var ue=require("react/jsx-runtime");function Jr(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function _o(e){let a=[];e.name&&a.push(e.name),a.push(e.line1),e.line2&&a.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&a.push(s),e.country&&a.push(e.country),a}function Ms({customer:e,onBack:a,className:s}){let{api:t}=te(),[n,i]=Qa.useState(null),[o,g]=Qa.useState([]),[v,h]=Qa.useState(!0),[r,b]=Qa.useState(null);Qa.useEffect(()=>{let u=!1;return h(!0),b(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([f,x])=>{u||(i(f),g(x.orders))}).catch(f=>{u||b(f instanceof Error?f.message:"Failed to load customer")}).finally(()=>{u||h(!1)}),()=>{u=!0}},[t,e.id,e.email]);let w=n?.addresses??[],p=n?.order_count??o.length;return(0,ue.jsxs)("div",{className:s,children:[(0,ue.jsxs)("div",{className:"af-mb-6",children:[(0,ue.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,ue.jsx)(mn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,ue.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,ue.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Jr(e.created_at)]})]}),v?(0,ue.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ue.jsx)(mn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?(0,ue.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):(0,ue.jsxs)("div",{className:"af-space-y-6",children:[(0,ue.jsx)(ha,{deliveries:n?.email_deliveries}),(0,ue.jsxs)("div",{children:[(0,ue.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,ue.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,ue.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ue.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,ue.jsx)("span",{children:e.email})]}),e.name&&(0,ue.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ue.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,ue.jsx)("span",{children:e.name})]}),e.phone&&(0,ue.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ue.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,ue.jsx)("span",{children:e.phone})]}),(0,ue.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ue.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,ue.jsx)("span",{children:p})]})]})]}),w.length>0&&(0,ue.jsxs)("div",{children:[(0,ue.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,ue.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:w.map(u=>(0,ue.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&(0,ue.jsx)(Z,{variant:"secondary",className:"af-mb-1",children:"Default"}),_o(u).map((f,x)=>(0,ue.jsx)("div",{children:f},x))]},u.id))})]}),(0,ue.jsxs)("div",{children:[(0,ue.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,ue.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,ue.jsxs)(Le,{children:[(0,ue.jsx)(Oe,{children:(0,ue.jsxs)(be,{children:[(0,ue.jsx)(F,{children:"Date"}),(0,ue.jsx)(F,{children:"Amount"}),(0,ue.jsx)(F,{children:"Status"})]})}),(0,ue.jsx)(Be,{children:o.map(u=>(0,ue.jsxs)(be,{children:[(0,ue.jsx)(M,{className:"af-text-muted-foreground",children:Jr(u.created_at)}),(0,ue.jsx)(M,{children:W(Zt(u),u.currency)}),(0,ue.jsx)(M,{children:(0,ue.jsx)($a,{status:u.status})})]},u.id))})]})]})]})]})}var ae=require("react/jsx-runtime");function Po(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Us({className:e}){let{customers:a,total:s,isLoading:t,error:n,page:i,pageSize:o,hasNextPage:g,hasPreviousPage:v,setPage:h,setPageSize:r,email:b,setEmail:w,refetch:p}=Fs(),[u,f]=pn.useState("list"),[x,N]=pn.useState(null),[C,O]=pn.useState(""),z=B=>{N(B),f("detail")},c=()=>{f("list"),N(null),p()};if(u==="detail"&&x)return(0,ae.jsx)("div",{className:e,children:(0,ae.jsx)(Ms,{customer:x,onBack:c})});let S=(0,ae.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,ae.jsx)(Se,{type:"email",value:C,onChange:B=>O(B.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),w(C.trim()))}}),(0,ae.jsxs)(P,{type:"button",variant:"outline",size:"sm",onClick:()=>w(C.trim()),children:[(0,ae.jsx)(Ra.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),b&&(0,ae.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{O(""),w("")},children:"Clear"})]});if(t)return(0,ae.jsxs)("div",{className:e,children:[S,(0,ae.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ae.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,ae.jsxs)("div",{className:e,children:[S,(0,ae.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ae.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return(0,ae.jsxs)("div",{className:e,children:[b&&S,(0,ae.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,ae.jsx)(Ra.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ae.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:b?"No customers match that email.":(0,ae.jsxs)(ae.Fragment,{children:["No customers yet.",(0,ae.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let E=i*o+1,J=Math.min((i+1)*o,s);return(0,ae.jsxs)("div",{className:e,children:[S,(0,ae.jsxs)(Le,{children:[(0,ae.jsx)(Oe,{children:(0,ae.jsxs)(be,{children:[(0,ae.jsx)(F,{children:"Email"}),(0,ae.jsx)(F,{children:"Name"}),(0,ae.jsx)(F,{children:"Customer since"}),(0,ae.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,ae.jsx)(Be,{children:a.map(B=>(0,ae.jsxs)(be,{children:[(0,ae.jsx)(M,{className:"af-font-medium",children:B.email}),(0,ae.jsx)(M,{children:B.name||(0,ae.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ae.jsx)(M,{className:"af-text-muted-foreground",children:Po(B.created_at)}),(0,ae.jsx)(M,{className:"af-text-right",children:(0,ae.jsx)(P,{variant:"ghost",size:"icon",onClick:()=>z(B),title:"View customer",children:(0,ae.jsx)(Ra.Eye,{className:"af-h-4 af-w-4"})})})]},B.id))})]}),(0,ae.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ae.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ae.jsxs)("span",{children:["Showing ",E,"-",J," of ",s]}),(0,ae.jsxs)(Wt,{value:String(o),onValueChange:B=>r(Number(B)),children:[(0,ae.jsx)(Bt,{className:"af-w-[70px] af-h-8",children:(0,ae.jsx)(Kt,{})}),(0,ae.jsxs)(Ft,{children:[(0,ae.jsx)(qe,{value:"10",children:"10"}),(0,ae.jsx)(qe,{value:"25",children:"25"}),(0,ae.jsx)(qe,{value:"50",children:"50"}),(0,ae.jsx)(qe,{value:"100",children:"100"})]})]}),(0,ae.jsx)("span",{children:"per page"})]}),(0,ae.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ae.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>h(i-1),disabled:!v,children:[(0,ae.jsx)(Ra.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ae.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>h(i+1),disabled:!g,children:["Next",(0,ae.jsx)(Ra.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ce=ne(require("react"),1),ut=require("lucide-react");var dt=ne(require("react"),1);function Xa({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=te(),[n,i]=dt.useState([]),[o,g]=dt.useState(0),[v,h]=dt.useState(null),[r,b]=dt.useState(!0),[w,p]=dt.useState(null),[u,f]=dt.useState(0),[x,N]=dt.useState(e),[C,O]=dt.useState(void 0),[z,c]=dt.useState(""),[S,E]=dt.useState(""),[J,B]=dt.useState(""),[R,H]=dt.useState(""),[y,Q]=dt.useState(""),le=C?C.join(","):"",ce=dt.useRef(0),ee=dt.useCallback(async()=>{let Y=++ce.current;b(!0),p(null);try{let oe={labels:le?le.split(","):void 0,customerEmail:z||void 0,q:S||void 0,from:J||void 0,to:R||void 0,retainerId:y||void 0,includeAggregates:s,limit:x,offset:u*x},fe=await t.getInvoices(oe);if(Y!==ce.current)return;if(u>0&&u*x>=fe.total){f(Math.max(0,Math.ceil(fe.total/x)-1));return}i(fe.invoices),g(fe.total),s&&h(fe.aggregates??null)}catch(oe){if(Y!==ce.current)return;p(oe instanceof Error?oe:new Error("Failed to fetch invoices"))}finally{Y===ce.current&&b(!1)}},[t,le,z,S,J,R,y,u,x,s]);dt.useEffect(()=>{ee()},[ee,a]);let _e=Y=>oe=>{f(0),Y(oe)};return{invoices:n,total:o,aggregates:v,isLoading:r,error:w,page:u,pageSize:x,hasNextPage:(u+1)*x<o,hasPreviousPage:u>0,setPage:f,setPageSize:_e(N),labels:C,setLabels:_e(O),customerEmail:z,setCustomerEmail:_e(c),q:S,setQ:_e(E),from:J,setFrom:_e(B),to:R,setTo:_e(H),retainerId:y,setRetainerId:_e(Q),clearFilters:()=>{f(0),O(void 0),c(""),E(""),B(""),H(""),Q("")},refetch:ee}}var l=require("react/jsx-runtime"),To={creating:"Creating",failed:"Failed",awaiting_payment:"Awaiting payment",overdue:"Overdue",payment_processing:"Payment processing",awaiting_authentication:"Awaiting authentication",paid:"Paid",paid_outside_stripe:"Paid outside Stripe",paid_by_credit:"Paid by credit",partially_refunded:"Partially refunded",refunded:"Refunded",disputed:"Disputed",voided:"Voided",uncollectible:"Marked uncollectible"};function qn(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:To[e.label]??e.label}function Co(e){switch(e){case"paid":case"paid_outside_stripe":case"paid_by_credit":return"success";case"overdue":case"disputed":case"failed":return"destructive";case"partially_refunded":case"refunded":case"payment_processing":case"awaiting_authentication":return"warning";case"awaiting_payment":return"secondary";default:return"outline"}}var zn={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},ko={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function us({invoice:e,className:a}){return(0,l.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,l.jsx)(Z,{variant:Co(e.label),className:a,children:qn(e)}),e.collection_method==="charge_automatically"&&(0,l.jsx)(Z,{variant:"secondary",children:"Managed in Stripe"})]})}function vn({delivery:e,className:a}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,l.jsx)(Z,{variant:s,className:a,children:zn[e.state]??e.state})}function ds(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ta(e){if(!e)return"\u2014";let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Yr={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Vn={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0};function Eo(e){let a=e==null?"":String(e),s=/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(a),t=s?`'${a}`:a;return s||/[",;\r\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}var $n=100,Hn=5e3;async function Io(e,a){let s=[],t=0;for(let n=0;n<Hn;n+=$n){let i=await e.getInvoices({...a,limit:$n,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<$n||s.length>=t)break}return{invoices:s.slice(0,Hn),total:t,truncated:t>s.length||t>Hn}}function Qr(e){let a=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],s=e.map(t=>[t.id,ds(t),qn(t),t.customer_name??"",t.customer_email??"",t.created_at,t.due_at??"",t.paid_at??"",t.currency.toUpperCase(),W(t.amount_subtotal,t.currency),W(t.tax_total,t.currency),W(t.amount_total,t.currency),t.amount_due===null?"":W(t.amount_due,t.currency),t.amount_paid===null?"":W(t.amount_paid,t.currency),W(t.amount_refunded,t.currency),t.payment_method??"",t.pay_url??"",t.retainer_id??"",t.replaces_order_id??"",t.replaced_by_order_id??"",t.tax_behavior??"",t.discount_total===void 0?"":W(t.discount_total,t.currency),t.collection_method??""]);return[a,...s].map(t=>t.map(Eo).join(",")).join(`
|
|
5
|
-
`)}function Ao(e){if(typeof document>"u")return;let a=new Blob([Qr(e)],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(a),t=document.createElement("a");t.href=s,t.download=`invoices-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(t),t.click(),document.body.removeChild(t),URL.revokeObjectURL(s)}function es({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:g=null,onClearRetainerFilter:v}){let{api:h}=te(),{invoices:r,total:b,isLoading:w,error:p,page:u,pageSize:f,hasNextPage:x,hasPreviousPage:N,setPage:C,labels:O,setLabels:z,customerEmail:c,setCustomerEmail:S,q:E,setQ:J,from:B,setFrom:R,to:H,setTo:y,retainerId:Q,setRetainerId:le,refetch:ce}=Xa({refreshKey:a}),[ee,_e]=Ce.useState("open"),[Y,oe]=Ce.useState(""),[fe,K]=Ce.useState(null),Pe=Ce.useRef(0),Me=Ce.useCallback(I=>{Pe.current++,q(!1),K(I)},[]),[xt,q]=Ce.useState(!1),[pe,xe]=Ce.useState(0),[de,Ue]=Ce.useState(null),[k,L]=Ce.useState(!1),[ge,Ke]=Ce.useState(0);Ce.useEffect(()=>{K(I=>{if(!I)return I;let He=r.find(U=>U.id===I.id);return He&&He!==I?He:I})},[r]);let[ze,at]=Ce.useState(!1),[Je,st]=Ce.useState(null),Gt=async()=>{if(!ze){at(!0),st(null);try{let{invoices:I,total:He,truncated:U}=await Io(h,{labels:O,customerEmail:c,q:E,from:B,to:H,retainerId:Q});Ao(I),st(U?`Exported the first ${I.length.toLocaleString()} of ${He.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{st("Couldn't export \u2014 try again.")}finally{at(!1)}}},ga=!c&&!E&&!B&&!H&&!Q,[se,De]=Ce.useState(null);Ce.useEffect(()=>{if(w||b>0||!ga||ee!=="open")return;let I=!1;return h.getInvoices({limit:1}).then(He=>{I||De(He.total>0)}).catch(()=>{I||De(!0)}),()=>{I=!0}},[h,w,b,ga,ee,a]),Ce.useEffect(()=>{z(Vn.open)},[]),Ce.useEffect(()=>{let I=g?.id??"";I!==Q&&(le(I),I&&(_e("all"),z(Vn.all),S(""),J(""),oe(""),R(""),y("")))},[g?.id]),Ce.useEffect(()=>{let I=!1;return L(!1),h.getInvoiceSettings().then(He=>{I||Ue({payments_active:He.payments_active,blocked:He.blocked})}).catch(()=>{I||L(!0)}),()=>{I=!0}},[h,a,ge]),Ce.useEffect(()=>{if(!s)return;let I=!1,He=Pe.current;return q(!1),h.getInvoice(s).then(U=>{!I&&He===Pe.current&&K(U)}).catch(()=>{!I&&He===Pe.current&&q(!0)}),()=>{I=!0}},[h,s,pe]),Ce.useEffect(()=>{t?.(fe!==null)},[fe,t]);let je=I=>{_e(I),z(Vn[I])},sa=I=>{let He=I.trim();if(!He){E&&J(""),c&&S("");return}if(He.includes("@")){E&&J(""),S(He);return}c&&S(""),J(He.replace(/^#/,""))},_t=r,ka=xt&&(0,l.jsxs)("div",{role:"alert",className:"af-mb-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't open the requested invoice. ",(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>xe(I=>I+1),children:"Retry opening invoice"})]});if(fe)return(0,l.jsxs)("div",{className:e,children:[ka,(0,l.jsx)(bn,{invoice:fe,refreshKey:a,onBack:()=>{Me(null),ce()}},fe.id)]});let lt=(0,l.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[k&&(0,l.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>Ke(I=>I+1),children:"Retry setup check"})]}),ka,de?.blocked&&(0,l.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",de.blocked.reason?`: ${de.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),g&&(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,l.jsxs)(Z,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",g.label]}),v&&(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:v,children:"Clear schedule filter"})]}),(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,l.jsx)("div",{role:"group","aria-label":"Invoice views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Object.keys(Yr).map(I=>(0,l.jsx)("button",{type:"button","aria-pressed":ee===I,onClick:()=>je(I),className:G("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",ee===I?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Yr[I]},I))}),(0,l.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,l.jsx)(ut.Search,{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"}),(0,l.jsx)(Se,{type:"text",value:Y,onChange:I=>oe(I.target.value),onBlur:()=>sa(Y),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),sa(Y))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,l.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,l.jsx)(Re,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,l.jsx)(Se,{id:"invoices-from",type:"date",value:B,max:H||void 0,onChange:I=>R(I.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,l.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,l.jsx)(Re,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,l.jsx)(Se,{id:"invoices-to",type:"date",value:H,min:B||void 0,onChange:I=>y(I.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,l.jsxs)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>void Gt(),disabled:ze||w||!!p||b===0,"aria-busy":ze,children:[(0,l.jsx)(ut.Download,{className:"af-h-4 af-w-4 af-mr-1"}),ze?"Exporting\u2026":"Export CSV (all matching)"]})]}),Je&&(0,l.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:Je})]});return w?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(I=>(0,l.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,l.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,l.jsx)(X,{className:"af-h-4 af-w-20"}),(0,l.jsx)(X,{className:"af-h-4 af-w-16"})]}),(0,l.jsx)(X,{className:"af-mt-2 af-h-3 af-w-40"})]},I))})]}):p?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>void ce(),children:"Retry"})]})]}):b===0&&ga&&se===!1&&ee==="open"?de?.blocked?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)(gn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)(gn,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):de&&!de.payments_active?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)(gn,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)(gn,{heading:"No invoices yet",body:!de||k?"Once invoice setup is ready, you can send invoices from the chat.":"Ask in the chat to send an invoice to a client for your services."})]}):(0,l.jsxs)("div",{className:e,children:[lt,_t.length===0?(0,l.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:"No invoices match."}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:_t.map(I=>(0,l.jsxs)("button",{type:"button",onClick:()=>Me(I),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,l.jsx)("span",{className:"af-font-medium",children:ds(I)}),(0,l.jsx)(us,{invoice:I})]}),(0,l.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:I.customer_name??I.customer_email??"\u2014"}),I.delivery&&(0,l.jsx)("div",{className:"af-mt-1",children:(0,l.jsx)(vn,{delivery:I.delivery})}),(0,l.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[(0,l.jsx)("span",{children:I.collection_method==="charge_automatically"?"Automatic collection":I.due_at?`Due ${ta(I.due_at)}`:"Due on receipt"}),(0,l.jsx)("span",{className:"af-font-medium af-tabular-nums",children:W(I.amount_due??I.amount_total,I.currency)})]})]},I.id))}),(0,l.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,l.jsxs)(Le,{children:[(0,l.jsx)(Oe,{children:(0,l.jsxs)(be,{children:[(0,l.jsx)(F,{children:"Invoice"}),(0,l.jsx)(F,{children:"Created"}),(0,l.jsx)(F,{children:"Customer"}),(0,l.jsx)(F,{children:"Due"}),(0,l.jsx)(F,{className:"af-text-right",children:"Amount"}),(0,l.jsx)(F,{children:"Status"}),(0,l.jsx)(F,{children:"Delivery"}),(0,l.jsx)(F,{className:"af-w-8"})]})}),(0,l.jsx)(Be,{children:_t.map(I=>(0,l.jsxs)(be,{className:"af-cursor-pointer",onClick:()=>Me(I),children:[(0,l.jsx)(M,{className:"af-font-medium",children:(0,l.jsx)("button",{type:"button",className:"af-text-left hover:af-underline focus-visible:af-ring-2 focus-visible:af-ring-ring",onClick:He=>{He.stopPropagation(),Me(I)},"aria-label":`Open invoice ${ds(I)}`,children:ds(I)})}),(0,l.jsx)(M,{children:ta(I.created_at)}),(0,l.jsxs)(M,{children:[(0,l.jsx)("div",{children:I.customer_name??"\u2014"}),(0,l.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:I.customer_email})]}),(0,l.jsx)(M,{children:I.collection_method==="charge_automatically"?"Automatic":I.due_at?ta(I.due_at):"On receipt"}),(0,l.jsx)(M,{className:"af-text-right af-tabular-nums",children:W(I.amount_due??I.amount_total,I.currency)}),(0,l.jsx)(M,{children:(0,l.jsx)(us,{invoice:I})}),(0,l.jsx)(M,{children:(0,l.jsx)(vn,{delivery:I.delivery})}),(0,l.jsx)(M,{children:(0,l.jsx)(ut.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},I.id))})]})}),(0,l.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,l.jsxs)("span",{children:[b," invoice",b===1?"":"s"]}),(0,l.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,l.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>C(u-1),disabled:!N,"aria-label":"Previous page",children:(0,l.jsx)(ut.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,l.jsxs)("span",{className:"af-tabular-nums",children:[u*f+1,"\u2013",Math.min((u+1)*f,b)]}),(0,l.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>C(u+1),disabled:!x,"aria-label":"Next page",children:(0,l.jsx)(ut.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function gn({heading:e,body:a,action:s}){return(0,l.jsxs)("div",{className:"af-rounded-md af-border af-px-6 af-py-10 af-text-center",children:[(0,l.jsx)(ut.FileText,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":"true"}),(0,l.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:e}),(0,l.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&(0,l.jsx)(P,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label})]})}var La="af-text-xs af-text-muted-foreground";function Zr(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function bn({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=te(),i=Ce.useRef(null);Ce.useEffect(()=>{i.current?.focus()},[e.id]);let[o,g]=Ce.useState(!1),[v,h]=Ce.useState(null),[r,b]=Ce.useState(!1),[w,p]=Ce.useState(!1),u=Ce.useRef(0),[f,x]=Ce.useState(null),[N,C]=Ce.useState(!1),[O,z]=Ce.useState(0);Ce.useEffect(()=>{let y=!1;return C(!1),n.getInvoice(e.id).then(Q=>{y||x({source:e,value:Q})}).catch(()=>{y||C(!0)}),()=>{y=!0}},[n,e,s,O]);let c=f?.source===e?f.value:e,S=c.collection_method==="charge_automatically";Ce.useEffect(()=>(u.current++,h(null),b(!1),p(!1),g(!1),()=>{u.current++}),[n,c,s]);let E=y=>y==null?"\u2014":W(y,c.currency),J=async()=>{if(!(!c.pay_url||!Zr()))try{await navigator.clipboard.writeText(c.pay_url),g(!0),setTimeout(()=>g(!1),1500)}catch{}},B=async()=>{if(v){h(null);return}let y=++u.current;p(!1),b(!0);try{let Q=await n.getInvoicePreview(c.id);y===u.current&&h(Q)}catch{y===u.current&&p(!0)}finally{y===u.current&&b(!1)}},R=c.bill_to,H=R?[R.company,R.name,R.address?.line1,R.address?.line2,[R.address?.city,R.address?.state,R.address?.postal_code].filter(Boolean).join(", "),R.address?.country,R.tax_id?`${R.tax_id.value}`:null,R.po_number?`PO ${R.po_number}`:null,R.service_period?`Service period: ${R.service_period}`:null].filter(y=>!!y&&y.length>0):[];return(0,l.jsxs)("div",{className:t,children:[(0,l.jsxs)("div",{className:"af-mb-4",children:[(0,l.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,l.jsx)(ut.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,l.jsxs)("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",ds(c)]}),(0,l.jsx)(us,{invoice:c}),(0,l.jsx)(vn,{delivery:c.delivery})]}),(0,l.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[c.customer_name??c.customer_email,c.customer_name&&c.customer_email?` \xB7 ${c.customer_email}`:""]})]}),N&&(0,l.jsxs)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't refresh this invoice. These details may be out of date. ",(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>z(y=>y+1),children:"Retry details"})]}),c.label==="failed"&&(0,l.jsx)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),c.label==="creating"&&(0,l.jsx)("p",{role:"status",className:"af-mb-4 af-text-sm af-text-muted-foreground",children:"This invoice is still being created. Its final details will appear when it is ready."}),(0,l.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,l.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,l.jsxs)(Le,{children:[(0,l.jsx)(Oe,{children:(0,l.jsxs)(be,{children:[(0,l.jsx)(F,{children:"Description"}),(0,l.jsx)(F,{className:"af-text-right",children:"Qty"}),(0,l.jsx)(F,{className:"af-text-right",children:"Amount"})]})}),(0,l.jsx)(Be,{children:c.line_items.map((y,Q)=>(0,l.jsxs)(be,{children:[(0,l.jsx)(M,{style:{overflowWrap:"anywhere"},children:y.description}),(0,l.jsx)(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:y.quantity}),(0,l.jsx)(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:E(y.amount)})]},Q))})]}),(0,l.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,l.jsx)(qa,{label:"Subtotal",value:E(c.amount_subtotal)}),(c.discount_total??0)>0&&(0,l.jsx)(qa,{label:"Discount",value:`-${E(c.discount_total)}`}),c.tax_total>0&&(0,l.jsx)(qa,{label:c.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:E(c.tax_total)}),(0,l.jsx)(qa,{label:"Total",value:E(c.amount_total),strong:!0}),c.credit_applied>0&&(0,l.jsx)(qa,{label:"Credit applied",value:`-${E(c.credit_applied)}`}),c.amount_due!==null&&c.amount_due!==c.amount_total&&(0,l.jsx)(qa,{label:"Amount due",value:E(c.amount_due),strong:!0}),c.amount_paid!==null&&c.amount_paid>0&&(0,l.jsx)(qa,{label:"Amount paid",value:E(c.amount_paid)}),c.amount_refunded>0&&(0,l.jsx)(qa,{label:"Refunded",value:E(c.amount_refunded)})]}),c.credit_notes?.length>0&&(0,l.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,l.jsx)("div",{className:La,children:"Credit notes"}),c.credit_notes.map(y=>(0,l.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,l.jsxs)("span",{className:"af-text-muted-foreground",children:[ta(y.created_at)," \xB7 ",y.origin==="dashboard"?"issued in Stripe":"refund",y.stripe_credit_note_id?"":" \xB7 being created"]}),(0,l.jsxs)("span",{className:"af-tabular-nums",children:["-",W(y.amount,y.currency)]})]},y.id))]})]}),(c.note||c.footer)&&(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[c.note&&(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:La,children:"Note"}),(0,l.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:c.note})]}),c.footer&&(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:La,children:"Footer"}),(0,l.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:c.footer})]})]}),v&&!S&&(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,l.jsxs)("div",{className:G(La,"af-break-words"),children:["Email preview \u2014 ",v.subject]}),(0,l.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,l.jsx)("iframe",{title:"Invoice email preview",srcDoc:v.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,l.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,l.jsx)(ea,{label:"Created",value:ta(c.created_at)}),(0,l.jsx)(ea,{label:"Due",value:c.collection_method==="charge_automatically"?"Managed in Stripe":c.due_at?ta(c.due_at):"On receipt"}),c.paid_at&&(0,l.jsx)(ea,{label:"Paid",value:ta(c.paid_at)}),c.payment_method&&(0,l.jsx)(ea,{label:"Paid by",value:c.paid_out_of_band?`${c.payment_method} (recorded outside Stripe)`:c.payment_method}),c.payment_state!=="none"&&(0,l.jsx)(ea,{label:"Payment",value:c.payment_state==="processing"?"Processing":c.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),c.delivery&&(0,l.jsx)(ea,{label:"Delivery",value:`${zn[c.delivery.state]} \xB7 ${c.delivery.recipient}`}),c.marked_uncollectible_at&&(0,l.jsx)(ea,{label:"Written off",value:ta(c.marked_uncollectible_at)}),c.correction_reason&&(0,l.jsx)(ea,{label:"Correction",value:c.correction_reason}),c.replaced_by_order_id&&(0,l.jsx)(ea,{label:"Replaced by",value:c.replaced_by_order_id}),c.collection_method==="charge_automatically"?(0,l.jsx)(ea,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):c.retainer_id&&(0,l.jsx)(ea,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),c.replaces_order_id&&(0,l.jsx)(ea,{label:"Replaces",value:c.replaces_order_id})]}),(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,l.jsx)("div",{className:La,children:"Reminders"}),S?(0,l.jsx)("div",{children:"View automatic payment reminders in Stripe."}):c.reminders.disabled?(0,l.jsx)("div",{children:"Off for this invoice."}):c.reminders.paused_until?(0,l.jsxs)("div",{children:["Paused until ",ta(c.reminders.paused_until),"."]}):c.reminders.next_at?(0,l.jsxs)("div",{children:["Next on ",ta(c.reminders.next_at),"."]}):c.reminders.final_sent_at?(0,l.jsxs)("div",{children:["Final reminder sent ",ta(c.reminders.final_sent_at),"."]}):(0,l.jsx)("div",{children:"None scheduled."}),!S&&(0,l.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",c.reminders.schedule.length===0?"none":c.reminders.schedule.map(y=>y<0?`${-y}d before`:y===0?"due day":`${y}d after`).join(", ")]})]}),c.communications&&c.communications.length>0&&(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,l.jsx)("div",{className:La,children:"Email delivery history"}),c.communications.map(y=>(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,l.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[ko[y.kind]??y.kind,y.kind==="reminder"&&y.slot!==null?` #${y.slot}`:"",(0,l.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",y.recipient]})]}),(0,l.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[zn[y.state]??y.state," \xB7 ",ta(y.state_at??y.created_at)]})]},y.id))]}),H.length>0&&(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,l.jsx)("div",{className:La,children:"Bill to"}),H.map((y,Q)=>(0,l.jsx)("div",{className:"af-break-words",children:y},Q))]}),(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[c.pay_url&&(0,l.jsxs)(P,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void J(),disabled:!Zr(),children:[(0,l.jsx)(ut.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":S?"Copy invoice link":"Copy pay link"]}),c.pdf_url&&(0,l.jsx)(P,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,l.jsxs)("a",{href:c.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,l.jsx)(ut.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!S&&(0,l.jsxs)(P,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void B(),disabled:r,children:[r?(0,l.jsx)(ut.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,l.jsx)(ut.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),v?"Hide email preview":w?"Retry email preview":"Show email preview"]}),w&&!S&&(0,l.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),c.pay_url&&(0,l.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:c.pay_url}),(0,l.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:S?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function ea({label:e,value:a}){return(0,l.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,l.jsx)("span",{className:G(La,"af-shrink-0"),children:e}),(0,l.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function qa({label:e,value:a,strong:s}){return(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,l.jsx)("dt",{className:G(La,s&&"af-font-medium af-text-foreground"),children:e}),(0,l.jsx)("dd",{className:G("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}var ei=require("lucide-react");var Ee=require("react/jsx-runtime"),Do={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Xr={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Lo(e){switch(e){case"active":return"success";case"paused":case"canceling":return"warning";case"failed":return"destructive";case"canceled":return"outline";default:return"secondary"}}function ti(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>Xr[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>Xr[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Do[e.status]}function ai(e){let a=e.interval==="year"?"every year":"every month";return`${W(e.amount,e.currency)} ${a}`}function Oo(e){return e.status==="canceled"?`Ended ${yn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${yn(e.next_cycle_at)}`:"Ends this period":e.collection_method==="charge_automatically"?"Billing schedule managed in Stripe":e.status==="paused"?"Future invoices paused":e.status==="failed"||e.status==="creating"?"Next invoice not scheduled yet":e.skip_next_cycle?e.next_cycle_at?`Skipping ${yn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${yn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function yn(e){if(!e)return"\u2014";let a=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(a);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function hn({retainer:e,className:a}){return(0,Ee.jsx)(Z,{variant:Lo(e.status),className:G("af-max-w-full af-whitespace-normal af-break-words",a),children:ti(e)})}function ts({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:g=0,isLoadingMore:v=!1,onLoadMore:h,includeEnded:r=!1,onIncludeEndedChange:b,className:w}){let p=!!b;if(!a&&!s&&e.length===0&&!(p&&(r||g>0)))return null;let u=o!==void 0?Math.max(0,o-e.length):0;return(0,Ee.jsxs)("section",{className:G("af-mb-6",w),"aria-label":"Recurring invoices",children:[(0,Ee.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Ee.jsx)(ei.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,Ee.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,Ee.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),p&&(0,Ee.jsx)(P,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>b?.(!r),children:r?"Hide ended recurring invoices":g>0&&e.length===0?`Show ended recurring invoices (${g})`:"Show ended recurring invoices"})]}),s?(0,Ee.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",(0,Ee.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?(0,Ee.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(f=>(0,Ee.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,Ee.jsx)(X,{className:"af-h-4 af-w-48"}),(0,Ee.jsx)(X,{className:"af-mt-2 af-h-3 af-w-32"})]},f))}):e.length===0?(0,Ee.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:r?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,Ee.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(f=>{let x=i===f.id;return(0,Ee.jsxs)("li",{className:G("af-rounded-md af-border af-p-3",x&&"af-border-primary af-bg-muted/40"),children:[(0,Ee.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,Ee.jsxs)("div",{className:"af-min-w-0",children:[(0,Ee.jsx)("div",{className:"af-truncate af-font-medium",children:f.customer_name??f.customer_email??"\u2014"}),(0,Ee.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:f.description})]}),(0,Ee.jsx)(hn,{retainer:f})]}),f.collection_method==="charge_automatically"?(0,Ee.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,Ee.jsx)(Z,{variant:"secondary",children:"Managed in Stripe"}),(0,Ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Automatic charging is enabled in Stripe. View or change the billing terms there. To edit this schedule from the chat, switch it back to sending invoices in Stripe."})]}):(0,Ee.jsx)("div",{className:"af-mt-2 af-text-sm",children:ai(f)}),(0,Ee.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-text-xs af-text-muted-foreground",children:[(0,Ee.jsxs)("span",{children:[Oo(f)," \xB7 ",f.cycles.count===0?"no invoices yet":`${f.cycles.paid} paid${f.cycles.open>0?`, ${f.cycles.open} open`:""}`]}),f.cycles.count>0&&(0,Ee.jsx)(P,{type:"button",variant:x?"secondary":"ghost",size:"sm",onClick:()=>n(f),"aria-pressed":x,children:x?"Showing invoices":"View invoices"})]}),f.status==="failed"&&f.operation?.last_error&&(0,Ee.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",f.operation.last_error,". Ask in the chat to try again."]})]},f.id)})}),!a&&!s&&u>0&&h&&(0,Ee.jsx)("div",{className:"af-mt-2",children:(0,Ee.jsx)(P,{type:"button",variant:"outline",size:"sm",onClick:h,disabled:v,children:v?"Loading\u2026":`Load more (${u} more)`})})]})}var si=ne(require("react"),1),zt=require("lucide-react");var _a=ne(require("react"),1);function as(){let{api:e}=te(),[a,s]=_a.useState(null),[t,n]=_a.useState(!0),[i,o]=_a.useState(null),g=_a.useRef(0),v=_a.useCallback(async()=>{let h=++g.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(h!==g.current)return;s(r)}catch(r){if(h!==g.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{h===g.current&&n(!1)}},[e]);return _a.useEffect(()=>{v()},[v]),{status:a,isLoading:t,error:i,refetch:v}}var he=require("react/jsx-runtime");function Vs({onConnectStripe:e,onUpgradePlan:a,className:s}){let{status:t,isLoading:n,error:i,refetch:o}=as(),[g,v]=si.useState(!1),h=async()=>{v(!0);try{await o()}finally{v(!1)}};return n&&!t?(0,he.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,he.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!t?(0,he.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,he.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):t.status==="active"?(0,he.jsx)("div",{className:s,children:(0,he.jsxs)("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:[(0,he.jsx)(zt.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,he.jsxs)("div",{children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,he.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",t.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,he.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[t.reason==="needs_stripe"&&(0,he.jsxs)("div",{className:"af-space-y-3",children:[(0,he.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,he.jsx)(zt.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,he.jsxs)("div",{children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,he.jsx)("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?(0,he.jsxs)(P,{onClick:e,children:[(0,he.jsx)(zt.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),t.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,he.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),t.reason==="needs_paid_plan"&&(0,he.jsxs)("div",{className:"af-space-y-3",children:[(0,he.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,he.jsx)(zt.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,he.jsxs)("div",{children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,he.jsx)("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."})]})]}),a?(0,he.jsx)(P,{onClick:a,children:"Upgrade plan"}):(0,he.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),t.reason==="account_disabled"&&(0,he.jsxs)("div",{className:"af-space-y-3",children:[(0,he.jsxs)("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:[(0,he.jsx)(zt.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,he.jsxs)("div",{children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),t.stripe_account_connected?(0,he.jsx)("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."}):(0,he.jsx)("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."})]})]}),(0,he.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&t.stripe_account_connected&&(0,he.jsxs)(P,{onClick:e,children:[(0,he.jsx)(zt.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,he.jsxs)(P,{variant:"outline",onClick:h,disabled:g,children:[g?(0,he.jsx)(zt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,he.jsx)(zt.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var St=ne(require("react"),1);function jn(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function ss({includeStats:e=!1,refreshKey:a}={}){let{api:s}=te(),[t,n]=St.useState([]),[i,o]=St.useState(!0),[g,v]=St.useState(null),h=St.useRef(0),r=St.useCallback(async()=>{let x=++h.current;try{o(!0),v(null);let N=await s.getProducts(e?{include:"stats"}:{});if(x!==h.current)return;n(N)}catch(N){if(x!==h.current)return;v(N instanceof Error?N:new Error("Failed to fetch products"))}finally{x===h.current&&o(!1)}},[s,e,a]);St.useEffect(()=>{r()},[r]);let b=St.useCallback(async x=>{let N=await s.createProduct(x);return n(C=>[N,...C]),N},[s]),w=St.useCallback(async(x,N)=>{let C=await s.updateProduct(x,N);return n(O=>jn(O,x,C)),C},[s]),p=St.useCallback(async x=>{await s.deleteProduct(x),n(N=>N.filter(C=>C.id!==x))},[s]),u=St.useCallback(async(x,N)=>{let C=await s.attachProductFile(x,N);return n(O=>jn(O,x,C)),C},[s]),f=St.useCallback(async(x,N)=>{let C=await s.attachProductFileFromUrl(x,N);return n(O=>jn(O,x,C)),C},[s]);return{products:t,isLoading:i,error:g,refetch:r,createProduct:b,updateProduct:w,deleteProduct:p,attachProductFile:u,attachProductFileFromUrl:f}}var Rt=ne(require("react"),1);var ni=["creating","active","paused","canceling"],Bo=["canceled","failed"];function ns({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=te(),[n,i]=Rt.useState([]),[o,g]=Rt.useState(0),[v,h]=Rt.useState(0),[r,b]=Rt.useState(!0),[w,p]=Rt.useState(!1),[u,f]=Rt.useState(null),[x,N]=Rt.useState(a),C=Rt.useRef(0),O=Rt.useCallback(async()=>{let c=++C.current;b(!0),p(!1),f(null);try{let S=await t.getRetainers({statuses:x?void 0:ni,limit:s,offset:0});if(c!==C.current)return;if(i(S.retainers),g(S.total),!x&&S.total===0){let E=await t.getRetainers({statuses:Bo,limit:1,offset:0});if(c!==C.current)return;h(E.total)}else h(0)}catch(S){if(c!==C.current)return;f(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{c===C.current&&b(!1)}},[t,x,s]);Rt.useEffect(()=>{O()},[O,e]);let z=Rt.useCallback(async()=>{if(r||w||n.length>=o)return;let c=C.current;p(!0);try{let S=await t.getRetainers({statuses:x?void 0:ni,limit:s,offset:n.length});if(c!==C.current)return;i(E=>{let J=new Set(E.map(B=>B.id));return[...E,...S.retainers.filter(B=>!J.has(B.id))]}),g(S.total)}catch(S){if(c!==C.current)return;f(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{c===C.current&&p(!1)}},[t,x,s,r,w,n.length,o]);return{retainers:n,total:o,endedTotal:v,hasMore:n.length<o,isLoading:r,isLoadingMore:w,error:u,includeEnded:x,setIncludeEnded:N,loadMore:z,refetch:O}}var Ne=require("react/jsx-runtime");function Gn({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=fs.useState(a),[g,v]=fs.useState("list"),[h,r]=fs.useState(null),b=ss(),{status:w,error:p}=as(),u=w?.currency,f=O=>{r(O),v("edit")},x=()=>{r(null),v("create")},N=()=>{v("list"),r(null)},C=O=>{r(O),v("edit")};return(0,Ne.jsxs)("div",{className:e,children:[(0,Ne.jsxs)("div",{className:"af-mb-6",children:[(0,Ne.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Ne.jsxs)(sn,{value:i,onValueChange:O=>o(O),children:[(0,Ne.jsxs)(bs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Ne.jsxs)(va,{value:"products",className:"af-gap-2",children:[(0,Ne.jsx)(aa.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Ne.jsxs)(va,{value:"orders",className:"af-gap-2",children:[(0,Ne.jsx)(aa.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Ne.jsxs)(va,{value:"invoices",className:"af-gap-2",children:[(0,Ne.jsx)(aa.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Ne.jsxs)(va,{value:"customers",className:"af-gap-2",children:[(0,Ne.jsx)(aa.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Ne.jsxs)(va,{value:"setup",className:"af-gap-2",children:[(0,Ne.jsx)(aa.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Ne.jsx)(ba,{value:"products",children:g==="list"?(0,Ne.jsx)(Is,{productsState:b,onSelectProduct:f,onCreateProduct:x}):(0,Ne.jsxs)("div",{children:[(0,Ne.jsxs)("div",{className:"af-mb-6",children:[(0,Ne.jsxs)(P,{variant:"ghost",size:"sm",onClick:N,className:"af-mb-2 af--ml-2",children:[(0,Ne.jsx)(aa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Ne.jsx)("h3",{className:"af-text-lg af-font-semibold",children:g==="create"?"New Product":h?.name})]}),g==="create"&&!u?(0,Ne.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:p?(0,Ne.jsxs)("div",{className:"af-text-destructive",children:["Error: ",p.message]}):(0,Ne.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Ne.jsx)(Ds,{productsState:b,product:g==="edit"?h:null,currency:u??"usd",onSaved:C},g==="edit"?h?.id??"edit":"new")]})}),(0,Ne.jsx)(ba,{value:"orders",children:(0,Ne.jsx)(Za,{onRefund:t})}),(0,Ne.jsx)(ba,{value:"invoices",children:(0,Ne.jsx)(Fo,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:w?.reason==="needs_paid_plan"})}),(0,Ne.jsx)(ba,{value:"customers",children:(0,Ne.jsx)(Us,{})}),(0,Ne.jsx)(ba,{value:"setup",children:(0,Ne.jsx)(Vs,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Fo({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=ns(),[n,i]=fs.useState(null),[o,g]=fs.useState(!1);return(0,Ne.jsxs)(Ne.Fragment,{children:[!o&&(0,Ne.jsx)(ts,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:v=>i(h=>h?.id===v.id?null:v),total:t.total,endedTotal:t.endedTotal,isLoadingMore:t.isLoadingMore,onLoadMore:()=>void t.loadMore(),includeEnded:t.includeEnded,onIncludeEndedChange:t.setIncludeEnded}),(0,Ne.jsx)(es,{onDetailOpenChange:g,onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>i(null)})]})}var ii=ne(require("react"),1);var Pa=ne(require("react"),1);function $s({refreshKey:e}={}){let{api:a}=te(),[s,t]=Pa.useState(null),[n,i]=Pa.useState(!0),[o,g]=Pa.useState(null),v=Pa.useRef(0),h=Pa.useCallback(async()=>{let r=++v.current;try{i(!0),g(null);let b=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==v.current)return;t(b)}catch(b){if(r!==v.current)return;g(b instanceof Error?b:new Error("Failed to fetch summary"))}finally{r===v.current&&i(!1)}},[a,e]);return Pa.useEffect(()=>{h()},[h]),{summary:s,isLoading:n,error:o,refetch:h}}var $e=require("react/jsx-runtime");function ri(e,a){if(e.settled.complete)return{headline:W(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:W(s.gross,s.currency),extra:e.totals.slice(1).map(t=>`+ ${W(t.gross,t.currency)} in ${t.currency.toUpperCase()}`)}:{headline:W(0,a),extra:[]}}function Wn({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:g,error:v,refetch:h}=$s({refreshKey:e}),[r,b]=ii.useState(!1),w=(0,$e.jsx)("div",{className:"af-mb-6",children:v&&!o?(0,$e.jsx)($t,{message:"Couldn't load your revenue summary.",onRetry:()=>h()}):(0,$e.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:g||!o?(0,$e.jsxs)($e.Fragment,{children:[(0,$e.jsx)(Ye,{label:"This week",children:(0,$e.jsx)(X,{className:"af-h-6 af-w-24"})}),(0,$e.jsx)(Ye,{label:"Today",children:(0,$e.jsx)(X,{className:"af-h-6 af-w-24"})}),(0,$e.jsx)(Ye,{label:"Needs attention",children:(0,$e.jsx)(X,{className:"af-h-6 af-w-10"})})]}):(0,$e.jsx)($e.Fragment,{children:(()=>{let p=ri(o.revenue.d7,o.currency),u=ri(o.revenue.today,o.currency);return(0,$e.jsxs)($e.Fragment,{children:[(0,$e.jsx)(Ye,{label:"This week",detail:p.extra.length>0?(0,$e.jsx)("div",{children:p.extra.map(f=>(0,$e.jsx)("div",{children:f},f))}):void 0,children:p.headline}),(0,$e.jsx)(Ye,{label:"Today",detail:u.extra.length>0?(0,$e.jsx)("div",{children:u.extra.map(f=>(0,$e.jsx)("div",{children:f},f))}):void 0,children:u.headline}),(0,$e.jsx)(Ye,{label:"Needs attention",valueClassName:o.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:o.needs_attention.count===0?"All clear":o.needs_attention.items[0]?.title??void 0,children:o.needs_attention.count})]})})()})})});return(0,$e.jsxs)(bt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[w,(0,$e.jsx)(Za,{refreshKey:e,initialOrderId:a,onDetailOpenChange:b,showFulfillment:!0,onRefund:s?t:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Oa=ne(require("react"),1),ms=require("lucide-react");var Ta=ne(require("react"),1),_n=require("lucide-react");var ht=require("react/jsx-runtime"),oi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ja="af-text-xs af-text-muted-foreground",xn="af-text-sm af-font-medium af-tabular-nums",Mo=3;function Uo(e){let a=e.pricing,s=a?.currency??e.currency;if(a?.custom_amount??e.allow_custom_amount){let v=e.min_amount??a?.min_amount??null,h=e.max_amount??a?.max_amount??null;return v!==null&&h!==null?{text:`Buyer chooses (${W(v,s)} \u2013 ${W(h,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=a?.min_amount??e.unit_amount,i=a?.max_amount??e.unit_amount;if(n===null||i===null)return{text:"Varies by variant",compareAt:null};let o=n===i?W(n,s):`${W(n,s)} \u2013 ${W(i,s)}`,g=a?.compare_at_amount??null;return{text:o,compareAt:g!==null&&g>i?W(g,s):null}}function wn({product:e,className:a}){let s=Uo(e);return(0,ht.jsxs)("div",{className:a,children:[(0,ht.jsx)("span",{className:xn,children:s.text}),s.compareAt&&(0,ht.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function Nn({product:e}){let a=e.inventory;return a?a.tracked?a.out_of_stock?(0,ht.jsx)(Z,{variant:"destructive",children:"Out of stock"}):a.low_stock?(0,ht.jsxs)(Z,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?(0,ht.jsx)(Z,{variant:"secondary",children:"Backorder"}):a.available===null?null:(0,ht.jsxs)(Z,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?(0,ht.jsx)(Z,{variant:"warning",children:"Low stock"}):null}function Sn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Rn(e){return e.map(a=>W(a.amount,a.currency)).join(" + ")}function li(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${W(e.min_amount,e.currency)} \u2013 ${W(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":W(e.unit_amount,e.currency)}function ci({variant:e}){let a=e.inventory;if(!a||!a.tracked)return(0,ht.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=a.available??0;return a.allow_backorder?(0,ht.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ht.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,s)}),(0,ht.jsx)(Z,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?(0,ht.jsx)(Z,{variant:"destructive",children:"Out of stock"}):(0,ht.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ht.jsx)("span",{className:"af-tabular-nums",children:s}),s<=Mo&&(0,ht.jsx)(Z,{variant:"warning",children:"Low"})]})}var j=require("react/jsx-runtime");function Hs({title:e,children:a,className:s}){return(0,j.jsxs)("section",{className:G("af-rounded-lg af-border af-p-4",s),children:[(0,j.jsx)("h4",{className:oi,children:e}),(0,j.jsx)("div",{className:"af-mt-3",children:a})]})}function di({src:e,className:a}){let[s,t]=Ta.useState(!1);return Ta.useEffect(()=>t(!1),[e]),!e||s?(0,j.jsx)("div",{"aria-hidden":"true",className:G("af-flex af-items-center af-justify-center af-bg-muted",a),children:(0,j.jsx)(_n.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,j.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:G("af-object-cover",a)})}function ui({product:e,showStats:a=!1,onBack:s}){let{api:t}=te(),[n,i]=Ta.useState(null),[o,g]=Ta.useState(!0),[v,h]=Ta.useState(null),[r,b]=Ta.useState(0),[w,p]=Ta.useState(0);Ta.useEffect(()=>{let c=!1;return g(!0),h(null),t.getProduct(e.id).then(S=>{c||i(S)}).catch(S=>{c||h(S instanceof Error?S:new Error("Failed to load product"))}).finally(()=>{c||g(!1)}),()=>{c=!0}},[t,e.id,r]);let u=n?{...e,...n}:e,f=u.images.length>0?u.images:e.images,x=f[w]??f[0],N=Sn(u),C=a?u.stats:void 0,O=n?.variants??[],z=O.length>1;return(0,j.jsxs)("div",{children:[(0,j.jsxs)("div",{className:"af-mb-6",children:[(0,j.jsxs)(P,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,j.jsx)(_n.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,j.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,j.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),(0,j.jsx)(Z,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),(0,j.jsx)(Nn,{product:u})]}),(0,j.jsx)(wn,{product:u,className:"af-mt-1"}),!u.active&&(0,j.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),(0,j.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsx)(di,{src:x,className:"af-h-48 af-w-full af-rounded-md af-border"}),f.length>1&&(0,j.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:f.map((c,S)=>(0,j.jsx)("button",{type:"button",onClick:()=>p(S),"aria-label":`Show photo ${S+1} of ${f.length}`,"aria-pressed":S===w,className:G("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",S===w?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,j.jsx)(di,{src:c,className:"af-h-12 af-w-12 af-rounded-md"})},`${c}-${S}`))})]}),(0,j.jsxs)("div",{className:"af-space-y-6",children:[u.description&&(0,j.jsx)(Hs,{title:"Description",children:(0,j.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?(0,j.jsxs)(Hs,{title:"Variants",children:[(0,j.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(c=>(0,j.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,j.jsx)(X,{className:"af-h-4 af-w-28"}),(0,j.jsx)(X,{className:"af-h-4 af-w-20"}),(0,j.jsx)(X,{className:"af-h-4 af-w-16"})]},c))}),(0,j.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):v?(0,j.jsx)($t,{message:"Couldn't load this product's variants.",onRetry:()=>b(c=>c+1)}):z?(0,j.jsx)(Hs,{title:`Variants \xB7 ${O.length}`,children:(0,j.jsx)("div",{className:"af-overflow-x-auto",children:(0,j.jsxs)(Le,{children:[(0,j.jsx)(Oe,{children:(0,j.jsxs)(be,{children:[(0,j.jsx)(F,{children:"Variant"}),(0,j.jsx)(F,{children:"SKU"}),(0,j.jsx)(F,{className:"af-text-right",children:"Price"}),(0,j.jsx)(F,{children:"Stock"})]})}),(0,j.jsx)(Be,{children:O.map(c=>(0,j.jsxs)(be,{children:[(0,j.jsxs)(M,{className:"af-font-medium",children:[c.title||c.option_values.map(S=>S.value).join(" / ")||"\u2014",!c.active&&(0,j.jsx)(Z,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,j.jsx)(M,{className:"af-text-muted-foreground",children:c.sku?(0,j.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:c.sku}):"\u2014"}),(0,j.jsxs)(M,{className:"af-whitespace-nowrap af-text-right",children:[(0,j.jsx)("div",{className:xn,children:li(c)}),c.compare_at_amount!==null&&c.unit_amount!==null&&c.compare_at_amount>c.unit_amount&&(0,j.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:W(c.compare_at_amount,c.currency)})]}),(0,j.jsx)(M,{className:"af-text-sm",children:(0,j.jsx)(ci,{variant:c})})]},c.id))})]})})}):null,(0,j.jsx)(Hs,{title:"Details",children:(0,j.jsxs)("dl",{className:"af-space-y-2",children:[(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Delivery"}),(0,j.jsx)("dd",{className:"af-text-sm",children:N==="Digital download"?u.fulfillment.filename??"Digital download":N??"Nothing to deliver"})]}),u.fulfillment.type==="redirect"&&u.fulfillment.url&&(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Sends buyers to"}),(0,j.jsx)("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Shipping address"}),(0,j.jsx)("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Most one buyer can order"}),(0,j.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),C&&(0,j.jsx)(Hs,{title:"Last 30 days",children:(0,j.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Units sold"}),(0,j.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:C.units_sold})]}),(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Orders"}),(0,j.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:C.orders})]}),(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Gross"}),(0,j.jsx)("dd",{className:xn,children:C.gross.length>0?Rn(C.gross):"\u2014"})]})]})}),(0,j.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var V=require("react/jsx-runtime"),Vo={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},$o=["all","active","draft","low_stock","out_of_stock"];function fi(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function mi(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Ho(e){return e.inventory?.out_of_stock??!1}function zo(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return mi(e);case"out_of_stock":return Ho(e);default:return!0}}function qo({product:e,showStats:a,onOpen:s}){let t=e.images[0],n=a?e.stats:void 0,i=Sn(e),o=e.variant_count??0;return(0,V.jsxs)("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[t?(0,V.jsx)("img",{src:t,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,V.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:(0,V.jsx)(ms.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,V.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,V.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,V.jsxs)("div",{className:"af-min-w-0",children:[(0,V.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,V.jsx)(wn,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,V.jsx)(Z,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Nn,{product:e}),o>1&&(0,V.jsxs)(Z,{variant:"outline",children:[o," variants"]}),i&&(0,V.jsx)(Z,{variant:"outline",children:i})]}),n&&(0,V.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Rn(n.gross)}`:""," ",(0,V.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function jo(){return(0,V.jsx)("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=>(0,V.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,V.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,V.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,V.jsx)(X,{className:"af-w-32"}),(0,V.jsx)(X,{className:"af-w-16"}),(0,V.jsx)(X,{className:"af-h-5 af-w-24"})]})]},e))})}function Kn({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:g}=ss({includeStats:a,refreshKey:e}),[v,h]=Oa.useState(null),[r,b]=Oa.useState("all"),[w,p]=Oa.useState(""),[u,f]=Oa.useState("newest"),x=Oa.useMemo(()=>{if(!a)return null;let R=null;for(let H of n)!H.stats||H.stats.units_sold===0||(!R||H.stats.units_sold>(R.stats?.units_sold??0))&&(R=H);return R},[n,a]),N=Oa.useMemo(()=>n.filter(mi).length,[n]),C=w.trim().toLowerCase(),O=Oa.useMemo(()=>{let H=[...n.filter(y=>zo(y,r)&&(!C||y.name.toLowerCase().includes(C)))];return u==="name"?H.sort((y,Q)=>y.name.localeCompare(Q.name)):u==="best_selling"?H.sort((y,Q)=>(Q.stats?.units_sold??0)-(y.stats?.units_sold??0)):H.sort((y,Q)=>fi(Q.created_at)-fi(y.created_at)),H},[n,r,C,u]),z=r!=="all"||!!C,c=()=>{b("all"),p("")},S=i||o!==null&&n.length===0,E=(0,V.jsx)("div",{className:"af-mb-6",children:(0,V.jsx)("div",{className:G("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:S?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Ye,{label:"Products",children:(0,V.jsx)(X,{className:"af-h-6 af-w-10"})}),a?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Ye,{label:"Best seller",children:(0,V.jsx)(X,{className:"af-h-6 af-w-28"})}),(0,V.jsx)(Ye,{label:"Low stock",children:(0,V.jsx)(X,{className:"af-h-6 af-w-10"})})]}):(0,V.jsx)(Ye,{label:"Active",children:(0,V.jsx)(X,{className:"af-h-6 af-w-10"})})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Ye,{label:"Products",children:n.length}),a?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Ye,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:x?`${x.stats?.units_sold??0} sold, last 30 days`:void 0,children:x?(0,V.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:x.name}):(0,V.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,V.jsx)(Ye,{label:"Low stock",children:N})]}):(0,V.jsx)(Ye,{label:"Active",children:n.filter(R=>R.active).length})]})})}),J=(0,V.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,V.jsx)("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:$o.map(R=>(0,V.jsx)("button",{type:"button","aria-pressed":r===R,onClick:()=>b(R),className:G("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===R?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Vo[R]},R))}),(0,V.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,V.jsx)(ms.Search,{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"}),(0,V.jsx)(Se,{type:"text",value:w,onChange:R=>p(R.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,V.jsxs)(Wt,{value:u,onValueChange:R=>f(R),children:[(0,V.jsx)(Bt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,V.jsx)(Kt,{})}),(0,V.jsxs)(Ft,{children:[(0,V.jsx)(qe,{value:"newest",children:"Newest"}),(0,V.jsx)(qe,{value:"name",children:"Name A\u2013Z"}),a&&(0,V.jsx)(qe,{value:"best_selling",children:"Best selling"})]})]}),z&&(0,V.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:c,children:"Clear filters"})]}),i&&n.length===0?(0,V.jsx)(X,{className:"af-h-4 af-w-28"}):(0,V.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:z?`${O.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${N>0?` \xB7 ${N} low stock`:""}`})]}),B;return v?B=(0,V.jsx)(ui,{product:v,showStats:a,onBack:()=>{h(null),g()}},v.id):i&&n.length===0?B=(0,V.jsxs)(V.Fragment,{children:[J,(0,V.jsx)(jo,{}),(0,V.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?B=(0,V.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,V.jsx)($t,{message:"Couldn't load your products.",onRetry:()=>g()})}):n.length===0?B=(0,V.jsxs)(Sa,{icon:(0,V.jsx)(ms.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,V.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):B=(0,V.jsxs)(V.Fragment,{children:[J,o&&(0,V.jsx)("div",{className:"af-mb-4",children:(0,V.jsx)($t,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>g()})}),O.length===0?(0,V.jsxs)(Sa,{children:["No products match these filters.",(0,V.jsx)("br",{}),(0,V.jsx)(P,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:c,children:"Show all products"})]}):(0,V.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:O.map(R=>(0,V.jsx)(qo,{product:R,showStats:a,onOpen:()=>h(R)},R.id))})]}),(0,V.jsxs)(bt,{title:"Products",onBackToWebsite:s,hideBackButton:!!v,className:t,children:[!v&&E,B]})}var ma=ne(require("react"),1),it=require("lucide-react");var qt=ne(require("react"),1);function zs({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=te(),[t,n]=qt.useState([]),[i,o]=qt.useState(!0),[g,v]=qt.useState(null),[h,r]=qt.useState(0),[b]=qt.useState(e),[w,p]=qt.useState(""),u=qt.useRef(0),f=qt.useCallback(async()=>{let x=++u.current;try{o(!0),v(null);let N={limit:b,offset:h*b};w.trim()&&(N.q=w.trim());let C=await s.getPeople(N);if(x!==u.current)return;n(C.people)}catch(N){if(x!==u.current)return;v(N instanceof Error?N:new Error("Failed to fetch people"))}finally{x===u.current&&o(!1)}},[s,h,b,w,a]);return qt.useEffect(()=>{f()},[f]),{people:t,isLoading:i,error:g,page:h,pageSize:b,hasNextPage:t.length===b,hasPreviousPage:h>0,setPage:r,q:w,setQ:x=>{p(x),r(0)},refetch:f}}var Ca=ne(require("react"),1);function qs(e,{refreshKey:a}={}){let{api:s}=te(),[t,n]=Ca.useState(null),[i,o]=Ca.useState(e!==null),[g,v]=Ca.useState(null),h=Ca.useRef(0),r=Ca.useCallback(async()=>{if(e===null){n(null),o(!1),v(null);return}let b=++h.current;try{o(!0),v(null);let w=await s.getPerson(e);if(b!==h.current)return;n(w)}catch(w){if(b!==h.current)return;v(w instanceof Error?w:new Error("Failed to fetch person"))}finally{b===h.current&&o(!1)}},[s,e,a]);return Ca.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:g,refetch:r}}var m=require("react/jsx-runtime"),Jn="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Go="af-text-xs af-text-muted-foreground";function ps(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Yn(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function Wo(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Ko({value:e,label:a}){let[s,t]=ma.useState(!1);return Wo()?(0,m.jsxs)(P,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),t(!0),setTimeout(()=>t(!1),1500)}catch{}},"aria-label":a,className:"af-shrink-0",children:[s?(0,m.jsx)(it.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,m.jsx)(it.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function pi(e){return(0,m.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,m.jsxs)(Z,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,m.jsx)(Z,{variant:"secondary",children:"Contact form"})]})}function gi(e){return e.name?e.name:e.email?e.email:(0,m.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Jo=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Yo=40;function Zo(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>Jo.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=Yo).sort((n,i)=>String(i[1]).trim().length-String(n[1]).trim().length)[0];return t?{message:String(t[1]),rest:a.filter(([n])=>n!==t[0])}:{message:null,rest:a}}function Qo(e){return e.replace(/_/g," ")}function Xo(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function el({data:e}){let{message:a,rest:s}=Zo(e);return a===null&&s.length===0?(0,m.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,m.jsxs)("div",{className:"af-space-y-3",children:[a!==null&&(0,m.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:a}),s.length>0&&(0,m.jsx)("dl",{className:"af-space-y-1",children:s.map(([t,n])=>(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,m.jsx)("dt",{className:G(Go,"af-w-28 af-shrink-0 af-capitalize"),children:Qo(t)}),(0,m.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Xo(n)})]},t))})]})}function vi({formName:e,createdAt:a,data:s}){return(0,m.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,m.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,m.jsx)(Z,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,m.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,m.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:ps(a)})]}),(0,m.jsx)(el,{data:s})]})}function tl(e){return e.charged_total??e.amount_total}function al({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=qs(e,{refreshKey:a}),g=Yn(e,t?.submissions[0]?.form_name);return(0,m.jsxs)("div",{children:[(0,m.jsxs)("div",{className:"af-mb-6",children:[(0,m.jsxs)(P,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,m.jsx)(it.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,m.jsxs)("div",{className:"af-min-w-0",children:[n?(0,m.jsx)(X,{className:"af-h-7 af-w-48"}):(0,m.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:t?.name||e}),(0,m.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,m.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,m.jsx)(Ko,{value:e,label:"Copy email address"})]})]}),(0,m.jsx)(P,{asChild:!0,children:(0,m.jsxs)("a",{href:g,children:[(0,m.jsx)(it.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?(0,m.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(v=>(0,m.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,m.jsx)(X,{className:"af-w-40"}),(0,m.jsx)(X,{className:"af-mt-2 af-w-64"})]},v)),(0,m.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?(0,m.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,m.jsx)($t,{message:"Couldn't load this person.",onRetry:()=>o()})}):(0,m.jsxs)("div",{className:"af-space-y-6",children:[t.customer&&(0,m.jsxs)("div",{children:[(0,m.jsx)("h4",{className:G(Jn,"af-mb-3"),children:"Customer"}),(0,m.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[t.customer.name&&(0,m.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,m.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,m.jsx)("dd",{children:t.customer.name})]}),t.customer.phone&&(0,m.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,m.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,m.jsx)("dd",{children:t.customer.phone})]}),(0,m.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,m.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,m.jsx)("dd",{children:ps(t.customer.created_at)})]})]})]}),t.orders.length>0&&(0,m.jsxs)("div",{children:[(0,m.jsx)("h4",{className:G(Jn,"af-mb-3"),children:"Purchases"}),(0,m.jsx)("div",{className:"af-overflow-x-auto",children:(0,m.jsxs)(Le,{children:[(0,m.jsx)(Oe,{children:(0,m.jsxs)(be,{children:[(0,m.jsx)(F,{children:"Order"}),(0,m.jsx)(F,{children:"Date"}),(0,m.jsx)(F,{className:"af-text-right",children:"Total"}),(0,m.jsx)(F,{children:"Status"})]})}),(0,m.jsx)(Be,{children:t.orders.map(v=>(0,m.jsxs)(be,{children:[(0,m.jsx)(M,{className:"af-whitespace-nowrap af-font-medium",children:Da(v)}),(0,m.jsx)(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ps(v.created_at)}),(0,m.jsx)(M,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:W(tl(v),v.currency)}),(0,m.jsx)(M,{children:(0,m.jsx)($a,{status:v.status})})]},v.id))})]})}),(0,m.jsx)("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."})]}),t.submissions.length>0&&(0,m.jsxs)("div",{children:[(0,m.jsx)("h4",{className:G(Jn,"af-mb-3"),children:"Messages"}),(0,m.jsx)("div",{className:"af-space-y-3",children:t.submissions.map(v=>(0,m.jsx)(vi,{formName:v.form_name,createdAt:v.created_at,data:v.data},v.id))})]})]})]})}function sl({submissionId:e,onBack:a}){let{api:s}=te(),[t,n]=ma.useState(null),[i,o]=ma.useState(!0),[g,v]=ma.useState(null),[h,r]=ma.useState(0);return ma.useEffect(()=>{let b=!1;return o(!0),v(null),s.getSubmission(e).then(w=>{b||n(w)}).catch(w=>{b||v(w instanceof Error?w:new Error("Failed to load submission"))}).finally(()=>{b||o(!1)}),()=>{b=!0}},[s,e,h]),(0,m.jsxs)("div",{children:[(0,m.jsxs)("div",{className:"af-mb-6",children:[(0,m.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,m.jsx)(it.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,m.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,m.jsx)(X,{className:"af-mt-1 af-h-4 af-w-32"}):t&&(0,m.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:ps(t.metadata.submitted_at)})]}),i?(0,m.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,m.jsx)(X,{className:"af-w-40"}),(0,m.jsx)(X,{className:"af-mt-2 af-w-64"}),(0,m.jsx)(X,{className:"af-mt-2 af-w-52"}),(0,m.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):g||!t?(0,m.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,m.jsx)($t,{message:"Couldn't load this submission.",onRetry:()=>r(b=>b+1)})}):(0,m.jsxs)("div",{className:"af-space-y-3",children:[(0,m.jsx)(vi,{formName:null,createdAt:t.metadata.submitted_at,data:t.data}),(0,m.jsx)("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 nl={all:"All",customers:"Customers",leads:"Leads"},rl=["all","customers","leads"];function il(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function Zn({refreshKey:e,onBackToWebsite:a,className:s}){let{people:t,isLoading:n,error:i,page:o,pageSize:g,hasNextPage:v,hasPreviousPage:h,setPage:r,q:b,setQ:w,refetch:p}=zs({refreshKey:e}),[u,f]=ma.useState({kind:"list"}),[x,N]=ma.useState(""),[C,O]=ma.useState("all"),z=B=>{B.email?f({kind:"person",email:B.email}):B.submission_id&&f({kind:"submission",submissionId:B.submission_id})},c=()=>{f({kind:"list"}),p()},S=B=>{let R=B.trim();R!==b&&w(R)},E=t.filter(B=>il(B,C)),J;if(u.kind==="person")J=(0,m.jsx)(al,{email:u.email,refreshKey:e,onBack:c});else if(u.kind==="submission")J=(0,m.jsx)(sl,{submissionId:u.submissionId,onBack:c});else{let B=(0,m.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,m.jsx)("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:rl.map(R=>(0,m.jsx)("button",{type:"button","aria-pressed":C===R,onClick:()=>O(R),className:G("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===R?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:nl[R]},R))}),(0,m.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,m.jsx)(it.Search,{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"}),(0,m.jsx)(Se,{type:"text",value:x,onChange:R=>N(R.target.value),onBlur:()=>S(x),onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),S(x))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),b&&(0,m.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{N(""),w("")},children:"Clear search"})]});if(n)J=(0,m.jsxs)("div",{children:[B,(0,m.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(R=>(0,m.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,m.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,m.jsx)(X,{className:"af-h-4 af-w-32"}),(0,m.jsx)(X,{className:"af-h-4 af-w-16"})]}),(0,m.jsx)(X,{className:"af-mt-2 af-h-5 af-w-28"}),(0,m.jsx)(X,{className:"af-mt-2 af-h-3 af-w-56"})]},R))}),(0,m.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,m.jsxs)(Le,{children:[(0,m.jsx)(Oe,{children:(0,m.jsxs)(be,{children:[(0,m.jsx)(F,{children:"Person"}),(0,m.jsx)(F,{children:"Came from"}),(0,m.jsx)(F,{children:"Latest message"}),(0,m.jsx)(F,{children:"Last activity"}),(0,m.jsx)(F,{className:"af-w-8"}),(0,m.jsx)(F,{className:"af-w-8"})]})}),(0,m.jsx)(Be,{"aria-hidden":"true",children:[0,1,2,3,4].map(R=>(0,m.jsxs)(be,{children:[(0,m.jsx)(M,{children:(0,m.jsx)(X,{className:"af-h-4 af-w-40"})}),(0,m.jsx)(M,{children:(0,m.jsx)(X,{className:"af-h-5 af-w-24"})}),(0,m.jsx)(M,{children:(0,m.jsx)(X,{className:"af-h-4 af-w-56"})}),(0,m.jsx)(M,{children:(0,m.jsx)(X,{className:"af-h-4 af-w-24"})}),(0,m.jsx)(M,{}),(0,m.jsx)(M,{})]},R))})]})}),(0,m.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)J=(0,m.jsxs)("div",{children:[B,(0,m.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,m.jsx)($t,{message:"Couldn't load your leads.",onRetry:()=>p()})})]});else if(E.length===0&&o===0){let R=!!b||C!=="all";J=(0,m.jsxs)("div",{children:[R&&B,R?(0,m.jsx)(Sa,{children:b?"Nobody matches that search.":C==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,m.jsx)(Sa,{icon:(0,m.jsx)(it.Users,{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(t.length===0)J=(0,m.jsxs)("div",{children:[B,(0,m.jsx)(Sa,{children:"No more results."}),(0,m.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,m.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>r(o-1),children:[(0,m.jsx)(it.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let R=o*g+1,H=o*g+t.length;J=(0,m.jsxs)("div",{children:[B,(0,m.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:E.map((y,Q)=>(0,m.jsxs)("div",{onClick:()=>z(y),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[(0,m.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,m.jsxs)("div",{className:"af-min-w-0",children:[(0,m.jsx)("button",{type:"button",onClick:le=>{le.stopPropagation(),z(y)},"aria-label":`Open ${y.name||y.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:gi(y)}),y.name&&y.email&&(0,m.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:y.email})]}),(0,m.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,m.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:ps(y.last_activity_at)}),y.email&&(0,m.jsx)(P,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,m.jsx)("a",{href:Yn(y.email),onClick:le=>le.stopPropagation(),"aria-label":`Email ${y.email}`,children:(0,m.jsx)(it.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,m.jsx)("div",{className:"af-mt-2",children:pi(y)}),y.latest_message_excerpt&&(0,m.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:y.latest_message_excerpt})]},y.email??y.submission_id??Q))}),(0,m.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,m.jsxs)(Le,{children:[(0,m.jsx)(Oe,{children:(0,m.jsxs)(be,{children:[(0,m.jsx)(F,{children:"Person"}),(0,m.jsx)(F,{children:"Came from"}),(0,m.jsx)(F,{children:"Latest message"}),(0,m.jsx)(F,{children:"Last activity"}),(0,m.jsx)(F,{className:"af-w-8",children:(0,m.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,m.jsx)(F,{className:"af-w-8"})]})}),(0,m.jsx)(Be,{children:E.map((y,Q)=>(0,m.jsxs)(be,{onClick:()=>z(y),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,m.jsxs)(M,{className:"af-max-w-[260px] af-font-medium",children:[(0,m.jsx)("button",{type:"button",onClick:le=>{le.stopPropagation(),z(y)},"aria-label":`Open ${y.name||y.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:gi(y)}),y.name&&y.email&&(0,m.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:y.email})]}),(0,m.jsx)(M,{children:pi(y)}),(0,m.jsx)(M,{className:"af-max-w-[320px]",children:y.latest_message_excerpt?(0,m.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:y.latest_message_excerpt}):(0,m.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,m.jsx)(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ps(y.last_activity_at)}),(0,m.jsx)(M,{className:"af-w-8",children:y.email&&(0,m.jsx)(P,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,m.jsx)("a",{href:Yn(y.email),onClick:le=>le.stopPropagation(),"aria-label":`Email ${y.email}`,children:(0,m.jsx)(it.Mail,{className:"af-h-4 af-w-4"})})})}),(0,m.jsx)(M,{className:"af-w-8 af-text-right",children:(0,m.jsx)(it.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},y.email??y.submission_id??Q))})]})}),(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,m.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:C==="all"?`Showing ${R}-${H}`:`${E.length} of ${t.length} on this page`}),(0,m.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,m.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>r(o-1),disabled:!h,children:[(0,m.jsx)(it.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,m.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>r(o+1),disabled:!v,children:["Next",(0,m.jsx)(it.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return(0,m.jsx)(bt,{title:"Leads",onBackToWebsite:a,hideBackButton:u.kind!=="list",className:s,children:J})}var rs=require("lucide-react");var Et=ne(require("react"),1);function js({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=te(),[t,n]=Et.useState([]),[i,o]=Et.useState(0),[g,v]=Et.useState(!0),[h,r]=Et.useState(null),[b,w]=Et.useState(0),[p,u]=Et.useState(e),[f,x]=Et.useState(void 0),N=Et.useRef(0),C=Et.useCallback(async()=>{let z=++N.current;try{v(!0),r(null);let c={limit:p,offset:b*p};f&&(c.status=f);let S=await s.getSubscriptions(c);if(z!==N.current)return;n(S.subscriptions),o(S.total)}catch(c){if(z!==N.current)return;r(c instanceof Error?c:new Error("Failed to fetch subscriptions"))}finally{z===N.current&&v(!1)}},[s,b,p,f,a]);Et.useEffect(()=>{C()},[C]);let O=Math.ceil(i/p);return{subscriptions:t,total:i,isLoading:g,error:h,page:b,pageSize:p,hasNextPage:b<O-1,hasPreviousPage:b>0,setPage:w,setPageSize:z=>{u(z),w(0)},status:f,setStatus:z=>{x(z),w(0)},refetch:C}}var D=require("react/jsx-runtime");function bi(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function yi({sub:e}){return e.status==="canceled"?(0,D.jsx)(Z,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,D.jsx)(Z,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,D.jsx)(Z,{variant:"warning",children:"Scheduled to cancel"}):(0,D.jsx)(Z,{variant:"success",children:"Active"}):(0,D.jsx)(Z,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function ol(e,a){let s=W(a,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function hi({sub:e}){let a=e.current_amount!==e.plan_amount;return(0,D.jsxs)("div",{children:[(0,D.jsx)("div",{className:"af-font-medium af-tabular-nums",children:ol(e,e.current_amount)}),a&&(0,D.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",W(e.plan_amount,e.currency)]})]})}function xi(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${bi(e.current_period_end)}`:"Ends at period end":e.current_period_end?bi(e.current_period_end):"\u2014"}function Qn({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:g,pageSize:v,hasNextPage:h,hasPreviousPage:r,setPage:b,refetch:w}=js({refreshKey:e}),p;if(i)p=(0,D.jsxs)("div",{children:[(0,D.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(u=>(0,D.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,D.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,D.jsx)(X,{className:"af-h-4 af-w-40"}),(0,D.jsx)(X,{className:"af-h-4 af-w-20"})]}),(0,D.jsx)(X,{className:"af-mt-2 af-h-3 af-w-32"}),(0,D.jsx)(X,{className:"af-mt-2 af-h-5 af-w-24"})]},u))}),(0,D.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,D.jsxs)(Le,{children:[(0,D.jsx)(Oe,{children:(0,D.jsxs)(be,{children:[(0,D.jsx)(F,{children:"Subscriber"}),(0,D.jsx)(F,{children:"Plan"}),(0,D.jsx)(F,{className:"af-text-right",children:"Amount"}),(0,D.jsx)(F,{children:"Renews"}),(0,D.jsx)(F,{children:"Status"})]})}),(0,D.jsx)(Be,{"aria-hidden":"true",children:[0,1,2,3,4].map(u=>(0,D.jsxs)(be,{children:[(0,D.jsx)(M,{children:(0,D.jsx)(X,{className:"af-h-4 af-w-44"})}),(0,D.jsx)(M,{children:(0,D.jsx)(X,{className:"af-h-4 af-w-32"})}),(0,D.jsx)(M,{className:"af-text-right",children:(0,D.jsx)(X,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,D.jsx)(M,{children:(0,D.jsx)(X,{className:"af-h-4 af-w-24"})}),(0,D.jsx)(M,{children:(0,D.jsx)(X,{className:"af-h-5 af-w-20"})})]},u))})]})}),(0,D.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=(0,D.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,D.jsx)($t,{message:"Couldn't load your subscriptions.",onRetry:()=>w()})});else if(t.length===0&&g===0)p=(0,D.jsx)(Sa,{icon:(0,D.jsx)(rs.Repeat,{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(t.length===0)p=(0,D.jsxs)("div",{children:[(0,D.jsx)(Sa,{children:"No more results."}),(0,D.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,D.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>b(g-1),children:[(0,D.jsx)(rs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let u=g*v+1,f=g*v+t.length;p=(0,D.jsxs)("div",{children:[(0,D.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(x=>(0,D.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,D.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,D.jsxs)("div",{className:"af-min-w-0",children:[(0,D.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:x.customer_email||(0,D.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,D.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:x.plan_title||"Untitled plan"})]}),(0,D.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,D.jsx)(hi,{sub:x})})]}),(0,D.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,D.jsx)(yi,{sub:x}),x.is_test&&(0,D.jsx)(Z,{variant:"outline",children:"Test"}),(0,D.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:xi(x)})]}),(0,D.jsx)(ha,{deliveries:x.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},x.id))}),(0,D.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,D.jsxs)(Le,{children:[(0,D.jsx)(Oe,{children:(0,D.jsxs)(be,{children:[(0,D.jsx)(F,{children:"Subscriber"}),(0,D.jsx)(F,{children:"Plan"}),(0,D.jsx)(F,{className:"af-text-right",children:"Amount"}),(0,D.jsx)(F,{children:"Renews"}),(0,D.jsx)(F,{children:"Status"})]})}),(0,D.jsx)(Be,{children:t.map(x=>(0,D.jsxs)(be,{children:[(0,D.jsx)(M,{className:"af-max-w-[240px]",children:(0,D.jsx)("div",{className:"af-truncate af-font-medium",children:x.customer_email||(0,D.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,D.jsx)(M,{className:"af-max-w-[220px]",children:(0,D.jsx)("div",{className:"af-truncate",children:x.plan_title||(0,D.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,D.jsx)(M,{className:"af-whitespace-nowrap af-text-right",children:(0,D.jsx)(hi,{sub:x})}),(0,D.jsx)(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:xi(x)}),(0,D.jsxs)(M,{children:[(0,D.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,D.jsx)(yi,{sub:x}),x.is_test&&(0,D.jsx)(Z,{variant:"outline",children:"Test"})]}),(0,D.jsx)(ha,{deliveries:x.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},x.id))})]})}),(0,D.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,D.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${u}-${f} of ${n}`}),(0,D.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,D.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>b(g-1),disabled:!r,children:[(0,D.jsx)(rs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,D.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>b(g+1),disabled:!h,children:["Next",(0,D.jsx)(rs.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,D.jsx)(bt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:p})}var Xn=ne(require("react"),1);var et=require("react/jsx-runtime");function er({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:g,isLoading:v,error:h,refetch:r}=Xa({refreshKey:e,initialPageSize:1,includeAggregates:!0}),b=ns({refreshKey:e}),[w,p]=Xn.useState(!1),[u,f]=Xn.useState(null),x=(0,et.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:h||!v&&!g?(0,et.jsxs)("div",{role:"alert",className:"sm:af-col-span-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't load invoice totals. ",(0,et.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):v||!g?(0,et.jsxs)(et.Fragment,{children:[(0,et.jsx)(Ye,{label:"Outstanding",children:(0,et.jsx)(X,{className:"af-h-6 af-w-24"})}),(0,et.jsx)(Ye,{label:"Overdue",children:(0,et.jsx)(X,{className:"af-h-6 af-w-24"})}),(0,et.jsx)(Ye,{label:"Paid this month",children:(0,et.jsx)(X,{className:"af-h-6 af-w-24"})})]}):(0,et.jsxs)(et.Fragment,{children:[(0,et.jsx)(Ye,{label:"Outstanding",detail:`${g.outstanding.count} open`,children:W(g.outstanding.amount,g.currency)}),(0,et.jsx)(Ye,{label:"Overdue",detail:g.overdue.count===0?"Nothing overdue":`${g.overdue.count} overdue`,valueClassName:g.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:W(g.overdue.amount,g.currency)}),(0,et.jsx)(Ye,{label:"Paid this month",detail:`${g.paid_this_month.count} paid`,children:W(g.paid_this_month.amount,g.currency)})]})});return(0,et.jsxs)(bt,{title:"Invoices",onBackToWebsite:s,hideBackButton:w,className:o,children:[x,!w&&(0,et.jsx)(ts,{retainers:b.retainers,isLoading:b.isLoading,error:b.error,onRetry:()=>void b.refetch(),activeRetainerId:u?.id??null,onShowCycles:N=>f(C=>C?.id===N.id?null:N),total:b.total,endedTotal:b.endedTotal,isLoadingMore:b.isLoadingMore,onLoadMore:()=>void b.loadMore(),includeEnded:b.includeEnded,onIncludeEndedChange:b.setIncludeEnded}),(0,et.jsx)(es,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:p,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:u?{id:u.id,label:`${u.customer_name??u.customer_email??"Recurring invoices"} \u2014 ${u.description}`}:null,onClearRetainerFilter:()=>f(null)})]})}var At=ne(require("react"),1);var ll=2e3,It=()=>({data:null,error:null,isLoading:!0});function Gs(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=te(),[i,o]=At.useState(It),[g,v]=At.useState(It),[h,r]=At.useState(It),[b,w]=At.useState(It),p=B=>Object.fromEntries(B.map(R=>[R,It()])),[u,f]=At.useState(()=>p(s)),x=At.useRef(0),N=s.join(","),C=JSON.stringify(t),O=`${e}:${N}:${C}`,[z,c]=At.useState({api:n,fetchIdentity:O});(z.api!==n||z.fetchIdentity!==O)&&(c({api:n,fetchIdentity:O}),x.current+=1,o(It),v(It),r(It),w(It),f(p(N?N.split(","):[])));let S=At.useCallback(async()=>{let B=++x.current,R=N?N.split(","):[];o(It),v(It),r(It),w(It),f(Object.fromEntries(R.map(Y=>[Y,It()])));let H=(Y,oe)=>oe.then(fe=>{B===x.current&&Y({data:fe,error:null,isLoading:!1})},fe=>{B===x.current&&Y({data:null,error:fe instanceof Error?fe:new Error("Failed to fetch report"),isLoading:!1})}),y=n.getAnalyticsStatus(),Q=H(o,y),le=Symbol("status-timeout"),ce,ee=await Promise.race([y.then(Y=>Y,()=>null),new Promise(Y=>{ce=setTimeout(()=>Y(le),ll)})]);if(clearTimeout(ce),B!==x.current)return;if(ee===le&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),ee!==null&&ee!==le&&(ee.collecting!==!0||ee.first_seen===null&&!ee.first_seen_unavailable||ee.first_seen!==null&&ee.first_seen_in_reports===!1)){let Y={data:null,error:null,isLoading:!1};v(Y),r(Y),w(Y),f(Object.fromEntries(R.map(oe=>[oe,{...Y}]))),await Q;return}await Promise.all([ee===le?Promise.resolve():Q,H(v,n.getAnalyticsSummary(e,t)),H(r,n.getAnalyticsTimeseries(e,t)),H(w,n.getAnalyticsChannels(e,t)),...R.map(Y=>n.getAnalyticsBreakdown(Y,e,t).then(oe=>{B===x.current&&f(fe=>({...fe,[Y]:{data:oe,error:null,isLoading:!1}}))},oe=>{B===x.current&&f(fe=>({...fe,[Y]:{data:null,error:oe instanceof Error?oe:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,N,C]),E=At.useCallback(async()=>{let B=x.current;try{let R=await n.getAnalyticsStatus();if(B!==x.current)return;o({data:R,error:null,isLoading:!1})}catch(R){if(B!==x.current)return;o(H=>({data:H.data,error:R instanceof Error?R:new Error("Failed to fetch status"),isLoading:!1}))}},[n]);At.useEffect(()=>{S()},[S,a]);let J=i.isLoading||g.isLoading||h.isLoading||b.isLoading||Object.values(u).some(B=>B.isLoading);return{status:i,summary:g,timeseries:h,channels:b,breakdowns:u,isLoading:J,refetch:S,refetchStatus:E}}var gt=ne(require("react"),1);var Pn=3e4,Tn=3;function Ws(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=te(),[o,g]=gt.useState(null),[v,h]=gt.useState(null),[r,b]=gt.useState(!1),[w,p]=gt.useState(null),[u,f]=gt.useState(!1),[x,N]=gt.useState(!0),[C,O]=gt.useState(0),z=gt.useRef(0),c=gt.useRef(0),S=gt.useRef(void 0);s!==void 0&&(S.current=s);let E=a?S.current===!0||S.current===void 0&&t:!0,[J,B]=gt.useState({api:i,identity:n}),R=n!==void 0&&n!==J.identity;(J.api!==i||R)&&(S.current=void 0,B({api:i,identity:n}),c.current+=1,z.current=0,g(null),h(null),b(!1),p(null),f(!1),N(!0),O(0));let H=gt.useRef(()=>{}),y=gt.useRef(null),Q=gt.useCallback(async()=>{if(y.current!==null&&y.current===c.current)return;let le=++c.current;y.current=le;try{let ce=await i.getAnalyticsRealtime();if(le!==c.current)return;if(ce.status==="unreachable"){f(!0),b(!0),N(!1),O(ee=>ee+1);return}z.current=0,f(!1),g(ce.data.current_visitors),h(ce.as_of),b(!1),p(null),N(!1),O(ee=>ee+1)}catch(ce){if(le!==c.current)return;z.current+=1,N(!1),O(ee=>ee+1),b(!0),z.current>=Tn&&p(ce instanceof Error?ce:new Error("Realtime unavailable"))}finally{y.current===le&&(y.current=null)}},[i]);return H.current=()=>void Q(),gt.useEffect(()=>{let le,ce=()=>{le===void 0&&(le=setInterval(()=>H.current(),Pn))},ee=()=>{le!==void 0&&(clearInterval(le),le=void 0)},_e=()=>{typeof document<"u"&&document.hidden?ee():(H.current(),ce())};return E?((typeof document>"u"||!document.hidden)&&(H.current(),ce()),document?.addEventListener("visibilitychange",_e),()=>{ee(),document?.removeEventListener("visibilitychange",_e),c.current+=1}):()=>{document?.removeEventListener("visibilitychange",_e)}},[J.api,J.identity,E]),{currentVisitors:o,asOf:v,isStale:r,error:w,isUnreachable:u,isInitialLoad:x,polls:C}}var We=ne(require("react"),1);var gs=ne(require("react"),1);var cl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function pa(e){let a=Math.abs(e);if(a<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[t,n]of s)if(a>=t){let i=e/t,o=Math.abs(i)<10?Math.round(i*10)/10:Math.round(i);return Math.abs(o)>=1e3&&t!==1e9?pa(o*t):`${o}${n}`}return String(e)}function Cn(e){return`${(e*100).toFixed(1)}%`}function Ks(e){let a=Math.max(0,Math.round(e));if(a<60)return`${a}s`;let s=Math.floor(a/60);return s<60?`${s}m ${a%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function Ni(e){let a=Math.max(0,Math.round(e));return a>=3600&&a%3600===0?`${a/3600}h`:a>=60&&a%60===0?`${a/60}m`:Ks(a)}function Si(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function Ri(e,a){if(!(!Number.isFinite(e)||e<=0))for(let s of a){let t=Math.ceil(e/s);if(t<=5)return Array.from({length:t+1},(n,i)=>Number((i*s).toPrecision(12)))}}function Js(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function _i(e){let a=new Date(e);return Number.isNaN(a.getTime())?"as of an unknown time":`as of ${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}function tr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${cl[a-1]} ${s}`}function wi(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function dl(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Pi(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=wi(e.to,s);for(let o=wi(e.from,s);o<i;o=dl(o))n.push(t.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function Ti(e){let a=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=new Date(`${e}T00:00:00Z`);if(Number.isNaN(t.getTime()))return e;let n=String(t.getUTCDate()).padStart(2,"0");return`${a[t.getUTCDay()]}, ${n} ${s[t.getUTCMonth()]}`}var jt=require("react/jsx-runtime");function Ci({what:e="This report",onRetry:a,collecting:s}){return(0,jt.jsxs)("div",{role:"status",className:"af-flex af-flex-col af-items-center af-gap-1 af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-8 af-text-center",children:[(0,jt.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,jt.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:s===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),a?(0,jt.jsx)("button",{type:"button",onClick:a,className:"af-mt-2 af-rounded-md af-border af-border-border af-px-3 af-py-1 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Try again"}):null]})}function ki({what:e="No data"}){return(0,jt.jsx)("div",{className:"af-flex af-items-center af-justify-center af-rounded-md af-px-4 af-py-8 af-text-center af-text-xs af-text-muted-foreground",children:e})}function Ys({sourced:e,error:a,isLoading:s,what:t,onRetry:n,collecting:i,children:o}){return s?(0,jt.jsx)("div",{role:"status","aria-label":`Loading ${t}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):a?(0,jt.jsx)(Ci,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?(0,jt.jsx)(Ci,{what:t,onRetry:n,collecting:i}):(0,jt.jsx)(jt.Fragment,{children:o(e.data)})}var ot=require("react/jsx-runtime");function ar({rows:e,dimension:a,metric:s,metricLabel:t,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:g}){if(e.length===0)return(0,ot.jsx)(ki,{what:i});let v=e.reduce((h,r)=>Math.max(h,Number(r[s]??0)),0)||1;return(0,ot.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,ot.jsx)("thead",{children:(0,ot.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,ot.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:a==="pathname"?"Page":"Name"}),(0,ot.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:t})]})}),(0,ot.jsx)("tbody",{children:e.map((h,r)=>{let b=Number(h[s]??0),w=h[a]??null,p=Js(w),u=n?h[n]:null,f=w!==null&&(g?g(w,u):!0);return(0,ot.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,ot.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,ot.jsx)("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,b/v*100)}%`}}),w!==null&&o&&f?(0,ot.jsx)("button",{type:"button",onClick:()=>o(w,u),title:`Filter by ${p}`,"aria-label":`Filter by ${p}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:p}):(0,ot.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:p}),u?(0,ot.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:u}):null]}),(0,ot.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:pa(b)})]},`${p}-${u??""}-${r}`)})})]})}function Zs({title:e,tabs:a,defaultTabId:s,headerRight:t}){let[n,i]=gs.useState(s),o=a.find(p=>p.id===n)??a[0],g=gs.useId(),v=p=>`${g}-tab-${p}`,h=p=>`${g}-panel-${p}`,r=gs.useRef(null),b=(p,u)=>{p.preventDefault();let f=(u+a.length)%a.length;i(a[f].id),r.current?.querySelectorAll('[role="tab"]')?.[f]?.focus()};return(0,ot.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,ot.jsxs)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:[(0,ot.jsx)("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:p=>{let u=a.findIndex(f=>f.id===n);p.key==="ArrowRight"&&b(p,u+1),p.key==="ArrowLeft"&&b(p,u-1),p.key==="Home"&&b(p,0),p.key==="End"&&b(p,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(p=>(0,ot.jsx)("button",{id:v(p.id),role:"tab",type:"button","aria-selected":p.id===n,"aria-controls":h(p.id),tabIndex:p.id===n?0:-1,onClick:()=>i(p.id),className:p.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:p.label},p.id))}),t]}),o?(0,ot.jsx)("div",{id:h(o.id),role:"tabpanel","aria-labelledby":v(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()}):null]})}var Dt=ne(require("react"),1),Ga=ne(require("@radix-ui/react-popover"),1);var is=3,os=100;var Ie=require("react/jsx-runtime"),Qs={channel:"Channel",source:"Source",campaign:"Campaign",utm_source:"UTM source",utm_medium:"UTM medium",utm_content:"UTM content",utm_term:"UTM term",page:"Page",entry_page:"Entry page",exit_page:"Exit page",country:"Country",region:"Region",city:"City",browser:"Browser",os:"Operating system",device:"Device"},ul=Object.keys(Qs);function Ei(e){let a=Qs[e.dimension],s=e.operator==="is_not"?"is not":"is",t=e.values.map(n=>Js(n)).join(" or ");return`${a} ${s} ${t}`}function sr(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));if(s>=0){let t=[...new Set([...e[s].values,...a.values])];return t.length>100||t.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:t}:n)}return a.values.length>100||e.length>=3?e:[...e,a]}function fl(e,a){let s={};for(let[t,n]of Object.entries(a)){let i=e.get(t)??new Set;for(let o of n)i.add(o);e.set(t,i),s[t]=[...i]}return s}function Ii(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));return s>=0?e.map((t,n)=>n===s?a:t):a.values.length>100||e.length>=3?e:[...e,a]}function ml(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Ai(e,a,s,t={}){if(e.api!==a.api||e.period!==a.period)return e.api=a.api,e.period=a.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=fl(e.byDimension,s);for(let[i,o]of Object.entries(t)){let g=e.foldsByLabel.get(i)??new Set;for(let v of o)g.add(v);e.foldsByLabel.set(i,g)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function Di(e){let{filters:a,onChange:s}=e,t=a.length>=3;return Dt.useEffect(()=>{if(a.length===0)return;let n=i=>{let o=i.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||i.key==="Escape"&&s([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[a.length,s]),(0,Ie.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[a.map((n,i)=>(0,Ie.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-1 af-rounded-full af-border af-border-border af-bg-muted af-py-1 af-pl-3 af-pr-1 af-text-xs",children:[(0,Ie.jsx)("span",{className:"af-text-foreground",children:Ei(n)}),(0,Ie.jsx)("button",{type:"button","aria-label":`Remove filter ${Ei(n)}`,onClick:()=>s(a.filter((o,g)=>g!==i)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),(0,Ie.jsx)(pl,{...e,disabled:t}),a.length>0?(0,Ie.jsx)("button",{type:"button",onClick:()=>s([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function pl({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,g]=Dt.useState(!1),v=Dt.useRef(null),[h,r]=Dt.useState(null);Dt.useEffect(()=>{r(v.current?.closest(".aifeatures-admin")??null)},[]);let[b,w]=Dt.useState(null),[p,u]=Dt.useState("is"),[f,x]=Dt.useState(""),[N,C]=Dt.useState([]);Dt.useEffect(()=>{o||(w(null),u("is"),x(""),C([]))},[o]);let O=Dt.useRef(t);O.current!==t&&(O.current=t,o&&g(!1),b!==null&&w(null),N.length>0&&C([]),f!==""&&x(""),p!=="is"&&u("is"));let z=R=>{let H=ml(R);w(H.dimension),C(H.picked),x(H.search),u(H.operator)},S=(b?s[b]??[]:[]).filter(R=>R.toLowerCase().includes(f.trim().toLowerCase())),E=b===null||N.length===0?null:sr(e,{dimension:b,operator:p,values:i?i(b,N):N}),J=E!==null&&E!==e,B=()=>{let R=E;!R||R===e||(a(R),g(!1))};return(0,Ie.jsxs)(Ga.Root,{open:o,onOpenChange:g,children:[(0,Ie.jsx)(Ga.Trigger,{asChild:!0,children:(0,Ie.jsx)("button",{ref:v,type:"button",disabled:!1,title:n?`At most ${3} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),(0,Ie.jsx)(Ga.Portal,{container:h,children:(0,Ie.jsx)(Ga.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:b===null?(0,Ie.jsxs)("div",{children:[(0,Ie.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Ie.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:ul.filter(R=>s[R]!==void 0).map(R=>{let H=s[R]?.length??0,y=!e.some(Q=>Q.dimension===R)&&e.length>=3;return(0,Ie.jsxs)("button",{type:"button",onClick:()=>z(R),disabled:H===0||y,className:"af-flex af-w-full af-items-center af-justify-between af-rounded-md af-px-2 af-py-1.5 af-text-left af-text-xs af-text-foreground hover:af-bg-muted disabled:af-text-muted-foreground disabled:hover:af-bg-transparent",children:[(0,Ie.jsx)("span",{children:Qs[R]}),(0,Ie.jsx)("span",{className:"af-text-muted-foreground",children:H===0?"no data":y?"no room":H})]},R)})})]}):(0,Ie.jsxs)("div",{children:[(0,Ie.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Ie.jsx)("button",{type:"button",onClick:()=>z(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Ie.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Qs[b]}),(0,Ie.jsxs)("select",{"aria-label":"Operator",value:p,onChange:R=>u(R.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,Ie.jsx)("option",{value:"is",children:"is"}),(0,Ie.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Ie.jsx)("input",{type:"text",value:f,onChange:R=>x(R.target.value),placeholder:"Search\u2026","aria-label":`Search ${Qs[b]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),(0,Ie.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:S.length===0?(0,Ie.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",f,"\u201D."]}):S.map(R=>(0,Ie.jsxs)("label",{className:"af-flex af-cursor-pointer af-items-center af-gap-2 af-rounded-md af-px-2 af-py-1.5 af-text-xs af-text-foreground hover:af-bg-muted",children:[(0,Ie.jsx)("input",{type:"checkbox",checked:N.includes(R),disabled:!N.includes(R)&&N.length>=100,onChange:H=>C(y=>H.target.checked?[...y,R]:y.filter(Q=>Q!==R))}),(0,Ie.jsx)("span",{className:"af-break-all",children:Js(R)})]},R))}),(0,Ie.jsx)("button",{type:"button",onClick:B,disabled:!J,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:N.length<=1?"Apply filter":N.length>=100?`Apply filter (${N.length} values \u2014 the maximum)`:`Apply filter (${N.length} values)`})]})})})]})}var Ze=require("react/jsx-runtime"),gl=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:pa,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:pa,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:pa,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:Cn,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Ks,chart:"visit_duration_seconds"}];function vl({current:e,previous:a,downIsGood:s}){if(a===0)return null;let t=(e-a)/a;if(Math.abs(t)<5e-4)return null;let n=t>0,i=s?!n:n,o=`${n?"+":""}${(t*100).toFixed(1)}%`;return(0,Ze.jsx)("span",{className:i?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:o})}function Li({summary:e,selected:a,onSelect:s}){return(0,Ze.jsx)("div",{className:"af-@container",children:(0,Ze.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:gl.map(t=>{let n=t.chart===a,i=s!==void 0,o=(0,Ze.jsxs)(Ze.Fragment,{children:[(0,Ze.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:t.label}),(0,Ze.jsxs)("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[(0,Ze.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?(0,Ze.jsx)(vl,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?(0,Ze.jsx)("button",{type:"button","aria-pressed":n,onClick:()=>s(t.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:o},t.key):(0,Ze.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},t.key)})})})}function nr({currentVisitors:e,asOf:a,isStale:s,isUnreachable:t,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!t)return(0,Ze.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1","aria-hidden":"true",children:[(0,Ze.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,Ze.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return(0,Ze.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?_i(a):"freshness unknown",g=i?" across the whole site, not the current filter,":"",v=s?`${e} current visitors${g} ${o} (not updating)`:`${e} current visitors${g} ${o}`;return(0,Ze.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:v,children:[(0,Ze.jsx)("span",{"aria-hidden":"true",className:s?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),(0,Ze.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,Ze.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),(0,Ze.jsx)("span",{className:"af-sr-only",children:v})]})}var Lt=require("recharts");var tt=require("react/jsx-runtime"),kn={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},ir={visitors:pa,visits:pa,pageviews:pa,views_per_visit:e=>e.toFixed(2),bounce_rate:Cn,visit_duration_seconds:Ks},bl=new Set(["visitors","visits","pageviews"]),yl={...ir,bounce_rate:Si,visit_duration_seconds:Ni},rr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],hl=[5,10,15,30,60,120,300,600,900,1800,3600,7200],xl=[.01,.02,.05,.1,.2,.25,.5,1],wl=[.25,.5,1,2,5,10,25,50],Nl={visitors:rr,visits:rr,pageviews:rr,views_per_visit:wl,bounce_rate:xl,visit_duration_seconds:hl};function Sl({active:e,payload:a,label:s,metric:t}){if(!e||!a||a.length===0)return null;let n=a[0].payload;return(0,tt.jsxs)("div",{className:"af-rounded-lg af-border af-border-border af-bg-popover af-px-3 af-py-2 af-text-popover-foreground af-shadow-md",children:[(0,tt.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:kn[t]}),(0,tt.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,tt.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,tt.jsx)("span",{className:"af-text-muted-foreground",children:Ti(String(s))}),(0,tt.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:ir[t](Number(n[t]??0))})]})]})}function Oi({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=Pi(a,e,t),o=ir[s],g=yl[s],v=Ri(i.reduce((r,b)=>Math.max(r,Number(b[s]??0)),0),Nl[s]),h=`${kn[s]} by day: ${i.map(r=>`${tr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return(0,tt.jsxs)("figure",{"aria-label":`${kn[s]} over time`,className:"af-m-0",children:[(0,tt.jsx)(Lt.ResponsiveContainer,{width:"100%",height:n,children:(0,tt.jsxs)(Lt.AreaChart,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,tt.jsx)("defs",{children:(0,tt.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,tt.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,tt.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,tt.jsx)(Lt.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,tt.jsx)(Lt.XAxis,{dataKey:"date",tickFormatter:tr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,tt.jsx)(Lt.YAxis,{allowDecimals:!bl.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...v?{ticks:v,domain:[0,v[v.length-1]]}:{},tickFormatter:r=>g(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,tt.jsx)(Lt.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,tt.jsx)(Sl,{metric:s})}),(0,tt.jsx)(Lt.Area,{type:"monotone",dataKey:s,name:kn[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,tt.jsx)("figcaption",{className:"af-sr-only",children:h})]})}var me=require("react/jsx-runtime"),Rl=3e4,_l="2026-08-13",Pl=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Tl=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Bi({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,className:n,published:i,lastPublishedAt:o}){let[g,v]=We.useState(30),h=e!==void 0&&a!==void 0,[r,b]=We.useState(e??[]),{api:w}=te(),[p,u]=We.useState(w);p!==w&&(u(w),!h&&r.length>0&&b([]));let f=h?e:r,x=We.useCallback(q=>{a&&a(q),h||b(q)},[a,h]),N=We.useCallback((q,pe,xe)=>{let de=Array.isArray(pe)?pe:[pe];if(de.length===0)return null;let Ue=sr(f,{dimension:q,operator:"is",values:de});if(xe&&(!xe.value||(Ue=Ii(Ue,{dimension:xe.dimension,operator:"is",values:[xe.value]}),!Ue.find(ge=>ge.dimension===xe.dimension&&ge.operator!=="is_not")?.values.includes(xe.value))))return null;let k=Ue.find(L=>L.dimension===q&&L.operator!=="is_not");return de.every(L=>k?.values.includes(L))?JSON.stringify(Ue)===JSON.stringify(f)?null:Ue:null},[f]),C=We.useCallback((q,pe,xe)=>N(q,pe,xe)!==null,[N]),O=We.useCallback((q,pe,xe)=>{let de=N(q,pe,xe);de&&x(de)},[N,x]),[z,c]=We.useState("visitors"),S=Gs(g,{refreshKey:s,breakdowns:Tl,filters:f}),E=S.status.data,J=E?.collecting===!0&&E.first_seen===null&&!E.first_seen_unavailable,B=E?.collecting===!0&&E.first_seen!==null&&E.first_seen_in_reports===!1,R=J||B,H=Ws({collecting:J?!1:E?.collecting,statusFailed:S.status.error!=null,identity:E?.analytics_id}),y=We.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),Q=We.useMemo(()=>{let q=S.breakdowns.sources?.data,pe={};if(!q||q.status!=="ok")return pe;for(let xe of q.data){let de=xe.source,Ue=xe.sources;typeof de=="string"&&Array.isArray(Ue)&&Ue.length>0&&(pe[de]=Ue)}return pe},[S.breakdowns.sources?.data]),le=We.useMemo(()=>{let q=(de,Ue)=>{let k=S.breakdowns[de]?.data;return!k||k.status!=="ok"?[]:[...new Set(k.data.map(L=>L[Ue]).filter(L=>typeof L=="string"&&L!==""))]};return{channel:S.channels.data?.status==="ok"?[...new Set(S.channels.data.data.map(de=>de.channel))]:[],source:q("sources","source"),campaign:q("utm/campaign","campaign"),page:q("pages","pathname"),entry_page:q("entry-pages","pathname"),exit_page:q("exit-pages","pathname"),country:q("countries","country"),browser:q("browsers","browser"),os:q("operating-systems","os"),device:q("devices","device")}},[S.breakdowns,S.channels.data]),[ce,ee]=We.useState({}),_e=JSON.stringify(le),[Y,oe]=We.useState(new Map),fe=JSON.stringify(Q);We.useEffect(()=>{let{suggestions:q,folds:pe}=Ai(y.current,{api:w,period:g},JSON.parse(_e),JSON.parse(fe));ee(q),oe(pe)},[_e,fe,w,g]);let K=We.useCallback((q,pe)=>q!=="source"?pe:[...new Set(pe.flatMap(xe=>{let de=[...Y.get(xe)??[],...Q[xe]??[]];return de.length>0?de:[xe]}))],[Y,Q]),Pe=We.useMemo(()=>{let q=[S.summary,S.timeseries,S.channels,...Object.values(S.breakdowns)];for(let pe of q){let xe=pe?.error;if(xe instanceof na&&xe.details?.code==="filter_unsupported")return xe.message}return null},[S.summary,S.timeseries,S.channels,S.breakdowns]),Me=(q,pe,xe,de,Ue,k,L,ge,Ke)=>()=>{let ze=S.breakdowns[q];return(0,me.jsx)(Ys,{sourced:ze?.data??null,error:ze?.error,isLoading:ze?.isLoading,what:pe,collecting:E?.collecting,onRetry:S.refetch,children:at=>{let Je=st=>ge?K(ge,[st]):st;return(0,me.jsx)(ar,{rows:at,dimension:xe,metric:de,metricLabel:Ue,secondary:k,emptyCopy:f.length>0?"No data for this filter":L,canFilter:ge?(st,Gt)=>C(ge,Je(st),Ke?{dimension:Ke,value:Gt}:void 0):()=>!1,onFilter:ge?(st,Gt)=>O(ge,Je(st),Ke?{dimension:Ke,value:Gt}:void 0):void 0})}})};We.useEffect(()=>{if(!R)return;let q,pe=()=>{q===void 0&&(q=setInterval(()=>void S.refetchStatus(),Rl))},xe=()=>{q!==void 0&&(clearInterval(q),q=void 0)},de=()=>{typeof document<"u"&&document.hidden?xe():(S.refetchStatus(),pe())};return(typeof document>"u"||!document.hidden)&&pe(),document?.addEventListener("visibilitychange",de),()=>{xe(),document?.removeEventListener("visibilitychange",de)}},[R,S.refetchStatus]);let xt=We.useRef(void 0);if(We.useEffect(()=>{if(!E){xt.current=void 0;return}let q=xt.current;xt.current=R,q===!0&&!R&&S.refetch()},[E,R,S.refetch]),E&&!E.collecting){let q=i===!1,pe=!!o&&String(o).slice(0,10)<_l;return(0,me.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:n,children:(0,me.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,me.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,me.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:q?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":pe?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return J?(0,me.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:n,children:(0,me.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,me.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,me.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:"Your site is set up and analytics is running. The first visit shows up here shortly after someone lands on a published page."})]})}):B?(0,me.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:n,children:(0,me.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,me.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,me.jsxs)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",E?.timezone?` ${E.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,me.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,me.jsx)(nr,{currentVisitors:H.currentVisitors,asOf:H.asOf,isStale:H.isStale,isUnreachable:H.isUnreachable||H.error!==null,isInitialLoad:H.isInitialLoad})})]})}):(0,me.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:n,children:(0,me.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,me.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,me.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Pl.map(q=>(0,me.jsx)("button",{type:"button","aria-pressed":q.value===g,onClick:()=>v(q.value),className:q.value===g?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:q.label},q.value))}),(0,me.jsx)(nr,{currentVisitors:H.currentVisitors,asOf:H.asOf,isStale:H.isStale,isUnreachable:H.isUnreachable||H.error!==null,isInitialLoad:H.isInitialLoad,scopeIsSiteWide:f.length>0})]}),(0,me.jsx)(Di,{filters:f,onChange:x,suggestions:ce,expandValues:K,resetKey:w}),Pe?(0,me.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,me.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,me.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:Pe}),(0,me.jsx)("button",{type:"button",onClick:()=>x([]),className:"af-mt-4 af-rounded-md af-border af-border-border af-px-3 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Clear filters"})]}):null,!Pe&&E?.timezone_defaulted?(0,me.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Reports are shown in UTC. Set a timezone to see them in your local days."}):null,Pe?null:(0,me.jsxs)(me.Fragment,{children:[(0,me.jsx)(Ys,{sourced:S.summary.data,error:S.summary.error,isLoading:S.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:S.refetch,children:q=>(0,me.jsxs)(me.Fragment,{children:[(0,me.jsx)(Li,{summary:q,selected:z,onSelect:c}),q.previous_unavailable?(0,me.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[q.previous_unavailable_reason==="filter"?"No comparison for this filter \u2014 the previous period has too many distinct traffic sources to resolve it. Try a shorter period, or filter by source instead.":"No comparison available right now \u2014 we couldn\u2019t check how far back this site\u2019s history goes. It should return on its own."," ","The numbers above are still for the period you selected."]}):null]})}),(0,me.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,me.jsx)(Ys,{sourced:S.timeseries.data,error:S.timeseries.error,isLoading:S.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:S.refetch,children:q=>{let pe=S.timeseries.data?.status==="ok"?S.timeseries.data.window:{from:"",to:""};return(0,me.jsx)(Oi,{rows:q,window:pe,metric:z,timeZone:(S.timeseries.data?.status==="ok"?S.timeseries.data.timezone:void 0)??E?.timezone??"UTC"})}})}),(0,me.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,me.jsx)(Zs,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,me.jsx)(Ys,{sourced:S.channels.data,error:S.channels.error,isLoading:S.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:S.refetch,children:q=>(0,me.jsx)(ar,{rows:q,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:f.length>0?"No data for this filter":"No data for this period",canFilter:pe=>C("channel",pe),onFilter:pe=>O("channel",pe)})})},{id:"sources",label:"Sources",render:Me("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:Me("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,me.jsx)(Zs,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:Me("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:Me("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:Me("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,me.jsx)(Zs,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:Me("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:Me("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:Me("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,me.jsx)(Zs,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:Me("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:Me("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:Me("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,FormSettings,FormSubmissions,FormsDashboard,FormsList,InvoiceDetail,InvoiceLabelBadge,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,chargedTotal,createApiClient,formatPrice,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useBusinessSummary,useCustomers,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSubmissions,useSubscriptions});
|
|
2
|
+
"use strict";var Vi=Object.create;var Xs=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var Hi=Object.getOwnPropertyNames;var zi=Object.getPrototypeOf,qi=Object.prototype.hasOwnProperty;var ji=(e,a)=>{for(var s in a)Xs(e,s,{get:a[s],enumerable:!0})},pr=(e,a,s,t)=>{if(a&&typeof a=="object"||typeof a=="function")for(let n of Hi(a))!qi.call(e,n)&&n!==s&&Xs(e,n,{get:()=>a[n],enumerable:!(t=$i(a,n))||t.enumerable});return e};var ne=(e,a,s)=>(s=e!=null?Vi(zi(e)):{},pr(a||!e||!e.__esModule?Xs(s,"default",{value:e,enumerable:!0}):s,e)),Gi=e=>pr(Xs({},"__esModule",{value:!0}),e);var Cl={};ji(Cl,{AifeaturesApiError:()=>na,AifeaturesProvider:()=>vr,AnalyticsView:()=>Bi,CustomerDetail:()=>Ms,CustomersList:()=>Us,FormSettings:()=>Es,FormSubmissions:()=>Rs,FormsDashboard:()=>An,FormsList:()=>hs,InvoiceDetail:()=>bn,InvoiceLabelBadge:()=>fs,InvoicesList:()=>es,InvoicesView:()=>er,LeadsView:()=>Zn,MAX_ANALYTICS_FILTERS:()=>os,MAX_ANALYTICS_FILTER_VALUES:()=>ls,OrderDetail:()=>Bs,OrderStatusBadge:()=>$a,OrdersList:()=>Za,OrdersView:()=>Wn,PaymentsDashboard:()=>Gn,PaymentsSetup:()=>Vs,ProductSettings:()=>Ds,ProductsList:()=>Is,ProductsView:()=>Kn,REALTIME_FAILURES_BEFORE_ERROR:()=>Tn,REALTIME_POLL_MS:()=>Pn,RetainerStatusBadge:()=>hn,RetainersPanel:()=>ts,SubmissionDetail:()=>Ns,SubscriptionsView:()=>Qn,VariantsEditor:()=>As,ViewShell:()=>bt,WebhookDeliveries:()=>Cs,WebhookSettings:()=>ks,chargedTotal:()=>Zt,createApiClient:()=>tn,formatPrice:()=>W,isZeroDecimalCurrency:()=>fa,toMajorUnits:()=>vt,toMinorUnits:()=>Qt,useAifeatures:()=>te,useAifeaturesContext:()=>te,useAnalytics:()=>Gs,useBusinessSummary:()=>$s,useCustomers:()=>Fs,useEventDestinations:()=>Ps,useForms:()=>Wa,useInvoices:()=>Xa,useOrders:()=>Ls,usePaymentsStatus:()=>as,usePeople:()=>zs,usePerson:()=>qs,useProducts:()=>ss,useRealtimeVisitors:()=>Ws,useRetainers:()=>ns,useSubmissions:()=>ws,useSubscriptions:()=>js});module.exports=Gi(Cl);var Fa=ne(require("react"),1);function en(e,a){let s=new URLSearchParams({period:String(e)});return a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var na=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function En(e,a){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${a}`}function tn(e,a="https://aifeatures.dev"){async function s(t,n={}){let i=`${a}${t}`,o=await fetch(i,{...n,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...n.headers}});if(!o.ok){let p;try{p=await o.json()}catch{}throw new na(En(p?.error,o.status),o.status,p)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(t){return s(`/api/v1/forms/${t}`)},async createForm(t){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(t)})},async updateForm(t,n){return s(`/api/v1/forms/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteForm(t){await s(`/api/v1/forms/${t}`,{method:"DELETE"})},async getSubmissions(t,n={}){let i=new URLSearchParams;n.limit!==void 0&&i.set("limit",String(n.limit)),n.offset!==void 0&&i.set("offset",String(n.offset));let o=i.toString(),p=`/api/v1/forms/${t}/submissions${o?`?${o}`:""}`;return s(p)},async getSubmission(t){return s(`/api/v1/submissions/${t}`)},async deleteSubmission(t){await s(`/api/v1/submissions/${t}`,{method:"DELETE"})},async downloadAttachment(t,n){let i=typeof n=="string"?{name:n}:n,o=i.name,p=i.id??i.name,g=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(p)}`,x=await fetch(g,{headers:{Authorization:`Bearer ${e}`}});if(!x.ok){let v;try{v=await x.json()}catch{}throw new na(En(v?.error,x.status),x.status,v)}let r=await x.blob(),y=URL.createObjectURL(r),w=document.createElement("a");w.href=y,w.download=o,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(y)},async getPaymentsStatus(){return s("/api/v1/payments/status")},async getProducts(t={}){let n=new URLSearchParams;t.include&&n.set("include",t.include);let i=n.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(t){return s(`/api/v1/products/${t}`)},async createProduct(t){return s("/api/v1/products",{method:"POST",body:JSON.stringify(t)})},async updateProduct(t,n){return s(`/api/v1/products/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteProduct(t){await s(`/api/v1/products/${t}`,{method:"DELETE"})},async attachProductFile(t,n){let i=new FormData;i.append("file",n);let o=await fetch(`${a}/api/v1/products/${t}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!o.ok){let p;try{p=await o.json()}catch{}throw new na(En(p?.error,o.status),o.status,p)}return o.json()},async attachProductFileFromUrl(t,n){return s(`/api/v1/products/${t}/file`,{method:"POST",body:JSON.stringify({source_url:n})})},async createOption(t,n){return s(`/api/v1/products/${t}/options`,{method:"POST",body:JSON.stringify(n)})},async updateOption(t,n){return s(`/api/v1/options/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteOption(t){await s(`/api/v1/options/${t}`,{method:"DELETE"})},async createVariant(t,n){return s(`/api/v1/products/${t}/variants`,{method:"POST",body:JSON.stringify(n)})},async updateVariant(t,n){return s(`/api/v1/variants/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteVariant(t){await s(`/api/v1/variants/${t}`,{method:"DELETE"})},async setVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory`,{method:"PUT",body:JSON.stringify(n)})},async adjustVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory/adjust`,{method:"POST",body:JSON.stringify(n)})},async getCustomers(t={}){let n=new URLSearchParams;t.email?n.set("email",t.email):t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(t){return s(`/api/v1/customers/${t}`)},async getOrders(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.source&&n.set("source",t.source),t.excludeStatus?.length&&n.set("exclude_status",t.excludeStatus.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.unfulfilledOnly&&n.set("unfulfilled_only","true"),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(t){return s(`/api/v1/orders/${t}`)},async getInvoices(t={}){let n=new URLSearchParams;t.labels?.length&&n.set("label",t.labels.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.customerId&&n.set("customer_id",t.customerId),t.q&&n.set("q",t.q),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.includeAggregates&&n.set("include","aggregates"),t.retainerId&&n.set("retainer_id",t.retainerId),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(t){return s(`/api/v1/invoices/${t}`)},async getInvoicePreview(t){return s(`/api/v1/invoices/${t}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(t={}){let n=new URLSearchParams;t.statuses?.length&&n.set("status",t.statuses.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/retainers${i?`?${i}`:""}`)},async getRetainer(t){return s(`/api/v1/retainers/${t}`)},async resendOrderReceipt(t){await s(`/api/v1/orders/${t}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(t){return s(`/api/v1/orders/${t}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(t,n){return s(`/api/v1/orders/${t}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:n.fulfilled,...n.trackingNumber!==void 0?{tracking_number:n.trackingNumber}:{}})})},async getSubscriptions(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getAnalyticsStatus(){return s("/api/v1/analytics/status")},async getAnalyticsSummary(t,n){return s(`/api/v1/analytics/summary?${en(t,n)}`)},async getAnalyticsTimeseries(t,n){return s(`/api/v1/analytics/timeseries?${en(t,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(t,n){return s(`/api/v1/analytics/channels?${en(t,n)}`)},async getAnalyticsBreakdown(t,n,i){let o=t.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${en(n,i)}`)},async getBusinessSummary(t){let n=new URLSearchParams;return n.set("tz_offset_minutes",String(t.tzOffsetMinutes)),s(`/api/v1/summary?${n.toString()}`)},async getPeople(t={}){let n=new URLSearchParams;t.since&&n.set("since",t.since),t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/people${i?`?${i}`:""}`)},async getPerson(t){return s(`/api/v1/people/${encodeURIComponent(t)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(t){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(t)})},async updateEventDestination(t,n){return s(`/api/v1/event-destinations/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteEventDestination(t){await s(`/api/v1/event-destinations/${t}`,{method:"DELETE"})},async rotateEventDestinationSecret(t){return s(`/api/v1/event-destinations/${t}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(t){return(await s(`/api/v1/event-destinations/${t}/secret`)).secret},async getEventDeliveries(t,n){let i=n===void 0?"":`?limit=${n}`;return(await s(`/api/v1/event-destinations/${t}/deliveries${i}`)).deliveries},async retryEventDelivery(t,n){return s(`/api/v1/event-destinations/${t}/deliveries/${n}/retry`,{method:"POST"})}}}var Ba=require("react/jsx-runtime"),gr=Fa.createContext(null);function Wi(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 vr({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=Fa.useMemo(()=>Wi(e),[e]),o=Fa.useMemo(()=>tn(e,a),[e,a]),p=Fa.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?(0,Ba.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:(0,Ba.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Ba.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Ba.jsx)("p",{className:"af-text-sm af-text-destructive",children:i})]})}):(0,Ba.jsx)(gr.Provider,{value:p,children:(0,Ba.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function te(){let e=Fa.useContext(gr);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var Va=ne(require("react"),1),cs=require("lucide-react");var an=ne(require("react"),1),ra=ne(require("@radix-ui/react-tabs"),1);var br=require("clsx"),yr=require("tailwind-merge"),Ki=(0,yr.extendTailwindMerge)({prefix:"af-"});function G(...e){return Ki((0,br.clsx)(e))}var nn=require("react/jsx-runtime"),sn=ra.Root,bs=an.forwardRef(({className:e,...a},s)=>(0,nn.jsx)(ra.List,{ref:s,className:G("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),...a}));bs.displayName=ra.List.displayName;var va=an.forwardRef(({className:e,...a},s)=>(0,nn.jsx)(ra.Trigger,{ref:s,className:G("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),...a}));va.displayName=ra.Trigger.displayName;var ba=an.forwardRef(({className:e,...a},s)=>(0,nn.jsx)(ra.Content,{ref:s,className:G("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),...a}));ba.displayName=ra.Content.displayName;var hr=ne(require("react"),1),xr=require("@radix-ui/react-slot"),wr=require("class-variance-authority");var Nr=require("react/jsx-runtime"),Ji=(0,wr.cva)("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"}}),P=hr.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>(0,Nr.jsx)(t?xr.Slot:"button",{className:G(Ji({variant:a,size:s,className:e})),ref:i,...n}));P.displayName="Button";var ys=require("lucide-react");var Ea=ne(require("react"),1);var ya=require("react/jsx-runtime"),Le=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,ya.jsx)("table",{ref:s,className:G("af-w-full af-caption-bottom af-text-sm",e),...a})}));Le.displayName="Table";var Oe=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("thead",{ref:s,className:G("[&_tr]:af-border-b",e),...a}));Oe.displayName="TableHeader";var Be=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("tbody",{ref:s,className:G("[&_tr:last-child]:af-border-0",e),...a}));Be.displayName="TableBody";var Yi=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("tfoot",{ref:s,className:G("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...a}));Yi.displayName="TableFooter";var be=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("tr",{ref:s,className:G("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));be.displayName="TableRow";var F=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("th",{ref:s,className:G("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),...a}));F.displayName="TableHead";var M=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("td",{ref:s,className:G("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));M.displayName="TableCell";var Zi=Ea.forwardRef(({className:e,...a},s)=>(0,ya.jsx)("caption",{ref:s,className:G("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));Zi.displayName="TableCaption";var ia=ne(require("react"),1);function Wa(){let{api:e}=te(),[a,s]=ia.useState([]),[t,n]=ia.useState(!0),[i,o]=ia.useState(null),p=ia.useCallback(async()=>{try{n(!0),o(null);let y=await e.getForms();s(y)}catch(y){o(y instanceof Error?y:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);ia.useEffect(()=>{p()},[p]);let g=ia.useCallback(async y=>{let w=await e.createForm(y);return s(v=>[...v,w]),w},[e]),x=ia.useCallback(async(y,w)=>{let v=await e.updateForm(y,w);return s(d=>d.map(u=>u.id===y?v:u)),v},[e]),r=ia.useCallback(async y=>{await e.deleteForm(y),s(w=>w.filter(v=>v.id!==y))},[e]);return{forms:a,isLoading:t,error:i,refetch:p,createForm:g,updateForm:x,deleteForm:r}}var Fe=require("react/jsx-runtime");function hs({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=Wa();return t?(0,Fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,Fe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,Fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,Fe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?(0,Fe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[(0,Fe.jsx)(ys.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Fe.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Fe.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Fe.jsx)("div",{className:a,children:(0,Fe.jsxs)(Le,{children:[(0,Fe.jsx)(Oe,{children:(0,Fe.jsxs)(be,{children:[(0,Fe.jsx)(F,{children:"Name"}),(0,Fe.jsx)(F,{children:"Endpoint"}),(0,Fe.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,Fe.jsx)(Be,{children:s.map(i=>(0,Fe.jsxs)(be,{children:[(0,Fe.jsx)(M,{className:"af-font-medium",children:i.name}),(0,Fe.jsx)(M,{children:(0,Fe.jsx)("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","")})}),(0,Fe.jsx)(M,{className:"af-text-right",children:(0,Fe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Fe.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[(0,Fe.jsx)(ys.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Fe.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[(0,Fe.jsx)(ys.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}var _r=require("lucide-react");var Sr=require("class-variance-authority");var Rr=require("react/jsx-runtime"),Qi=(0,Sr.cva)("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 Z({className:e,variant:a,...s}){return(0,Rr.jsx)("div",{className:G(Qi({variant:a}),e),...s})}var Ot=require("react/jsx-runtime"),Xi={form_notification:"Form notification",purchase_receipt:"Buyer receipt",merchant_sale:"Sale notification",subscription_payment_failed:"Payment reminder",subscription_cancellation:"Cancellation confirmation",subscription_address_change:"Address change confirmation",merchant_subscription_canceled:"Subscription cancellation notice",account_login:"Sign-in email",oversell_refund:"Refund notification",merchant_oversell:"Stock issue notification",dispute_opened:"Dispute notification"};function rn(e){switch(e.state){case"sending":return{label:"Sending",variant:"secondary",detail:null};case"sent":return{label:"Sent",variant:"secondary",detail:"Accepted for sending. Delivery has not been confirmed yet."};case"delivered":return{label:"Delivered",variant:"success",detail:"Accepted by the recipient\u2019s email server. This does not confirm it was read."};case"delivery_delayed":return{label:"Delayed",variant:"warning",detail:"Delivery is delayed. The email provider is still trying."};case"bounced":return{label:"Bounced",variant:"destructive",detail:"A receiving email server rejected this message."};case"complained":return{label:"Marked as spam",variant:"destructive",detail:"A recipient marked this email as spam. Do not resend it to that recipient."};case"suppressed":return{label:"Delivery blocked",variant:"destructive",detail:"The email provider blocked delivery to a recipient after a previous delivery problem or spam complaint."};case"failed":return{label:"Send failed",variant:"destructive",detail:"The email provider reported a sending failure."};case"unknown":return{label:"Delivery unconfirmed",variant:"warning",detail:"We could not confirm whether the email was sent. Check with the recipient before sending it again."}}}function In(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function eo(e){return["sending","sent","delivered","delivery_delayed","unknown","complained"].includes(e.state)?null:e.kind==="form_notification"?"Check this form\u2019s notification email addresses in its settings. The submission is saved here.":e.kind==="merchant_sale"||e.kind==="merchant_oversell"?"Check your notification email addresses. You can view and fulfill this order here.":e.kind==="dispute_opened"?"Check your notification email addresses and review this dispute in Stripe.":e.kind==="merchant_subscription_canceled"?"Check your notification email addresses. The subscription status is still shown here.":e.kind==="account_login"?"Ask the customer to confirm their email address and request a new sign-in link once the delivery problem is resolved.":e.kind==="purchase_receipt"?"Contact the buyer another way to confirm their email address. Payment and download details are still available on this order.":"Contact the customer another way to confirm their email address. Email delivery does not change their subscription or payment status."}function xs({deliveries:e,label:a="Email needs attention"}){return In(e)?(0,Ot.jsxs)("span",{className:"af-mt-1 af-flex af-items-center af-gap-1 af-text-xs af-font-normal af-text-amber-800 dark:af-text-amber-300",children:[(0,Ot.jsx)(_r.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function ha({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||In([n]));return t.length?(0,Ot.jsx)("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:t.map(n=>{let i=rn(n),o=eo(n);return(0,Ot.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Ot.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Ot.jsx)("span",{className:"af-font-medium",children:Xi[n.kind]??"Email notification"}),(0,Ot.jsx)(Z,{variant:i.variant,children:i.label})]}),(0,Ot.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&In([n])&&(0,Ot.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This status applies to the message sent to this group. It does not mean every recipient had a delivery problem."}),i.detail&&(0,Ot.jsx)("p",{className:"af-mt-1",children:i.detail}),o&&(0,Ot.jsx)("p",{className:"af-mt-1",children:o})]},n.id)})}):null}var Ss=ne(require("react"),1),xa=require("lucide-react");var Ma=ne(require("react"),1),Te=ne(require("@radix-ui/react-select"),1),Ka=require("lucide-react");var rt=require("react/jsx-runtime"),Wt=Te.Root;var Kt=Te.Value,Bt=Ma.forwardRef(({className:e,children:a,...s},t)=>(0,rt.jsxs)(Te.Trigger,{ref:t,className:G("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[a,(0,rt.jsx)(Te.Icon,{asChild:!0,children:(0,rt.jsx)(Ka.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Bt.displayName=Te.Trigger.displayName;var Pr=Ma.forwardRef(({className:e,...a},s)=>(0,rt.jsx)(Te.ScrollUpButton,{ref:s,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:(0,rt.jsx)(Ka.ChevronUp,{className:"af-h-4 af-w-4"})}));Pr.displayName=Te.ScrollUpButton.displayName;var Tr=Ma.forwardRef(({className:e,...a},s)=>(0,rt.jsx)(Te.ScrollDownButton,{ref:s,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:(0,rt.jsx)(Ka.ChevronDown,{className:"af-h-4 af-w-4"})}));Tr.displayName=Te.ScrollDownButton.displayName;var Ft=Ma.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>(0,rt.jsx)(Te.Portal,{children:(0,rt.jsxs)(Te.Content,{ref:n,className:G("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...t,children:[(0,rt.jsx)(Pr,{}),(0,rt.jsx)(Te.Viewport,{className:G("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:a}),(0,rt.jsx)(Tr,{})]})}));Ft.displayName=Te.Content.displayName;var to=Ma.forwardRef(({className:e,...a},s)=>(0,rt.jsx)(Te.Label,{ref:s,className:G("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));to.displayName=Te.Label.displayName;var qe=Ma.forwardRef(({className:e,children:a,...s},t)=>(0,rt.jsxs)(Te.Item,{ref:t,className:G("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...s,children:[(0,rt.jsx)("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:(0,rt.jsx)(Te.ItemIndicator,{children:(0,rt.jsx)(Ka.Check,{className:"af-h-4 af-w-4"})})}),(0,rt.jsx)(Te.ItemText,{children:a})]}));qe.displayName=Te.Item.displayName;var ao=Ma.forwardRef(({className:e,...a},s)=>(0,rt.jsx)(Te.Separator,{ref:s,className:G("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));ao.displayName=Te.Separator.displayName;var Jt=ne(require("react"),1);function ws({formId:e,initialPageSize:a=25}){let{api:s}=te(),[t,n]=Jt.useState([]),[i,o]=Jt.useState(0),[p,g]=Jt.useState(!0),[x,r]=Jt.useState(null),[y,w]=Jt.useState(0),[v,d]=Jt.useState(a),u=Jt.useCallback(async()=>{if(e)try{g(!0),r(null);let T={limit:v,offset:y*v},A=await s.getSubmissions(e,T);n(A.submissions),o(A.total)}catch(T){r(T instanceof Error?T:new Error("Failed to fetch submissions"))}finally{g(!1)}},[s,e,y,v]);Jt.useEffect(()=>{u()},[u]);let h=Jt.useCallback(async T=>{await s.deleteSubmission(T),n(A=>A.filter(H=>H.id!==T)),o(A=>A-1)},[s]),N=Math.ceil(i/v);return{submissions:t,total:i,isLoading:p,error:x,page:y,pageSize:v,hasNextPage:y<N-1,hasPreviousPage:y>0,setPage:w,setPageSize:T=>{d(T),w(0)},refetch:u,deleteSubmission:h}}var kr=ne(require("react"),1),wt=require("lucide-react");var ye=require("react/jsx-runtime");function Cr(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function so(e){if(e===0)return"0 B";let a=1024,s=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(a));return`${parseFloat((e/Math.pow(a,t)).toFixed(1))} ${s[t]}`}function Ns({submission:e,onBack:a}){let{api:s}=te(),[t,n]=kr.useState(null),i=g=>g.id??g.name,o=async g=>{n(i(g));try{await s.downloadAttachment(e.id,g)}catch(x){console.error("Download failed:",x)}finally{n(null)}},p=Object.entries(e.data).filter(([g])=>!g.startsWith("_"));return(0,ye.jsxs)("div",{children:[(0,ye.jsxs)("div",{className:"af-mb-6",children:[(0,ye.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,ye.jsx)(wt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,ye.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,ye.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Cr(e.metadata.submitted_at)]})]}),(0,ye.jsxs)("div",{className:"af-space-y-6",children:[(0,ye.jsx)(ha,{deliveries:e.email_deliveries}),(0,ye.jsxs)("div",{children:[(0,ye.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,ye.jsxs)("div",{className:"af-space-y-3",children:[p.map(([g,x])=>(0,ye.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,ye.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:g.replace(/_/g," ")}),(0,ye.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof x=="string"&&x.includes(`
|
|
3
|
+
`)?(0,ye.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:x}):String(x)})]},g)),p.length===0&&(0,ye.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,ye.jsxs)("div",{children:[(0,ye.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,ye.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((g,x)=>(0,ye.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ye.jsx)(wt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,ye.jsx)("span",{className:"af-text-sm",children:g.name}),(0,ye.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",so(g.size),")"]})]}),(0,ye.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>o(g),disabled:t===i(g),children:[t===i(g)?(0,ye.jsx)(wt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,ye.jsx)(wt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(g)?"Downloading...":"Download"]})]},x))})]}),(0,ye.jsxs)("div",{children:[(0,ye.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,ye.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,ye.jsx)(wt.Clock,{className:"af-h-4 af-w-4"}),(0,ye.jsx)("span",{children:Cr(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,ye.jsx)(wt.Globe,{className:"af-h-4 af-w-4"}),(0,ye.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,ye.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,ye.jsx)(wt.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,ye.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,ye.jsx)(wt.Mail,{className:"af-h-4 af-w-4"}),(0,ye.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var ie=require("react/jsx-runtime");function no(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ro(e){let a=["email","Email","EMAIL","e-mail","mail"];for(let s of a)if(typeof e[s]=="string")return e[s];return null}function io(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")&&!n.toLowerCase().includes("email"));if(a.length===0)return"";let[,s]=a[0],t=String(s);return t.length>50?t.slice(0,50)+"...":t}function Rs({formId:e,className:a,defaultSubmissionId:s}){let{submissions:t,total:n,isLoading:i,error:o,page:p,pageSize:g,hasNextPage:x,hasPreviousPage:r,setPage:y,setPageSize:w}=ws({formId:e}),[v,d]=Ss.useState("list"),[u,h]=Ss.useState(null);Ss.useEffect(()=>{if(s&&t.length>0){let c=t.find(S=>S.id===s);c&&(h(c),d("detail"))}},[s,t]);let N=c=>{h(c),d("detail")},T=()=>{d("list"),h(null)};if(v==="detail"&&u)return(0,ie.jsx)("div",{className:a,children:(0,ie.jsx)(Ns,{submission:u,onBack:T})});if(i)return(0,ie.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,ie.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(o)return(0,ie.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,ie.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(t.length===0&&p===0)return(0,ie.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[(0,ie.jsx)(xa.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ie.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,ie.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let A=p*g+1,H=Math.min((p+1)*g,n);return(0,ie.jsxs)("div",{className:a,children:[(0,ie.jsxs)(Le,{children:[(0,ie.jsx)(Oe,{children:(0,ie.jsxs)(be,{children:[(0,ie.jsx)(F,{children:"Email"}),(0,ie.jsx)(F,{children:"Preview"}),(0,ie.jsx)(F,{children:"Date"}),(0,ie.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,ie.jsx)(Be,{children:t.map(c=>{let S=ro(c.data),E=io(c.data);return(0,ie.jsxs)(be,{children:[(0,ie.jsxs)(M,{className:"af-font-medium",children:[(0,ie.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[S||(0,ie.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),c.attachments.length>0&&(0,ie.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${c.attachments.length} attachment(s)`,children:[(0,ie.jsx)(xa.Paperclip,{className:"af-h-3 af-w-3"}),(0,ie.jsx)("span",{className:"af-text-xs",children:c.attachments.length})]})]}),(0,ie.jsx)(xs,{deliveries:c.email_deliveries,label:"Notification email needs attention"})]}),(0,ie.jsx)(M,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:E||(0,ie.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,ie.jsx)(M,{className:"af-text-muted-foreground",children:no(c.metadata.submitted_at)}),(0,ie.jsx)(M,{className:"af-text-right",children:(0,ie.jsx)(P,{variant:"ghost",size:"icon",onClick:()=>N(c),title:"View details",children:(0,ie.jsx)(xa.Eye,{className:"af-h-4 af-w-4"})})})]},c.id)})})]}),(0,ie.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ie.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ie.jsxs)("span",{children:["Showing ",A,"-",H," of ",n]}),(0,ie.jsxs)(Wt,{value:String(g),onValueChange:c=>w(Number(c)),children:[(0,ie.jsx)(Bt,{className:"af-w-[70px] af-h-8",children:(0,ie.jsx)(Kt,{})}),(0,ie.jsxs)(Ft,{children:[(0,ie.jsx)(qe,{value:"10",children:"10"}),(0,ie.jsx)(qe,{value:"25",children:"25"}),(0,ie.jsx)(qe,{value:"50",children:"50"}),(0,ie.jsx)(qe,{value:"100",children:"100"})]})]}),(0,ie.jsx)("span",{children:"per page"})]}),(0,ie.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ie.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>y(p-1),disabled:!r,children:[(0,ie.jsx)(xa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ie.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>y(p+1),disabled:!x,children:["Next",(0,ie.jsx)(xa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ut=ne(require("react"),1),Ua=require("lucide-react");var Er=ne(require("react"),1);var Ir=require("react/jsx-runtime"),Se=Er.forwardRef(({className:e,type:a,...s},t)=>(0,Ir.jsx)("input",{type:a,className:G("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:t,...s}));Se.displayName="Input";var Ar=ne(require("react"),1),Dr=require("class-variance-authority");var Lr=require("react/jsx-runtime"),oo=(0,Dr.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Re=Ar.forwardRef(({className:e,...a},s)=>(0,Lr.jsx)("label",{ref:s,className:G(oo(),e),...a}));Re.displayName="Label";var Yt=ne(require("react"),1),Nt=require("lucide-react");var _s=ne(require("react"),1),ft=ne(require("@radix-ui/react-dialog"),1),Or=require("lucide-react");var Ct=require("react/jsx-runtime"),wa=ft.Root;var lo=ft.Portal;var Br=_s.forwardRef(({className:e,...a},s)=>(0,Ct.jsx)(ft.Overlay,{ref:s,className:G("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));Br.displayName=ft.Overlay.displayName;var oa=_s.forwardRef(({className:e,children:a,...s},t)=>(0,Ct.jsx)(lo,{children:(0,Ct.jsxs)("div",{className:"aifeatures-admin",children:[(0,Ct.jsx)(Br,{}),(0,Ct.jsxs)(ft.Content,{ref:t,className:G("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[a,(0,Ct.jsxs)(ft.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:[(0,Ct.jsx)(Or.X,{className:"af-h-4 af-w-4"}),(0,Ct.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));oa.displayName=ft.Content.displayName;var la=({className:e,...a})=>(0,Ct.jsx)("div",{className:G("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...a});la.displayName="DialogHeader";var ca=({className:e,...a})=>(0,Ct.jsx)("div",{className:G("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...a});ca.displayName="DialogFooter";var da=_s.forwardRef(({className:e,...a},s)=>(0,Ct.jsx)(ft.Title,{ref:s,className:G("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));da.displayName=ft.Title.displayName;var ua=_s.forwardRef(({className:e,...a},s)=>(0,Ct.jsx)(ft.Description,{ref:s,className:G("af-text-sm af-text-muted-foreground",e),...a}));ua.displayName=ft.Description.displayName;var Mt=ne(require("react"),1);function Ps(){let{api:e}=te(),[a,s]=Mt.useState([]),[t,n]=Mt.useState(!0),[i,o]=Mt.useState(null),p=Mt.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(v){o(v instanceof Error?v:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);Mt.useEffect(()=>{p()},[p]);let g=Mt.useCallback(async v=>{let d=await e.createEventDestination(v);return s(u=>[d,...u]),d},[e]),x=Mt.useCallback(async(v,d)=>{let u=await e.updateEventDestination(v,d);return s(h=>h.map(N=>N.id===v?u:N)),u},[e]),r=Mt.useCallback(async v=>{await e.deleteEventDestination(v),s(d=>d.filter(u=>u.id!==v))},[e]),y=Mt.useCallback(async v=>{let d=await e.rotateEventDestinationSecret(v);return s(u=>u.map(h=>h.id===v?d:h)),d},[e]),w=Mt.useCallback(v=>e.getEventDestinationSecret(v),[e]);return{destinations:a,isLoading:t,error:i,refetch:p,createDestination:g,updateDestination:x,deleteDestination:r,rotateSecret:y,getSecret:w}}var Ia=ne(require("react"),1),Ts=require("lucide-react");var mt=require("react/jsx-runtime");function Cs({destinationId:e,limit:a=25,className:s}){let{api:t}=te(),[n,i]=Ia.useState([]),[o,p]=Ia.useState(!0),[g,x]=Ia.useState(null),[r,y]=Ia.useState(null),w=Ia.useCallback(async()=>{try{p(!0),x(null),i(await t.getEventDeliveries(e,a))}catch(d){x(d instanceof Error?d.message:"Failed to load deliveries")}finally{p(!1)}},[t,e,a]);Ia.useEffect(()=>{w()},[w]);let v=async d=>{try{y(d.id),x(null);let u=await t.retryEventDelivery(e,d.id);i(h=>h.map(N=>N.id===d.id?u:N))}catch(u){x(u instanceof Error?u.message:"Retry failed")}finally{y(null)}};return o?(0,mt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,mt.jsx)(Ts.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):g?(0,mt.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:g}):n.length===0?(0,mt.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):(0,mt.jsx)("div",{className:s,children:(0,mt.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(d=>{let u=d.delivered_at!==null;return(0,mt.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,mt.jsxs)("div",{className:"af-min-w-0",children:[(0,mt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[u?(0,mt.jsx)(Z,{variant:"secondary",children:d.last_status??200}):(0,mt.jsx)(Z,{variant:"destructive",children:d.last_status??"failed"}),(0,mt.jsx)("span",{className:"af-text-sm af-truncate",children:d.type})]}),(0,mt.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[d.event_id," \xB7 ",d.created_at,d.attempts>0&&` \xB7 ${d.attempts} failed ${d.attempts===1?"attempt":"attempts"}`]}),!u&&d.last_error&&(0,mt.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:d.last_error})]}),(0,mt.jsx)(P,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===d.id,onClick:()=>v(d),children:r===d.id?(0,mt.jsx)(Ts.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,mt.jsx)(Ts.RotateCw,{className:"af-h-4 af-w-4"})})]},d.id)})})})}var re=require("react/jsx-runtime");function ks({formId:e,topics:a,description:s,className:t}){let{destinations:n,isLoading:i,error:o,createDestination:p,updateDestination:g,deleteDestination:x,rotateSecret:r,getSecret:y}=Ps(),[w,v]=Yt.useState(""),[d,u]=Yt.useState(!1),[h,N]=Yt.useState(null),[T,A]=Yt.useState(null),[H,c]=Yt.useState(null),[S,E]=Yt.useState(!1),[J,B]=Yt.useState(null),[R,z]=Yt.useState(null),[b,Q]=Yt.useState(null),le=Yt.useMemo(()=>n.filter(K=>K.form_id===e),[n,e]),ce=async()=>{let K=w.trim();if(K){if(!K.startsWith("https://")){N("Webhook URLs must start with https://");return}try{u(!0),N(null),await p({url:K,form_id:e,...a&&a.length>0?{topics:a}:{}}),v("")}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to add webhook")}finally{u(!1)}}},ee=async K=>{try{z(K.id),N(null),await r(K.id),E(!1),c(await y(K.id))}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to rotate secret")}finally{z(null)}},_e=async K=>{try{z(K.id),N(null),await g(K.id,{status:"active"})}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to re-enable")}finally{z(null)}},Y=async()=>{if(J)try{z(J.id),await x(J.id),B(null)}catch(K){N(K instanceof Error?K.message:"Failed to delete")}finally{z(null)}},oe=async K=>{if(T===K.id){A(null),c(null);return}try{z(K.id),N(null),E(!1),A(K.id),c(await y(K.id))}catch(Pe){A(null),N(Pe instanceof Error?Pe.message:"Failed to read secret")}finally{z(null)}},fe=async()=>{if(H)try{await navigator.clipboard.writeText(H),E(!0)}catch{}};return(0,re.jsxs)("div",{className:t,children:[(0,re.jsxs)("div",{className:"af-space-y-1",children:[(0,re.jsx)(Re,{children:"Webhooks"}),(0,re.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:s??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),(0,re.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,re.jsx)(Se,{value:w,placeholder:"https://hooks.zapier.com/...",onChange:K=>v(K.target.value),onKeyDown:K=>{K.key==="Enter"&&(K.preventDefault(),ce())},disabled:d}),(0,re.jsxs)(P,{onClick:ce,disabled:d||!w.trim(),children:[d?(0,re.jsx)(Nt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,re.jsx)(Nt.Plus,{className:"af-h-4 af-w-4"}),(0,re.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(h||o)&&(0,re.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:h||o?.message}),(0,re.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[i&&(0,re.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,re.jsx)(Nt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&le.length===0&&(0,re.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),le.map(K=>(0,re.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,re.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,re.jsxs)("div",{className:"af-min-w-0",children:[(0,re.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,re.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:K.url}),K.status==="disabled"?(0,re.jsx)(Z,{variant:"destructive",children:"Disabled"}):(0,re.jsx)(Z,{variant:"secondary",children:"Active"})]}),(0,re.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:K.topics.includes("*")?"All events":K.topics.join(", ")})]}),(0,re.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,re.jsx)(P,{variant:"ghost",size:"sm",onClick:()=>Q(b===K.id?null:K.id),children:b===K.id?"Hide log":"Deliveries"}),(0,re.jsx)(P,{variant:"ghost",size:"sm",onClick:()=>oe(K),disabled:R===K.id,children:T===K.id?"Hide secret":"Show secret"}),(0,re.jsx)(P,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:R===K.id,onClick:()=>B(K),children:(0,re.jsx)(Nt.Trash2,{className:"af-h-4 af-w-4"})})]})]}),K.status==="disabled"&&(0,re.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[(0,re.jsx)(Nt.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,re.jsxs)("div",{className:"af-text-sm",children:[(0,re.jsxs)("p",{children:["We stopped sending after repeated failures."," ",K.disabled_reason]}),(0,re.jsx)(P,{variant:"outline",size:"sm",className:"af-mt-2",disabled:R===K.id,onClick:()=>_e(K),children:"Re-enable"})]})]}),T===K.id&&H&&(0,re.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,re.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Optional. Use this if you want your endpoint to check that a delivery really came from us. Rotating replaces it."}),(0,re.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,re.jsx)(Se,{readOnly:!0,value:H,className:"af-font-mono"}),(0,re.jsx)(P,{variant:"outline",title:"Copy signing secret",onClick:fe,children:S?(0,re.jsx)(Nt.Check,{className:"af-h-4 af-w-4"}):(0,re.jsx)(Nt.Copy,{className:"af-h-4 af-w-4"})}),(0,re.jsx)(P,{variant:"outline",title:"Rotate signing secret",disabled:R===K.id,onClick:()=>ee(K),children:R===K.id?(0,re.jsx)(Nt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,re.jsx)(Nt.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),b===K.id&&(0,re.jsx)(Cs,{destinationId:K.id})]},K.id))]}),(0,re.jsx)(wa,{open:!!J,onOpenChange:K=>{!K&&!R&&B(null)},children:(0,re.jsxs)(oa,{children:[(0,re.jsxs)(la,{children:[(0,re.jsx)(da,{children:"Delete this webhook?"}),(0,re.jsxs)(ua,{children:["New submissions will stop being sent to ",J?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),(0,re.jsxs)(ca,{children:[(0,re.jsx)(P,{variant:"outline",onClick:()=>B(null),disabled:!!R,children:"Cancel"}),(0,re.jsx)(P,{variant:"destructive",onClick:Y,disabled:!!R,children:R?"Deleting...":"Delete"})]})]})})]})}var we=require("react/jsx-runtime");function Es({form:e,onSaved:a,className:s}){let{updateForm:t}=Wa(),[n,i]=Ut.useState(!1),[o,p]=Ut.useState(null),[g,x]=Ut.useState(null),[r,y]=Ut.useState(e.name),[w,v]=Ut.useState(e.redirect_url||""),[d,u]=Ut.useState(e.email_recipients),[h,N]=Ut.useState("");Ut.useEffect(()=>{y(e.name),v(e.redirect_url||""),u(e.email_recipients),x(null)},[e]);let T=Ut.useCallback(async E=>{try{i(!0),x(null);let J=await t(e.id,E);p(new Date),a?.(J)}catch(J){x(J instanceof Error?J.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);Ut.useEffect(()=>{if(o){let E=setTimeout(()=>p(null),2e3);return()=>clearTimeout(E)}},[o]);let A=async()=>{let E=h.trim().toLowerCase();if(!E)return;if(!E.includes("@")){x("Please enter a valid email address");return}if(d.includes(E)){x("This email is already added");return}let J=[...d,E];u(J),N(""),x(null),await T({email_recipients:J})},H=async E=>{let J=d.filter(B=>B!==E);u(J),await T({email_recipients:J})},c=async()=>{r!==e.name&&await T({name:r})},S=async()=>{let E=w||null;E!==e.redirect_url&&await T({redirect_url:E})};return(0,we.jsxs)("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&(0,we.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,we.jsxs)("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:[(0,we.jsx)(Ua.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,we.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,we.jsxs)("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:[(0,we.jsx)(Ua.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,we.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{htmlFor:"form-name",children:"Form Name"}),(0,we.jsx)(Se,{id:"form-name",value:r,onChange:E=>y(E.target.value),onBlur:c,placeholder:"Contact Form"}),(0,we.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{children:"Email Recipients"}),(0,we.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,we.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[d.map(E=>(0,we.jsxs)(Z,{variant:"secondary",className:"af-gap-1",children:[E,(0,we.jsx)("button",{type:"button",onClick:()=>H(E),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,we.jsx)(Ua.X,{className:"af-h-3 af-w-3"})})]},E)),d.length===0&&(0,we.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,we.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,we.jsx)(Se,{type:"email",value:h,onChange:E=>N(E.target.value),placeholder:"Add email address",onKeyDown:E=>{E.key==="Enter"&&(E.preventDefault(),A())},disabled:n}),(0,we.jsx)(P,{type:"button",variant:"outline",onClick:A,disabled:!h.trim()||n,children:(0,we.jsx)(Ua.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,we.jsx)(Se,{id:"redirect-url",value:w,onChange:E=>v(E.target.value),onBlur:S,placeholder:"/thank-you"}),(0,we.jsx)("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."})]}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{children:"Form Endpoint"}),(0,we.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,we.jsx)("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})}),(0,we.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,we.jsxs)("div",{className:"af-space-y-2",children:[(0,we.jsx)(Re,{children:"Captcha Protection"}),(0,we.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,we.jsx)(Z,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,we.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,we.jsx)(ks,{formId:e.id}),g&&(0,we.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g})]})}var Ve=require("react/jsx-runtime");function An({className:e,submissionId:a}){let{api:s}=te(),[t,n]=Va.useState("list"),[i,o]=Va.useState(null),[p,g]=Va.useState("submissions"),[x,r]=Va.useState(a),[y,w]=Va.useState(!!a);Va.useEffect(()=>{if(!a)return;async function h(){try{let N=await s.getSubmission(a),T=await s.getForm(N.form_id);o(T),n("detail"),g("submissions"),r(a)}catch(N){console.error("Failed to load submission for deep link:",N)}finally{w(!1)}}h()},[a,s]);let v=(h,N)=>{o(h),n("detail"),g(N),r(void 0)},d=()=>{n("list"),o(null),r(void 0)},u=h=>{o(h)};return y?(0,Ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,Ve.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Ve.jsxs)("div",{className:e,children:[t==="list"&&(0,Ve.jsxs)("div",{children:[(0,Ve.jsxs)("div",{className:"af-mb-6",children:[(0,Ve.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,Ve.jsx)(hs,{onSelectForm:v})]}),t==="detail"&&i&&(0,Ve.jsxs)("div",{children:[(0,Ve.jsxs)("div",{className:"af-mb-6",children:[(0,Ve.jsxs)(P,{variant:"ghost",size:"sm",onClick:d,className:"af-mb-2 af--ml-2",children:[(0,Ve.jsx)(cs.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),(0,Ve.jsx)("h2",{className:"af-text-lg af-font-semibold",children:i.name}),(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:(0,Ve.jsx)("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),(0,Ve.jsxs)(sn,{value:p,onValueChange:h=>g(h),children:[(0,Ve.jsxs)(bs,{className:"af-mb-4",children:[(0,Ve.jsxs)(va,{value:"submissions",className:"af-gap-2",children:[(0,Ve.jsx)(cs.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,Ve.jsxs)(va,{value:"settings",className:"af-gap-2",children:[(0,Ve.jsx)(cs.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,Ve.jsx)(ba,{value:"submissions",children:(0,Ve.jsx)(Rs,{formId:i.id,defaultSubmissionId:x})}),(0,Ve.jsx)(ba,{value:"settings",children:(0,Ve.jsx)(Es,{form:i,onSaved:u})})]})]})]})}var ms=ne(require("react"),1),aa=require("lucide-react");var on=ne(require("react"),1),Aa=require("lucide-react");var co=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function fa(e){return co.has(e.toLowerCase())}function W(e,a,s){let t=fa(a)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:a.toUpperCase()}).format(t)}catch{return`${t} ${a.toUpperCase()}`}}function Zt(e){let a=e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0;return e.amount_total+(e.shipping_total??0)+a}function Qt(e,a){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let t=fa(a)?s:s*100;return Math.round(t)}function vt(e,a){return fa(a)?e:e/100}var ve=require("react/jsx-runtime");function uo(e){if(e.allow_custom_amount){let a=e.min_amount!==null?W(e.min_amount,e.currency):"?",s=e.max_amount!==null?W(e.max_amount,e.currency):"?";return`Buyer chooses (${a} - ${s})`}return e.unit_amount===null?"Varies by variant":W(e.unit_amount,e.currency)}function fo(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Is({productsState:e,onSelectProduct:a,onCreateProduct:s,className:t}){let{products:n,isLoading:i,error:o,deleteProduct:p}=e,[g,x]=on.useState(null),[r,y]=on.useState(!1),[w,v]=on.useState(null),d=async()=>{if(g)try{y(!0),v(null),await p(g.id),x(null)}catch(u){v(u instanceof Error?u.message:"Failed to delete product")}finally{y(!1)}};return i?(0,ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ve.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ve.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?(0,ve.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,ve.jsx)(Aa.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ve.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,ve.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,ve.jsxs)(P,{variant:"outline",onClick:()=>s?.(),children:[(0,ve.jsx)(Aa.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,ve.jsxs)("div",{className:t,children:[(0,ve.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,ve.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[(0,ve.jsx)(Aa.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,ve.jsxs)(Le,{children:[(0,ve.jsx)(Oe,{children:(0,ve.jsxs)(be,{children:[(0,ve.jsx)(F,{children:"Name"}),(0,ve.jsx)(F,{children:"Price"}),(0,ve.jsx)(F,{children:"Fulfillment"}),(0,ve.jsx)(F,{children:"Status"}),(0,ve.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,ve.jsx)(Be,{children:n.map(u=>(0,ve.jsxs)(be,{children:[(0,ve.jsx)(M,{className:"af-font-medium",children:u.name}),(0,ve.jsx)(M,{children:uo(u)}),(0,ve.jsx)(M,{className:"af-text-muted-foreground",children:fo(u)}),(0,ve.jsx)(M,{children:(0,ve.jsx)(Z,{variant:u.active?"success":"secondary",children:u.active?"Active":"Inactive"})}),(0,ve.jsx)(M,{className:"af-text-right",children:(0,ve.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,ve.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>a?.(u),children:[(0,ve.jsx)(Aa.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,ve.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>{v(null),x(u)},children:[(0,ve.jsx)(Aa.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},u.id))})]}),(0,ve.jsx)(wa,{open:!!g,onOpenChange:u=>{!u&&!r&&x(null)},children:(0,ve.jsxs)(oa,{children:[(0,ve.jsxs)(la,{children:[(0,ve.jsx)(da,{children:"Delete product?"}),(0,ve.jsxs)(ua,{children:['"',g?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),w&&(0,ve.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:w}),(0,ve.jsxs)(ca,{children:[(0,ve.jsx)(P,{variant:"outline",onClick:()=>x(null),disabled:r,children:"Cancel"}),(0,ve.jsx)(P,{variant:"destructive",onClick:d,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}var We=ne(require("react"),1),Vt=require("lucide-react");var ct=ne(require("react"),1),Xt=require("lucide-react");var C=require("react/jsx-runtime");function Dn(e){return e.option_values.length>0?e.option_values.map(a=>a.value).join(" / "):e.title||"Default"}function As({productId:e,currency:a,className:s}){let{api:t}=te(),n=fa(a)?"1":"0.01",[i,o]=ct.useState(null),[p,g]=ct.useState(!0),[x,r]=ct.useState(null),[y,w]=ct.useState(null),[v,d]=ct.useState(!1),u=ct.useRef(!0);ct.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);let h=ct.useCallback(async()=>{try{let k=await t.getProduct(e);if(!u.current)return;o(k)}catch(k){if(!u.current)return;r(k instanceof Error?k.message:"Failed to load product")}finally{u.current&&g(!1)}},[t,e]);ct.useEffect(()=>{h()},[h]);let N=async k=>{w(null),d(!0);try{await k(),await h()}catch(O){u.current&&w(O instanceof Error?O.message:"Something went wrong")}finally{u.current&&d(!1)}},[T,A]=ct.useState(""),[H,c]=ct.useState(""),[S,E]=ct.useState({}),J=()=>N(async()=>{let k=T.trim(),O=H.split(",").map(ge=>ge.trim()).filter(Boolean);if(!k)throw new Error("Option name is required");if(O.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:k,values:O}),u.current&&(A(""),c(""))}),B=k=>N(async()=>{let O=(S[k.id]??"").trim();if(!O)throw new Error("Enter a value");await t.updateOption(k.id,{add_values:[O]}),u.current&&E(ge=>({...ge,[k.id]:""}))}),R=(k,O)=>N(()=>t.updateOption(k.id,{remove_values:[O]})),z=k=>N(()=>t.deleteOption(k.id)),[b,Q]=ct.useState(null),[le,ce]=ct.useState(null),[ee,_e]=ct.useState(!1),[Y,oe]=ct.useState(null),fe=i?.options??[],K=i?.variants??[],Pe=()=>{ce(null),Q({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(fe.map(k=>[k.id,k.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Me=k=>{ce(null);let O=k.inventory?.on_hand??0,ge=O<0?"":String(O);Q({variant:k,title:k.title??"",sku:k.sku??"",unitAmount:k.unit_amount!=null?String(vt(k.unit_amount,a)):"",compareAt:k.compare_at_amount!=null?String(vt(k.compare_at_amount,a)):"",active:k.active,optionValues:{},tracked:k.inventory?.tracked??!1,onHand:ge,initialOnHand:ge,allowBackorder:k.inventory?.allow_backorder??!1})},xt=async()=>{if(!b)return;ce(null);let k=b.variant?.allow_custom_amount??!1,O=null,ge=null;if(!k){if(O=Qt(b.unitAmount,a),O===null||O<=0){ce("Enter a valid price");return}if(b.compareAt.trim()&&(ge=Qt(b.compareAt,a),ge===null||ge<=O)){ce("Compare-at price must be greater than the price");return}}let Je=b.onHand.trim()!==b.initialOnHand.trim(),ze=parseInt(b.onHand,10);if(b.tracked&&Je&&(!Number.isFinite(ze)||ze<0)){ce("On-hand quantity must be zero or more");return}try{if(_e(!0),b.variant)await t.updateVariant(b.variant.id,{title:b.title.trim()||null,sku:b.sku.trim()||null,...k?{}:{unit_amount:O,compare_at_amount:ge},active:b.active}),await t.setVariantInventory(b.variant.id,{tracked:b.tracked,on_hand:b.tracked&&Je?ze:void 0,allow_backorder:b.allowBackorder});else{let st={};for(let Ye of fe){let nt=b.optionValues[Ye.id];if(!nt){ce(`Choose a ${Ye.title}`),_e(!1);return}st[Ye.title]=nt}await t.createVariant(e,{title:b.title.trim()||null,sku:b.sku.trim()||null,unit_amount:O,compare_at_amount:ge,active:b.active,option_values:fe.length>0?st:void 0,inventory:b.tracked?{tracked:!0,on_hand:ze,allow_backorder:b.allowBackorder}:{tracked:!1,allow_backorder:b.allowBackorder}})}await h(),u.current&&Q(null)}catch(st){if(u.current&&ce(st instanceof Error?st.message:"Failed to save variant"),b.variant)try{let Ye=await t.getProduct(e);u.current&&o(Ye)}catch{}}finally{u.current&&_e(!1)}},q=()=>N(async()=>{Y&&(await t.deleteVariant(Y.id),u.current&&oe(null))}),pe=b?.variant?.allow_custom_amount??!1,xe=b?.variant!=null&&b.variant.option_values.length===0&&fe.length>0&&!b.variant.active,de=b?.variant?.inventory!=null&&b.variant.inventory.on_hand<0?-b.variant.inventory.on_hand:null;function Ue(k){let O=k.inventory;if(!O||!O.tracked)return(0,C.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let ge=O.available??O.on_hand;return ge<0?(0,C.jsxs)("span",{children:[-ge," backordered"]}):(0,C.jsxs)("span",{children:[ge," in stock",O.allow_backorder&&(0,C.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return p?(0,C.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:(0,C.jsx)(Xt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):x?(0,C.jsx)("div",{className:s,children:(0,C.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:x})}):(0,C.jsxs)("div",{className:`af-space-y-6 ${s||""}`,children:[(0,C.jsxs)("div",{className:"af-space-y-3",children:[(0,C.jsxs)("div",{children:[(0,C.jsx)(Re,{children:"Options"}),(0,C.jsx)("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."})]}),fe.length>0&&(0,C.jsx)("div",{className:"af-space-y-3",children:fe.map(k=>(0,C.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,C.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,C.jsx)("span",{className:"af-text-sm af-font-medium",children:k.title}),(0,C.jsx)(P,{variant:"ghost",size:"sm",onClick:()=>z(k),disabled:v,children:(0,C.jsx)(Xt.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,C.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:k.values.map(O=>(0,C.jsxs)(Z,{variant:"secondary",className:"af-gap-1",children:[O.value,(0,C.jsx)("button",{type:"button",onClick:()=>R(k,O.value),className:"af-ml-1 hover:af-text-destructive",disabled:v,title:"Remove value",children:(0,C.jsx)(Xt.X,{className:"af-h-3 af-w-3"})})]},O.id))}),(0,C.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,C.jsx)(Se,{value:S[k.id]??"",onChange:O=>E(ge=>({...ge,[k.id]:O.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),B(k))},disabled:v}),(0,C.jsx)(P,{type:"button",variant:"outline",size:"sm",onClick:()=>B(k),disabled:v||!(S[k.id]??"").trim(),children:(0,C.jsx)(Xt.Plus,{className:"af-h-4 af-w-4"})})]})]},k.id))}),(0,C.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsx)(Re,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,C.jsx)(Se,{id:"new-option-title",value:T,onChange:k=>A(k.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:v})]}),(0,C.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,C.jsx)(Re,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,C.jsx)(Se,{id:"new-option-values",value:H,onChange:k=>c(k.target.value),placeholder:"S, M, L",disabled:v})]}),(0,C.jsxs)(P,{type:"button",variant:"outline",onClick:J,disabled:v||!T.trim()||!H.trim(),children:[(0,C.jsx)(Xt.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,C.jsxs)("div",{className:"af-space-y-3",children:[(0,C.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,C.jsx)(Re,{children:"Variants"}),(0,C.jsxs)(P,{type:"button",variant:"outline",size:"sm",onClick:Pe,disabled:v||fe.length===0,children:[(0,C.jsx)(Xt.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),fe.length===0&&(0,C.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),K.length===0?(0,C.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,C.jsxs)(Le,{children:[(0,C.jsx)(Oe,{children:(0,C.jsxs)(be,{children:[(0,C.jsx)(F,{children:"Variant"}),(0,C.jsx)(F,{children:"SKU"}),(0,C.jsx)(F,{children:"Price"}),(0,C.jsx)(F,{children:"Stock"}),(0,C.jsx)(F,{children:"Status"}),(0,C.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,C.jsx)(Be,{children:K.map(k=>(0,C.jsxs)(be,{children:[(0,C.jsx)(M,{className:"af-font-medium",children:Dn(k)}),(0,C.jsx)(M,{className:"af-text-muted-foreground",children:k.sku||"-"}),(0,C.jsx)(M,{children:k.unit_amount!=null?(0,C.jsxs)("span",{children:[k.compare_at_amount!=null&&(0,C.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:W(k.compare_at_amount,k.currency)}),W(k.unit_amount,k.currency)]}):k.allow_custom_amount?(0,C.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,C.jsx)(M,{children:Ue(k)}),(0,C.jsx)(M,{children:(0,C.jsx)(Z,{variant:k.active?"success":"secondary",children:k.active?"Active":"Inactive"})}),(0,C.jsx)(M,{className:"af-text-right",children:(0,C.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,C.jsx)(P,{variant:"ghost",size:"sm",onClick:()=>Me(k),disabled:v,children:"Edit"}),(0,C.jsx)(P,{variant:"ghost",size:"icon",onClick:()=>oe(k),disabled:v,title:"Delete variant",children:(0,C.jsx)(Xt.Trash2,{className:"af-h-4 af-w-4"})})]})})]},k.id))})]})]}),y&&(0,C.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:y}),(0,C.jsx)(wa,{open:b!==null,onOpenChange:k=>{!k&&!ee&&Q(null)},children:(0,C.jsxs)(oa,{children:[(0,C.jsxs)(la,{children:[(0,C.jsx)(da,{children:b?.variant?"Edit variant":"Add variant"}),(0,C.jsx)(ua,{children:"Price, markdown, and stock live on the variant."})]}),b&&(0,C.jsxs)("div",{className:"af-space-y-3",children:[b.variant?b.variant.option_values.length>0&&(0,C.jsxs)("div",{className:"af-text-sm",children:[(0,C.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Dn(b.variant)]}):fe.map(k=>(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:k.title}),(0,C.jsxs)(Wt,{value:b.optionValues[k.id]??"",onValueChange:O=>Q(ge=>ge&&{...ge,optionValues:{...ge.optionValues,[k.id]:O}}),children:[(0,C.jsx)(Bt,{children:(0,C.jsx)(Kt,{placeholder:`Choose ${k.title}`})}),(0,C.jsx)(Ft,{children:k.values.map(O=>(0,C.jsx)(qe,{value:O.value,children:O.value},O.id))})]})]},k.id)),pe?(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,C.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,C.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsxs)(Re,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",a.toUpperCase(),")"]}),(0,C.jsx)(Se,{id:"variant-price",type:"number",min:"0",step:n,value:b.unitAmount,onChange:k=>Q(O=>O&&{...O,unitAmount:k.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsx)(Re,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,C.jsx)(Se,{id:"variant-compare",type:"number",min:"0",step:n,value:b.compareAt,onChange:k=>Q(O=>O&&{...O,compareAt:k.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsx)(Re,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,C.jsx)(Se,{id:"variant-sku",value:b.sku,onChange:k=>Q(O=>O&&{...O,sku:k.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,C.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,C.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,C.jsx)("input",{type:"checkbox",checked:b.tracked,onChange:k=>Q(O=>O&&{...O,tracked:k.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),b.tracked&&(0,C.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,C.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsx)(Re,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,C.jsx)(Se,{id:"variant-onhand",type:"number",min:"0",step:"1",value:b.onHand,onChange:k=>Q(O=>O&&{...O,onHand:k.target.value}),placeholder:de!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,C.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,C.jsx)("input",{type:"checkbox",checked:b.allowBackorder,onChange:k=>Q(O=>O&&{...O,allowBackorder:k.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),de!=null&&(0,C.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",de," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,C.jsx)("input",{type:"checkbox",checked:b.active,onChange:k=>Q(O=>O&&{...O,active:k.target.checked}),className:"af-h-4 af-w-4",disabled:xe}),"Active (buyers can purchase this variant)"]}),xe&&(0,C.jsx)("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."})]}),le&&(0,C.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:le})]}),(0,C.jsxs)(ca,{children:[(0,C.jsx)(P,{variant:"outline",onClick:()=>Q(null),disabled:ee,children:"Cancel"}),(0,C.jsxs)(P,{onClick:xt,disabled:ee,children:[ee?(0,C.jsx)(Xt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,b?.variant?"Save":"Add variant"]})]})]})}),(0,C.jsx)(wa,{open:Y!==null,onOpenChange:k=>{!k&&!v&&oe(null)},children:(0,C.jsxs)(oa,{children:[(0,C.jsxs)(la,{children:[(0,C.jsx)(da,{children:"Delete variant?"}),(0,C.jsx)(ua,{children:Y&&`"${Dn(Y)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,C.jsxs)(ca,{children:[(0,C.jsx)(P,{variant:"outline",onClick:()=>oe(null),disabled:v,children:"Cancel"}),(0,C.jsx)(P,{variant:"destructive",onClick:q,disabled:v,children:"Delete"})]})]})})]})}var $=require("react/jsx-runtime");function mo(e){if(e===0)return"0 B";let a=1024,s=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(a));return`${parseFloat((e/Math.pow(a,t)).toFixed(1))} ${s[t]}`}function Ds({productsState:e,product:a,currency:s,onSaved:t,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:p,attachProductFileFromUrl:g}=e,x=!!a,r=a?.currency??s,y=fa(r)?"1":"0.01",w=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[v,d]=We.useState(!1),[u,h]=We.useState(null),N=We.useRef(!0);We.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]);let[T,A]=We.useState(a?.name??""),[H,c]=We.useState(a?.description??""),[S,E]=We.useState(a?.allow_custom_amount?"custom":"fixed"),[J,B]=We.useState(a?.unit_amount!=null?String(vt(a.unit_amount,r)):""),[R,z]=We.useState(a?.min_amount!=null?String(vt(a.min_amount,r)):""),[b,Q]=We.useState(a?.max_amount!=null?String(vt(a.max_amount,r)):""),[le,ce]=We.useState(String(a?.max_quantity??10)),ee=We.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(vt(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(vt(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(vt(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[_e,Y]=We.useState(a?.collect_shipping_address??!1),[oe,fe]=We.useState(a?.active??!0),[K,Pe]=We.useState(a?.images??[]),[Me,xt]=We.useState(""),[q,pe]=We.useState(a?.fulfillment??null),[xe,de]=We.useState(!1),[Ue,k]=We.useState(""),[O,ge]=We.useState(null),Je=We.useRef(null),ze=v||xe,st=()=>{let se=Me.trim();if(se){if(K.includes(se)){h("This image URL is already added");return}Pe(De=>[...De,se]),xt(""),h(null)}},Ye=se=>{Pe(De=>De.filter(Ge=>Ge!==se))},nt=async()=>{if(h(null),!T.trim()){h("Product name is required");return}let se=null,De=null,Ge=null,sa=!x||S!==ee.pricingMode||(S==="fixed"?J!==ee.unitAmount:R!==ee.minAmount||b!==ee.maxAmount),_t=!x||le!==ee.maxQuantity,ka=w||S==="fixed";if(!(w||!sa))if(S==="fixed"){if(se=Qt(J,r),se===null||se<=0){h("Enter a valid price");return}}else{if(De=Qt(R,r),Ge=Qt(b,r),De===null||Ge===null){h("Enter valid minimum and maximum amounts");return}if(Ge<De){h("Maximum amount must be at least the minimum amount");return}}let lt=parseInt(le,10);if(ka&&_t&&(!Number.isFinite(lt)||lt<1)){h("Max quantity must be at least 1");return}try{d(!0);let Xe;if(x&&a){let I={name:T.trim(),description:H.trim()||null,images:K,collect_shipping_address:_e,active:oe};!w&&sa&&(I.allow_custom_amount=S==="custom",S==="fixed"?I.unit_amount=se:(I.min_amount=De,I.max_amount=Ge)),ka&&_t&&(I.max_quantity=lt),Xe=await o(a.id,I),ee.pricingMode=Xe.allow_custom_amount?"custom":"fixed",ee.unitAmount=Xe.unit_amount!=null?String(vt(Xe.unit_amount,r)):"",ee.minAmount=Xe.min_amount!=null?String(vt(Xe.min_amount,r)):"",ee.maxAmount=Xe.max_amount!=null?String(vt(Xe.max_amount,r)):"",ee.maxQuantity=String(Xe.max_quantity)}else{let I={name:T.trim(),allow_custom_amount:S==="custom",collect_shipping_address:_e,active:oe};H.trim()&&(I.description=H.trim()),K.length>0&&(I.images=K),S==="fixed"?(I.unit_amount=se,I.max_quantity=lt):(I.min_amount=De,I.max_amount=Ge),Xe=await i(I)}if(!N.current)return;pe(Xe.fulfillment),t?.(Xe)}catch(Xe){if(!N.current)return;h(Xe instanceof Error?Xe.message:"Failed to save product")}finally{N.current&&d(!1)}},Gt=async se=>{let De=se.target.files?.[0];if(!(!De||!a))try{de(!0),ge(null);let Ge=await p(a.id,De);if(!N.current)return;pe(Ge.fulfillment),t?.(Ge)}catch(Ge){if(!N.current)return;ge(Ge instanceof Error?Ge.message:"Failed to upload file")}finally{N.current&&(de(!1),Je.current&&(Je.current.value=""))}},ga=async()=>{let se=Ue.trim();if(!(!se||!a))try{de(!0),ge(null);let De=await g(a.id,se);if(!N.current)return;pe(De.fulfillment),k(""),t?.(De)}catch(De){if(!N.current)return;ge(De instanceof Error?De.message:"Failed to fetch file")}finally{N.current&&de(!1)}};return(0,$.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{htmlFor:"product-name",children:"Name"}),(0,$.jsx)(Se,{id:"product-name",value:T,onChange:se=>A(se.target.value),placeholder:"My product"})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{htmlFor:"product-description",children:"Description"}),(0,$.jsx)("textarea",{id:"product-description",value:H,onChange:se=>c(se.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"})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{children:"Pricing"}),w?(0,$.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(Wt,{value:S,onValueChange:se=>E(se),children:[(0,$.jsx)(Bt,{className:"af-w-[260px]",children:(0,$.jsx)(Kt,{})}),(0,$.jsxs)(Ft,{children:[(0,$.jsx)(qe,{value:"fixed",children:"Fixed price"}),(0,$.jsx)(qe,{value:"custom",children:"Buyer chooses the amount"})]})]}),S==="fixed"?(0,$.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsxs)(Re,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),(0,$.jsx)(Se,{id:"product-price",type:"number",min:"0",step:y,value:J,onChange:se=>B(se.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsxs)(Re,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),(0,$.jsx)(Se,{id:"product-min-amount",type:"number",min:"0",step:y,value:R,onChange:se=>z(se.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsxs)(Re,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),(0,$.jsx)(Se,{id:"product-max-amount",type:"number",min:"0",step:y,value:b,onChange:se=>Q(se.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,$.jsx)("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."})]}),(0,$.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",r.toUpperCase(),"), which follows the country of your payment account."]})]}),(w||S==="fixed")&&(0,$.jsxs)("div",{className:"af-space-y-1",children:[(0,$.jsx)(Re,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,$.jsx)(Se,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:le,onChange:se=>ce(se.target.value),className:"af-w-[140px]"})]})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{children:"Images"}),(0,$.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,$.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[K.map(se=>(0,$.jsxs)(Z,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,$.jsx)("span",{className:"af-truncate",children:se}),(0,$.jsx)("button",{type:"button",onClick:()=>Ye(se),className:"af-ml-1 hover:af-text-destructive",disabled:v,children:(0,$.jsx)(Vt.X,{className:"af-h-3 af-w-3"})})]},se)),K.length===0&&(0,$.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,$.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,$.jsx)(Se,{type:"url",value:Me,onChange:se=>xt(se.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:se=>{se.key==="Enter"&&(se.preventDefault(),st())},disabled:v}),(0,$.jsx)(P,{type:"button",variant:"outline",onClick:st,disabled:!Me.trim()||v,children:(0,$.jsx)(Vt.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{children:"Digital File"}),(0,$.jsx)("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."}),x?(0,$.jsxs)("div",{className:"af-space-y-3",children:[q?.type==="download"&&(0,$.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,$.jsx)(Vt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,$.jsx)("span",{className:"af-text-sm",children:q.filename}),q.size!=null&&(0,$.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",mo(q.size),")"]})]}),q?.type==="redirect"&&q.url&&(0,$.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,$.jsx)(Vt.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,$.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",q.url]})]}),(0,$.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,$.jsx)("input",{ref:Je,type:"file",onChange:Gt,className:"af-hidden",disabled:ze}),(0,$.jsxs)(P,{type:"button",variant:"outline",size:"sm",onClick:()=>Je.current?.click(),disabled:ze,children:[xe?(0,$.jsx)(Vt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,$.jsx)(Vt.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),q?.type==="download"?"Replace file":"Upload file"]}),(0,$.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,$.jsx)(Se,{type:"url",value:Ue,onChange:se=>k(se.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:xe}),(0,$.jsx)(P,{type:"button",variant:"outline",size:"sm",onClick:ga,disabled:!Ue.trim()||ze,children:"Fetch from URL"})]}),O&&(0,$.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:O})]}):(0,$.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsx)(Re,{children:"Settings"}),(0,$.jsxs)("div",{className:"af-space-y-2",children:[(0,$.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,$.jsx)("input",{type:"checkbox",checked:_e,onChange:se=>Y(se.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,$.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,$.jsx)("input",{type:"checkbox",checked:oe,onChange:se=>fe(se.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),x&&a&&(0,$.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,$.jsx)(Re,{children:"Options & Variants"}),(0,$.jsx)(As,{productId:a.id,currency:r})]}),u&&(0,$.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u}),(0,$.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,$.jsxs)(P,{type:"button",onClick:nt,disabled:ze,children:[v?(0,$.jsx)(Vt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,x?"Save changes":"Create product"]})})]})}var yt=ne(require("react"),1),Ht=require("lucide-react");var et=ne(require("react"),1);var po=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Ls({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=te(),[t,n]=et.useState([]),[i,o]=et.useState(0),[p,g]=et.useState(!0),[x,r]=et.useState(null),[y,w]=et.useState(0),[v,d]=et.useState(e),[u,h]=et.useState(void 0),[N,T]=et.useState(""),[A,H]=et.useState(""),[c,S]=et.useState(""),[E,J]=et.useState(!1),[B,R]=et.useState(!1),[z,b]=et.useState(void 0),Q=z?z.join(","):"",le=et.useMemo(()=>{if(!Q)return;let Y=new Set(Q.split(","));return po.filter(oe=>!Y.has(oe))},[Q]),ce=et.useRef(0),ee=et.useCallback(async()=>{let Y=++ce.current;try{g(!0),r(null);let oe={limit:v,offset:y*v};u?oe.status=u:le?oe.excludeStatus=le:E||(oe.excludeStatus=["pending","expired"]),N.trim()&&(oe.customerEmail=N.trim()),A.trim()&&(oe.from=A.trim()),c.trim()&&(oe.to=c.trim()),B&&(oe.unfulfilledOnly=!0);let fe=await s.getOrders(oe);if(Y!==ce.current)return;n(fe.orders),o(fe.total)}catch(oe){if(Y!==ce.current)return;r(oe instanceof Error?oe:new Error("Failed to fetch orders"))}finally{Y===ce.current&&g(!1)}},[s,y,v,u,le,E,B,N,A,c,a]);et.useEffect(()=>{ee()},[ee]);let _e=Math.ceil(i/v);return{orders:t,total:i,isLoading:p,error:x,page:y,pageSize:v,hasNextPage:y<_e-1,hasPreviousPage:y>0,setPage:w,setPageSize:Y=>{d(Y),w(0)},status:u,setStatus:Y=>{h(Y),w(0)},statusIn:z,setStatusIn:Y=>{b(Y&&Y.length>0?Y:void 0),w(0)},customerEmail:N,setCustomerEmail:Y=>{T(Y),w(0)},from:A,setFrom:Y=>{H(Y),w(0)},to:c,setTo:Y=>{S(Y),w(0)},showAbandoned:E,setShowAbandoned:Y=>{J(Y),w(0)},unfulfilledOnly:B,setUnfulfilledOnly:Y=>{R(Y),w(0)},clearFilters:()=>{h(void 0),b(void 0),J(!1),R(!1),T(""),H(""),S(""),w(0)},refetch:ee}}var it=ne(require("react"),1),ke=require("lucide-react");var Fr=ne(require("react"),1),Na=ne(require("@radix-ui/react-popover"),1);var ln=require("react/jsx-runtime"),Mr=Na.Root,Ur=Na.Trigger;var Ln=Fr.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>(0,ln.jsx)(Na.Portal,{children:(0,ln.jsx)("div",{className:"aifeatures-admin",children:(0,ln.jsx)(Na.Content,{ref:n,align:a,sideOffset:s,className:G("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),...t})})}));Ln.displayName=Na.Content.displayName;var Os=require("react/jsx-runtime"),go={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function vo(e){return go[e]??e}function Vr(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 Ja({status:e,className:a}){return(0,Os.jsx)(Z,{variant:Vr(e),className:a,children:vo(e)})}function $a({status:e}){return(0,Os.jsx)(Ja,{status:e})}function ds({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,Os.jsx)(Z,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Os.jsx)(Z,{variant:"warning",className:a,children:"Needs shipping"}):null:null}function Da(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var f=require("react/jsx-runtime"),qr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ya="af-text-xs af-text-muted-foreground";function On(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jr(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 cn=24,yo=["paid","partially_refunded"],ho=["paid","partially_refunded","disputed"],xo=/^[A-Za-z0-9 _-]*$/,$r=100;function Mn(e,a,s,t,n){let i=yo.includes(t);return a==="sent"?{label:"Sent",variant:"success",detail:null}:a==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:a==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${cn} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${cn} tries used). Nothing is being retried while the order is ${t.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:a==="failed_final"?s<cn&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:s<cn&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${s} attempt${s===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:a==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${t==="refunded"?"because the order was refunded":t==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:a==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(a),variant:"secondary",detail:null}}function Hr({title:e,recipient:a,status:s,attempts:t,side:n,orderStatus:i,action:o,delivery:p}){if(p)return(0,f.jsxs)("div",{children:[(0,f.jsx)(ha,{deliveries:[p]}),o&&(0,f.jsx)("div",{className:"af-mt-2",children:o})]});let g=Mn(n,s,t,i,a);return(0,f.jsxs)("div",{children:[(0,f.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,f.jsxs)("div",{className:"af-min-w-0",children:[(0,f.jsx)("div",{className:"af-text-sm",children:e}),a&&(0,f.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:a})]}),(0,f.jsx)(Z,{variant:g.variant,className:"af-shrink-0",children:g.label})]}),g.detail&&(0,f.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:g.detail}),o&&(0,f.jsx)("div",{className:"af-mt-2",children:o})]})}function zr(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=bo(e.address)?e.address:null;if(s){for(let n of["line1","line2"]){let i=s[n];typeof i=="string"&&i&&a.push(i)}let t=["city","state","postal_code"].map(n=>s[n]).filter(n=>typeof n=="string"&&!!n).join(", ");t&&a.push(t),typeof s.country=="string"&&s.country&&a.push(s.country)}return a.length>0?a:Object.entries(e).map(([t,n])=>`${t}: ${jr(n)}`)}function wo(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Un({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=it.useState(!1);if(!wo())return null;let p=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},g=i?(0,f.jsx)(ke.Check,{className:"af-h-3 af-w-3"}):(0,f.jsx)(ke.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,f.jsx)(P,{variant:"ghost",size:"icon",className:G("af-h-6 af-w-6 af-shrink-0",t),onClick:p,title:a,"aria-label":a,children:g}):(0,f.jsxs)(P,{variant:"outline",size:"sm",className:t,onClick:p,"aria-label":a,children:[i?(0,f.jsx)(ke.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,f.jsx)(ke.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function Bn({label:e,value:a}){return(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:Ya,children:e}),(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,f.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:a}),(0,f.jsx)(Un,{value:a,label:`Copy ${e}`})]})]})}function No({src:e}){let[a,s]=it.useState(!1);return!e||a?(0,f.jsx)("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:(0,f.jsx)(ke.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,f.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>s(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Ha({title:e,action:a,children:s,className:t}){return(0,f.jsxs)("section",{className:G("af-rounded-lg af-border af-p-4",t),children:[(0,f.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,f.jsx)("h4",{className:qr,children:e}),a]}),(0,f.jsx)("div",{className:"af-mt-3",children:s})]})}function za({label:e,emphasis:a,divider:s,children:t}){return(0,f.jsxs)("div",{className:G("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[(0,f.jsx)("span",{className:a?"af-text-base af-font-semibold":Ya,children:e}),(0,f.jsx)("span",{className:G("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function Fn({onSelect:e,disabled:a,icon:s,children:t}){return(0,f.jsxs)(P,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:a,children:[(0,f.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),t]})}function So(e){let a=[];if(a.push({key:"placed",text:"Order placed",at:e.created_at}),e.paid_at&&a.push({key:"paid",text:`Payment received \u2014 ${W(Zt(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),t=s?rn(s):Mn("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);a.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${t.label.toLowerCase()}`,at:null,tone:t.variant==="destructive"?"destructive":t.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),t=s?rn(s):Mn("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);a.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${t.label.toLowerCase()}`,at:null,tone:t.variant==="destructive"?"destructive":t.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&a.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&&a.push({key:"refunded",text:`Refunded ${W(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&a.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),a}function Bs({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:p=!1,hasNextOrder:g=!1}){let{api:x}=te(),[r,y]=it.useState(e),[w,v]=it.useState(null),[d,u]=it.useState(null),[h,N]=it.useState(!1),[T,A]=it.useState(!1),[H,c]=it.useState(!1),[S,E]=it.useState(!1),[J,B]=it.useState(""),[R,z]=it.useState(!1),[b,Q]=it.useState(null),[le,ce]=it.useState(!1),[ee,_e]=it.useState(""),[Y,oe]=it.useState([]),[fe,K]=it.useState(!1),[Pe,Me]=it.useState(!1),[xt,q]=it.useState(null);it.useEffect(()=>{y(e)},[e]);let pe=D=>{let Ae=D.id===r.id&&D.email_deliveries===void 0?{...D,email_deliveries:r.email_deliveries}:D;y(Ae),t?.(Ae)},xe=Object.entries(r.metadata??{}),de=Zt(r)-r.amount_refunded,Ue=(r.status==="paid"||r.status==="partially_refunded")&&de>0,k=D=>(typeof D.unitAmount=="number"?D.unitAmount:0)*(typeof D.quantity=="number"&&D.quantity>0?D.quantity:1),O=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),ge=Y.reduce((D,Ae)=>D+k(r.line_items[Ae]??{}),0)+(fe?O:0),Je=r.tax_total??0,ze=r.automatic_tax&&r.tax_behavior==="exclusive"&&Je>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,Je-(r.tax_refunded??0)),Math.round(Je*ge/(r.amount_total+(r.shipping_total??0)))):0,st=ge+ze,Ye=Y.length>0||fe,nt=Ye?st:Qt(ee,r.currency),Gt=fa(r.currency)?"1":"0.01",ga=async()=>{try{N(!0),v(null),u(null),await x.resendOrderReceipt(r.id);let D=await x.getOrder(r.id);pe(D),u("Receipt email queued.")}catch(D){v(D instanceof Error?D.message:"Failed to resend receipt")}finally{N(!1)}},se=async()=>{try{A(!0),v(null),u(null);let D=await x.resetOrderDownloads(r.id);pe(D),c(!1),u("Download count reset.")}catch(D){v(D instanceof Error?D.message:"Failed to reset downloads")}finally{A(!1)}},De=r.line_items.some(D=>D.collectShippingAddress===!0),Ge=typeof r.merchant_fulfilled_at=="string",sa=ho.includes(r.status),_t=J.trim(),ka=xo.test(_t)&&_t.length<=$r,lt=async D=>{try{z(!0),Q(null),u(null);let Ae=await x.setOrderFulfillment(r.id,{fulfilled:D,...D&&_t?{trackingNumber:_t}:{}});pe(Ae),B(""),u(D?"Marked as shipped.":"Marked as not shipped.")}catch(Ae){Ae instanceof na&&Ae.status===409?Q(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Q(Ae instanceof Error?Ae.message:"Failed to update the order")}finally{z(!1)}},Xe=()=>{q(null),_e(String(vt(de,r.currency))),oe([]),K(!1),ce(!0)},I=D=>oe(Ae=>Ae.includes(D)?Ae.filter(Tt=>Tt!==D):[...Ae,D]),He=async(D,Ae)=>{if(s)try{Me(!0),q(null),await s(r,D,Ae);let Tt=await x.getOrder(r.id);pe(Tt),ce(!1),u("Refund issued.")}catch(Tt){q(Tt instanceof Error?Tt.message:"Refund failed")}finally{Me(!1)}},U=async()=>{if(Ye){if(st<=0){q("The lines you picked were charged nothing");return}if(st>de){q(`That selection exceeds the refundable remainder (${W(de,r.currency)})`);return}await He(st,{...Y.length>0?{line_items:[...Y].sort((Ae,Tt)=>Ae-Tt)}:{},...fe?{shipping:!0}:{}});return}let D=Qt(ee,r.currency);if(D===null||D<=0){q("Enter a valid refund amount");return}if(D>de){q(`Amount exceeds the refundable remainder (${W(de,r.currency)})`);return}await He(D,{amount:D})},Pt=()=>He(de,{full:!0}),or=r.fulfillment_type==="download",lr=n&&De,Fi=So(r),Mi=r.shipping_address?zr(r.shipping_address).join(`
|
|
4
|
+
`):"",cr=r.shipping_total!=null,dr=!!r.automatic_tax&&r.tax_behavior==="exclusive"&&(r.tax_total??0)>0,Ui=!(r.automatic_tax&&r.tax_behavior==="exclusive")&&(r.tax_total??0)>0,ur=cr||dr,vs=[];return vs.push((0,f.jsx)(Fn,{icon:h?(0,f.jsx)(ke.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,f.jsx)(ke.Mail,{className:"af-h-4 af-w-4"}),disabled:h||r.fulfillment_status!=="fulfilled",onSelect:()=>{E(!1),ga()},children:"Resend receipt"},"resend")),or&&vs.push((0,f.jsx)(Fn,{icon:(0,f.jsx)(ke.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:T,onSelect:()=>{E(!1),c(!0)},children:"Reset download count"},"reset")),Ue&&vs.push((0,f.jsxs)("div",{children:[(0,f.jsx)(Fn,{icon:(0,f.jsx)(ke.Undo2,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{E(!1),Xe()},children:"Refund\u2026"}),!s&&(0,f.jsx)("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),(0,f.jsxs)("div",{children:[(0,f.jsxs)("div",{className:"af-mb-6",children:[(0,f.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,f.jsx)(ke.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,f.jsxs)("div",{className:"af-min-w-0",children:[(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,f.jsx)("h3",{className:"af-text-xl af-font-semibold",children:Da(r)}),(0,f.jsx)(Ja,{status:r.status}),n&&(0,f.jsx)(ds,{order:r}),r.is_test&&(0,f.jsx)(Z,{variant:"outline",children:"Test"})]}),(0,f.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",On(r.created_at)]}),r.is_test&&(0,f.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&(0,f.jsxs)("div",{className:"af-flex af-items-center",children:[(0,f.jsx)(P,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!p,"aria-label":"Previous order",children:(0,f.jsx)(ke.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,f.jsx)(P,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!g,"aria-label":"Next order",children:(0,f.jsx)(ke.ChevronRight,{className:"af-h-4 af-w-4"})})]}),lr&&(Ge?(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,f.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${On(r.merchant_fulfilled_at)}`:""]}),sa&&(0,f.jsxs)(P,{variant:"ghost",size:"sm",onClick:()=>lt(!1),disabled:R,children:[R?(0,f.jsx)(ke.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,f.jsx)(ke.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):sa?(0,f.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,f.jsx)(Se,{value:J,onChange:D=>B(D.target.value),placeholder:"Tracking number (optional)",maxLength:$r,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:R}),(0,f.jsxs)(P,{variant:"default",className:"af-shrink-0",onClick:()=>lt(!0),disabled:R||!ka,children:[R?(0,f.jsx)(ke.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,f.jsx)(ke.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),vs.length>0&&(0,f.jsxs)(Mr,{open:S,onOpenChange:E,children:[(0,f.jsx)(Ur,{asChild:!0,children:(0,f.jsx)(P,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,f.jsx)(ke.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,f.jsx)(Ln,{children:(0,f.jsx)("div",{className:"af-space-y-0.5",children:vs})})]})]})]}),lr&&!Ge&&!ka&&(0,f.jsx)("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."}),b&&(0,f.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:b}),d&&(0,f.jsx)("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:d}),w&&(0,f.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:w})]}),(0,f.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,f.jsxs)("div",{className:"af-space-y-6",children:[r.line_items.length>0&&(0,f.jsx)(Ha,{title:"Items",children:(0,f.jsx)("ul",{className:"af-space-y-3",children:r.line_items.map((D,Ae)=>{let Tt=typeof D.name=="string"&&D.name?D.name:"Item",fr=typeof D.quantity=="number"&&D.quantity>0?D.quantity:1,mr=typeof D.unitAmount=="number";return(0,f.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,f.jsx)(No,{src:typeof D.imageUrl=="string"&&D.imageUrl?D.imageUrl:void 0}),(0,f.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,f.jsxs)("div",{className:"af-text-sm af-font-medium",children:[Tt,typeof D.variantTitle=="string"&&D.variantTitle&&(0,f.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",D.variantTitle]})]}),(0,f.jsxs)("div",{className:Ya,children:[fr," \xD7"," ",mr?W(D.unitAmount,r.currency):"\u2014"]}),D.refunded===!0&&(0,f.jsx)(Z,{variant:"secondary",className:"af-mt-1",children:D.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,f.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:mr?W(D.unitAmount*fr,r.currency):"\u2014"})]},Ae)})})}),xe.length>0&&(0,f.jsx)(Ha,{title:"Order details",children:(0,f.jsx)("dl",{className:"af-space-y-2",children:xe.map(([D,Ae])=>(0,f.jsxs)("div",{children:[(0,f.jsx)("dt",{className:G(Ya,"af-capitalize"),children:D.replace(/_/g," ")}),(0,f.jsx)("dd",{className:"af-text-sm af-break-words",children:jr(Ae)})]},D))})}),(0,f.jsx)(Ha,{title:"Totals",children:(0,f.jsxs)("div",{className:"af-w-full",children:[ur&&(0,f.jsx)(za,{label:"Subtotal",children:W(r.amount_total,r.currency)}),cr&&(0,f.jsx)(za,{label:"Shipping",children:r.shipping_total===0?"Free":W(r.shipping_total??0,r.currency)}),dr&&(0,f.jsx)(za,{label:"Tax",children:W(r.tax_total??0,r.currency)}),(0,f.jsx)(za,{label:"Total",emphasis:!0,divider:ur,children:W(Zt(r),r.currency)}),Ui&&(0,f.jsx)(za,{label:"incl. tax",children:W(r.tax_total??0,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&(0,f.jsxs)(za,{label:"Your price",children:[W(r.base_amount_total,r.base_currency),(0,f.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(za,{label:"Refunded",children:["\u2212",W(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&(0,f.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",W(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),(0,f.jsx)(za,{label:"Net",children:(0,f.jsx)("span",{className:"af-font-medium",children:W(Math.max(0,Zt(r)-r.amount_refunded),r.currency)})})]})]})}),(0,f.jsx)(Ha,{title:"Timeline",children:(0,f.jsx)("ol",{className:"af-space-y-3",children:Fi.map(D=>(0,f.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,f.jsx)("span",{"aria-hidden":"true",className:G("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",D.tone==="destructive"?"af-bg-destructive":D.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,f.jsxs)("div",{className:"af-min-w-0",children:[(0,f.jsx)("div",{className:"af-text-sm af-break-words",children:D.text}),D.at&&(0,f.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:On(D.at)})]})]},D.key))})})]}),(0,f.jsxs)("div",{className:"af-space-y-6",children:[(0,f.jsx)(Ha,{title:"Customer",children:(0,f.jsxs)("div",{className:"af-space-y-2",children:[(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:Ya,children:"Email"}),(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,f.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||(0,f.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&(0,f.jsx)(Un,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:Ya,children:"Name"}),(0,f.jsx)("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:Ya,children:"Customer record"}),(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,f.jsx)("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),(0,f.jsx)(Z,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&(0,f.jsx)(Ha,{title:"Ship to",action:(0,f.jsx)(Un,{value:Mi,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,f.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:zr(r.shipping_address).map((D,Ae)=>(0,f.jsx)("div",{children:D},Ae))})}),(0,f.jsxs)(Ha,{title:"Emails",children:[(0,f.jsx)(ha,{deliveries:r.email_deliveries?.filter(D=>!["purchase_receipt","merchant_sale"].includes(D.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,f.jsxs)("div",{className:"af-space-y-4",children:[(0,f.jsx)(Hr,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(D=>D.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:(0,f.jsxs)(P,{variant:"outline",size:"sm",onClick:ga,disabled:h||r.fulfillment_status!=="fulfilled",children:[h?(0,f.jsx)(ke.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,f.jsx)(ke.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,f.jsx)(Hr,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(D=>D.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),or&&(0,f.jsx)(Ha,{title:"Download",children:(0,f.jsxs)("div",{className:"af-space-y-2",children:[(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,f.jsx)(ke.Download,{className:"af-h-4 af-w-4"}),(0,f.jsxs)("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&(0,f.jsx)("a",{href:r.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,f.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,f.jsx)("summary",{className:G(qr,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,f.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,f.jsx)(Bn,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&(0,f.jsx)(Bn,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&(0,f.jsx)(Bn,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),(0,f.jsx)(wa,{open:H,onOpenChange:D=>{!D&&!T&&c(!1)},children:(0,f.jsxs)(oa,{children:[(0,f.jsxs)(la,{children:[(0,f.jsx)(da,{children:"Reset download count?"}),(0,f.jsx)(ua,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,f.jsxs)(ca,{children:[(0,f.jsx)(P,{variant:"outline",onClick:()=>c(!1),disabled:T,children:"Cancel"}),(0,f.jsx)(P,{onClick:se,disabled:T,children:T?"Resetting...":"Reset"})]})]})}),(0,f.jsx)(wa,{open:le,onOpenChange:D=>{!D&&!Pe&&ce(!1)},children:(0,f.jsxs)(oa,{children:[(0,f.jsxs)(la,{children:[(0,f.jsx)(da,{children:"Refund order"}),(0,f.jsxs)(ua,{children:["Refund up to ",W(de,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,f.jsxs)("div",{className:"af-space-y-4",children:[(r.line_items.length>0||O>0)&&(0,f.jsxs)("div",{className:"af-space-y-2",children:[(0,f.jsx)(Re,{children:"Items"}),(0,f.jsxs)("div",{className:"af-space-y-2",children:[r.line_items.map((D,Ae)=>{let Tt=D.refunded===!0;return(0,f.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,f.jsx)("input",{type:"checkbox",checked:Y.includes(Ae),onChange:()=>I(Ae),disabled:Pe||Tt,className:"af-h-4 af-w-4"}),(0,f.jsxs)("span",{className:Tt?"af-text-muted-foreground af-line-through":void 0,children:[typeof D.name=="string"&&D.name?D.name:"Item",typeof D.variantTitle=="string"&&D.variantTitle?` \u2014 ${D.variantTitle}`:"",typeof D.quantity=="number"&&D.quantity>1?` \xD7 ${D.quantity}`:""]}),(0,f.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Tt?"Refunded":W(k(D),r.currency)})]},Ae)}),O>0&&(0,f.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,f.jsx)("input",{type:"checkbox",checked:fe,onChange:D=>K(D.target.checked),disabled:Pe,className:"af-h-4 af-w-4"}),(0,f.jsx)("span",{children:"Shipping"}),(0,f.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:W(O,r.currency)})]})]})]}),(0,f.jsxs)("div",{className:"af-space-y-2",children:[(0,f.jsxs)(Re,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),(0,f.jsx)(Se,{id:"refund-amount",type:"number",min:"0",step:Gt,value:Ye?String(vt(st,r.currency)):ee,onChange:D=>_e(D.target.value),disabled:Pe||Ye}),Ye&&(0,f.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),xt&&(0,f.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:xt}),(0,f.jsxs)(ca,{children:[(0,f.jsx)(P,{variant:"outline",onClick:()=>ce(!1),disabled:Pe,children:"Cancel"}),(0,f.jsx)(P,{variant:"outline",onClick:Pt,disabled:Pe,children:"Refund everything"}),(0,f.jsx)(P,{variant:"destructive",onClick:U,disabled:Pe,children:Pe?"Refunding...":nt!==null&&nt>0?`Refund ${W(nt,r.currency)}`:"Refund"})]})]})})]})}var dn=ne(require("react"),1),un=require("lucide-react");var pt=require("react/jsx-runtime");function bt({title:e,onBackToWebsite:a,hideBackButton:s=!1,children:t,className:n}){let i=dn.useRef(null);return dn.useEffect(()=>{i.current?.focus()},[]),(0,pt.jsxs)("div",{className:G("af-bg-background",n),children:[(0,pt.jsxs)("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:[(0,pt.jsx)("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),a&&!s&&(0,pt.jsxs)(P,{type:"button",variant:"outline",size:"sm",onClick:a,children:[(0,pt.jsx)(un.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,pt.jsx)("div",{className:"af-p-4",children:t})]})}function X({className:e}){return(0,pt.jsx)("div",{"aria-hidden":"true",className:G("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function Ze({label:e,children:a,detail:s,valueClassName:t}){return(0,pt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,pt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,pt.jsx)("div",{className:G("af-mt-1 af-text-lg af-font-semibold",t),children:a}),s&&(0,pt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function $t({message:e,onRetry:a}){return(0,pt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,pt.jsx)("span",{children:e}),(0,pt.jsxs)(P,{type:"button",variant:"ghost",size:"sm",onClick:a,children:[(0,pt.jsx)(un.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Sa({icon:e,children:a}){return(0,pt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,pt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:a})]})}var _=require("react/jsx-runtime"),Ro={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Gr={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Wr(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Kr(e){let a=Array.isArray(e.line_items)?e.line_items:[],s=a[0];if(!s)return"\u2014";let t=typeof s.name=="string"&&s.name?s.name:"Item",n=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,i=n>1?`${t} \xD7${n}`:t;return a.length>1?`${i} +${a.length-1} more`:i}function fn(e){return e.customer?.name||e.customer_name||null}function Za({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o}){let{api:p}=te(),g=Ls({refreshKey:s}),{orders:x,total:r,isLoading:y,error:w,page:v,pageSize:d,hasNextPage:u,hasPreviousPage:h,setPage:N,setPageSize:T,customerEmail:A,setCustomerEmail:H,setStatusIn:c,from:S,setFrom:E,to:J,setTo:B,showAbandoned:R,setShowAbandoned:z,setUnfulfilledOnly:b,refetch:Q}=g,[le,ce]=yt.useState("list"),[ee,_e]=yt.useState(null),[Y,oe]=yt.useState(""),[fe,K]=yt.useState(""),[Pe,Me]=yt.useState(n?"needs_shipping":"all"),[xt,q]=yt.useState(!1),[pe,xe]=yt.useState(!!t),[de,Ue]=yt.useState(null);yt.useEffect(()=>{if(!t)return;let U=!1;return xe(!0),Ue(null),p.getOrder(t).then(Pt=>{U||(_e(Pt),ce("detail"))}).catch(()=>{U||Ue("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{U||xe(!1)}),()=>{U=!0}},[p,t]);let k=yt.useCallback(U=>{Me(U);let Pt=Gr[U];c(Pt.statusIn),b(Pt.unfulfilledOnly)},[c,b]);yt.useEffect(()=>{n&&b(!0)},[]);let O=yt.useRef(!n);yt.useEffect(()=>{O.current||y||(O.current=!0,x.length===0&&k("all"))},[y,x.length,k]);let ge=le==="detail"&&!!ee;yt.useEffect(()=>{o?.(ge)},[ge,o]);let Je=(S?1:0)+(J?1:0)+(R?1:0),ze=Je>0||!!A||!!fe,st=!!S&&!!J&&S>J,Ye=U=>{_e(U),ce("detail")},nt=()=>{ce("list"),_e(null),Q()},Gt=U=>{let Pt=U.trim();if(!Pt){K(""),A&&H("");return}if(Pt.startsWith("#")||/^\d+$/.test(Pt)){K(Pt),A&&H("");return}K(""),H(Pt)},ga=()=>{oe(""),K(""),H(""),E(""),B(""),z(!1),q(!1)},se=fe.replace(/^#/,"").toLowerCase(),De=se?x.filter(U=>String(U.order_number??"")===se||U.id.toLowerCase().startsWith(se)):x,Ge=ee?x.findIndex(U=>U.id===ee.id):-1,sa=Ge>0,_t=Ge>=0&&Ge<x.length-1;if(pe)return(0,_.jsx)("div",{className:a,children:(0,_.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,_.jsx)(Ht.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(le==="detail"&&ee)return(0,_.jsx)("div",{className:a,children:(0,_.jsx)(Bs,{order:ee,onBack:nt,onRefund:e,onOrderUpdated:U=>_e(U),allowFulfillment:n,onPrevOrder:sa?()=>_e(x[Ge-1]):void 0,onNextOrder:_t?()=>_e(x[Ge+1]):void 0,hasPrevOrder:sa,hasNextOrder:_t},ee.id)});let lt=(0,_.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[de&&(0,_.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:de}),(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)("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:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(U=>(0,_.jsx)("button",{type:"button","aria-pressed":Pe===U,onClick:()=>k(U),className:G("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Pe===U?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ro[U]},U))}),(0,_.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,_.jsx)(Ht.Search,{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"}),(0,_.jsx)(Se,{type:"text",value:Y,onChange:U=>oe(U.target.value),onBlur:()=>Gt(Y),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),Gt(Y))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,_.jsxs)(P,{type:"button",variant:Je>0?"secondary":"ghost",size:"sm",onClick:()=>q(U=>!U),"aria-expanded":xt,children:[(0,_.jsx)(Ht.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Je>0&&(0,_.jsx)(Z,{variant:"secondary",className:"af-ml-2",children:Je})]}),ze&&(0,_.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:ga,children:"Clear filters"})]}),(xt||!!S||!!J)&&(0,_.jsxs)("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:[(0,_.jsx)(Re,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,_.jsx)(Se,{id:"orders-from",type:"date",value:S,max:J||void 0,onChange:U=>E(U.target.value),className:"af-w-[170px]"}),(0,_.jsx)(Re,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,_.jsx)(Se,{id:"orders-to",type:"date",value:J,min:S||void 0,onChange:U=>B(U.target.value),className:"af-w-[170px]"}),!Gr[Pe].statusIn&&(0,_.jsx)(P,{type:"button",variant:R?"secondary":"ghost",size:"sm",onClick:()=>z(!R),"aria-pressed":R,children:R?"Hide abandoned":"Show abandoned"})]}),st&&(0,_.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(y)return(0,_.jsxs)("div",{className:a,children:[lt,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,_.jsx)(X,{className:"af-h-4 af-w-16"}),(0,_.jsx)(X,{className:"af-h-4 af-w-14"})]}),(0,_.jsx)(X,{className:"af-mt-2 af-h-3 af-w-40"}),(0,_.jsx)(X,{className:"af-mt-2 af-h-3 af-w-24"})]},U))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(Le,{children:[(0,_.jsx)(Oe,{children:(0,_.jsxs)(be,{children:[(0,_.jsx)(F,{children:"Order"}),(0,_.jsx)(F,{children:"Date"}),(0,_.jsx)(F,{children:"Customer"}),(0,_.jsx)(F,{children:"Items"}),(0,_.jsx)(F,{className:"af-text-right",children:"Total"}),(0,_.jsx)(F,{children:"Status"}),(0,_.jsx)(F,{className:"af-w-8"})]})}),(0,_.jsx)(Be,{"aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,_.jsxs)(be,{children:[(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-4 af-w-14"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-4 af-w-24"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-4 af-w-40"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-4 af-w-32"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,_.jsx)(M,{children:(0,_.jsx)(X,{className:"af-h-5 af-w-16"})}),(0,_.jsx)(M,{})]},U))})]})}),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(w)return(0,_.jsxs)("div",{className:a,children:[lt,(0,_.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,_.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,_.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>Q(),children:"Try again"})]})]});let Xe=Pe!=="all";if(De.length===0&&v===0)return(0,_.jsxs)("div",{className:a,children:[(ze||Xe)&<,(0,_.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,_.jsx)(Ht.Receipt,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,_.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:ze||Xe?"No orders match these filters.":i??(0,_.jsxs)(_.Fragment,{children:["No orders yet.",(0,_.jsx)("br",{}),"Orders will appear here when someone buys from your website."]})}),!ze&&!Xe&&(0,_.jsx)(P,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>z(!0),children:"Show abandoned checkouts"})]})]});let I=v*d+1,He=Math.min((v+1)*d,r);return(0,_.jsxs)("div",{className:a,children:[lt,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:De.map(U=>(0,_.jsxs)("button",{type:"button",onClick:()=>Ye(U),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[(0,_.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,_.jsx)("span",{className:"af-font-medium",children:Da(U)}),(0,_.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:W(Zt(U),U.currency)})]}),(0,_.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,_.jsxs)("div",{className:"af-truncate af-text-sm",children:[U.customer_email||(0,_.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),fn(U)&&(0,_.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",fn(U)]})]}),(0,_.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Kr(U)}),U.amount_refunded>0&&(0,_.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",W(U.amount_refunded,U.currency)," refunded"]})]}),(0,_.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,_.jsx)(Ja,{status:U.status}),(0,_.jsx)(xs,{deliveries:U.email_deliveries}),U.is_test&&(0,_.jsx)(Z,{variant:"outline",children:"Test"}),n&&(0,_.jsx)(ds,{order:U}),(0,_.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Wr(U.created_at)})]})]},U.id))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(Le,{children:[(0,_.jsx)(Oe,{children:(0,_.jsxs)(be,{children:[(0,_.jsx)(F,{children:"Order"}),(0,_.jsx)(F,{children:"Date"}),(0,_.jsx)(F,{children:"Customer"}),(0,_.jsx)(F,{children:"Items"}),(0,_.jsx)(F,{className:"af-text-right",children:"Total"}),(0,_.jsx)(F,{children:"Status"}),(0,_.jsx)(F,{className:"af-w-8"})]})}),(0,_.jsx)(Be,{children:De.map(U=>(0,_.jsxs)(be,{onClick:()=>Ye(U),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,_.jsxs)(M,{className:"af-whitespace-nowrap af-font-medium",children:[(0,_.jsx)("button",{type:"button",onClick:Pt=>{Pt.stopPropagation(),Ye(U)},"aria-label":`Open order ${Da(U)}`,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:Da(U)}),U.is_test&&(0,_.jsx)(Z,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,_.jsx)(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Wr(U.created_at)}),(0,_.jsxs)(M,{className:"af-max-w-[220px]",children:[(0,_.jsx)("div",{className:"af-truncate",children:U.customer_email||(0,_.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),fn(U)&&(0,_.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:fn(U)})]}),(0,_.jsx)(M,{className:"af-max-w-[220px]",children:(0,_.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:Kr(U)})}),(0,_.jsxs)(M,{className:"af-whitespace-nowrap af-text-right",children:[(0,_.jsx)("div",{className:"af-font-medium af-tabular-nums",children:W(Zt(U),U.currency)}),U.amount_refunded>0&&(0,_.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",W(U.amount_refunded,U.currency)," ","refunded"]})]}),(0,_.jsx)(M,{children:(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,_.jsx)(Ja,{status:U.status}),(0,_.jsx)(xs,{deliveries:U.email_deliveries}),n&&(0,_.jsx)(ds,{order:U})]})}),(0,_.jsx)(M,{className:"af-w-8 af-text-right",children:(0,_.jsx)(Ht.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},U.id))})]})}),(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,_.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,_.jsx)("span",{children:se?`${De.length} matching this page`:`Showing ${I}-${He} of ${r}`}),(0,_.jsxs)(Wt,{value:String(d),onValueChange:U=>T(Number(U)),children:[(0,_.jsx)(Bt,{className:"af-w-[70px] af-h-8",children:(0,_.jsx)(Kt,{})}),(0,_.jsxs)(Ft,{children:[(0,_.jsx)(qe,{value:"10",children:"10"}),(0,_.jsx)(qe,{value:"25",children:"25"}),(0,_.jsx)(qe,{value:"50",children:"50"}),(0,_.jsx)(qe,{value:"100",children:"100"})]})]}),(0,_.jsx)("span",{children:"per page"})]}),(0,_.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>N(v-1),disabled:!h,children:[(0,_.jsx)(Ht.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,_.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>N(v+1),disabled:!u,children:["Next",(0,_.jsx)(Ht.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var pn=ne(require("react"),1),Ra=require("lucide-react");var kt=ne(require("react"),1);function Fs({initialPageSize:e=25}={}){let{api:a}=te(),[s,t]=kt.useState([]),[n,i]=kt.useState(0),[o,p]=kt.useState(!0),[g,x]=kt.useState(null),[r,y]=kt.useState(0),[w,v]=kt.useState(e),[d,u]=kt.useState(""),h=kt.useRef(0),N=kt.useCallback(async()=>{let A=++h.current;try{p(!0),x(null);let H={limit:w,offset:r*w};d.trim()&&(H.email=d.trim());let c=await a.getCustomers(H);if(A!==h.current)return;t(c.customers),i(c.total)}catch(H){if(A!==h.current)return;x(H instanceof Error?H:new Error("Failed to fetch customers"))}finally{A===h.current&&p(!1)}},[a,r,w,d]);kt.useEffect(()=>{N()},[N]);let T=Math.ceil(n/w);return{customers:s,total:n,isLoading:o,error:g,page:r,pageSize:w,hasNextPage:r<T-1,hasPreviousPage:r>0,setPage:y,setPageSize:A=>{v(A),y(0)},email:d,setEmail:A=>{u(A),y(0)},refetch:N}}var Qa=ne(require("react"),1),mn=require("lucide-react");var ue=require("react/jsx-runtime");function Jr(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function _o(e){let a=[];e.name&&a.push(e.name),a.push(e.line1),e.line2&&a.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&a.push(s),e.country&&a.push(e.country),a}function Ms({customer:e,onBack:a,className:s}){let{api:t}=te(),[n,i]=Qa.useState(null),[o,p]=Qa.useState([]),[g,x]=Qa.useState(!0),[r,y]=Qa.useState(null);Qa.useEffect(()=>{let d=!1;return x(!0),y(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([u,h])=>{d||(i(u),p(h.orders))}).catch(u=>{d||y(u instanceof Error?u.message:"Failed to load customer")}).finally(()=>{d||x(!1)}),()=>{d=!0}},[t,e.id,e.email]);let w=n?.addresses??[],v=n?.order_count??o.length;return(0,ue.jsxs)("div",{className:s,children:[(0,ue.jsxs)("div",{className:"af-mb-6",children:[(0,ue.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,ue.jsx)(mn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,ue.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,ue.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Jr(e.created_at)]})]}),g?(0,ue.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ue.jsx)(mn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?(0,ue.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):(0,ue.jsxs)("div",{className:"af-space-y-6",children:[(0,ue.jsx)(ha,{deliveries:n?.email_deliveries}),(0,ue.jsxs)("div",{children:[(0,ue.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,ue.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,ue.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ue.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,ue.jsx)("span",{children:e.email})]}),e.name&&(0,ue.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ue.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,ue.jsx)("span",{children:e.name})]}),e.phone&&(0,ue.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ue.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,ue.jsx)("span",{children:e.phone})]}),(0,ue.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ue.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,ue.jsx)("span",{children:v})]})]})]}),w.length>0&&(0,ue.jsxs)("div",{children:[(0,ue.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,ue.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:w.map(d=>(0,ue.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[d.is_default&&(0,ue.jsx)(Z,{variant:"secondary",className:"af-mb-1",children:"Default"}),_o(d).map((u,h)=>(0,ue.jsx)("div",{children:u},h))]},d.id))})]}),(0,ue.jsxs)("div",{children:[(0,ue.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,ue.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,ue.jsxs)(Le,{children:[(0,ue.jsx)(Oe,{children:(0,ue.jsxs)(be,{children:[(0,ue.jsx)(F,{children:"Date"}),(0,ue.jsx)(F,{children:"Amount"}),(0,ue.jsx)(F,{children:"Status"})]})}),(0,ue.jsx)(Be,{children:o.map(d=>(0,ue.jsxs)(be,{children:[(0,ue.jsx)(M,{className:"af-text-muted-foreground",children:Jr(d.created_at)}),(0,ue.jsx)(M,{children:W(Zt(d),d.currency)}),(0,ue.jsx)(M,{children:(0,ue.jsx)($a,{status:d.status})})]},d.id))})]})]})]})]})}var ae=require("react/jsx-runtime");function Po(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Us({className:e}){let{customers:a,total:s,isLoading:t,error:n,page:i,pageSize:o,hasNextPage:p,hasPreviousPage:g,setPage:x,setPageSize:r,email:y,setEmail:w,refetch:v}=Fs(),[d,u]=pn.useState("list"),[h,N]=pn.useState(null),[T,A]=pn.useState(""),H=B=>{N(B),u("detail")},c=()=>{u("list"),N(null),v()};if(d==="detail"&&h)return(0,ae.jsx)("div",{className:e,children:(0,ae.jsx)(Ms,{customer:h,onBack:c})});let S=(0,ae.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,ae.jsx)(Se,{type:"email",value:T,onChange:B=>A(B.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),w(T.trim()))}}),(0,ae.jsxs)(P,{type:"button",variant:"outline",size:"sm",onClick:()=>w(T.trim()),children:[(0,ae.jsx)(Ra.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),y&&(0,ae.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{A(""),w("")},children:"Clear"})]});if(t)return(0,ae.jsxs)("div",{className:e,children:[S,(0,ae.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ae.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,ae.jsxs)("div",{className:e,children:[S,(0,ae.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ae.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return(0,ae.jsxs)("div",{className:e,children:[y&&S,(0,ae.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,ae.jsx)(Ra.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ae.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:y?"No customers match that email.":(0,ae.jsxs)(ae.Fragment,{children:["No customers yet.",(0,ae.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let E=i*o+1,J=Math.min((i+1)*o,s);return(0,ae.jsxs)("div",{className:e,children:[S,(0,ae.jsxs)(Le,{children:[(0,ae.jsx)(Oe,{children:(0,ae.jsxs)(be,{children:[(0,ae.jsx)(F,{children:"Email"}),(0,ae.jsx)(F,{children:"Name"}),(0,ae.jsx)(F,{children:"Customer since"}),(0,ae.jsx)(F,{className:"af-text-right",children:"Actions"})]})}),(0,ae.jsx)(Be,{children:a.map(B=>(0,ae.jsxs)(be,{children:[(0,ae.jsx)(M,{className:"af-font-medium",children:B.email}),(0,ae.jsx)(M,{children:B.name||(0,ae.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ae.jsx)(M,{className:"af-text-muted-foreground",children:Po(B.created_at)}),(0,ae.jsx)(M,{className:"af-text-right",children:(0,ae.jsx)(P,{variant:"ghost",size:"icon",onClick:()=>H(B),title:"View customer",children:(0,ae.jsx)(Ra.Eye,{className:"af-h-4 af-w-4"})})})]},B.id))})]}),(0,ae.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ae.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ae.jsxs)("span",{children:["Showing ",E,"-",J," of ",s]}),(0,ae.jsxs)(Wt,{value:String(o),onValueChange:B=>r(Number(B)),children:[(0,ae.jsx)(Bt,{className:"af-w-[70px] af-h-8",children:(0,ae.jsx)(Kt,{})}),(0,ae.jsxs)(Ft,{children:[(0,ae.jsx)(qe,{value:"10",children:"10"}),(0,ae.jsx)(qe,{value:"25",children:"25"}),(0,ae.jsx)(qe,{value:"50",children:"50"}),(0,ae.jsx)(qe,{value:"100",children:"100"})]})]}),(0,ae.jsx)("span",{children:"per page"})]}),(0,ae.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ae.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>x(i-1),disabled:!g,children:[(0,ae.jsx)(Ra.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ae.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>x(i+1),disabled:!p,children:["Next",(0,ae.jsx)(Ra.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ce=ne(require("react"),1),ut=require("lucide-react");var dt=ne(require("react"),1);function Xa({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=te(),[n,i]=dt.useState([]),[o,p]=dt.useState(0),[g,x]=dt.useState(null),[r,y]=dt.useState(!0),[w,v]=dt.useState(null),[d,u]=dt.useState(0),[h,N]=dt.useState(e),[T,A]=dt.useState(void 0),[H,c]=dt.useState(""),[S,E]=dt.useState(""),[J,B]=dt.useState(""),[R,z]=dt.useState(""),[b,Q]=dt.useState(""),le=T?T.join(","):"",ce=dt.useRef(0),ee=dt.useCallback(async()=>{let Y=++ce.current;y(!0),v(null);try{let oe={labels:le?le.split(","):void 0,customerEmail:H||void 0,q:S||void 0,from:J||void 0,to:R||void 0,retainerId:b||void 0,includeAggregates:s,limit:h,offset:d*h},fe=await t.getInvoices(oe);if(Y!==ce.current)return;if(d>0&&d*h>=fe.total){u(Math.max(0,Math.ceil(fe.total/h)-1));return}i(fe.invoices),p(fe.total),s&&x(fe.aggregates??null)}catch(oe){if(Y!==ce.current)return;v(oe instanceof Error?oe:new Error("Failed to fetch invoices"))}finally{Y===ce.current&&y(!1)}},[t,le,H,S,J,R,b,d,h,s]);dt.useEffect(()=>{ee()},[ee,a]);let _e=Y=>oe=>{u(0),Y(oe)};return{invoices:n,total:o,aggregates:g,isLoading:r,error:w,page:d,pageSize:h,hasNextPage:(d+1)*h<o,hasPreviousPage:d>0,setPage:u,setPageSize:_e(N),labels:T,setLabels:_e(A),customerEmail:H,setCustomerEmail:_e(c),q:S,setQ:_e(E),from:J,setFrom:_e(B),to:R,setTo:_e(z),retainerId:b,setRetainerId:_e(Q),clearFilters:()=>{u(0),A(void 0),c(""),E(""),B(""),z(""),Q("")},refetch:ee}}var l=require("react/jsx-runtime"),To={creating:"Creating",failed:"Failed",awaiting_payment:"Awaiting payment",overdue:"Overdue",payment_processing:"Payment processing",awaiting_authentication:"Awaiting authentication",paid:"Paid",paid_outside_stripe:"Paid outside Stripe",paid_by_credit:"Paid by credit",partially_refunded:"Partially refunded",refunded:"Refunded",disputed:"Disputed",voided:"Voided",uncollectible:"Marked uncollectible"};function qn(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:To[e.label]??e.label}function Co(e){switch(e){case"paid":case"paid_outside_stripe":case"paid_by_credit":return"success";case"overdue":case"disputed":case"failed":return"destructive";case"partially_refunded":case"refunded":case"payment_processing":case"awaiting_authentication":return"warning";case"awaiting_payment":return"secondary";default:return"outline"}}var zn={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},ko={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function fs({invoice:e,className:a}){return(0,l.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,l.jsx)(Z,{variant:Co(e.label),className:a,children:qn(e)}),e.collection_method==="charge_automatically"&&(0,l.jsx)(Z,{variant:"secondary",children:"Managed in Stripe"})]})}function vn({delivery:e,className:a}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,l.jsx)(Z,{variant:s,className:a,children:zn[e.state]??e.state})}function us(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ta(e){if(!e)return"\u2014";let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Yr={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Vn={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0};function Eo(e){let a=e==null?"":String(e),s=/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(a),t=s?`'${a}`:a;return s||/[",;\r\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}var $n=100,Hn=5e3;async function Io(e,a){let s=[],t=0;for(let n=0;n<Hn;n+=$n){let i=await e.getInvoices({...a,limit:$n,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<$n||s.length>=t)break}return{invoices:s.slice(0,Hn),total:t,truncated:t>s.length||t>Hn}}function Qr(e){let a=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],s=e.map(t=>[t.id,us(t),qn(t),t.customer_name??"",t.customer_email??"",t.created_at,t.due_at??"",t.paid_at??"",t.currency.toUpperCase(),W(t.amount_subtotal,t.currency),W(t.tax_total,t.currency),W(t.amount_total,t.currency),t.amount_due===null?"":W(t.amount_due,t.currency),t.amount_paid===null?"":W(t.amount_paid,t.currency),W(t.amount_refunded,t.currency),t.payment_method??"",t.pay_url??"",t.retainer_id??"",t.replaces_order_id??"",t.replaced_by_order_id??"",t.tax_behavior??"",t.discount_total===void 0?"":W(t.discount_total,t.currency),t.collection_method??""]);return[a,...s].map(t=>t.map(Eo).join(",")).join(`
|
|
5
|
+
`)}function Ao(e){if(typeof document>"u")return;let a=new Blob([Qr(e)],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(a),t=document.createElement("a");t.href=s,t.download=`invoices-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(t),t.click(),document.body.removeChild(t),URL.revokeObjectURL(s)}function es({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:p=null,onClearRetainerFilter:g}){let{api:x}=te(),{invoices:r,total:y,isLoading:w,error:v,page:d,pageSize:u,hasNextPage:h,hasPreviousPage:N,setPage:T,labels:A,setLabels:H,customerEmail:c,setCustomerEmail:S,q:E,setQ:J,from:B,setFrom:R,to:z,setTo:b,retainerId:Q,setRetainerId:le,refetch:ce}=Xa({refreshKey:a}),[ee,_e]=Ce.useState("open"),[Y,oe]=Ce.useState(""),[fe,K]=Ce.useState(null),Pe=Ce.useRef(0),Me=Ce.useCallback(I=>{Pe.current++,q(!1),K(I)},[]),[xt,q]=Ce.useState(!1),[pe,xe]=Ce.useState(0),[de,Ue]=Ce.useState(null),[k,O]=Ce.useState(!1),[ge,Je]=Ce.useState(0);Ce.useEffect(()=>{K(I=>{if(!I)return I;let He=r.find(U=>U.id===I.id);return He&&He!==I?He:I})},[r]);let[ze,st]=Ce.useState(!1),[Ye,nt]=Ce.useState(null),Gt=async()=>{if(!ze){st(!0),nt(null);try{let{invoices:I,total:He,truncated:U}=await Io(x,{labels:A,customerEmail:c,q:E,from:B,to:z,retainerId:Q});Ao(I),nt(U?`Exported the first ${I.length.toLocaleString()} of ${He.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{nt("Couldn't export \u2014 try again.")}finally{st(!1)}}},ga=!c&&!E&&!B&&!z&&!Q,[se,De]=Ce.useState(null);Ce.useEffect(()=>{if(w||y>0||!ga||ee!=="open")return;let I=!1;return x.getInvoices({limit:1}).then(He=>{I||De(He.total>0)}).catch(()=>{I||De(!0)}),()=>{I=!0}},[x,w,y,ga,ee,a]),Ce.useEffect(()=>{H(Vn.open)},[]),Ce.useEffect(()=>{let I=p?.id??"";I!==Q&&(le(I),I&&(_e("all"),H(Vn.all),S(""),J(""),oe(""),R(""),b("")))},[p?.id]),Ce.useEffect(()=>{let I=!1;return O(!1),x.getInvoiceSettings().then(He=>{I||Ue({payments_active:He.payments_active,blocked:He.blocked})}).catch(()=>{I||O(!0)}),()=>{I=!0}},[x,a,ge]),Ce.useEffect(()=>{if(!s)return;let I=!1,He=Pe.current;return q(!1),x.getInvoice(s).then(U=>{!I&&He===Pe.current&&K(U)}).catch(()=>{!I&&He===Pe.current&&q(!0)}),()=>{I=!0}},[x,s,pe]),Ce.useEffect(()=>{t?.(fe!==null)},[fe,t]);let Ge=I=>{_e(I),H(Vn[I])},sa=I=>{let He=I.trim();if(!He){E&&J(""),c&&S("");return}if(He.includes("@")){E&&J(""),S(He);return}c&&S(""),J(He.replace(/^#/,""))},_t=r,ka=xt&&(0,l.jsxs)("div",{role:"alert",className:"af-mb-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't open the requested invoice. ",(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>xe(I=>I+1),children:"Retry opening invoice"})]});if(fe)return(0,l.jsxs)("div",{className:e,children:[ka,(0,l.jsx)(bn,{invoice:fe,refreshKey:a,onBack:()=>{Me(null),ce()}},fe.id)]});let lt=(0,l.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[k&&(0,l.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>Je(I=>I+1),children:"Retry setup check"})]}),ka,de?.blocked&&(0,l.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",de.blocked.reason?`: ${de.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),p&&(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,l.jsxs)(Z,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",p.label]}),g&&(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:g,children:"Clear schedule filter"})]}),(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,l.jsx)("div",{role:"group","aria-label":"Invoice views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Object.keys(Yr).map(I=>(0,l.jsx)("button",{type:"button","aria-pressed":ee===I,onClick:()=>Ge(I),className:G("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",ee===I?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Yr[I]},I))}),(0,l.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,l.jsx)(ut.Search,{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"}),(0,l.jsx)(Se,{type:"text",value:Y,onChange:I=>oe(I.target.value),onBlur:()=>sa(Y),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),sa(Y))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,l.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,l.jsx)(Re,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,l.jsx)(Se,{id:"invoices-from",type:"date",value:B,max:z||void 0,onChange:I=>R(I.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,l.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,l.jsx)(Re,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,l.jsx)(Se,{id:"invoices-to",type:"date",value:z,min:B||void 0,onChange:I=>b(I.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,l.jsxs)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>void Gt(),disabled:ze||w||!!v||y===0,"aria-busy":ze,children:[(0,l.jsx)(ut.Download,{className:"af-h-4 af-w-4 af-mr-1"}),ze?"Exporting\u2026":"Export CSV (all matching)"]})]}),Ye&&(0,l.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:Ye})]});return w?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(I=>(0,l.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,l.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,l.jsx)(X,{className:"af-h-4 af-w-20"}),(0,l.jsx)(X,{className:"af-h-4 af-w-16"})]}),(0,l.jsx)(X,{className:"af-mt-2 af-h-3 af-w-40"})]},I))})]}):v?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>void ce(),children:"Retry"})]})]}):y===0&&ga&&se===!1&&ee==="open"?de?.blocked?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)(gn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)(gn,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):de&&!de.payments_active?(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)(gn,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):(0,l.jsxs)("div",{className:e,children:[lt,(0,l.jsx)(gn,{heading:"No invoices yet",body:!de||k?"Once invoice setup is ready, you can send invoices from the chat.":"Ask in the chat to send an invoice to a client for your services."})]}):(0,l.jsxs)("div",{className:e,children:[lt,_t.length===0?(0,l.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:"No invoices match."}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:_t.map(I=>(0,l.jsxs)("button",{type:"button",onClick:()=>Me(I),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,l.jsx)("span",{className:"af-font-medium",children:us(I)}),(0,l.jsx)(fs,{invoice:I})]}),(0,l.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:I.customer_name??I.customer_email??"\u2014"}),I.delivery&&(0,l.jsx)("div",{className:"af-mt-1",children:(0,l.jsx)(vn,{delivery:I.delivery})}),(0,l.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[(0,l.jsx)("span",{children:I.collection_method==="charge_automatically"?"Automatic collection":I.due_at?`Due ${ta(I.due_at)}`:"Due on receipt"}),(0,l.jsx)("span",{className:"af-font-medium af-tabular-nums",children:W(I.amount_due??I.amount_total,I.currency)})]})]},I.id))}),(0,l.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,l.jsxs)(Le,{children:[(0,l.jsx)(Oe,{children:(0,l.jsxs)(be,{children:[(0,l.jsx)(F,{children:"Invoice"}),(0,l.jsx)(F,{children:"Created"}),(0,l.jsx)(F,{children:"Customer"}),(0,l.jsx)(F,{children:"Due"}),(0,l.jsx)(F,{className:"af-text-right",children:"Amount"}),(0,l.jsx)(F,{children:"Status"}),(0,l.jsx)(F,{children:"Delivery"}),(0,l.jsx)(F,{className:"af-w-8"})]})}),(0,l.jsx)(Be,{children:_t.map(I=>(0,l.jsxs)(be,{className:"af-cursor-pointer",onClick:()=>Me(I),children:[(0,l.jsx)(M,{className:"af-font-medium",children:(0,l.jsx)("button",{type:"button",className:"af-text-left hover:af-underline focus-visible:af-ring-2 focus-visible:af-ring-ring",onClick:He=>{He.stopPropagation(),Me(I)},"aria-label":`Open invoice ${us(I)}`,children:us(I)})}),(0,l.jsx)(M,{children:ta(I.created_at)}),(0,l.jsxs)(M,{children:[(0,l.jsx)("div",{children:I.customer_name??"\u2014"}),(0,l.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:I.customer_email})]}),(0,l.jsx)(M,{children:I.collection_method==="charge_automatically"?"Automatic":I.due_at?ta(I.due_at):"On receipt"}),(0,l.jsx)(M,{className:"af-text-right af-tabular-nums",children:W(I.amount_due??I.amount_total,I.currency)}),(0,l.jsx)(M,{children:(0,l.jsx)(fs,{invoice:I})}),(0,l.jsx)(M,{children:(0,l.jsx)(vn,{delivery:I.delivery})}),(0,l.jsx)(M,{children:(0,l.jsx)(ut.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},I.id))})]})}),(0,l.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,l.jsxs)("span",{children:[y," invoice",y===1?"":"s"]}),(0,l.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,l.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>T(d-1),disabled:!N,"aria-label":"Previous page",children:(0,l.jsx)(ut.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,l.jsxs)("span",{className:"af-tabular-nums",children:[d*u+1,"\u2013",Math.min((d+1)*u,y)]}),(0,l.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>T(d+1),disabled:!h,"aria-label":"Next page",children:(0,l.jsx)(ut.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function gn({heading:e,body:a,action:s}){return(0,l.jsxs)("div",{className:"af-rounded-md af-border af-px-6 af-py-10 af-text-center",children:[(0,l.jsx)(ut.FileText,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":"true"}),(0,l.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:e}),(0,l.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&(0,l.jsx)(P,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label})]})}var La="af-text-xs af-text-muted-foreground";function Zr(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function bn({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=te(),i=Ce.useRef(null);Ce.useEffect(()=>{i.current?.focus()},[e.id]);let[o,p]=Ce.useState(!1),[g,x]=Ce.useState(null),[r,y]=Ce.useState(!1),[w,v]=Ce.useState(!1),d=Ce.useRef(0),[u,h]=Ce.useState(null),[N,T]=Ce.useState(!1),[A,H]=Ce.useState(0);Ce.useEffect(()=>{let b=!1;return T(!1),n.getInvoice(e.id).then(Q=>{b||h({source:e,value:Q})}).catch(()=>{b||T(!0)}),()=>{b=!0}},[n,e,s,A]);let c=u?.source===e?u.value:e,S=c.collection_method==="charge_automatically";Ce.useEffect(()=>(d.current++,x(null),y(!1),v(!1),p(!1),()=>{d.current++}),[n,c,s]);let E=b=>b==null?"\u2014":W(b,c.currency),J=async()=>{if(!(!c.pay_url||!Zr()))try{await navigator.clipboard.writeText(c.pay_url),p(!0),setTimeout(()=>p(!1),1500)}catch{}},B=async()=>{if(g){x(null);return}let b=++d.current;v(!1),y(!0);try{let Q=await n.getInvoicePreview(c.id);b===d.current&&x(Q)}catch{b===d.current&&v(!0)}finally{b===d.current&&y(!1)}},R=c.bill_to,z=R?[R.company,R.name,R.address?.line1,R.address?.line2,[R.address?.city,R.address?.state,R.address?.postal_code].filter(Boolean).join(", "),R.address?.country,R.tax_id?`${R.tax_id.value}`:null,R.po_number?`PO ${R.po_number}`:null,R.service_period?`Service period: ${R.service_period}`:null].filter(b=>!!b&&b.length>0):[];return(0,l.jsxs)("div",{className:t,children:[(0,l.jsxs)("div",{className:"af-mb-4",children:[(0,l.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,l.jsx)(ut.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,l.jsxs)("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",us(c)]}),(0,l.jsx)(fs,{invoice:c}),(0,l.jsx)(vn,{delivery:c.delivery})]}),(0,l.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[c.customer_name??c.customer_email,c.customer_name&&c.customer_email?` \xB7 ${c.customer_email}`:""]})]}),N&&(0,l.jsxs)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't refresh this invoice. These details may be out of date. ",(0,l.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>H(b=>b+1),children:"Retry details"})]}),c.label==="failed"&&(0,l.jsx)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),c.label==="creating"&&(0,l.jsx)("p",{role:"status",className:"af-mb-4 af-text-sm af-text-muted-foreground",children:"This invoice is still being created. Its final details will appear when it is ready."}),(0,l.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,l.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,l.jsxs)(Le,{children:[(0,l.jsx)(Oe,{children:(0,l.jsxs)(be,{children:[(0,l.jsx)(F,{children:"Description"}),(0,l.jsx)(F,{className:"af-text-right",children:"Qty"}),(0,l.jsx)(F,{className:"af-text-right",children:"Amount"})]})}),(0,l.jsx)(Be,{children:c.line_items.map((b,Q)=>(0,l.jsxs)(be,{children:[(0,l.jsx)(M,{style:{overflowWrap:"anywhere"},children:b.description}),(0,l.jsx)(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:b.quantity}),(0,l.jsx)(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:E(b.amount)})]},Q))})]}),(0,l.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,l.jsx)(qa,{label:"Subtotal",value:E(c.amount_subtotal)}),(c.discount_total??0)>0&&(0,l.jsx)(qa,{label:"Discount",value:`-${E(c.discount_total)}`}),c.tax_total>0&&(0,l.jsx)(qa,{label:c.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:E(c.tax_total)}),(0,l.jsx)(qa,{label:"Total",value:E(c.amount_total),strong:!0}),c.credit_applied>0&&(0,l.jsx)(qa,{label:"Credit applied",value:`-${E(c.credit_applied)}`}),c.amount_due!==null&&c.amount_due!==c.amount_total&&(0,l.jsx)(qa,{label:"Amount due",value:E(c.amount_due),strong:!0}),c.amount_paid!==null&&c.amount_paid>0&&(0,l.jsx)(qa,{label:"Amount paid",value:E(c.amount_paid)}),c.amount_refunded>0&&(0,l.jsx)(qa,{label:"Refunded",value:E(c.amount_refunded)})]}),c.credit_notes?.length>0&&(0,l.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,l.jsx)("div",{className:La,children:"Credit notes"}),c.credit_notes.map(b=>(0,l.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,l.jsxs)("span",{className:"af-text-muted-foreground",children:[ta(b.created_at)," \xB7 ",b.origin==="dashboard"?"issued in Stripe":"refund",b.stripe_credit_note_id?"":" \xB7 being created"]}),(0,l.jsxs)("span",{className:"af-tabular-nums",children:["-",W(b.amount,b.currency)]})]},b.id))]})]}),(c.note||c.footer)&&(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[c.note&&(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:La,children:"Note"}),(0,l.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:c.note})]}),c.footer&&(0,l.jsxs)("div",{children:[(0,l.jsx)("div",{className:La,children:"Footer"}),(0,l.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:c.footer})]})]}),g&&!S&&(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,l.jsxs)("div",{className:G(La,"af-break-words"),children:["Email preview \u2014 ",g.subject]}),(0,l.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,l.jsx)("iframe",{title:"Invoice email preview",srcDoc:g.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,l.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,l.jsx)(ea,{label:"Created",value:ta(c.created_at)}),(0,l.jsx)(ea,{label:"Due",value:c.collection_method==="charge_automatically"?"Managed in Stripe":c.due_at?ta(c.due_at):"On receipt"}),c.paid_at&&(0,l.jsx)(ea,{label:"Paid",value:ta(c.paid_at)}),c.payment_method&&(0,l.jsx)(ea,{label:"Paid by",value:c.paid_out_of_band?`${c.payment_method} (recorded outside Stripe)`:c.payment_method}),c.payment_state!=="none"&&(0,l.jsx)(ea,{label:"Payment",value:c.payment_state==="processing"?"Processing":c.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),c.delivery&&(0,l.jsx)(ea,{label:"Delivery",value:`${zn[c.delivery.state]} \xB7 ${c.delivery.recipient}`}),c.marked_uncollectible_at&&(0,l.jsx)(ea,{label:"Written off",value:ta(c.marked_uncollectible_at)}),c.correction_reason&&(0,l.jsx)(ea,{label:"Correction",value:c.correction_reason}),c.replaced_by_order_id&&(0,l.jsx)(ea,{label:"Replaced by",value:c.replaced_by_order_id}),c.collection_method==="charge_automatically"?(0,l.jsx)(ea,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):c.retainer_id&&(0,l.jsx)(ea,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),c.replaces_order_id&&(0,l.jsx)(ea,{label:"Replaces",value:c.replaces_order_id})]}),(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,l.jsx)("div",{className:La,children:"Reminders"}),S?(0,l.jsx)("div",{children:"View automatic payment reminders in Stripe."}):c.reminders.disabled?(0,l.jsx)("div",{children:"Off for this invoice."}):c.reminders.paused_until?(0,l.jsxs)("div",{children:["Paused until ",ta(c.reminders.paused_until),"."]}):c.reminders.next_at?(0,l.jsxs)("div",{children:["Next on ",ta(c.reminders.next_at),"."]}):c.reminders.final_sent_at?(0,l.jsxs)("div",{children:["Final reminder sent ",ta(c.reminders.final_sent_at),"."]}):(0,l.jsx)("div",{children:"None scheduled."}),!S&&(0,l.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",c.reminders.schedule.length===0?"none":c.reminders.schedule.map(b=>b<0?`${-b}d before`:b===0?"due day":`${b}d after`).join(", ")]})]}),c.communications&&c.communications.length>0&&(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,l.jsx)("div",{className:La,children:"Email delivery history"}),c.communications.map(b=>(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,l.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[ko[b.kind]??b.kind,b.kind==="reminder"&&b.slot!==null?` #${b.slot}`:"",(0,l.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",b.recipient]})]}),(0,l.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[zn[b.state]??b.state," \xB7 ",ta(b.state_at??b.created_at)]})]},b.id))]}),z.length>0&&(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,l.jsx)("div",{className:La,children:"Bill to"}),z.map((b,Q)=>(0,l.jsx)("div",{className:"af-break-words",children:b},Q))]}),(0,l.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[c.pay_url&&(0,l.jsxs)(P,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void J(),disabled:!Zr(),children:[(0,l.jsx)(ut.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":S?"Copy invoice link":"Copy pay link"]}),c.pdf_url&&(0,l.jsx)(P,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,l.jsxs)("a",{href:c.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,l.jsx)(ut.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!S&&(0,l.jsxs)(P,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void B(),disabled:r,children:[r?(0,l.jsx)(ut.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,l.jsx)(ut.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),g?"Hide email preview":w?"Retry email preview":"Show email preview"]}),w&&!S&&(0,l.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),c.pay_url&&(0,l.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:c.pay_url}),(0,l.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:S?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function ea({label:e,value:a}){return(0,l.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,l.jsx)("span",{className:G(La,"af-shrink-0"),children:e}),(0,l.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function qa({label:e,value:a,strong:s}){return(0,l.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,l.jsx)("dt",{className:G(La,s&&"af-font-medium af-text-foreground"),children:e}),(0,l.jsx)("dd",{className:G("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}var ei=require("lucide-react");var Ee=require("react/jsx-runtime"),Do={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Xr={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Lo(e){switch(e){case"active":return"success";case"paused":case"canceling":return"warning";case"failed":return"destructive";case"canceled":return"outline";default:return"secondary"}}function ti(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>Xr[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>Xr[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Do[e.status]}function ai(e){let a=e.interval==="year"?"every year":"every month";return`${W(e.amount,e.currency)} ${a}`}function Oo(e){return e.status==="canceled"?`Ended ${yn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${yn(e.next_cycle_at)}`:"Ends this period":e.collection_method==="charge_automatically"?"Billing schedule managed in Stripe":e.status==="paused"?"Future invoices paused":e.status==="failed"||e.status==="creating"?"Next invoice not scheduled yet":e.skip_next_cycle?e.next_cycle_at?`Skipping ${yn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${yn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function yn(e){if(!e)return"\u2014";let a=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(a);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function hn({retainer:e,className:a}){return(0,Ee.jsx)(Z,{variant:Lo(e.status),className:G("af-max-w-full af-whitespace-normal af-break-words",a),children:ti(e)})}function ts({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:p=0,isLoadingMore:g=!1,onLoadMore:x,includeEnded:r=!1,onIncludeEndedChange:y,className:w}){let v=!!y;if(!a&&!s&&e.length===0&&!(v&&(r||p>0)))return null;let d=o!==void 0?Math.max(0,o-e.length):0;return(0,Ee.jsxs)("section",{className:G("af-mb-6",w),"aria-label":"Recurring invoices",children:[(0,Ee.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Ee.jsx)(ei.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,Ee.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,Ee.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),v&&(0,Ee.jsx)(P,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>y?.(!r),children:r?"Hide ended recurring invoices":p>0&&e.length===0?`Show ended recurring invoices (${p})`:"Show ended recurring invoices"})]}),s?(0,Ee.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",(0,Ee.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?(0,Ee.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(u=>(0,Ee.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,Ee.jsx)(X,{className:"af-h-4 af-w-48"}),(0,Ee.jsx)(X,{className:"af-mt-2 af-h-3 af-w-32"})]},u))}):e.length===0?(0,Ee.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:r?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,Ee.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(u=>{let h=i===u.id;return(0,Ee.jsxs)("li",{className:G("af-rounded-md af-border af-p-3",h&&"af-border-primary af-bg-muted/40"),children:[(0,Ee.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,Ee.jsxs)("div",{className:"af-min-w-0",children:[(0,Ee.jsx)("div",{className:"af-truncate af-font-medium",children:u.customer_name??u.customer_email??"\u2014"}),(0,Ee.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:u.description})]}),(0,Ee.jsx)(hn,{retainer:u})]}),u.collection_method==="charge_automatically"?(0,Ee.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,Ee.jsx)(Z,{variant:"secondary",children:"Managed in Stripe"}),(0,Ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Automatic charging is enabled in Stripe. View or change the billing terms there. To edit this schedule from the chat, switch it back to sending invoices in Stripe."})]}):(0,Ee.jsx)("div",{className:"af-mt-2 af-text-sm",children:ai(u)}),(0,Ee.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-text-xs af-text-muted-foreground",children:[(0,Ee.jsxs)("span",{children:[Oo(u)," \xB7 ",u.cycles.count===0?"no invoices yet":`${u.cycles.paid} paid${u.cycles.open>0?`, ${u.cycles.open} open`:""}`]}),u.cycles.count>0&&(0,Ee.jsx)(P,{type:"button",variant:h?"secondary":"ghost",size:"sm",onClick:()=>n(u),"aria-pressed":h,children:h?"Showing invoices":"View invoices"})]}),u.status==="failed"&&u.operation?.last_error&&(0,Ee.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",u.operation.last_error,". Ask in the chat to try again."]})]},u.id)})}),!a&&!s&&d>0&&x&&(0,Ee.jsx)("div",{className:"af-mt-2",children:(0,Ee.jsx)(P,{type:"button",variant:"outline",size:"sm",onClick:x,disabled:g,children:g?"Loading\u2026":`Load more (${d} more)`})})]})}var si=ne(require("react"),1),zt=require("lucide-react");var _a=ne(require("react"),1);function as(){let{api:e}=te(),[a,s]=_a.useState(null),[t,n]=_a.useState(!0),[i,o]=_a.useState(null),p=_a.useRef(0),g=_a.useCallback(async()=>{let x=++p.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(x!==p.current)return;s(r)}catch(r){if(x!==p.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{x===p.current&&n(!1)}},[e]);return _a.useEffect(()=>{g()},[g]),{status:a,isLoading:t,error:i,refetch:g}}var he=require("react/jsx-runtime");function Vs({onConnectStripe:e,onUpgradePlan:a,className:s}){let{status:t,isLoading:n,error:i,refetch:o}=as(),[p,g]=si.useState(!1),x=async()=>{g(!0);try{await o()}finally{g(!1)}};return n&&!t?(0,he.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,he.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!t?(0,he.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,he.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):t.status==="active"?(0,he.jsx)("div",{className:s,children:(0,he.jsxs)("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:[(0,he.jsx)(zt.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,he.jsxs)("div",{children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,he.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",t.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,he.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[t.reason==="needs_stripe"&&(0,he.jsxs)("div",{className:"af-space-y-3",children:[(0,he.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,he.jsx)(zt.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,he.jsxs)("div",{children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,he.jsx)("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?(0,he.jsxs)(P,{onClick:e,children:[(0,he.jsx)(zt.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),t.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,he.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),t.reason==="needs_paid_plan"&&(0,he.jsxs)("div",{className:"af-space-y-3",children:[(0,he.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,he.jsx)(zt.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,he.jsxs)("div",{children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,he.jsx)("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."})]})]}),a?(0,he.jsx)(P,{onClick:a,children:"Upgrade plan"}):(0,he.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),t.reason==="account_disabled"&&(0,he.jsxs)("div",{className:"af-space-y-3",children:[(0,he.jsxs)("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:[(0,he.jsx)(zt.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,he.jsxs)("div",{children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),t.stripe_account_connected?(0,he.jsx)("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."}):(0,he.jsx)("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."})]})]}),(0,he.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&t.stripe_account_connected&&(0,he.jsxs)(P,{onClick:e,children:[(0,he.jsx)(zt.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,he.jsxs)(P,{variant:"outline",onClick:x,disabled:p,children:[p?(0,he.jsx)(zt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,he.jsx)(zt.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var St=ne(require("react"),1);function jn(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function ss({includeStats:e=!1,refreshKey:a}={}){let{api:s}=te(),[t,n]=St.useState([]),[i,o]=St.useState(!0),[p,g]=St.useState(null),x=St.useRef(0),r=St.useCallback(async()=>{let h=++x.current;try{o(!0),g(null);let N=await s.getProducts(e?{include:"stats"}:{});if(h!==x.current)return;n(N)}catch(N){if(h!==x.current)return;g(N instanceof Error?N:new Error("Failed to fetch products"))}finally{h===x.current&&o(!1)}},[s,e,a]);St.useEffect(()=>{r()},[r]);let y=St.useCallback(async h=>{let N=await s.createProduct(h);return n(T=>[N,...T]),N},[s]),w=St.useCallback(async(h,N)=>{let T=await s.updateProduct(h,N);return n(A=>jn(A,h,T)),T},[s]),v=St.useCallback(async h=>{await s.deleteProduct(h),n(N=>N.filter(T=>T.id!==h))},[s]),d=St.useCallback(async(h,N)=>{let T=await s.attachProductFile(h,N);return n(A=>jn(A,h,T)),T},[s]),u=St.useCallback(async(h,N)=>{let T=await s.attachProductFileFromUrl(h,N);return n(A=>jn(A,h,T)),T},[s]);return{products:t,isLoading:i,error:p,refetch:r,createProduct:y,updateProduct:w,deleteProduct:v,attachProductFile:d,attachProductFileFromUrl:u}}var Rt=ne(require("react"),1);var ni=["creating","active","paused","canceling"],Bo=["canceled","failed"];function ns({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=te(),[n,i]=Rt.useState([]),[o,p]=Rt.useState(0),[g,x]=Rt.useState(0),[r,y]=Rt.useState(!0),[w,v]=Rt.useState(!1),[d,u]=Rt.useState(null),[h,N]=Rt.useState(a),T=Rt.useRef(0),A=Rt.useCallback(async()=>{let c=++T.current;y(!0),v(!1),u(null);try{let S=await t.getRetainers({statuses:h?void 0:ni,limit:s,offset:0});if(c!==T.current)return;if(i(S.retainers),p(S.total),!h&&S.total===0){let E=await t.getRetainers({statuses:Bo,limit:1,offset:0});if(c!==T.current)return;x(E.total)}else x(0)}catch(S){if(c!==T.current)return;u(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{c===T.current&&y(!1)}},[t,h,s]);Rt.useEffect(()=>{A()},[A,e]);let H=Rt.useCallback(async()=>{if(r||w||n.length>=o)return;let c=T.current;v(!0);try{let S=await t.getRetainers({statuses:h?void 0:ni,limit:s,offset:n.length});if(c!==T.current)return;i(E=>{let J=new Set(E.map(B=>B.id));return[...E,...S.retainers.filter(B=>!J.has(B.id))]}),p(S.total)}catch(S){if(c!==T.current)return;u(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{c===T.current&&v(!1)}},[t,h,s,r,w,n.length,o]);return{retainers:n,total:o,endedTotal:g,hasMore:n.length<o,isLoading:r,isLoadingMore:w,error:d,includeEnded:h,setIncludeEnded:N,loadMore:H,refetch:A}}var Ne=require("react/jsx-runtime");function Gn({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=ms.useState(a),[p,g]=ms.useState("list"),[x,r]=ms.useState(null),y=ss(),{status:w,error:v}=as(),d=w?.currency,u=A=>{r(A),g("edit")},h=()=>{r(null),g("create")},N=()=>{g("list"),r(null)},T=A=>{r(A),g("edit")};return(0,Ne.jsxs)("div",{className:e,children:[(0,Ne.jsxs)("div",{className:"af-mb-6",children:[(0,Ne.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Ne.jsxs)(sn,{value:i,onValueChange:A=>o(A),children:[(0,Ne.jsxs)(bs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Ne.jsxs)(va,{value:"products",className:"af-gap-2",children:[(0,Ne.jsx)(aa.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Ne.jsxs)(va,{value:"orders",className:"af-gap-2",children:[(0,Ne.jsx)(aa.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Ne.jsxs)(va,{value:"invoices",className:"af-gap-2",children:[(0,Ne.jsx)(aa.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Ne.jsxs)(va,{value:"customers",className:"af-gap-2",children:[(0,Ne.jsx)(aa.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Ne.jsxs)(va,{value:"setup",className:"af-gap-2",children:[(0,Ne.jsx)(aa.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Ne.jsx)(ba,{value:"products",children:p==="list"?(0,Ne.jsx)(Is,{productsState:y,onSelectProduct:u,onCreateProduct:h}):(0,Ne.jsxs)("div",{children:[(0,Ne.jsxs)("div",{className:"af-mb-6",children:[(0,Ne.jsxs)(P,{variant:"ghost",size:"sm",onClick:N,className:"af-mb-2 af--ml-2",children:[(0,Ne.jsx)(aa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Ne.jsx)("h3",{className:"af-text-lg af-font-semibold",children:p==="create"?"New Product":x?.name})]}),p==="create"&&!d?(0,Ne.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:v?(0,Ne.jsxs)("div",{className:"af-text-destructive",children:["Error: ",v.message]}):(0,Ne.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Ne.jsx)(Ds,{productsState:y,product:p==="edit"?x:null,currency:d??"usd",onSaved:T},p==="edit"?x?.id??"edit":"new")]})}),(0,Ne.jsx)(ba,{value:"orders",children:(0,Ne.jsx)(Za,{onRefund:t})}),(0,Ne.jsx)(ba,{value:"invoices",children:(0,Ne.jsx)(Fo,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:w?.reason==="needs_paid_plan"})}),(0,Ne.jsx)(ba,{value:"customers",children:(0,Ne.jsx)(Us,{})}),(0,Ne.jsx)(ba,{value:"setup",children:(0,Ne.jsx)(Vs,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Fo({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=ns(),[n,i]=ms.useState(null),[o,p]=ms.useState(!1);return(0,Ne.jsxs)(Ne.Fragment,{children:[!o&&(0,Ne.jsx)(ts,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:g=>i(x=>x?.id===g.id?null:g),total:t.total,endedTotal:t.endedTotal,isLoadingMore:t.isLoadingMore,onLoadMore:()=>void t.loadMore(),includeEnded:t.includeEnded,onIncludeEndedChange:t.setIncludeEnded}),(0,Ne.jsx)(es,{onDetailOpenChange:p,onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>i(null)})]})}var ii=ne(require("react"),1);var Pa=ne(require("react"),1);function $s({refreshKey:e}={}){let{api:a}=te(),[s,t]=Pa.useState(null),[n,i]=Pa.useState(!0),[o,p]=Pa.useState(null),g=Pa.useRef(0),x=Pa.useCallback(async()=>{let r=++g.current;try{i(!0),p(null);let y=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==g.current)return;t(y)}catch(y){if(r!==g.current)return;p(y instanceof Error?y:new Error("Failed to fetch summary"))}finally{r===g.current&&i(!1)}},[a,e]);return Pa.useEffect(()=>{x()},[x]),{summary:s,isLoading:n,error:o,refetch:x}}var $e=require("react/jsx-runtime");function ri(e,a){if(e.settled.complete)return{headline:W(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:W(s.gross,s.currency),extra:e.totals.slice(1).map(t=>`+ ${W(t.gross,t.currency)} in ${t.currency.toUpperCase()}`)}:{headline:W(0,a),extra:[]}}function Wn({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:p,error:g,refetch:x}=$s({refreshKey:e}),[r,y]=ii.useState(!1),w=(0,$e.jsx)("div",{className:"af-mb-6",children:g&&!o?(0,$e.jsx)($t,{message:"Couldn't load your revenue summary.",onRetry:()=>x()}):(0,$e.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:p||!o?(0,$e.jsxs)($e.Fragment,{children:[(0,$e.jsx)(Ze,{label:"This week",children:(0,$e.jsx)(X,{className:"af-h-6 af-w-24"})}),(0,$e.jsx)(Ze,{label:"Today",children:(0,$e.jsx)(X,{className:"af-h-6 af-w-24"})}),(0,$e.jsx)(Ze,{label:"Needs attention",children:(0,$e.jsx)(X,{className:"af-h-6 af-w-10"})})]}):(0,$e.jsx)($e.Fragment,{children:(()=>{let v=ri(o.revenue.d7,o.currency),d=ri(o.revenue.today,o.currency);return(0,$e.jsxs)($e.Fragment,{children:[(0,$e.jsx)(Ze,{label:"This week",detail:v.extra.length>0?(0,$e.jsx)("div",{children:v.extra.map(u=>(0,$e.jsx)("div",{children:u},u))}):void 0,children:v.headline}),(0,$e.jsx)(Ze,{label:"Today",detail:d.extra.length>0?(0,$e.jsx)("div",{children:d.extra.map(u=>(0,$e.jsx)("div",{children:u},u))}):void 0,children:d.headline}),(0,$e.jsx)(Ze,{label:"Needs attention",valueClassName:o.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:o.needs_attention.count===0?"All clear":o.needs_attention.items[0]?.title??void 0,children:o.needs_attention.count})]})})()})})});return(0,$e.jsxs)(bt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[w,(0,$e.jsx)(Za,{refreshKey:e,initialOrderId:a,onDetailOpenChange:y,showFulfillment:!0,onRefund:s?t:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Oa=ne(require("react"),1),ps=require("lucide-react");var Ta=ne(require("react"),1),_n=require("lucide-react");var ht=require("react/jsx-runtime"),oi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ja="af-text-xs af-text-muted-foreground",xn="af-text-sm af-font-medium af-tabular-nums",Mo=3;function Uo(e){let a=e.pricing,s=a?.currency??e.currency;if(a?.custom_amount??e.allow_custom_amount){let g=e.min_amount??a?.min_amount??null,x=e.max_amount??a?.max_amount??null;return g!==null&&x!==null?{text:`Buyer chooses (${W(g,s)} \u2013 ${W(x,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=a?.min_amount??e.unit_amount,i=a?.max_amount??e.unit_amount;if(n===null||i===null)return{text:"Varies by variant",compareAt:null};let o=n===i?W(n,s):`${W(n,s)} \u2013 ${W(i,s)}`,p=a?.compare_at_amount??null;return{text:o,compareAt:p!==null&&p>i?W(p,s):null}}function wn({product:e,className:a}){let s=Uo(e);return(0,ht.jsxs)("div",{className:a,children:[(0,ht.jsx)("span",{className:xn,children:s.text}),s.compareAt&&(0,ht.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function Nn({product:e}){let a=e.inventory;return a?a.tracked?a.out_of_stock?(0,ht.jsx)(Z,{variant:"destructive",children:"Out of stock"}):a.low_stock?(0,ht.jsxs)(Z,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?(0,ht.jsx)(Z,{variant:"secondary",children:"Backorder"}):a.available===null?null:(0,ht.jsxs)(Z,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?(0,ht.jsx)(Z,{variant:"warning",children:"Low stock"}):null}function Sn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Rn(e){return e.map(a=>W(a.amount,a.currency)).join(" + ")}function li(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${W(e.min_amount,e.currency)} \u2013 ${W(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":W(e.unit_amount,e.currency)}function ci({variant:e}){let a=e.inventory;if(!a||!a.tracked)return(0,ht.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=a.available??0;return a.allow_backorder?(0,ht.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ht.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,s)}),(0,ht.jsx)(Z,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?(0,ht.jsx)(Z,{variant:"destructive",children:"Out of stock"}):(0,ht.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ht.jsx)("span",{className:"af-tabular-nums",children:s}),s<=Mo&&(0,ht.jsx)(Z,{variant:"warning",children:"Low"})]})}var j=require("react/jsx-runtime");function Hs({title:e,children:a,className:s}){return(0,j.jsxs)("section",{className:G("af-rounded-lg af-border af-p-4",s),children:[(0,j.jsx)("h4",{className:oi,children:e}),(0,j.jsx)("div",{className:"af-mt-3",children:a})]})}function di({src:e,className:a}){let[s,t]=Ta.useState(!1);return Ta.useEffect(()=>t(!1),[e]),!e||s?(0,j.jsx)("div",{"aria-hidden":"true",className:G("af-flex af-items-center af-justify-center af-bg-muted",a),children:(0,j.jsx)(_n.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,j.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:G("af-object-cover",a)})}function ui({product:e,showStats:a=!1,onBack:s}){let{api:t}=te(),[n,i]=Ta.useState(null),[o,p]=Ta.useState(!0),[g,x]=Ta.useState(null),[r,y]=Ta.useState(0),[w,v]=Ta.useState(0);Ta.useEffect(()=>{let c=!1;return p(!0),x(null),t.getProduct(e.id).then(S=>{c||i(S)}).catch(S=>{c||x(S instanceof Error?S:new Error("Failed to load product"))}).finally(()=>{c||p(!1)}),()=>{c=!0}},[t,e.id,r]);let d=n?{...e,...n}:e,u=d.images.length>0?d.images:e.images,h=u[w]??u[0],N=Sn(d),T=a?d.stats:void 0,A=n?.variants??[],H=A.length>1;return(0,j.jsxs)("div",{children:[(0,j.jsxs)("div",{className:"af-mb-6",children:[(0,j.jsxs)(P,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,j.jsx)(_n.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,j.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,j.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:d.name}),(0,j.jsx)(Z,{variant:d.active?"success":"secondary",children:d.active?"Active":"Draft"}),(0,j.jsx)(Nn,{product:d})]}),(0,j.jsx)(wn,{product:d,className:"af-mt-1"}),!d.active&&(0,j.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),(0,j.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsx)(di,{src:h,className:"af-h-48 af-w-full af-rounded-md af-border"}),u.length>1&&(0,j.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:u.map((c,S)=>(0,j.jsx)("button",{type:"button",onClick:()=>v(S),"aria-label":`Show photo ${S+1} of ${u.length}`,"aria-pressed":S===w,className:G("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",S===w?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,j.jsx)(di,{src:c,className:"af-h-12 af-w-12 af-rounded-md"})},`${c}-${S}`))})]}),(0,j.jsxs)("div",{className:"af-space-y-6",children:[d.description&&(0,j.jsx)(Hs,{title:"Description",children:(0,j.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:d.description})}),o?(0,j.jsxs)(Hs,{title:"Variants",children:[(0,j.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(c=>(0,j.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,j.jsx)(X,{className:"af-h-4 af-w-28"}),(0,j.jsx)(X,{className:"af-h-4 af-w-20"}),(0,j.jsx)(X,{className:"af-h-4 af-w-16"})]},c))}),(0,j.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):g?(0,j.jsx)($t,{message:"Couldn't load this product's variants.",onRetry:()=>y(c=>c+1)}):H?(0,j.jsx)(Hs,{title:`Variants \xB7 ${A.length}`,children:(0,j.jsx)("div",{className:"af-overflow-x-auto",children:(0,j.jsxs)(Le,{children:[(0,j.jsx)(Oe,{children:(0,j.jsxs)(be,{children:[(0,j.jsx)(F,{children:"Variant"}),(0,j.jsx)(F,{children:"SKU"}),(0,j.jsx)(F,{className:"af-text-right",children:"Price"}),(0,j.jsx)(F,{children:"Stock"})]})}),(0,j.jsx)(Be,{children:A.map(c=>(0,j.jsxs)(be,{children:[(0,j.jsxs)(M,{className:"af-font-medium",children:[c.title||c.option_values.map(S=>S.value).join(" / ")||"\u2014",!c.active&&(0,j.jsx)(Z,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,j.jsx)(M,{className:"af-text-muted-foreground",children:c.sku?(0,j.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:c.sku}):"\u2014"}),(0,j.jsxs)(M,{className:"af-whitespace-nowrap af-text-right",children:[(0,j.jsx)("div",{className:xn,children:li(c)}),c.compare_at_amount!==null&&c.unit_amount!==null&&c.compare_at_amount>c.unit_amount&&(0,j.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:W(c.compare_at_amount,c.currency)})]}),(0,j.jsx)(M,{className:"af-text-sm",children:(0,j.jsx)(ci,{variant:c})})]},c.id))})]})})}):null,(0,j.jsx)(Hs,{title:"Details",children:(0,j.jsxs)("dl",{className:"af-space-y-2",children:[(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Delivery"}),(0,j.jsx)("dd",{className:"af-text-sm",children:N==="Digital download"?d.fulfillment.filename??"Digital download":N??"Nothing to deliver"})]}),d.fulfillment.type==="redirect"&&d.fulfillment.url&&(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Sends buyers to"}),(0,j.jsx)("dd",{className:"af-break-all af-text-sm",children:d.fulfillment.url})]}),(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Shipping address"}),(0,j.jsx)("dd",{className:"af-text-sm",children:d.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Most one buyer can order"}),(0,j.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:d.max_quantity})]})]})}),T&&(0,j.jsx)(Hs,{title:"Last 30 days",children:(0,j.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Units sold"}),(0,j.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:T.units_sold})]}),(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Orders"}),(0,j.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:T.orders})]}),(0,j.jsxs)("div",{children:[(0,j.jsx)("dt",{className:ja,children:"Gross"}),(0,j.jsx)("dd",{className:xn,children:T.gross.length>0?Rn(T.gross):"\u2014"})]})]})}),(0,j.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var V=require("react/jsx-runtime"),Vo={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},$o=["all","active","draft","low_stock","out_of_stock"];function fi(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function mi(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Ho(e){return e.inventory?.out_of_stock??!1}function zo(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return mi(e);case"out_of_stock":return Ho(e);default:return!0}}function qo({product:e,showStats:a,onOpen:s}){let t=e.images[0],n=a?e.stats:void 0,i=Sn(e),o=e.variant_count??0;return(0,V.jsxs)("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[t?(0,V.jsx)("img",{src:t,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,V.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:(0,V.jsx)(ps.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,V.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,V.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,V.jsxs)("div",{className:"af-min-w-0",children:[(0,V.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,V.jsx)(wn,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,V.jsx)(Z,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Nn,{product:e}),o>1&&(0,V.jsxs)(Z,{variant:"outline",children:[o," variants"]}),i&&(0,V.jsx)(Z,{variant:"outline",children:i})]}),n&&(0,V.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Rn(n.gross)}`:""," ",(0,V.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function jo(){return(0,V.jsx)("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=>(0,V.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,V.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,V.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,V.jsx)(X,{className:"af-w-32"}),(0,V.jsx)(X,{className:"af-w-16"}),(0,V.jsx)(X,{className:"af-h-5 af-w-24"})]})]},e))})}function Kn({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:p}=ss({includeStats:a,refreshKey:e}),[g,x]=Oa.useState(null),[r,y]=Oa.useState("all"),[w,v]=Oa.useState(""),[d,u]=Oa.useState("newest"),h=Oa.useMemo(()=>{if(!a)return null;let R=null;for(let z of n)!z.stats||z.stats.units_sold===0||(!R||z.stats.units_sold>(R.stats?.units_sold??0))&&(R=z);return R},[n,a]),N=Oa.useMemo(()=>n.filter(mi).length,[n]),T=w.trim().toLowerCase(),A=Oa.useMemo(()=>{let z=[...n.filter(b=>zo(b,r)&&(!T||b.name.toLowerCase().includes(T)))];return d==="name"?z.sort((b,Q)=>b.name.localeCompare(Q.name)):d==="best_selling"?z.sort((b,Q)=>(Q.stats?.units_sold??0)-(b.stats?.units_sold??0)):z.sort((b,Q)=>fi(Q.created_at)-fi(b.created_at)),z},[n,r,T,d]),H=r!=="all"||!!T,c=()=>{y("all"),v("")},S=i||o!==null&&n.length===0,E=(0,V.jsx)("div",{className:"af-mb-6",children:(0,V.jsx)("div",{className:G("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:S?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Ze,{label:"Products",children:(0,V.jsx)(X,{className:"af-h-6 af-w-10"})}),a?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Ze,{label:"Best seller",children:(0,V.jsx)(X,{className:"af-h-6 af-w-28"})}),(0,V.jsx)(Ze,{label:"Low stock",children:(0,V.jsx)(X,{className:"af-h-6 af-w-10"})})]}):(0,V.jsx)(Ze,{label:"Active",children:(0,V.jsx)(X,{className:"af-h-6 af-w-10"})})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Ze,{label:"Products",children:n.length}),a?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Ze,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:h?`${h.stats?.units_sold??0} sold, last 30 days`:void 0,children:h?(0,V.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:h.name}):(0,V.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,V.jsx)(Ze,{label:"Low stock",children:N})]}):(0,V.jsx)(Ze,{label:"Active",children:n.filter(R=>R.active).length})]})})}),J=(0,V.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,V.jsx)("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:$o.map(R=>(0,V.jsx)("button",{type:"button","aria-pressed":r===R,onClick:()=>y(R),className:G("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===R?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Vo[R]},R))}),(0,V.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,V.jsx)(ps.Search,{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"}),(0,V.jsx)(Se,{type:"text",value:w,onChange:R=>v(R.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,V.jsxs)(Wt,{value:d,onValueChange:R=>u(R),children:[(0,V.jsx)(Bt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,V.jsx)(Kt,{})}),(0,V.jsxs)(Ft,{children:[(0,V.jsx)(qe,{value:"newest",children:"Newest"}),(0,V.jsx)(qe,{value:"name",children:"Name A\u2013Z"}),a&&(0,V.jsx)(qe,{value:"best_selling",children:"Best selling"})]})]}),H&&(0,V.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:c,children:"Clear filters"})]}),i&&n.length===0?(0,V.jsx)(X,{className:"af-h-4 af-w-28"}):(0,V.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:H?`${A.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${N>0?` \xB7 ${N} low stock`:""}`})]}),B;return g?B=(0,V.jsx)(ui,{product:g,showStats:a,onBack:()=>{x(null),p()}},g.id):i&&n.length===0?B=(0,V.jsxs)(V.Fragment,{children:[J,(0,V.jsx)(jo,{}),(0,V.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?B=(0,V.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,V.jsx)($t,{message:"Couldn't load your products.",onRetry:()=>p()})}):n.length===0?B=(0,V.jsxs)(Sa,{icon:(0,V.jsx)(ps.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,V.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):B=(0,V.jsxs)(V.Fragment,{children:[J,o&&(0,V.jsx)("div",{className:"af-mb-4",children:(0,V.jsx)($t,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>p()})}),A.length===0?(0,V.jsxs)(Sa,{children:["No products match these filters.",(0,V.jsx)("br",{}),(0,V.jsx)(P,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:c,children:"Show all products"})]}):(0,V.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:A.map(R=>(0,V.jsx)(qo,{product:R,showStats:a,onOpen:()=>x(R)},R.id))})]}),(0,V.jsxs)(bt,{title:"Products",onBackToWebsite:s,hideBackButton:!!g,className:t,children:[!g&&E,B]})}var ma=ne(require("react"),1),ot=require("lucide-react");var qt=ne(require("react"),1);function zs({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=te(),[t,n]=qt.useState([]),[i,o]=qt.useState(!0),[p,g]=qt.useState(null),[x,r]=qt.useState(0),[y]=qt.useState(e),[w,v]=qt.useState(""),d=qt.useRef(0),u=qt.useCallback(async()=>{let h=++d.current;try{o(!0),g(null);let N={limit:y,offset:x*y};w.trim()&&(N.q=w.trim());let T=await s.getPeople(N);if(h!==d.current)return;n(T.people)}catch(N){if(h!==d.current)return;g(N instanceof Error?N:new Error("Failed to fetch people"))}finally{h===d.current&&o(!1)}},[s,x,y,w,a]);return qt.useEffect(()=>{u()},[u]),{people:t,isLoading:i,error:p,page:x,pageSize:y,hasNextPage:t.length===y,hasPreviousPage:x>0,setPage:r,q:w,setQ:h=>{v(h),r(0)},refetch:u}}var Ca=ne(require("react"),1);function qs(e,{refreshKey:a}={}){let{api:s}=te(),[t,n]=Ca.useState(null),[i,o]=Ca.useState(e!==null),[p,g]=Ca.useState(null),x=Ca.useRef(0),r=Ca.useCallback(async()=>{if(e===null){n(null),o(!1),g(null);return}let y=++x.current;try{o(!0),g(null);let w=await s.getPerson(e);if(y!==x.current)return;n(w)}catch(w){if(y!==x.current)return;g(w instanceof Error?w:new Error("Failed to fetch person"))}finally{y===x.current&&o(!1)}},[s,e,a]);return Ca.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:p,refetch:r}}var m=require("react/jsx-runtime"),Jn="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Go="af-text-xs af-text-muted-foreground";function gs(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Yn(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function Wo(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Ko({value:e,label:a}){let[s,t]=ma.useState(!1);return Wo()?(0,m.jsxs)(P,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),t(!0),setTimeout(()=>t(!1),1500)}catch{}},"aria-label":a,className:"af-shrink-0",children:[s?(0,m.jsx)(ot.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,m.jsx)(ot.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function pi(e){return(0,m.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,m.jsxs)(Z,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,m.jsx)(Z,{variant:"secondary",children:"Contact form"})]})}function gi(e){return e.name?e.name:e.email?e.email:(0,m.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Jo=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Yo=40;function Zo(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>Jo.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=Yo).sort((n,i)=>String(i[1]).trim().length-String(n[1]).trim().length)[0];return t?{message:String(t[1]),rest:a.filter(([n])=>n!==t[0])}:{message:null,rest:a}}function Qo(e){return e.replace(/_/g," ")}function Xo(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function el({data:e}){let{message:a,rest:s}=Zo(e);return a===null&&s.length===0?(0,m.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,m.jsxs)("div",{className:"af-space-y-3",children:[a!==null&&(0,m.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:a}),s.length>0&&(0,m.jsx)("dl",{className:"af-space-y-1",children:s.map(([t,n])=>(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,m.jsx)("dt",{className:G(Go,"af-w-28 af-shrink-0 af-capitalize"),children:Qo(t)}),(0,m.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Xo(n)})]},t))})]})}function vi({formName:e,createdAt:a,data:s}){return(0,m.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,m.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,m.jsx)(Z,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,m.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,m.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:gs(a)})]}),(0,m.jsx)(el,{data:s})]})}function tl(e){return e.charged_total??e.amount_total}function al({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=qs(e,{refreshKey:a}),p=Yn(e,t?.submissions[0]?.form_name);return(0,m.jsxs)("div",{children:[(0,m.jsxs)("div",{className:"af-mb-6",children:[(0,m.jsxs)(P,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,m.jsx)(ot.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,m.jsxs)("div",{className:"af-min-w-0",children:[n?(0,m.jsx)(X,{className:"af-h-7 af-w-48"}):(0,m.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:t?.name||e}),(0,m.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,m.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,m.jsx)(Ko,{value:e,label:"Copy email address"})]})]}),(0,m.jsx)(P,{asChild:!0,children:(0,m.jsxs)("a",{href:p,children:[(0,m.jsx)(ot.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?(0,m.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(g=>(0,m.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,m.jsx)(X,{className:"af-w-40"}),(0,m.jsx)(X,{className:"af-mt-2 af-w-64"})]},g)),(0,m.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?(0,m.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,m.jsx)($t,{message:"Couldn't load this person.",onRetry:()=>o()})}):(0,m.jsxs)("div",{className:"af-space-y-6",children:[t.customer&&(0,m.jsxs)("div",{children:[(0,m.jsx)("h4",{className:G(Jn,"af-mb-3"),children:"Customer"}),(0,m.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[t.customer.name&&(0,m.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,m.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,m.jsx)("dd",{children:t.customer.name})]}),t.customer.phone&&(0,m.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,m.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,m.jsx)("dd",{children:t.customer.phone})]}),(0,m.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,m.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,m.jsx)("dd",{children:gs(t.customer.created_at)})]})]})]}),t.orders.length>0&&(0,m.jsxs)("div",{children:[(0,m.jsx)("h4",{className:G(Jn,"af-mb-3"),children:"Purchases"}),(0,m.jsx)("div",{className:"af-overflow-x-auto",children:(0,m.jsxs)(Le,{children:[(0,m.jsx)(Oe,{children:(0,m.jsxs)(be,{children:[(0,m.jsx)(F,{children:"Order"}),(0,m.jsx)(F,{children:"Date"}),(0,m.jsx)(F,{className:"af-text-right",children:"Total"}),(0,m.jsx)(F,{children:"Status"})]})}),(0,m.jsx)(Be,{children:t.orders.map(g=>(0,m.jsxs)(be,{children:[(0,m.jsx)(M,{className:"af-whitespace-nowrap af-font-medium",children:Da(g)}),(0,m.jsx)(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:gs(g.created_at)}),(0,m.jsx)(M,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:W(tl(g),g.currency)}),(0,m.jsx)(M,{children:(0,m.jsx)($a,{status:g.status})})]},g.id))})]})}),(0,m.jsx)("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."})]}),t.submissions.length>0&&(0,m.jsxs)("div",{children:[(0,m.jsx)("h4",{className:G(Jn,"af-mb-3"),children:"Messages"}),(0,m.jsx)("div",{className:"af-space-y-3",children:t.submissions.map(g=>(0,m.jsx)(vi,{formName:g.form_name,createdAt:g.created_at,data:g.data},g.id))})]})]})]})}function sl({submissionId:e,onBack:a}){let{api:s}=te(),[t,n]=ma.useState(null),[i,o]=ma.useState(!0),[p,g]=ma.useState(null),[x,r]=ma.useState(0);return ma.useEffect(()=>{let y=!1;return o(!0),g(null),s.getSubmission(e).then(w=>{y||n(w)}).catch(w=>{y||g(w instanceof Error?w:new Error("Failed to load submission"))}).finally(()=>{y||o(!1)}),()=>{y=!0}},[s,e,x]),(0,m.jsxs)("div",{children:[(0,m.jsxs)("div",{className:"af-mb-6",children:[(0,m.jsxs)(P,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,m.jsx)(ot.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,m.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,m.jsx)(X,{className:"af-mt-1 af-h-4 af-w-32"}):t&&(0,m.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:gs(t.metadata.submitted_at)})]}),i?(0,m.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,m.jsx)(X,{className:"af-w-40"}),(0,m.jsx)(X,{className:"af-mt-2 af-w-64"}),(0,m.jsx)(X,{className:"af-mt-2 af-w-52"}),(0,m.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):p||!t?(0,m.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,m.jsx)($t,{message:"Couldn't load this submission.",onRetry:()=>r(y=>y+1)})}):(0,m.jsxs)("div",{className:"af-space-y-3",children:[(0,m.jsx)(vi,{formName:null,createdAt:t.metadata.submitted_at,data:t.data}),(0,m.jsx)("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 nl={all:"All",customers:"Customers",leads:"Leads"},rl=["all","customers","leads"];function il(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function Zn({refreshKey:e,onBackToWebsite:a,className:s}){let{people:t,isLoading:n,error:i,page:o,pageSize:p,hasNextPage:g,hasPreviousPage:x,setPage:r,q:y,setQ:w,refetch:v}=zs({refreshKey:e}),[d,u]=ma.useState({kind:"list"}),[h,N]=ma.useState(""),[T,A]=ma.useState("all"),H=B=>{B.email?u({kind:"person",email:B.email}):B.submission_id&&u({kind:"submission",submissionId:B.submission_id})},c=()=>{u({kind:"list"}),v()},S=B=>{let R=B.trim();R!==y&&w(R)},E=t.filter(B=>il(B,T)),J;if(d.kind==="person")J=(0,m.jsx)(al,{email:d.email,refreshKey:e,onBack:c});else if(d.kind==="submission")J=(0,m.jsx)(sl,{submissionId:d.submissionId,onBack:c});else{let B=(0,m.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,m.jsx)("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:rl.map(R=>(0,m.jsx)("button",{type:"button","aria-pressed":T===R,onClick:()=>A(R),className:G("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",T===R?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:nl[R]},R))}),(0,m.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,m.jsx)(ot.Search,{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"}),(0,m.jsx)(Se,{type:"text",value:h,onChange:R=>N(R.target.value),onBlur:()=>S(h),onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),S(h))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),y&&(0,m.jsx)(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{N(""),w("")},children:"Clear search"})]});if(n)J=(0,m.jsxs)("div",{children:[B,(0,m.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(R=>(0,m.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,m.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,m.jsx)(X,{className:"af-h-4 af-w-32"}),(0,m.jsx)(X,{className:"af-h-4 af-w-16"})]}),(0,m.jsx)(X,{className:"af-mt-2 af-h-5 af-w-28"}),(0,m.jsx)(X,{className:"af-mt-2 af-h-3 af-w-56"})]},R))}),(0,m.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,m.jsxs)(Le,{children:[(0,m.jsx)(Oe,{children:(0,m.jsxs)(be,{children:[(0,m.jsx)(F,{children:"Person"}),(0,m.jsx)(F,{children:"Came from"}),(0,m.jsx)(F,{children:"Latest message"}),(0,m.jsx)(F,{children:"Last activity"}),(0,m.jsx)(F,{className:"af-w-8"}),(0,m.jsx)(F,{className:"af-w-8"})]})}),(0,m.jsx)(Be,{"aria-hidden":"true",children:[0,1,2,3,4].map(R=>(0,m.jsxs)(be,{children:[(0,m.jsx)(M,{children:(0,m.jsx)(X,{className:"af-h-4 af-w-40"})}),(0,m.jsx)(M,{children:(0,m.jsx)(X,{className:"af-h-5 af-w-24"})}),(0,m.jsx)(M,{children:(0,m.jsx)(X,{className:"af-h-4 af-w-56"})}),(0,m.jsx)(M,{children:(0,m.jsx)(X,{className:"af-h-4 af-w-24"})}),(0,m.jsx)(M,{}),(0,m.jsx)(M,{})]},R))})]})}),(0,m.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)J=(0,m.jsxs)("div",{children:[B,(0,m.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,m.jsx)($t,{message:"Couldn't load your leads.",onRetry:()=>v()})})]});else if(E.length===0&&o===0){let R=!!y||T!=="all";J=(0,m.jsxs)("div",{children:[R&&B,R?(0,m.jsx)(Sa,{children:y?"Nobody matches that search.":T==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,m.jsx)(Sa,{icon:(0,m.jsx)(ot.Users,{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(t.length===0)J=(0,m.jsxs)("div",{children:[B,(0,m.jsx)(Sa,{children:"No more results."}),(0,m.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,m.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>r(o-1),children:[(0,m.jsx)(ot.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let R=o*p+1,z=o*p+t.length;J=(0,m.jsxs)("div",{children:[B,(0,m.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:E.map((b,Q)=>(0,m.jsxs)("div",{onClick:()=>H(b),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[(0,m.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,m.jsxs)("div",{className:"af-min-w-0",children:[(0,m.jsx)("button",{type:"button",onClick:le=>{le.stopPropagation(),H(b)},"aria-label":`Open ${b.name||b.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:gi(b)}),b.name&&b.email&&(0,m.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:b.email})]}),(0,m.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,m.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:gs(b.last_activity_at)}),b.email&&(0,m.jsx)(P,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,m.jsx)("a",{href:Yn(b.email),onClick:le=>le.stopPropagation(),"aria-label":`Email ${b.email}`,children:(0,m.jsx)(ot.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,m.jsx)("div",{className:"af-mt-2",children:pi(b)}),b.latest_message_excerpt&&(0,m.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:b.latest_message_excerpt})]},b.email??b.submission_id??Q))}),(0,m.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,m.jsxs)(Le,{children:[(0,m.jsx)(Oe,{children:(0,m.jsxs)(be,{children:[(0,m.jsx)(F,{children:"Person"}),(0,m.jsx)(F,{children:"Came from"}),(0,m.jsx)(F,{children:"Latest message"}),(0,m.jsx)(F,{children:"Last activity"}),(0,m.jsx)(F,{className:"af-w-8",children:(0,m.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,m.jsx)(F,{className:"af-w-8"})]})}),(0,m.jsx)(Be,{children:E.map((b,Q)=>(0,m.jsxs)(be,{onClick:()=>H(b),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,m.jsxs)(M,{className:"af-max-w-[260px] af-font-medium",children:[(0,m.jsx)("button",{type:"button",onClick:le=>{le.stopPropagation(),H(b)},"aria-label":`Open ${b.name||b.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:gi(b)}),b.name&&b.email&&(0,m.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:b.email})]}),(0,m.jsx)(M,{children:pi(b)}),(0,m.jsx)(M,{className:"af-max-w-[320px]",children:b.latest_message_excerpt?(0,m.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:b.latest_message_excerpt}):(0,m.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,m.jsx)(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:gs(b.last_activity_at)}),(0,m.jsx)(M,{className:"af-w-8",children:b.email&&(0,m.jsx)(P,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,m.jsx)("a",{href:Yn(b.email),onClick:le=>le.stopPropagation(),"aria-label":`Email ${b.email}`,children:(0,m.jsx)(ot.Mail,{className:"af-h-4 af-w-4"})})})}),(0,m.jsx)(M,{className:"af-w-8 af-text-right",children:(0,m.jsx)(ot.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},b.email??b.submission_id??Q))})]})}),(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,m.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:T==="all"?`Showing ${R}-${z}`:`${E.length} of ${t.length} on this page`}),(0,m.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,m.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>r(o-1),disabled:!x,children:[(0,m.jsx)(ot.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,m.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>r(o+1),disabled:!g,children:["Next",(0,m.jsx)(ot.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return(0,m.jsx)(bt,{title:"Leads",onBackToWebsite:a,hideBackButton:d.kind!=="list",className:s,children:J})}var rs=require("lucide-react");var Et=ne(require("react"),1);function js({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=te(),[t,n]=Et.useState([]),[i,o]=Et.useState(0),[p,g]=Et.useState(!0),[x,r]=Et.useState(null),[y,w]=Et.useState(0),[v,d]=Et.useState(e),[u,h]=Et.useState(void 0),N=Et.useRef(0),T=Et.useCallback(async()=>{let H=++N.current;try{g(!0),r(null);let c={limit:v,offset:y*v};u&&(c.status=u);let S=await s.getSubscriptions(c);if(H!==N.current)return;n(S.subscriptions),o(S.total)}catch(c){if(H!==N.current)return;r(c instanceof Error?c:new Error("Failed to fetch subscriptions"))}finally{H===N.current&&g(!1)}},[s,y,v,u,a]);Et.useEffect(()=>{T()},[T]);let A=Math.ceil(i/v);return{subscriptions:t,total:i,isLoading:p,error:x,page:y,pageSize:v,hasNextPage:y<A-1,hasPreviousPage:y>0,setPage:w,setPageSize:H=>{d(H),w(0)},status:u,setStatus:H=>{h(H),w(0)},refetch:T}}var L=require("react/jsx-runtime");function bi(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function yi({sub:e}){return e.status==="canceled"?(0,L.jsx)(Z,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,L.jsx)(Z,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,L.jsx)(Z,{variant:"warning",children:"Scheduled to cancel"}):(0,L.jsx)(Z,{variant:"success",children:"Active"}):(0,L.jsx)(Z,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function ol(e,a){let s=W(a,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function hi({sub:e}){let a=e.current_amount!==e.plan_amount;return(0,L.jsxs)("div",{children:[(0,L.jsx)("div",{className:"af-font-medium af-tabular-nums",children:ol(e,e.current_amount)}),a&&(0,L.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",W(e.plan_amount,e.currency)]})]})}function xi(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${bi(e.current_period_end)}`:"Ends at period end":e.current_period_end?bi(e.current_period_end):"\u2014"}function Qn({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:p,pageSize:g,hasNextPage:x,hasPreviousPage:r,setPage:y,refetch:w}=js({refreshKey:e}),v;if(i)v=(0,L.jsxs)("div",{children:[(0,L.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(d=>(0,L.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,L.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,L.jsx)(X,{className:"af-h-4 af-w-40"}),(0,L.jsx)(X,{className:"af-h-4 af-w-20"})]}),(0,L.jsx)(X,{className:"af-mt-2 af-h-3 af-w-32"}),(0,L.jsx)(X,{className:"af-mt-2 af-h-5 af-w-24"})]},d))}),(0,L.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,L.jsxs)(Le,{children:[(0,L.jsx)(Oe,{children:(0,L.jsxs)(be,{children:[(0,L.jsx)(F,{children:"Subscriber"}),(0,L.jsx)(F,{children:"Plan"}),(0,L.jsx)(F,{className:"af-text-right",children:"Amount"}),(0,L.jsx)(F,{children:"Renews"}),(0,L.jsx)(F,{children:"Status"})]})}),(0,L.jsx)(Be,{"aria-hidden":"true",children:[0,1,2,3,4].map(d=>(0,L.jsxs)(be,{children:[(0,L.jsx)(M,{children:(0,L.jsx)(X,{className:"af-h-4 af-w-44"})}),(0,L.jsx)(M,{children:(0,L.jsx)(X,{className:"af-h-4 af-w-32"})}),(0,L.jsx)(M,{className:"af-text-right",children:(0,L.jsx)(X,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,L.jsx)(M,{children:(0,L.jsx)(X,{className:"af-h-4 af-w-24"})}),(0,L.jsx)(M,{children:(0,L.jsx)(X,{className:"af-h-5 af-w-20"})})]},d))})]})}),(0,L.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)v=(0,L.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,L.jsx)($t,{message:"Couldn't load your subscriptions.",onRetry:()=>w()})});else if(t.length===0&&p===0)v=(0,L.jsx)(Sa,{icon:(0,L.jsx)(rs.Repeat,{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(t.length===0)v=(0,L.jsxs)("div",{children:[(0,L.jsx)(Sa,{children:"No more results."}),(0,L.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,L.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>y(p-1),children:[(0,L.jsx)(rs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let d=p*g+1,u=p*g+t.length;v=(0,L.jsxs)("div",{children:[(0,L.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(h=>(0,L.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,L.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,L.jsxs)("div",{className:"af-min-w-0",children:[(0,L.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:h.customer_email||(0,L.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,L.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:h.plan_title||"Untitled plan"})]}),(0,L.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,L.jsx)(hi,{sub:h})})]}),(0,L.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,L.jsx)(yi,{sub:h}),h.is_test&&(0,L.jsx)(Z,{variant:"outline",children:"Test"}),(0,L.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:xi(h)})]}),(0,L.jsx)(ha,{deliveries:h.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},h.id))}),(0,L.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,L.jsxs)(Le,{children:[(0,L.jsx)(Oe,{children:(0,L.jsxs)(be,{children:[(0,L.jsx)(F,{children:"Subscriber"}),(0,L.jsx)(F,{children:"Plan"}),(0,L.jsx)(F,{className:"af-text-right",children:"Amount"}),(0,L.jsx)(F,{children:"Renews"}),(0,L.jsx)(F,{children:"Status"})]})}),(0,L.jsx)(Be,{children:t.map(h=>(0,L.jsxs)(be,{children:[(0,L.jsx)(M,{className:"af-max-w-[240px]",children:(0,L.jsx)("div",{className:"af-truncate af-font-medium",children:h.customer_email||(0,L.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,L.jsx)(M,{className:"af-max-w-[220px]",children:(0,L.jsx)("div",{className:"af-truncate",children:h.plan_title||(0,L.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,L.jsx)(M,{className:"af-whitespace-nowrap af-text-right",children:(0,L.jsx)(hi,{sub:h})}),(0,L.jsx)(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:xi(h)}),(0,L.jsxs)(M,{children:[(0,L.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,L.jsx)(yi,{sub:h}),h.is_test&&(0,L.jsx)(Z,{variant:"outline",children:"Test"})]}),(0,L.jsx)(ha,{deliveries:h.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},h.id))})]})}),(0,L.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,L.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${d}-${u} of ${n}`}),(0,L.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,L.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>y(p-1),disabled:!r,children:[(0,L.jsx)(rs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,L.jsxs)(P,{variant:"outline",size:"sm",onClick:()=>y(p+1),disabled:!x,children:["Next",(0,L.jsx)(rs.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,L.jsx)(bt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:v})}var Xn=ne(require("react"),1);var tt=require("react/jsx-runtime");function er({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:p,isLoading:g,error:x,refetch:r}=Xa({refreshKey:e,initialPageSize:1,includeAggregates:!0}),y=ns({refreshKey:e}),[w,v]=Xn.useState(!1),[d,u]=Xn.useState(null),h=(0,tt.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:x||!g&&!p?(0,tt.jsxs)("div",{role:"alert",className:"sm:af-col-span-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't load invoice totals. ",(0,tt.jsx)(P,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):g||!p?(0,tt.jsxs)(tt.Fragment,{children:[(0,tt.jsx)(Ze,{label:"Outstanding",children:(0,tt.jsx)(X,{className:"af-h-6 af-w-24"})}),(0,tt.jsx)(Ze,{label:"Overdue",children:(0,tt.jsx)(X,{className:"af-h-6 af-w-24"})}),(0,tt.jsx)(Ze,{label:"Paid this month",children:(0,tt.jsx)(X,{className:"af-h-6 af-w-24"})})]}):(0,tt.jsxs)(tt.Fragment,{children:[(0,tt.jsx)(Ze,{label:"Outstanding",detail:`${p.outstanding.count} open`,children:W(p.outstanding.amount,p.currency)}),(0,tt.jsx)(Ze,{label:"Overdue",detail:p.overdue.count===0?"Nothing overdue":`${p.overdue.count} overdue`,valueClassName:p.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:W(p.overdue.amount,p.currency)}),(0,tt.jsx)(Ze,{label:"Paid this month",detail:`${p.paid_this_month.count} paid`,children:W(p.paid_this_month.amount,p.currency)})]})});return(0,tt.jsxs)(bt,{title:"Invoices",onBackToWebsite:s,hideBackButton:w,className:o,children:[h,!w&&(0,tt.jsx)(ts,{retainers:y.retainers,isLoading:y.isLoading,error:y.error,onRetry:()=>void y.refetch(),activeRetainerId:d?.id??null,onShowCycles:N=>u(T=>T?.id===N.id?null:N),total:y.total,endedTotal:y.endedTotal,isLoadingMore:y.isLoadingMore,onLoadMore:()=>void y.loadMore(),includeEnded:y.includeEnded,onIncludeEndedChange:y.setIncludeEnded}),(0,tt.jsx)(es,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:v,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:d?{id:d.id,label:`${d.customer_name??d.customer_email??"Recurring invoices"} \u2014 ${d.description}`}:null,onClearRetainerFilter:()=>u(null)})]})}var At=ne(require("react"),1);var ll=2e3,It=()=>({data:null,error:null,isLoading:!0});function Gs(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=te(),[i,o]=At.useState(It),[p,g]=At.useState(It),[x,r]=At.useState(It),[y,w]=At.useState(It),v=B=>Object.fromEntries(B.map(R=>[R,It()])),[d,u]=At.useState(()=>v(s)),h=At.useRef(0),N=s.join(","),T=JSON.stringify(t),A=`${e}:${N}:${T}`,[H,c]=At.useState({api:n,fetchIdentity:A});(H.api!==n||H.fetchIdentity!==A)&&(c({api:n,fetchIdentity:A}),h.current+=1,o(It),g(It),r(It),w(It),u(v(N?N.split(","):[])));let S=At.useCallback(async()=>{let B=++h.current,R=N?N.split(","):[];o(It),g(It),r(It),w(It),u(Object.fromEntries(R.map(Y=>[Y,It()])));let z=(Y,oe)=>oe.then(fe=>{B===h.current&&Y({data:fe,error:null,isLoading:!1})},fe=>{B===h.current&&Y({data:null,error:fe instanceof Error?fe:new Error("Failed to fetch report"),isLoading:!1})}),b=n.getAnalyticsStatus(),Q=z(o,b),le=Symbol("status-timeout"),ce,ee=await Promise.race([b.then(Y=>Y,()=>null),new Promise(Y=>{ce=setTimeout(()=>Y(le),ll)})]);if(clearTimeout(ce),B!==h.current)return;if(ee===le&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),ee!==null&&ee!==le&&(ee.collecting!==!0||ee.first_seen===null&&!ee.first_seen_unavailable||ee.first_seen!==null&&ee.first_seen_in_reports===!1)){let Y={data:null,error:null,isLoading:!1};g(Y),r(Y),w(Y),u(Object.fromEntries(R.map(oe=>[oe,{...Y}]))),await Q;return}await Promise.all([ee===le?Promise.resolve():Q,z(g,n.getAnalyticsSummary(e,t)),z(r,n.getAnalyticsTimeseries(e,t)),z(w,n.getAnalyticsChannels(e,t)),...R.map(Y=>n.getAnalyticsBreakdown(Y,e,t).then(oe=>{B===h.current&&u(fe=>({...fe,[Y]:{data:oe,error:null,isLoading:!1}}))},oe=>{B===h.current&&u(fe=>({...fe,[Y]:{data:null,error:oe instanceof Error?oe:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,N,T]),E=At.useCallback(async()=>{let B=h.current;try{let R=await n.getAnalyticsStatus();if(B!==h.current)return;o({data:R,error:null,isLoading:!1})}catch(R){if(B!==h.current)return;o(z=>({data:z.data,error:R instanceof Error?R:new Error("Failed to fetch status"),isLoading:!1}))}},[n]);At.useEffect(()=>{S()},[S,a]);let J=i.isLoading||p.isLoading||x.isLoading||y.isLoading||Object.values(d).some(B=>B.isLoading);return{status:i,summary:p,timeseries:x,channels:y,breakdowns:d,isLoading:J,refetch:S,refetchStatus:E}}var gt=ne(require("react"),1);var Pn=3e4,Tn=3;function Ws(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=te(),[o,p]=gt.useState(null),[g,x]=gt.useState(null),[r,y]=gt.useState(!1),[w,v]=gt.useState(null),[d,u]=gt.useState(!1),[h,N]=gt.useState(!0),[T,A]=gt.useState(0),H=gt.useRef(0),c=gt.useRef(0),S=gt.useRef(void 0);s!==void 0&&(S.current=s);let E=a?S.current===!0||S.current===void 0&&t:!0,[J,B]=gt.useState({api:i,identity:n}),R=n!==void 0&&n!==J.identity;(J.api!==i||R)&&(S.current=void 0,B({api:i,identity:n}),c.current+=1,H.current=0,p(null),x(null),y(!1),v(null),u(!1),N(!0),A(0));let z=gt.useRef(()=>{}),b=gt.useRef(null),Q=gt.useCallback(async()=>{if(b.current!==null&&b.current===c.current)return;let le=++c.current;b.current=le;try{let ce=await i.getAnalyticsRealtime();if(le!==c.current)return;if(ce.status==="unreachable"){u(!0),y(!0),N(!1),A(ee=>ee+1);return}H.current=0,u(!1),p(ce.data.current_visitors),x(ce.as_of),y(!1),v(null),N(!1),A(ee=>ee+1)}catch(ce){if(le!==c.current)return;H.current+=1,N(!1),A(ee=>ee+1),y(!0),H.current>=Tn&&v(ce instanceof Error?ce:new Error("Realtime unavailable"))}finally{b.current===le&&(b.current=null)}},[i]);return z.current=()=>void Q(),gt.useEffect(()=>{let le,ce=()=>{le===void 0&&(le=setInterval(()=>z.current(),Pn))},ee=()=>{le!==void 0&&(clearInterval(le),le=void 0)},_e=()=>{typeof document<"u"&&document.hidden?ee():(z.current(),ce())};return E?((typeof document>"u"||!document.hidden)&&(z.current(),ce()),document?.addEventListener("visibilitychange",_e),()=>{ee(),document?.removeEventListener("visibilitychange",_e),c.current+=1}):()=>{document?.removeEventListener("visibilitychange",_e)}},[J.api,J.identity,E]),{currentVisitors:o,asOf:g,isStale:r,error:w,isUnreachable:d,isInitialLoad:h,polls:T}}var Ke=ne(require("react"),1);var is=ne(require("react"),1);var cl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function pa(e){let a=Math.abs(e);if(a<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[t,n]of s)if(a>=t){let i=e/t,o=Math.abs(i)<10?Math.round(i*10)/10:Math.round(i);return Math.abs(o)>=1e3&&t!==1e9?pa(o*t):`${o}${n}`}return String(e)}function Cn(e){return`${(e*100).toFixed(1)}%`}function Ks(e){let a=Math.max(0,Math.round(e));if(a<60)return`${a}s`;let s=Math.floor(a/60);return s<60?`${s}m ${a%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function Ni(e){let a=Math.max(0,Math.round(e));return a>=3600&&a%3600===0?`${a/3600}h`:a>=60&&a%60===0?`${a/60}m`:Ks(a)}function Si(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function Ri(e,a){if(!(!Number.isFinite(e)||e<=0))for(let s of a){let t=Math.ceil(e/s);if(t<=5)return Array.from({length:t+1},(n,i)=>Number((i*s).toPrecision(12)))}}function Js(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function _i(e){let a=new Date(e);return Number.isNaN(a.getTime())?"as of an unknown time":`as of ${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}function tr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${cl[a-1]} ${s}`}function wi(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function dl(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Pi(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=wi(e.to,s);for(let o=wi(e.from,s);o<i;o=dl(o))n.push(t.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function Ti(e){let a=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=new Date(`${e}T00:00:00Z`);if(Number.isNaN(t.getTime()))return e;let n=String(t.getUTCDate()).padStart(2,"0");return`${a[t.getUTCDay()]}, ${n} ${s[t.getUTCMonth()]}`}var jt=require("react/jsx-runtime");function Ci({what:e="This report",onRetry:a,collecting:s}){return(0,jt.jsxs)("div",{role:"status",className:"af-flex af-flex-col af-items-center af-gap-1 af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-8 af-text-center",children:[(0,jt.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,jt.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:s===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),a?(0,jt.jsx)("button",{type:"button",onClick:a,className:"af-mt-2 af-rounded-md af-border af-border-border af-px-3 af-py-1 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Try again"}):null]})}function ki({what:e="No data"}){return(0,jt.jsx)("div",{className:"af-flex af-items-center af-justify-center af-rounded-md af-px-4 af-py-8 af-text-center af-text-xs af-text-muted-foreground",children:e})}function Ys({sourced:e,error:a,isLoading:s,what:t,onRetry:n,collecting:i,children:o}){return s?(0,jt.jsx)("div",{role:"status","aria-label":`Loading ${t}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):a?(0,jt.jsx)(Ci,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?(0,jt.jsx)(Ci,{what:t,onRetry:n,collecting:i}):(0,jt.jsx)(jt.Fragment,{children:o(e.data)})}var je=require("react/jsx-runtime");function ar({rows:e,dimension:a,metric:s,metricLabel:t,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:p,maxRows:g=9}){let[x,r]=is.useState(!1);if(e.length===0)return(0,je.jsx)(ki,{what:i});let y=e.reduce((d,u)=>Math.max(d,Number(u[s]??0)),0)||1,w=Math.max(0,e.length-g),v=x?e:e.slice(0,g);return(0,je.jsxs)(je.Fragment,{children:[(0,je.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,je.jsx)("thead",{children:(0,je.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,je.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:a==="pathname"?"Page":"Name"}),(0,je.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:t})]})}),(0,je.jsx)("tbody",{children:v.map((d,u)=>{let h=Number(d[s]??0),N=d[a]??null,T=Js(N),A=n?d[n]:null,H=N!==null&&(p?p(N,A):!0);return(0,je.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,je.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,je.jsx)("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,h/y*100)}%`}}),N!==null&&o&&H?(0,je.jsx)("button",{type:"button",onClick:()=>o(N,A),title:`Filter by ${T}`,"aria-label":`Filter by ${T}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:T}):(0,je.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:T}),A?(0,je.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:A}):null]}),(0,je.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:pa(h)})]},`${T}-${A??""}-${u}`)})})]}),w>0?(0,je.jsx)("button",{type:"button",onClick:()=>r(d=>!d),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:x?"Show fewer":`Show all ${e.length}`}):null]})}function Zs({title:e,tabs:a,defaultTabId:s,headerRight:t}){let[n,i]=is.useState(s),o=a.find(v=>v.id===n)??a[0],p=is.useId(),g=v=>`${p}-tab-${v}`,x=v=>`${p}-panel-${v}`,r=is.useRef(null),y=(v,d)=>{v.preventDefault();let u=(d+a.length)%a.length;i(a[u].id),r.current?.querySelectorAll('[role="tab"]')?.[u]?.focus()};return(0,je.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,je.jsxs)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:[(0,je.jsx)("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:v=>{let d=a.findIndex(u=>u.id===n);v.key==="ArrowRight"&&y(v,d+1),v.key==="ArrowLeft"&&y(v,d-1),v.key==="Home"&&y(v,0),v.key==="End"&&y(v,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(v=>(0,je.jsx)("button",{id:g(v.id),role:"tab",type:"button","aria-selected":v.id===n,"aria-controls":x(v.id),tabIndex:v.id===n?0:-1,onClick:()=>i(v.id),className:v.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:v.label},v.id))}),t]}),o?(0,je.jsx)("div",{id:x(o.id),role:"tabpanel","aria-labelledby":g(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var Dt=ne(require("react"),1),Ga=ne(require("@radix-ui/react-popover"),1);var os=3,ls=100;var Ie=require("react/jsx-runtime"),Qs={channel:"Channel",source:"Source",campaign:"Campaign",utm_source:"UTM source",utm_medium:"UTM medium",utm_content:"UTM content",utm_term:"UTM term",page:"Page",entry_page:"Entry page",exit_page:"Exit page",country:"Country",region:"Region",city:"City",browser:"Browser",os:"Operating system",device:"Device"},ul=Object.keys(Qs);function Ei(e){let a=Qs[e.dimension],s=e.operator==="is_not"?"is not":"is",t=e.values.map(n=>Js(n)).join(" or ");return`${a} ${s} ${t}`}function sr(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));if(s>=0){let t=[...new Set([...e[s].values,...a.values])];return t.length>100||t.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:t}:n)}return a.values.length>100||e.length>=3?e:[...e,a]}function fl(e,a){let s={};for(let[t,n]of Object.entries(a)){let i=e.get(t)??new Set;for(let o of n)i.add(o);e.set(t,i),s[t]=[...i]}return s}function Ii(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));return s>=0?e.map((t,n)=>n===s?a:t):a.values.length>100||e.length>=3?e:[...e,a]}function ml(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Ai(e,a,s,t={}){if(e.api!==a.api||e.period!==a.period)return e.api=a.api,e.period=a.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=fl(e.byDimension,s);for(let[i,o]of Object.entries(t)){let p=e.foldsByLabel.get(i)??new Set;for(let g of o)p.add(g);e.foldsByLabel.set(i,p)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function Di(e){let{filters:a,onChange:s}=e,t=a.length>=3;return Dt.useEffect(()=>{if(a.length===0)return;let n=i=>{let o=i.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||i.key==="Escape"&&s([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[a.length,s]),(0,Ie.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[a.map((n,i)=>(0,Ie.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-1 af-rounded-full af-border af-border-border af-bg-muted af-py-1 af-pl-3 af-pr-1 af-text-xs",children:[(0,Ie.jsx)("span",{className:"af-text-foreground",children:Ei(n)}),(0,Ie.jsx)("button",{type:"button","aria-label":`Remove filter ${Ei(n)}`,onClick:()=>s(a.filter((o,p)=>p!==i)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),(0,Ie.jsx)(pl,{...e,disabled:t}),a.length>0?(0,Ie.jsx)("button",{type:"button",onClick:()=>s([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function pl({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,p]=Dt.useState(!1),g=Dt.useRef(null),[x,r]=Dt.useState(null);Dt.useEffect(()=>{r(g.current?.closest(".aifeatures-admin")??null)},[]);let[y,w]=Dt.useState(null),[v,d]=Dt.useState("is"),[u,h]=Dt.useState(""),[N,T]=Dt.useState([]);Dt.useEffect(()=>{o||(w(null),d("is"),h(""),T([]))},[o]);let A=Dt.useRef(t);A.current!==t&&(A.current=t,o&&p(!1),y!==null&&w(null),N.length>0&&T([]),u!==""&&h(""),v!=="is"&&d("is"));let H=R=>{let z=ml(R);w(z.dimension),T(z.picked),h(z.search),d(z.operator)},S=(y?s[y]??[]:[]).filter(R=>R.toLowerCase().includes(u.trim().toLowerCase())),E=y===null||N.length===0?null:sr(e,{dimension:y,operator:v,values:i?i(y,N):N}),J=E!==null&&E!==e,B=()=>{let R=E;!R||R===e||(a(R),p(!1))};return(0,Ie.jsxs)(Ga.Root,{open:o,onOpenChange:p,children:[(0,Ie.jsx)(Ga.Trigger,{asChild:!0,children:(0,Ie.jsx)("button",{ref:g,type:"button",disabled:!1,title:n?`At most ${3} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),(0,Ie.jsx)(Ga.Portal,{container:x,children:(0,Ie.jsx)(Ga.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:y===null?(0,Ie.jsxs)("div",{children:[(0,Ie.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Ie.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:ul.filter(R=>s[R]!==void 0).map(R=>{let z=s[R]?.length??0,b=!e.some(Q=>Q.dimension===R)&&e.length>=3;return(0,Ie.jsxs)("button",{type:"button",onClick:()=>H(R),disabled:z===0||b,className:"af-flex af-w-full af-items-center af-justify-between af-rounded-md af-px-2 af-py-1.5 af-text-left af-text-xs af-text-foreground hover:af-bg-muted disabled:af-text-muted-foreground disabled:hover:af-bg-transparent",children:[(0,Ie.jsx)("span",{children:Qs[R]}),(0,Ie.jsx)("span",{className:"af-text-muted-foreground",children:z===0?"no data":b?"no room":z})]},R)})})]}):(0,Ie.jsxs)("div",{children:[(0,Ie.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Ie.jsx)("button",{type:"button",onClick:()=>H(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Ie.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Qs[y]}),(0,Ie.jsxs)("select",{"aria-label":"Operator",value:v,onChange:R=>d(R.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,Ie.jsx)("option",{value:"is",children:"is"}),(0,Ie.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Ie.jsx)("input",{type:"text",value:u,onChange:R=>h(R.target.value),placeholder:"Search\u2026","aria-label":`Search ${Qs[y]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),(0,Ie.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:S.length===0?(0,Ie.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",u,"\u201D."]}):S.map(R=>(0,Ie.jsxs)("label",{className:"af-flex af-cursor-pointer af-items-center af-gap-2 af-rounded-md af-px-2 af-py-1.5 af-text-xs af-text-foreground hover:af-bg-muted",children:[(0,Ie.jsx)("input",{type:"checkbox",checked:N.includes(R),disabled:!N.includes(R)&&N.length>=100,onChange:z=>T(b=>z.target.checked?[...b,R]:b.filter(Q=>Q!==R))}),(0,Ie.jsx)("span",{className:"af-break-all",children:Js(R)})]},R))}),(0,Ie.jsx)("button",{type:"button",onClick:B,disabled:!J,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:N.length<=1?"Apply filter":N.length>=100?`Apply filter (${N.length} values \u2014 the maximum)`:`Apply filter (${N.length} values)`})]})})})]})}var Qe=require("react/jsx-runtime"),gl=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:pa,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:pa,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:pa,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:Cn,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Ks,chart:"visit_duration_seconds"}];function vl({current:e,previous:a,downIsGood:s}){if(a===0)return null;let t=(e-a)/a;if(Math.abs(t)<5e-4)return null;let n=t>0,i=s?!n:n,o=`${n?"+":""}${(t*100).toFixed(1)}%`;return(0,Qe.jsx)("span",{className:i?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:o})}function Li({summary:e,selected:a,onSelect:s}){return(0,Qe.jsx)("div",{className:"af-@container",children:(0,Qe.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:gl.map(t=>{let n=t.chart===a,i=s!==void 0,o=(0,Qe.jsxs)(Qe.Fragment,{children:[(0,Qe.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:t.label}),(0,Qe.jsxs)("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[(0,Qe.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?(0,Qe.jsx)(vl,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?(0,Qe.jsx)("button",{type:"button","aria-pressed":n,onClick:()=>s(t.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:o},t.key):(0,Qe.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},t.key)})})})}function nr({currentVisitors:e,asOf:a,isStale:s,isUnreachable:t,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!t)return(0,Qe.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1","aria-hidden":"true",children:[(0,Qe.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,Qe.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return(0,Qe.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?_i(a):"freshness unknown",p=i?" across the whole site, not the current filter,":"",g=s?`${e} current visitors${p} ${o} (not updating)`:`${e} current visitors${p} ${o}`;return(0,Qe.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:g,children:[(0,Qe.jsx)("span",{"aria-hidden":"true",className:s?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),(0,Qe.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,Qe.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),(0,Qe.jsx)("span",{className:"af-sr-only",children:g})]})}var Lt=require("recharts");var at=require("react/jsx-runtime"),kn={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},ir={visitors:pa,visits:pa,pageviews:pa,views_per_visit:e=>e.toFixed(2),bounce_rate:Cn,visit_duration_seconds:Ks},bl=new Set(["visitors","visits","pageviews"]),yl={...ir,bounce_rate:Si,visit_duration_seconds:Ni},rr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],hl=[5,10,15,30,60,120,300,600,900,1800,3600,7200],xl=[.01,.02,.05,.1,.2,.25,.5,1],wl=[.25,.5,1,2,5,10,25,50],Nl={visitors:rr,visits:rr,pageviews:rr,views_per_visit:wl,bounce_rate:xl,visit_duration_seconds:hl};function Sl({active:e,payload:a,label:s,metric:t}){if(!e||!a||a.length===0)return null;let n=a[0].payload;return(0,at.jsxs)("div",{className:"af-rounded-lg af-border af-border-border af-bg-popover af-px-3 af-py-2 af-text-popover-foreground af-shadow-md",children:[(0,at.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:kn[t]}),(0,at.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,at.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,at.jsx)("span",{className:"af-text-muted-foreground",children:Ti(String(s))}),(0,at.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:ir[t](Number(n[t]??0))})]})]})}function Oi({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=Pi(a,e,t),o=ir[s],p=yl[s],g=Ri(i.reduce((r,y)=>Math.max(r,Number(y[s]??0)),0),Nl[s]),x=`${kn[s]} by day: ${i.map(r=>`${tr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return(0,at.jsxs)("figure",{"aria-label":`${kn[s]} over time`,className:"af-m-0",children:[(0,at.jsx)(Lt.ResponsiveContainer,{width:"100%",height:n,children:(0,at.jsxs)(Lt.AreaChart,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,at.jsx)("defs",{children:(0,at.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,at.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,at.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,at.jsx)(Lt.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,at.jsx)(Lt.XAxis,{dataKey:"date",tickFormatter:tr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,at.jsx)(Lt.YAxis,{allowDecimals:!bl.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...g?{ticks:g,domain:[0,g[g.length-1]]}:{},tickFormatter:r=>p(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,at.jsx)(Lt.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,at.jsx)(Sl,{metric:s})}),(0,at.jsx)(Lt.Area,{type:"monotone",dataKey:s,name:kn[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,at.jsx)("figcaption",{className:"af-sr-only",children:x})]})}var me=require("react/jsx-runtime"),Rl=3e4,_l="2026-08-13",Pl=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Tl=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Bi({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,className:n,published:i,lastPublishedAt:o}){let[p,g]=Ke.useState(30),x=e!==void 0&&a!==void 0,[r,y]=Ke.useState(e??[]),{api:w}=te(),[v,d]=Ke.useState(w);v!==w&&(d(w),!x&&r.length>0&&y([]));let u=x?e:r,h=Ke.useCallback(q=>{a&&a(q),x||y(q)},[a,x]),N=Ke.useCallback((q,pe,xe)=>{let de=Array.isArray(pe)?pe:[pe];if(de.length===0)return null;let Ue=sr(u,{dimension:q,operator:"is",values:de});if(xe&&(!xe.value||(Ue=Ii(Ue,{dimension:xe.dimension,operator:"is",values:[xe.value]}),!Ue.find(ge=>ge.dimension===xe.dimension&&ge.operator!=="is_not")?.values.includes(xe.value))))return null;let k=Ue.find(O=>O.dimension===q&&O.operator!=="is_not");return de.every(O=>k?.values.includes(O))?JSON.stringify(Ue)===JSON.stringify(u)?null:Ue:null},[u]),T=Ke.useCallback((q,pe,xe)=>N(q,pe,xe)!==null,[N]),A=Ke.useCallback((q,pe,xe)=>{let de=N(q,pe,xe);de&&h(de)},[N,h]),[H,c]=Ke.useState("visitors"),S=Gs(p,{refreshKey:s,breakdowns:Tl,filters:u}),E=S.status.data,J=E?.collecting===!0&&E.first_seen===null&&!E.first_seen_unavailable,B=E?.collecting===!0&&E.first_seen!==null&&E.first_seen_in_reports===!1,R=J||B,z=Ws({collecting:J?!1:E?.collecting,statusFailed:S.status.error!=null,identity:E?.analytics_id}),b=Ke.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),Q=Ke.useMemo(()=>{let q=S.breakdowns.sources?.data,pe={};if(!q||q.status!=="ok")return pe;for(let xe of q.data){let de=xe.source,Ue=xe.sources;typeof de=="string"&&Array.isArray(Ue)&&Ue.length>0&&(pe[de]=Ue)}return pe},[S.breakdowns.sources?.data]),le=Ke.useMemo(()=>{let q=(de,Ue)=>{let k=S.breakdowns[de]?.data;return!k||k.status!=="ok"?[]:[...new Set(k.data.map(O=>O[Ue]).filter(O=>typeof O=="string"&&O!==""))]};return{channel:S.channels.data?.status==="ok"?[...new Set(S.channels.data.data.map(de=>de.channel))]:[],source:q("sources","source"),campaign:q("utm/campaign","campaign"),page:q("pages","pathname"),entry_page:q("entry-pages","pathname"),exit_page:q("exit-pages","pathname"),country:q("countries","country"),browser:q("browsers","browser"),os:q("operating-systems","os"),device:q("devices","device")}},[S.breakdowns,S.channels.data]),[ce,ee]=Ke.useState({}),_e=JSON.stringify(le),[Y,oe]=Ke.useState(new Map),fe=JSON.stringify(Q);Ke.useEffect(()=>{let{suggestions:q,folds:pe}=Ai(b.current,{api:w,period:p},JSON.parse(_e),JSON.parse(fe));ee(q),oe(pe)},[_e,fe,w,p]);let K=Ke.useCallback((q,pe)=>q!=="source"?pe:[...new Set(pe.flatMap(xe=>{let de=[...Y.get(xe)??[],...Q[xe]??[]];return de.length>0?de:[xe]}))],[Y,Q]),Pe=Ke.useMemo(()=>{let q=[S.summary,S.timeseries,S.channels,...Object.values(S.breakdowns)];for(let pe of q){let xe=pe?.error;if(xe instanceof na&&xe.details?.code==="filter_unsupported")return xe.message}return null},[S.summary,S.timeseries,S.channels,S.breakdowns]),Me=(q,pe,xe,de,Ue,k,O,ge,Je)=>()=>{let ze=S.breakdowns[q];return(0,me.jsx)(Ys,{sourced:ze?.data??null,error:ze?.error,isLoading:ze?.isLoading,what:pe,collecting:E?.collecting,onRetry:S.refetch,children:st=>{let Ye=nt=>ge?K(ge,[nt]):nt;return(0,me.jsx)(ar,{rows:st,dimension:xe,metric:de,metricLabel:Ue,secondary:k,emptyCopy:u.length>0?"No data for this filter":O,canFilter:ge?(nt,Gt)=>T(ge,Ye(nt),Je?{dimension:Je,value:Gt}:void 0):()=>!1,onFilter:ge?(nt,Gt)=>A(ge,Ye(nt),Je?{dimension:Je,value:Gt}:void 0):void 0})}})};Ke.useEffect(()=>{if(!R)return;let q,pe=()=>{q===void 0&&(q=setInterval(()=>void S.refetchStatus(),Rl))},xe=()=>{q!==void 0&&(clearInterval(q),q=void 0)},de=()=>{typeof document<"u"&&document.hidden?xe():(S.refetchStatus(),pe())};return(typeof document>"u"||!document.hidden)&&pe(),document?.addEventListener("visibilitychange",de),()=>{xe(),document?.removeEventListener("visibilitychange",de)}},[R,S.refetchStatus]);let xt=Ke.useRef(void 0);if(Ke.useEffect(()=>{if(!E){xt.current=void 0;return}let q=xt.current;xt.current=R,q===!0&&!R&&S.refetch()},[E,R,S.refetch]),E&&!E.collecting){let q=i===!1,pe=!!o&&String(o).slice(0,10)<_l;return(0,me.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:n,children:(0,me.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,me.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,me.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:q?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":pe?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return J?(0,me.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:n,children:(0,me.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,me.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,me.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:"Your site is set up and analytics is running. The first visit shows up here shortly after someone lands on a published page."})]})}):B?(0,me.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:n,children:(0,me.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,me.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,me.jsxs)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",E?.timezone?` ${E.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,me.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,me.jsx)(nr,{currentVisitors:z.currentVisitors,asOf:z.asOf,isStale:z.isStale,isUnreachable:z.isUnreachable||z.error!==null,isInitialLoad:z.isInitialLoad})})]})}):(0,me.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:n,children:(0,me.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,me.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,me.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Pl.map(q=>(0,me.jsx)("button",{type:"button","aria-pressed":q.value===p,onClick:()=>g(q.value),className:q.value===p?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:q.label},q.value))}),(0,me.jsx)(nr,{currentVisitors:z.currentVisitors,asOf:z.asOf,isStale:z.isStale,isUnreachable:z.isUnreachable||z.error!==null,isInitialLoad:z.isInitialLoad,scopeIsSiteWide:u.length>0})]}),(0,me.jsx)(Di,{filters:u,onChange:h,suggestions:ce,expandValues:K,resetKey:w}),Pe?(0,me.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,me.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,me.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:Pe}),(0,me.jsx)("button",{type:"button",onClick:()=>h([]),className:"af-mt-4 af-rounded-md af-border af-border-border af-px-3 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Clear filters"})]}):null,!Pe&&E?.timezone_defaulted?(0,me.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Reports are shown in UTC. Set a timezone to see them in your local days."}):null,Pe?null:(0,me.jsxs)(me.Fragment,{children:[(0,me.jsx)(Ys,{sourced:S.summary.data,error:S.summary.error,isLoading:S.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:S.refetch,children:q=>(0,me.jsxs)(me.Fragment,{children:[(0,me.jsx)(Li,{summary:q,selected:H,onSelect:c}),q.previous_unavailable?(0,me.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[q.previous_unavailable_reason==="filter"?"No comparison for this filter \u2014 the previous period has too many distinct traffic sources to resolve it. Try a shorter period, or filter by source instead.":"No comparison available right now \u2014 we couldn\u2019t check how far back this site\u2019s history goes. It should return on its own."," ","The numbers above are still for the period you selected."]}):null]})}),(0,me.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,me.jsx)(Ys,{sourced:S.timeseries.data,error:S.timeseries.error,isLoading:S.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:S.refetch,children:q=>{let pe=S.timeseries.data?.status==="ok"?S.timeseries.data.window:{from:"",to:""};return(0,me.jsx)(Oi,{rows:q,window:pe,metric:H,timeZone:(S.timeseries.data?.status==="ok"?S.timeseries.data.timezone:void 0)??E?.timezone??"UTC"})}})}),(0,me.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,me.jsx)(Zs,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,me.jsx)(Ys,{sourced:S.channels.data,error:S.channels.error,isLoading:S.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:S.refetch,children:q=>(0,me.jsx)(ar,{rows:q,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:u.length>0?"No data for this filter":"No data for this period",canFilter:pe=>T("channel",pe),onFilter:pe=>A("channel",pe)})})},{id:"sources",label:"Sources",render:Me("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:Me("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,me.jsx)(Zs,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:Me("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:Me("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:Me("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,me.jsx)(Zs,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:Me("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:Me("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:Me("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,me.jsx)(Zs,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:Me("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:Me("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:Me("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,FormSettings,FormSubmissions,FormsDashboard,FormsList,InvoiceDetail,InvoiceLabelBadge,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,chargedTotal,createApiClient,formatPrice,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useBusinessSummary,useCustomers,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSubmissions,useSubscriptions});
|