@aifeatures/admin-react 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- "use strict";var To=Object.create;var wn=Object.defineProperty;var ko=Object.getOwnPropertyDescriptor;var Eo=Object.getOwnPropertyNames;var Ao=Object.getPrototypeOf,Io=Object.prototype.hasOwnProperty;var Do=(e,a)=>{for(var s in a)wn(e,s,{get:a[s],enumerable:!0})},Kr=(e,a,s,t)=>{if(a&&typeof a=="object"||typeof a=="function")for(let n of Eo(a))!Io.call(e,n)&&n!==s&&wn(e,n,{get:()=>a[n],enumerable:!(t=ko(a,n))||t.enumerable});return e};var ce=(e,a,s)=>(s=e!=null?To(Ao(e)):{},Kr(a||!e||!e.__esModule?wn(s,"default",{value:e,enumerable:!0}):s,e)),Lo=e=>Kr(wn({},"__esModule",{value:!0}),e);var Rc={};Do(Rc,{AifeaturesApiError:()=>Bt,AifeaturesProvider:()=>Yr,AnalyticsView:()=>xo,CustomerDetail:()=>nn,CustomersList:()=>rn,DashboardView:()=>Ro,FormSettings:()=>Zs,FormSubmissions:()=>zs,FormsDashboard:()=>dr,FormsList:()=>Ms,InvoiceDetail:()=>Vn,InvoiceLabelBadge:()=>Ts,InvoicesList:()=>Ka,InvoicesView:()=>Ar,LeadsView:()=>dn,MAX_ANALYTICS_FILTERS:()=>Ns,MAX_ANALYTICS_FILTER_VALUES:()=>Ss,OrderDetail:()=>an,OrderStatusBadge:()=>as,OrdersList:()=>Wa,OrdersView:()=>Rr,PaymentsDashboard:()=>_r,PaymentsSetup:()=>on,ProductSettings:()=>Xs,ProductsList:()=>Ys,ProductsView:()=>Pr,PromosPanel:()=>cs,REALTIME_FAILURES_BEFORE_ERROR:()=>Jn,REALTIME_POLL_MS:()=>Zn,RetainerStatusBadge:()=>Hn,RetainersPanel:()=>ps,SubmissionDetail:()=>$s,SubscriptionsView:()=>kr,VariantsEditor:()=>Qs,ViewShell:()=>bt,WebhookDeliveries:()=>Gs,WebhookSettings:()=>Ks,chargedTotal:()=>Da,createApiClient:()=>Sn,formatPrice:()=>j,isZeroDecimalCurrency:()=>aa,toMajorUnits:()=>mt,toMinorUnits:()=>Ft,useAifeatures:()=>oe,useAifeaturesContext:()=>oe,useAnalytics:()=>hs,useBusinessSummary:()=>bs,useCustomers:()=>sn,useEventDestinations:()=>js,useForms:()=>os,useInvoices:()=>ms,useOrders:()=>en,usePaymentsStatus:()=>za,usePeople:()=>cn,usePerson:()=>un,useProducts:()=>gs,useRealtimeVisitors:()=>mn,useRetainers:()=>vs,useSubmissions:()=>Vs,useSubscriptions:()=>fn});module.exports=Lo(Rc);var Qa=ce(require("react"),1);var rr="aifeatures:analytics:timezone",ir;function Os(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function Zr(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function is(){return or()??Os()}function or(){if(ir!==void 0)return ir;try{let e=window.localStorage.getItem(rr);return Zr(e)?e:null}catch{return null}}function lr(e){if(!(e!==null&&!Zr(e))){ir=e;try{e===null?window.localStorage.removeItem(rr):window.localStorage.setItem(rr,e)}catch{}}}function Nn(e,a){let s=new URLSearchParams({period:String(e)}),t=is();return t&&s.set("timezone",t),a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var Bt=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function cr(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 Sn(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 Bt(cr(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,f=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(g)}`,p=await fetch(f,{headers:{Authorization:`Bearer ${e}`}});if(!p.ok){let h;try{h=await p.json()}catch{}throw new Bt(cr(h?.error,p.status),p.status,h)}let r=await p.blob(),y=URL.createObjectURL(r),x=document.createElement("a");x.href=y,x.download=o,document.body.appendChild(x),x.click(),document.body.removeChild(x),URL.revokeObjectURL(y)},async getPaymentsStatus(){return s("/api/v1/payments/status")},getPromos(t){let n=new URLSearchParams({limit:"10"});return t&&n.set("cursor",t),s(`/api/v1/promos?${n}`)},getPromo(t){return s(`/api/v1/promos/${encodeURIComponent(t)}`)},createPromo(t){return s("/api/v1/promos",{method:"POST",body:JSON.stringify(t)})},disablePromo(t){return s(`/api/v1/promos/${encodeURIComponent(t)}/disable`,{method:"POST"})},replacePromo(t,n){return s(`/api/v1/promos/${encodeURIComponent(t)}/replace`,{method:"POST",body:JSON.stringify(n)})},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 Bt(cr(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(){let t=new URLSearchParams,n=is();n&&t.set("timezone",n);let i=t.toString();return s(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(t,n){return s(`/api/v1/analytics/summary?${Nn(t,n)}`)},async getAnalyticsTimeseries(t,n){return s(`/api/v1/analytics/timeseries?${Nn(t,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(t,n){return s(`/api/v1/analytics/channels?${Nn(t,n)}`)},async getAnalyticsConversions(t){return s((()=>{let n=new URLSearchParams({period:String(t)}),i=is();return i&&n.set("timezone",i),`/api/v1/analytics/conversions?${n.toString()}`})())},async getAnalyticsBreakdown(t,n,i){let o=t.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${Nn(n,i)}`)},async getBusinessSummary(t){let n=new URLSearchParams;n.set("tz_offset_minutes",String(t.tzOffsetMinutes));let i=is();return i&&n.set("timezone",i),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 Ya=require("react/jsx-runtime"),Jr=Qa.createContext(null);function Oo(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 Yr({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=Qa.useMemo(()=>Oo(e),[e]),o=Qa.useMemo(()=>Sn(e,a),[e,a]),g=Qa.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?(0,Ya.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:(0,Ya.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Ya.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Ya.jsx)("p",{className:"af-text-sm af-text-destructive",children:i})]})}):(0,Ya.jsx)(Jr.Provider,{value:g,children:(0,Ya.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function oe(){let e=Qa.useContext(Jr);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var ts=ce(require("react"),1),_s=require("lucide-react");var _n=ce(require("react"),1),ba=ce(require("@radix-ui/react-tabs"),1);var Qr=require("clsx"),Xr=require("tailwind-merge"),Bo=(0,Xr.extendTailwindMerge)({prefix:"af-"});function X(...e){return Bo((0,Qr.clsx)(e))}var Pn=require("react/jsx-runtime"),Rn=ba.Root,Bs=_n.forwardRef(({className:e,...a},s)=>(0,Pn.jsx)(ba.List,{ref:s,className:X("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=ba.List.displayName;var ya=_n.forwardRef(({className:e,...a},s)=>(0,Pn.jsx)(ba.Trigger,{ref:s,className:X("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}));ya.displayName=ba.Trigger.displayName;var ha=_n.forwardRef(({className:e,...a},s)=>(0,Pn.jsx)(ba.Content,{ref:s,className:X("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}));ha.displayName=ba.Content.displayName;var ei=ce(require("react"),1),ti=require("@radix-ui/react-slot"),ai=require("class-variance-authority");var si=require("react/jsx-runtime"),Fo=(0,ai.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"}}),_=ei.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>(0,si.jsx)(t?ti.Slot:"button",{className:X(Fo({variant:a,size:s,className:e})),ref:i,...n}));_.displayName="Button";var Fs=require("lucide-react");var $a=ce(require("react"),1);var Ta=require("react/jsx-runtime"),Ue=$a.forwardRef(({className:e,...a},s)=>(0,Ta.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,Ta.jsx)("table",{ref:s,className:X("af-w-full af-caption-bottom af-text-sm",e),...a})}));Ue.displayName="Table";var Ve=$a.forwardRef(({className:e,...a},s)=>(0,Ta.jsx)("thead",{ref:s,className:X("[&_tr]:af-border-b",e),...a}));Ve.displayName="TableHeader";var $e=$a.forwardRef(({className:e,...a},s)=>(0,Ta.jsx)("tbody",{ref:s,className:X("[&_tr:last-child]:af-border-0",e),...a}));$e.displayName="TableBody";var Mo=$a.forwardRef(({className:e,...a},s)=>(0,Ta.jsx)("tfoot",{ref:s,className:X("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...a}));Mo.displayName="TableFooter";var he=$a.forwardRef(({className:e,...a},s)=>(0,Ta.jsx)("tr",{ref:s,className:X("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));he.displayName="TableRow";var V=$a.forwardRef(({className:e,...a},s)=>(0,Ta.jsx)("th",{ref:s,className:X("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}));V.displayName="TableHead";var $=$a.forwardRef(({className:e,...a},s)=>(0,Ta.jsx)("td",{ref:s,className:X("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));$.displayName="TableCell";var Uo=$a.forwardRef(({className:e,...a},s)=>(0,Ta.jsx)("caption",{ref:s,className:X("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));Uo.displayName="TableCaption";var xa=ce(require("react"),1);function os(){let{api:e}=oe(),[a,s]=xa.useState([]),[t,n]=xa.useState(!0),[i,o]=xa.useState(null),g=xa.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]);xa.useEffect(()=>{g()},[g]);let f=xa.useCallback(async y=>{let x=await e.createForm(y);return s(h=>[...h,x]),x},[e]),p=xa.useCallback(async(y,x)=>{let h=await e.updateForm(y,x);return s(u=>u.map(l=>l.id===y?h:l)),h},[e]),r=xa.useCallback(async y=>{await e.deleteForm(y),s(x=>x.filter(h=>h.id!==y))},[e]);return{forms:a,isLoading:t,error:i,refetch:g,createForm:f,updateForm:p,deleteForm:r}}var He=require("react/jsx-runtime");function Ms({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=os();return t?(0,He.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,He.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,He.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,He.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?(0,He.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[(0,He.jsx)(Fs.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,He.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,He.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,He.jsx)("div",{className:a,children:(0,He.jsxs)(Ue,{children:[(0,He.jsx)(Ve,{children:(0,He.jsxs)(he,{children:[(0,He.jsx)(V,{children:"Name"}),(0,He.jsx)(V,{children:"Endpoint"}),(0,He.jsx)(V,{className:"af-text-right",children:"Actions"})]})}),(0,He.jsx)($e,{children:s.map(i=>(0,He.jsxs)(he,{children:[(0,He.jsx)($,{className:"af-font-medium",children:i.name}),(0,He.jsx)($,{children:(0,He.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,He.jsx)($,{className:"af-text-right",children:(0,He.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,He.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[(0,He.jsx)(Fs.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,He.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[(0,He.jsx)(Fs.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}var ii=require("lucide-react");var ni=require("class-variance-authority");var ri=require("react/jsx-runtime"),Vo=(0,ni.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 ae({className:e,variant:a,...s}){return(0,ri.jsx)("div",{className:X(Vo({variant:a}),e),...s})}var Yt=require("react/jsx-runtime"),$o={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 Cn(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 ur(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function Ho(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 Us({deliveries:e,label:a="Email needs attention"}){return ur(e)?(0,Yt.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,Yt.jsx)(ii.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function ka({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||ur([n]));return t.length?(0,Yt.jsx)("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:t.map(n=>{let i=Cn(n),o=Ho(n);return(0,Yt.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Yt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Yt.jsx)("span",{className:"af-font-medium",children:$o[n.kind]??"Email notification"}),(0,Yt.jsx)(ae,{variant:i.variant,children:i.label})]}),(0,Yt.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&&ur([n])&&(0,Yt.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,Yt.jsx)("p",{className:"af-mt-1",children:i.detail}),o&&(0,Yt.jsx)("p",{className:"af-mt-1",children:o})]},n.id)})}):null}var Hs=ce(require("react"),1),Ea=require("lucide-react");var Xa=ce(require("react"),1),Ce=ce(require("@radix-ui/react-select"),1),ls=require("lucide-react");var ft=require("react/jsx-runtime"),ca=Ce.Root;var ua=Ce.Value,Qt=Xa.forwardRef(({className:e,children:a,...s},t)=>(0,ft.jsxs)(Ce.Trigger,{ref:t,className:X("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,ft.jsx)(Ce.Icon,{asChild:!0,children:(0,ft.jsx)(ls.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Qt.displayName=Ce.Trigger.displayName;var oi=Xa.forwardRef(({className:e,...a},s)=>(0,ft.jsx)(Ce.ScrollUpButton,{ref:s,className:X("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:(0,ft.jsx)(ls.ChevronUp,{className:"af-h-4 af-w-4"})}));oi.displayName=Ce.ScrollUpButton.displayName;var li=Xa.forwardRef(({className:e,...a},s)=>(0,ft.jsx)(Ce.ScrollDownButton,{ref:s,className:X("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:(0,ft.jsx)(ls.ChevronDown,{className:"af-h-4 af-w-4"})}));li.displayName=Ce.ScrollDownButton.displayName;var Xt=Xa.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>(0,ft.jsx)(Ce.Portal,{children:(0,ft.jsxs)(Ce.Content,{ref:n,className:X("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,ft.jsx)(oi,{}),(0,ft.jsx)(Ce.Viewport,{className:X("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,ft.jsx)(li,{})]})}));Xt.displayName=Ce.Content.displayName;var zo=Xa.forwardRef(({className:e,...a},s)=>(0,ft.jsx)(Ce.Label,{ref:s,className:X("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));zo.displayName=Ce.Label.displayName;var Je=Xa.forwardRef(({className:e,children:a,...s},t)=>(0,ft.jsxs)(Ce.Item,{ref:t,className:X("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,ft.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,ft.jsx)(Ce.ItemIndicator,{children:(0,ft.jsx)(ls.Check,{className:"af-h-4 af-w-4"})})}),(0,ft.jsx)(Ce.ItemText,{children:a})]}));Je.displayName=Ce.Item.displayName;var qo=Xa.forwardRef(({className:e,...a},s)=>(0,ft.jsx)(Ce.Separator,{ref:s,className:X("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));qo.displayName=Ce.Separator.displayName;var da=ce(require("react"),1);function Vs({formId:e,initialPageSize:a=25}){let{api:s}=oe(),[t,n]=da.useState([]),[i,o]=da.useState(0),[g,f]=da.useState(!0),[p,r]=da.useState(null),[y,x]=da.useState(0),[h,u]=da.useState(a),l=da.useCallback(async()=>{if(e)try{f(!0),r(null);let S={limit:h,offset:y*h},O=await s.getSubmissions(e,S);n(O.submissions),o(O.total)}catch(S){r(S instanceof Error?S:new Error("Failed to fetch submissions"))}finally{f(!1)}},[s,e,y,h]);da.useEffect(()=>{l()},[l]);let v=da.useCallback(async S=>{await s.deleteSubmission(S),n(O=>O.filter(F=>F.id!==S)),o(O=>O-1)},[s]),N=Math.ceil(i/h);return{submissions:t,total:i,isLoading:g,error:p,page:y,pageSize:h,hasNextPage:y<N-1,hasPreviousPage:y>0,setPage:x,setPageSize:S=>{u(S),x(0)},refetch:l,deleteSubmission:v}}var ui=ce(require("react"),1),Dt=require("lucide-react");var xe=require("react/jsx-runtime");function ci(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function jo(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 $s({submission:e,onBack:a}){let{api:s}=oe(),[t,n]=ui.useState(null),i=f=>f.id??f.name,o=async f=>{n(i(f));try{await s.downloadAttachment(e.id,f)}catch(p){console.error("Download failed:",p)}finally{n(null)}},g=Object.entries(e.data).filter(([f])=>!f.startsWith("_"));return(0,xe.jsxs)("div",{children:[(0,xe.jsxs)("div",{className:"af-mb-6",children:[(0,xe.jsxs)(_,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,xe.jsx)(Dt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,xe.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,xe.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",ci(e.metadata.submitted_at)]})]}),(0,xe.jsxs)("div",{className:"af-space-y-6",children:[(0,xe.jsx)(ka,{deliveries:e.email_deliveries}),(0,xe.jsxs)("div",{children:[(0,xe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,xe.jsxs)("div",{className:"af-space-y-3",children:[g.map(([f,p])=>(0,xe.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,xe.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:f.replace(/_/g," ")}),(0,xe.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof p=="string"&&p.includes(`
3
- `)?(0,xe.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:p}):String(p)})]},f)),g.length===0&&(0,xe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,xe.jsxs)("div",{children:[(0,xe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,xe.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((f,p)=>(0,xe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,xe.jsx)(Dt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,xe.jsx)("span",{className:"af-text-sm",children:f.name}),(0,xe.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",jo(f.size),")"]})]}),(0,xe.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>o(f),disabled:t===i(f),children:[t===i(f)?(0,xe.jsx)(Dt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,xe.jsx)(Dt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(f)?"Downloading...":"Download"]})]},p))})]}),(0,xe.jsxs)("div",{children:[(0,xe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,xe.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Dt.Clock,{className:"af-h-4 af-w-4"}),(0,xe.jsx)("span",{children:ci(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Dt.Globe,{className:"af-h-4 af-w-4"}),(0,xe.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,xe.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Dt.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,xe.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Dt.Mail,{className:"af-h-4 af-w-4"}),(0,xe.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var me=require("react/jsx-runtime");function Wo(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Go(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 Ko(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 zs({formId:e,className:a,defaultSubmissionId:s}){let{submissions:t,total:n,isLoading:i,error:o,page:g,pageSize:f,hasNextPage:p,hasPreviousPage:r,setPage:y,setPageSize:x}=Vs({formId:e}),[h,u]=Hs.useState("list"),[l,v]=Hs.useState(null);Hs.useEffect(()=>{if(s&&t.length>0){let c=t.find(A=>A.id===s);c&&(v(c),u("detail"))}},[s,t]);let N=c=>{v(c),u("detail")},S=()=>{u("list"),v(null)};if(h==="detail"&&l)return(0,me.jsx)("div",{className:a,children:(0,me.jsx)($s,{submission:l,onBack:S})});if(i)return(0,me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,me.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(o)return(0,me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,me.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(t.length===0&&g===0)return(0,me.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[(0,me.jsx)(Ea.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,me.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,me.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let O=g*f+1,F=Math.min((g+1)*f,n);return(0,me.jsxs)("div",{className:a,children:[(0,me.jsxs)(Ue,{children:[(0,me.jsx)(Ve,{children:(0,me.jsxs)(he,{children:[(0,me.jsx)(V,{children:"Email"}),(0,me.jsx)(V,{children:"Preview"}),(0,me.jsx)(V,{children:"Date"}),(0,me.jsx)(V,{className:"af-text-right",children:"Actions"})]})}),(0,me.jsx)($e,{children:t.map(c=>{let A=Go(c.data),D=Ko(c.data);return(0,me.jsxs)(he,{children:[(0,me.jsxs)($,{className:"af-font-medium",children:[(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[A||(0,me.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),c.attachments.length>0&&(0,me.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${c.attachments.length} attachment(s)`,children:[(0,me.jsx)(Ea.Paperclip,{className:"af-h-3 af-w-3"}),(0,me.jsx)("span",{className:"af-text-xs",children:c.attachments.length})]})]}),(0,me.jsx)(Us,{deliveries:c.email_deliveries,label:"Notification email needs attention"})]}),(0,me.jsx)($,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:D||(0,me.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,me.jsx)($,{className:"af-text-muted-foreground",children:Wo(c.metadata.submitted_at)}),(0,me.jsx)($,{className:"af-text-right",children:(0,me.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>N(c),title:"View details",children:(0,me.jsx)(Ea.Eye,{className:"af-h-4 af-w-4"})})})]},c.id)})})]}),(0,me.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,me.jsxs)("span",{children:["Showing ",O,"-",F," of ",n]}),(0,me.jsxs)(ca,{value:String(f),onValueChange:c=>x(Number(c)),children:[(0,me.jsx)(Qt,{className:"af-w-[70px] af-h-8",children:(0,me.jsx)(ua,{})}),(0,me.jsxs)(Xt,{children:[(0,me.jsx)(Je,{value:"10",children:"10"}),(0,me.jsx)(Je,{value:"25",children:"25"}),(0,me.jsx)(Je,{value:"50",children:"50"}),(0,me.jsx)(Je,{value:"100",children:"100"})]})]}),(0,me.jsx)("span",{children:"per page"})]}),(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,me.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>y(g-1),disabled:!r,children:[(0,me.jsx)(Ea.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,me.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>y(g+1),disabled:!p,children:["Next",(0,me.jsx)(Ea.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var ta=ce(require("react"),1),es=require("lucide-react");var di=ce(require("react"),1);var fi=require("react/jsx-runtime"),we=di.forwardRef(({className:e,type:a,...s},t)=>(0,fi.jsx)("input",{type:a,className:X("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}));we.displayName="Input";var mi=ce(require("react"),1),pi=require("class-variance-authority");var gi=require("react/jsx-runtime"),Zo=(0,pi.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),_e=mi.forwardRef(({className:e,...a},s)=>(0,gi.jsx)("label",{ref:s,className:X(Zo(),e),...a}));_e.displayName="Label";var fa=ce(require("react"),1),Lt=require("lucide-react");var qs=ce(require("react"),1),wt=ce(require("@radix-ui/react-dialog"),1),vi=require("lucide-react");var qt=require("react/jsx-runtime"),Aa=wt.Root;var Jo=wt.Portal;var bi=qs.forwardRef(({className:e,...a},s)=>(0,qt.jsx)(wt.Overlay,{ref:s,className:X("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));bi.displayName=wt.Overlay.displayName;var wa=qs.forwardRef(({className:e,children:a,...s},t)=>(0,qt.jsx)(Jo,{children:(0,qt.jsxs)("div",{className:"aifeatures-admin",children:[(0,qt.jsx)(bi,{}),(0,qt.jsxs)(wt.Content,{ref:t,className:X("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,qt.jsxs)(wt.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,qt.jsx)(vi.X,{className:"af-h-4 af-w-4"}),(0,qt.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));wa.displayName=wt.Content.displayName;var Na=({className:e,...a})=>(0,qt.jsx)("div",{className:X("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...a});Na.displayName="DialogHeader";var Sa=({className:e,...a})=>(0,qt.jsx)("div",{className:X("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...a});Sa.displayName="DialogFooter";var _a=qs.forwardRef(({className:e,...a},s)=>(0,qt.jsx)(wt.Title,{ref:s,className:X("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));_a.displayName=wt.Title.displayName;var Ra=qs.forwardRef(({className:e,...a},s)=>(0,qt.jsx)(wt.Description,{ref:s,className:X("af-text-sm af-text-muted-foreground",e),...a}));Ra.displayName=wt.Description.displayName;var ea=ce(require("react"),1);function js(){let{api:e}=oe(),[a,s]=ea.useState([]),[t,n]=ea.useState(!0),[i,o]=ea.useState(null),g=ea.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(h){o(h instanceof Error?h:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);ea.useEffect(()=>{g()},[g]);let f=ea.useCallback(async h=>{let u=await e.createEventDestination(h);return s(l=>[u,...l]),u},[e]),p=ea.useCallback(async(h,u)=>{let l=await e.updateEventDestination(h,u);return s(v=>v.map(N=>N.id===h?l:N)),l},[e]),r=ea.useCallback(async h=>{await e.deleteEventDestination(h),s(u=>u.filter(l=>l.id!==h))},[e]),y=ea.useCallback(async h=>{let u=await e.rotateEventDestinationSecret(h);return s(l=>l.map(v=>v.id===h?u:v)),u},[e]),x=ea.useCallback(h=>e.getEventDestinationSecret(h),[e]);return{destinations:a,isLoading:t,error:i,refetch:g,createDestination:f,updateDestination:p,deleteDestination:r,rotateSecret:y,getSecret:x}}var Ha=ce(require("react"),1),Ws=require("lucide-react");var Nt=require("react/jsx-runtime");function Gs({destinationId:e,limit:a=25,className:s}){let{api:t}=oe(),[n,i]=Ha.useState([]),[o,g]=Ha.useState(!0),[f,p]=Ha.useState(null),[r,y]=Ha.useState(null),x=Ha.useCallback(async()=>{try{g(!0),p(null),i(await t.getEventDeliveries(e,a))}catch(u){p(u instanceof Error?u.message:"Failed to load deliveries")}finally{g(!1)}},[t,e,a]);Ha.useEffect(()=>{x()},[x]);let h=async u=>{try{y(u.id),p(null);let l=await t.retryEventDelivery(e,u.id);i(v=>v.map(N=>N.id===u.id?l:N))}catch(l){p(l instanceof Error?l.message:"Retry failed")}finally{y(null)}};return o?(0,Nt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,Nt.jsx)(Ws.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):f?(0,Nt.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:f}):n.length===0?(0,Nt.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,Nt.jsx)("div",{className:s,children:(0,Nt.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(u=>{let l=u.delivered_at!==null;return(0,Nt.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,Nt.jsxs)("div",{className:"af-min-w-0",children:[(0,Nt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[l?(0,Nt.jsx)(ae,{variant:"secondary",children:u.last_status??200}):(0,Nt.jsx)(ae,{variant:"destructive",children:u.last_status??"failed"}),(0,Nt.jsx)("span",{className:"af-text-sm af-truncate",children:u.type})]}),(0,Nt.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"}`]}),!l&&u.last_error&&(0,Nt.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),(0,Nt.jsx)(_,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===u.id,onClick:()=>h(u),children:r===u.id?(0,Nt.jsx)(Ws.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Nt.jsx)(Ws.RotateCw,{className:"af-h-4 af-w-4"})})]},u.id)})})})}var fe=require("react/jsx-runtime");function Ks({formId:e,topics:a,description:s,className:t}){let{destinations:n,isLoading:i,error:o,createDestination:g,updateDestination:f,deleteDestination:p,rotateSecret:r,getSecret:y}=js(),[x,h]=fa.useState(""),[u,l]=fa.useState(!1),[v,N]=fa.useState(null),[S,O]=fa.useState(null),[F,c]=fa.useState(null),[A,D]=fa.useState(!1),[te,P]=fa.useState(null),[E,U]=fa.useState(null),[w,Z]=fa.useState(null),ee=fa.useMemo(()=>n.filter(J=>J.form_id===e),[n,e]),q=async()=>{let J=x.trim();if(J){if(!J.startsWith("https://")){N("Webhook URLs must start with https://");return}try{l(!0),N(null),await g({url:J,form_id:e,...a&&a.length>0?{topics:a}:{}}),h("")}catch(Re){N(Re instanceof Error?Re.message:"Failed to add webhook")}finally{l(!1)}}},de=async J=>{try{U(J.id),N(null),await r(J.id),D(!1),c(await y(J.id))}catch(Re){N(Re instanceof Error?Re.message:"Failed to rotate secret")}finally{U(null)}},K=async J=>{try{U(J.id),N(null),await f(J.id,{status:"active"})}catch(Re){N(Re instanceof Error?Re.message:"Failed to re-enable")}finally{U(null)}},Q=async()=>{if(te)try{U(te.id),await p(te.id),P(null)}catch(J){N(J instanceof Error?J.message:"Failed to delete")}finally{U(null)}},G=async J=>{if(S===J.id){O(null),c(null);return}try{U(J.id),N(null),D(!1),O(J.id),c(await y(J.id))}catch(Re){O(null),N(Re instanceof Error?Re.message:"Failed to read secret")}finally{U(null)}},ie=async()=>{if(F)try{await navigator.clipboard.writeText(F),D(!0)}catch{}};return(0,fe.jsxs)("div",{className:t,children:[(0,fe.jsxs)("div",{className:"af-space-y-1",children:[(0,fe.jsx)(_e,{children:"Webhooks"}),(0,fe.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,fe.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,fe.jsx)(we,{value:x,placeholder:"https://hooks.zapier.com/...",onChange:J=>h(J.target.value),onKeyDown:J=>{J.key==="Enter"&&(J.preventDefault(),q())},disabled:u}),(0,fe.jsxs)(_,{onClick:q,disabled:u||!x.trim(),children:[u?(0,fe.jsx)(Lt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,fe.jsx)(Lt.Plus,{className:"af-h-4 af-w-4"}),(0,fe.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(v||o)&&(0,fe.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:v||o?.message}),(0,fe.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[i&&(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,fe.jsx)(Lt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&ee.length===0&&(0,fe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),ee.map(J=>(0,fe.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,fe.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,fe.jsxs)("div",{className:"af-min-w-0",children:[(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,fe.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:J.url}),J.status==="disabled"?(0,fe.jsx)(ae,{variant:"destructive",children:"Disabled"}):(0,fe.jsx)(ae,{variant:"secondary",children:"Active"})]}),(0,fe.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:J.topics.includes("*")?"All events":J.topics.join(", ")})]}),(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,fe.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>Z(w===J.id?null:J.id),children:w===J.id?"Hide log":"Deliveries"}),(0,fe.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>G(J),disabled:E===J.id,children:S===J.id?"Hide secret":"Show secret"}),(0,fe.jsx)(_,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:E===J.id,onClick:()=>P(J),children:(0,fe.jsx)(Lt.Trash2,{className:"af-h-4 af-w-4"})})]})]}),J.status==="disabled"&&(0,fe.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,fe.jsx)(Lt.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,fe.jsxs)("div",{className:"af-text-sm",children:[(0,fe.jsxs)("p",{children:["We stopped sending after repeated failures."," ",J.disabled_reason]}),(0,fe.jsx)(_,{variant:"outline",size:"sm",className:"af-mt-2",disabled:E===J.id,onClick:()=>K(J),children:"Re-enable"})]})]}),S===J.id&&F&&(0,fe.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,fe.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,fe.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,fe.jsx)(we,{readOnly:!0,value:F,className:"af-font-mono"}),(0,fe.jsx)(_,{variant:"outline",title:"Copy signing secret",onClick:ie,children:A?(0,fe.jsx)(Lt.Check,{className:"af-h-4 af-w-4"}):(0,fe.jsx)(Lt.Copy,{className:"af-h-4 af-w-4"})}),(0,fe.jsx)(_,{variant:"outline",title:"Rotate signing secret",disabled:E===J.id,onClick:()=>de(J),children:E===J.id?(0,fe.jsx)(Lt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,fe.jsx)(Lt.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),w===J.id&&(0,fe.jsx)(Gs,{destinationId:J.id})]},J.id))]}),(0,fe.jsx)(Aa,{open:!!te,onOpenChange:J=>{!J&&!E&&P(null)},children:(0,fe.jsxs)(wa,{children:[(0,fe.jsxs)(Na,{children:[(0,fe.jsx)(_a,{children:"Delete this webhook?"}),(0,fe.jsxs)(Ra,{children:["New submissions will stop being sent to ",te?.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,fe.jsxs)(Sa,{children:[(0,fe.jsx)(_,{variant:"outline",onClick:()=>P(null),disabled:!!E,children:"Cancel"}),(0,fe.jsx)(_,{variant:"destructive",onClick:Q,disabled:!!E,children:E?"Deleting...":"Delete"})]})]})})]})}var Se=require("react/jsx-runtime");function Zs({form:e,onSaved:a,className:s}){let{updateForm:t}=os(),[n,i]=ta.useState(!1),[o,g]=ta.useState(null),[f,p]=ta.useState(null),[r,y]=ta.useState(e.name),[x,h]=ta.useState(e.redirect_url||""),[u,l]=ta.useState(e.email_recipients),[v,N]=ta.useState("");ta.useEffect(()=>{y(e.name),h(e.redirect_url||""),l(e.email_recipients),p(null)},[e]);let S=ta.useCallback(async D=>{try{i(!0),p(null);let te=await t(e.id,D);g(new Date),a?.(te)}catch(te){p(te instanceof Error?te.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);ta.useEffect(()=>{if(o){let D=setTimeout(()=>g(null),2e3);return()=>clearTimeout(D)}},[o]);let O=async()=>{let D=v.trim().toLowerCase();if(!D)return;if(!D.includes("@")){p("Please enter a valid email address");return}if(u.includes(D)){p("This email is already added");return}let te=[...u,D];l(te),N(""),p(null),await S({email_recipients:te})},F=async D=>{let te=u.filter(P=>P!==D);l(te),await S({email_recipients:te})},c=async()=>{r!==e.name&&await S({name:r})},A=async()=>{let D=x||null;D!==e.redirect_url&&await S({redirect_url:D})};return(0,Se.jsxs)("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&(0,Se.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,Se.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,Se.jsx)(es.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,Se.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,Se.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,Se.jsx)(es.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,Se.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{htmlFor:"form-name",children:"Form Name"}),(0,Se.jsx)(we,{id:"form-name",value:r,onChange:D=>y(D.target.value),onBlur:c,placeholder:"Contact Form"}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{children:"Email Recipients"}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,Se.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(D=>(0,Se.jsxs)(ae,{variant:"secondary",className:"af-gap-1",children:[D,(0,Se.jsx)("button",{type:"button",onClick:()=>F(D),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,Se.jsx)(es.X,{className:"af-h-3 af-w-3"})})]},D)),u.length===0&&(0,Se.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,Se.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Se.jsx)(we,{type:"email",value:v,onChange:D=>N(D.target.value),placeholder:"Add email address",onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),O())},disabled:n}),(0,Se.jsx)(_,{type:"button",variant:"outline",onClick:O,disabled:!v.trim()||n,children:(0,Se.jsx)(es.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,Se.jsx)(we,{id:"redirect-url",value:x,onChange:D=>h(D.target.value),onBlur:A,placeholder:"/thank-you"}),(0,Se.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,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{children:"Form Endpoint"}),(0,Se.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Se.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,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{children:"Captcha Protection"}),(0,Se.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Se.jsx)(ae,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,Se.jsx)(Ks,{formId:e.id}),f&&(0,Se.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f})]})}var je=require("react/jsx-runtime");function dr({className:e,submissionId:a}){let{api:s}=oe(),[t,n]=ts.useState("list"),[i,o]=ts.useState(null),[g,f]=ts.useState("submissions"),[p,r]=ts.useState(a),[y,x]=ts.useState(!!a);ts.useEffect(()=>{if(!a)return;async function v(){try{let N=await s.getSubmission(a),S=await s.getForm(N.form_id);o(S),n("detail"),f("submissions"),r(a)}catch(N){console.error("Failed to load submission for deep link:",N)}finally{x(!1)}}v()},[a,s]);let h=(v,N)=>{o(v),n("detail"),f(N),r(void 0)},u=()=>{n("list"),o(null),r(void 0)},l=v=>{o(v)};return y?(0,je.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,je.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,je.jsxs)("div",{className:e,children:[t==="list"&&(0,je.jsxs)("div",{children:[(0,je.jsxs)("div",{className:"af-mb-6",children:[(0,je.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,je.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,je.jsx)(Ms,{onSelectForm:h})]}),t==="detail"&&i&&(0,je.jsxs)("div",{children:[(0,je.jsxs)("div",{className:"af-mb-6",children:[(0,je.jsxs)(_,{variant:"ghost",size:"sm",onClick:u,className:"af-mb-2 af--ml-2",children:[(0,je.jsx)(_s.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),(0,je.jsx)("h2",{className:"af-text-lg af-font-semibold",children:i.name}),(0,je.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:(0,je.jsx)("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),(0,je.jsxs)(Rn,{value:g,onValueChange:v=>f(v),children:[(0,je.jsxs)(Bs,{className:"af-mb-4",children:[(0,je.jsxs)(ya,{value:"submissions",className:"af-gap-2",children:[(0,je.jsx)(_s.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,je.jsxs)(ya,{value:"settings",className:"af-gap-2",children:[(0,je.jsx)(_s.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,je.jsx)(ha,{value:"submissions",children:(0,je.jsx)(zs,{formId:i.id,defaultSubmissionId:p})}),(0,je.jsx)(ha,{value:"settings",children:(0,je.jsx)(Zs,{form:i,onSaved:l})})]})]})]})}var Me=ce(require("react"),1);var Ia=ce(require("react"),1);function za(){let{api:e}=oe(),[a,s]=Ia.useState(null),[t,n]=Ia.useState(!0),[i,o]=Ia.useState(null),g=Ia.useRef(0),f=Ia.useCallback(async()=>{let p=++g.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(p!==g.current)return;s(r)}catch(r){if(p!==g.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{p===g.current&&n(!1)}},[e]);return Ia.useEffect(()=>{f()},[f]),{status:a,isLoading:t,error:i,refetch:f}}var Yo=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function aa(e){return Yo.has(e.toLowerCase())}function j(e,a,s){let t=aa(a)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:a.toUpperCase()}).format(t)}catch{return`${t} ${a.toUpperCase()}`}}function Da(e){let a=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+a}function Ft(e,a){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let t=aa(a)?s:s*100;return Math.round(t)}function mt(e,a){return aa(a)?e:e/100}function Tn(e){return e.amount_paid??Math.max(0,Da(e)-(e.credit_applied??0))}var re=require("react/jsx-runtime");function Js(e){return e instanceof Bt&&e.status===404?"Promo management is not available yet. Try again after the service is updated.":e instanceof Error?e.message:"Could not complete the request."}function yi(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${j(e.amount_off,e.currency)} off`:"Discount unavailable"}function cs(){let{api:e,siteToken:a}=oe();return(0,re.jsx)(Qo,{api:e},a)}function Qo({api:e}){let{status:a,error:s}=za(),[t,n]=Me.useState([]),[i,o]=Me.useState(null),[g,f]=Me.useState(null),[p,r]=Me.useState(!1),[y,x]=Me.useState(!1),[h,u]=Me.useState(""),[l,v]=Me.useState(null),[N,S]=Me.useState(null),[O,F]=Me.useState(!1),c=Me.useRef(0),A=Me.useCallback(async P=>{let E=++c.current;r(!0),u("");try{let U=await e.getPromos(P);if(E!==c.current)return;n(w=>P?[...w,...U.promos.filter(Z=>!w.some(ee=>ee.id===Z.id))]:U.promos),o(U.next_cursor),f(U.checkout_enabled)}catch(U){E===c.current&&u(Js(U))}finally{E===c.current&&r(!1)}},[e]);Me.useEffect(()=>(A(),()=>{c.current++}),[A]);async function D(P){let E=++c.current;r(!0),u(""),F(!1);try{let U=await e.getPromo(P);E===c.current&&v(U)}catch(U){E===c.current&&u(Js(U))}finally{E===c.current&&r(!1)}}async function te(){if(l){x(!0),r(!0),u("");try{let P=await e.disablePromo(l.id);if(v(P),!["inactive","expired","exhausted"].includes(P.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");F(!1),await A()}catch(P){u(Js(P))}finally{x(!1),r(!1)}}}return N?(0,re.jsx)(Xo,{currency:a?.currency??void 0,replaces:N.replaces,onCancel:()=>S(null),onSave:async P=>{let E=N.replaces?await e.replacePromo(N.replaces.id,P):await e.createPromo(P),U=await e.getPromo(E.id);if(U.status==="pending"||U.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");v(U),S(null),await A()}}):(0,re.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,re.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,re.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,re.jsx)(_,{disabled:p||!a?.currency,onClick:()=>{u(""),S({})},children:"Create promo code"})]}),(0,re.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),g===!1&&(0,re.jsx)("p",{role:"status",className:"af-rounded-md af-border af-p-3 af-text-sm",children:"Checkout code entry is not enabled yet. You can prepare codes, but buyers cannot enter them in our checkout until it is enabled."}),!a?.currency&&(0,re.jsx)("p",{className:"af-text-sm",children:s?Js(s):"Connect Stripe and set the payment currency before creating codes."}),h&&(0,re.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[h," ",(0,re.jsx)(_,{variant:"outline",disabled:p,onClick:()=>l?void D(l.id):void A(),children:"Refresh"})]}),l?(0,re.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,re.jsx)(_,{variant:"ghost",disabled:y,onClick:()=>{v(null),F(!1),A()},children:"Back to codes"}),(0,re.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),(0,re.jsxs)("p",{children:[yi(l)," \xB7 ",l.status]}),(0,re.jsxs)("p",{className:"af-text-sm",children:[l.times_redeemed==null?"Usage unavailable":`${l.times_redeemed} redemptions`,l.max_redemptions!=null?` / ${l.max_redemptions} maximum`:""]}),(0,re.jsxs)("p",{className:"af-text-sm",children:[l.minimum_amount!=null&&l.currency?`Minimum order: ${j(l.minimum_amount,l.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,re.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",l.duration==="repeating"?`${l.duration_in_months} months`:l.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,re.jsx)("p",{className:"af-text-sm",children:l.expires_at?`Expires ${new Date(l.expires_at).toLocaleString()}`:"No expiry"}),(0,re.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,re.jsx)(_,{variant:"outline",disabled:p,onClick:()=>void D(l.id),children:"Refresh details"}),(0,re.jsx)(_,{variant:"outline",disabled:p||l.status==="pending"||l.status==="unavailable"||!a?.currency,onClick:()=>S({replaces:l}),children:"Replace with new code"}),(0,re.jsx)(_,{variant:"outline",disabled:p||!["active","pending","unavailable"].includes(l.status),onClick:()=>F(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),O&&(0,re.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,re.jsxs)("p",{className:"af-text-sm",children:[l.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${l.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,re.jsx)(_,{disabled:p,onClick:()=>void te(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,re.jsx)(_,{variant:"ghost",disabled:p,onClick:()=>F(!1),children:"Cancel"})]})]}):(0,re.jsxs)(re.Fragment,{children:[t.map(P=>(0,re.jsxs)("button",{type:"button",disabled:p,onClick:()=>void D(P.id),className:"af-w-full af-rounded-lg af-border af-p-4 af-text-left hover:af-bg-muted focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[(0,re.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,re.jsx)("span",{className:"af-font-semibold af-break-all",children:P.code}),(0,re.jsx)("span",{className:"af-text-sm",children:P.status})]}),(0,re.jsxs)("div",{className:"af-text-sm",children:[yi(P)," \xB7"," ",P.times_redeemed==null?"Usage unavailable":`${P.times_redeemed} redemptions`]})]},P.id)),!p&&!h&&t.length===0&&(0,re.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),p&&(0,re.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),i&&(0,re.jsx)(_,{variant:"outline",disabled:p,onClick:()=>void A(i),children:"Load more"})]})]})}function Xo({currency:e,replaces:a,onCancel:s,onSave:t}){let[n,i]=Me.useState(""),[o,g]=Me.useState(a?.name??""),[f,p]=Me.useState(a?.amount_off!=null?"fixed":"percent"),[r,y]=Me.useState(a?.percent_off?.toString()??(a?.amount_off!=null&&e?String(mt(a.amount_off,e)):"")),[x,h]=Me.useState(a?.minimum_amount!=null&&e?String(mt(a.minimum_amount,e)):""),[u,l]=Me.useState(()=>{if(!a?.expires_at)return"";let K=new Date(a.expires_at);return Number.isFinite(K.getTime())?new Date(K.getTime()-K.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[v,N]=Me.useState(a?.max_redemptions?.toString()??""),[S,O]=Me.useState(a?.duration??"once"),[F,c]=Me.useState(a?.duration_in_months?.toString()??"3"),[A,D]=Me.useState(null),[te,P]=Me.useState(!1),[E,U]=Me.useState(""),w=Me.useRef(!1),Z=e&&aa(e)?"1":"0.01";async function ee(K){if(K.preventDefault(),w.current)return;U("");let Q=A;if(!Q){if(!e){U("Payment currency is not available.");return}if(a&&n.trim().toUpperCase()===a.code.toUpperCase()){U("Choose a different code for the replacement.");return}let G=Ft(r,e),ie=x?Ft(x,e):null;if(f==="fixed"&&(!G||G>999999999999)||x&&(!ie||ie>999999999999)){U("Enter a positive amount within the supported range.");return}if(u&&new Date(u).getTime()<=Date.now()){U("Choose a future expiry.");return}Q={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:S,...f==="percent"?{percent_off:Number(r)}:{amount_off:G,currency:e},...x?{minimum_amount:ie,currency:e}:{},...u?{expires_at:new Date(u).toISOString()}:{},...v?{max_redemptions:Number(v)}:{},...S==="repeating"?{duration_in_months:Number(F)}:{}},D(Q)}w.current=!0,P(!0);try{await t(Q)}catch(G){U(Js(G)),G instanceof Bt&&G.status>=400&&G.status<500&&G.details?.retryable!==!0&&D(null)}finally{w.current=!1,P(!1)}}let q=(K,Q,G,ie={})=>(0,re.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[K,(0,re.jsx)(we,{"aria-label":K,value:Q,onChange:J=>G(J.target.value),...ie})]}),de="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,re.jsxs)("form",{onSubmit:ee,className:"af-max-w-xl af-space-y-4","aria-label":a?"Replace promo code":"Create promo code",children:[(0,re.jsx)("h3",{className:"af-text-lg af-font-semibold",children:a?`Replace ${a.code}`:"Create promo code"}),a&&(0,re.jsx)("p",{className:"af-text-sm",children:"Use a different code. The old code will be disabled only after the replacement is created. Existing subscription discounts continue."}),(0,re.jsxs)("fieldset",{disabled:te||!!A,className:"af-grid af-gap-4",children:[q("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),q("Name",o,g,{required:!0,maxLength:40}),(0,re.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,re.jsxs)("select",{"aria-label":"Discount type",className:de,value:f,onChange:K=>p(K.target.value),children:[(0,re.jsx)("option",{value:"percent",children:"Percentage"}),(0,re.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),q("Discount",r,y,{type:"number",required:!0,min:f==="percent"?"0.01":Z,max:f==="percent"?"100":void 0,step:f==="percent"?"0.01":Z}),q("Minimum order amount",x,h,{type:"number",min:Z,step:Z,placeholder:e?.toUpperCase()}),(0,re.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),q("Expires at (local time)",u,l,{type:"datetime-local",step:1}),q("Maximum redemptions",v,N,{type:"number",min:1,max:1e6,step:1}),(0,re.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,re.jsxs)("select",{"aria-label":"Subscription duration",className:de,value:S,onChange:K=>O(K.target.value),children:[(0,re.jsx)("option",{value:"once",children:"First invoice only"}),(0,re.jsx)("option",{value:"forever",children:"Every invoice"}),(0,re.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),S==="repeating"&&q("Months",F,c,{type:"number",required:!0,min:1,max:36,step:1})]}),E&&(0,re.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:E}),A&&!te&&(0,re.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,re.jsx)("span",{className:"af-break-all",children:A.request_id})]}),(0,re.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,re.jsx)(_,{type:"submit",disabled:te,children:te?"Saving\u2026":A?"Retry same request":a?"Create replacement":"Create code"}),(0,re.jsx)(_,{type:"button",variant:"ghost",disabled:te||!!A,onClick:s,children:"Cancel"})]})]})}var ks=ce(require("react"),1),va=require("lucide-react");var kn=ce(require("react"),1),qa=require("lucide-react");var ve=require("react/jsx-runtime");function el(e){if(e.allow_custom_amount){let a=e.min_amount!==null?j(e.min_amount,e.currency):"?",s=e.max_amount!==null?j(e.max_amount,e.currency):"?";return`Buyer chooses (${a} - ${s})`}return e.unit_amount===null?"Varies by variant":j(e.unit_amount,e.currency)}function tl(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Ys({productsState:e,onSelectProduct:a,onCreateProduct:s,className:t}){let{products:n,isLoading:i,error:o,deleteProduct:g}=e,[f,p]=kn.useState(null),[r,y]=kn.useState(!1),[x,h]=kn.useState(null),u=async()=>{if(f)try{y(!0),h(null),await g(f.id),p(null)}catch(l){h(l instanceof Error?l.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)(qa.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)(_,{variant:"outline",onClick:()=>s?.(),children:[(0,ve.jsx)(qa.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)(_,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[(0,ve.jsx)(qa.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,ve.jsxs)(Ue,{children:[(0,ve.jsx)(Ve,{children:(0,ve.jsxs)(he,{children:[(0,ve.jsx)(V,{children:"Name"}),(0,ve.jsx)(V,{children:"Price"}),(0,ve.jsx)(V,{children:"Fulfillment"}),(0,ve.jsx)(V,{children:"Status"}),(0,ve.jsx)(V,{className:"af-text-right",children:"Actions"})]})}),(0,ve.jsx)($e,{children:n.map(l=>(0,ve.jsxs)(he,{children:[(0,ve.jsx)($,{className:"af-font-medium",children:l.name}),(0,ve.jsx)($,{children:el(l)}),(0,ve.jsx)($,{className:"af-text-muted-foreground",children:tl(l)}),(0,ve.jsx)($,{children:(0,ve.jsx)(ae,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),(0,ve.jsx)($,{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)(_,{variant:"ghost",size:"sm",onClick:()=>a?.(l),children:[(0,ve.jsx)(qa.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,ve.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>{h(null),p(l)},children:[(0,ve.jsx)(qa.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),(0,ve.jsx)(Aa,{open:!!f,onOpenChange:l=>{!l&&!r&&p(null)},children:(0,ve.jsxs)(wa,{children:[(0,ve.jsxs)(Na,{children:[(0,ve.jsx)(_a,{children:"Delete product?"}),(0,ve.jsxs)(Ra,{children:['"',f?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),x&&(0,ve.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:x}),(0,ve.jsxs)(Sa,{children:[(0,ve.jsx)(_,{variant:"outline",onClick:()=>p(null),disabled:r,children:"Cancel"}),(0,ve.jsx)(_,{variant:"destructive",onClick:u,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}var Xe=ce(require("react"),1),sa=require("lucide-react");var vt=ce(require("react"),1),ma=require("lucide-react");var T=require("react/jsx-runtime");function fr(e){return e.option_values.length>0?e.option_values.map(a=>a.value).join(" / "):e.title||"Default"}function Qs({productId:e,currency:a,className:s}){let{api:t}=oe(),n=aa(a)?"1":"0.01",[i,o]=vt.useState(null),[g,f]=vt.useState(!0),[p,r]=vt.useState(null),[y,x]=vt.useState(null),[h,u]=vt.useState(!1),l=vt.useRef(!0);vt.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let v=vt.useCallback(async()=>{try{let C=await t.getProduct(e);if(!l.current)return;o(C)}catch(C){if(!l.current)return;r(C instanceof Error?C.message:"Failed to load product")}finally{l.current&&f(!1)}},[t,e]);vt.useEffect(()=>{v()},[v]);let N=async C=>{x(null),u(!0);try{await C(),await v()}catch(L){l.current&&x(L instanceof Error?L.message:"Something went wrong")}finally{l.current&&u(!1)}},[S,O]=vt.useState(""),[F,c]=vt.useState(""),[A,D]=vt.useState({}),te=()=>N(async()=>{let C=S.trim(),L=F.split(",").map(I=>I.trim()).filter(Boolean);if(!C)throw new Error("Option name is required");if(L.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:C,values:L}),l.current&&(O(""),c(""))}),P=C=>N(async()=>{let L=(A[C.id]??"").trim();if(!L)throw new Error("Enter a value");await t.updateOption(C.id,{add_values:[L]}),l.current&&D(I=>({...I,[C.id]:""}))}),E=(C,L)=>N(()=>t.updateOption(C.id,{remove_values:[L]})),U=C=>N(()=>t.deleteOption(C.id)),[w,Z]=vt.useState(null),[ee,q]=vt.useState(null),[de,K]=vt.useState(!1),[Q,G]=vt.useState(null),ie=i?.options??[],J=i?.variants??[],Re=()=>{q(null),Z({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(ie.map(C=>[C.id,C.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Qe=C=>{q(null);let L=C.inventory?.on_hand??0,I=L<0?"":String(L);Z({variant:C,title:C.title??"",sku:C.sku??"",unitAmount:C.unit_amount!=null?String(mt(C.unit_amount,a)):"",compareAt:C.compare_at_amount!=null?String(mt(C.compare_at_amount,a)):"",active:C.active,optionValues:{},tracked:C.inventory?.tracked??!1,onHand:I,initialOnHand:I,allowBackorder:C.inventory?.allow_backorder??!1})},ot=async()=>{if(!w)return;q(null);let C=w.variant?.allow_custom_amount??!1,L=null,I=null;if(!C){if(L=Ft(w.unitAmount,a),L===null||L<=0){q("Enter a valid price");return}if(w.compareAt.trim()&&(I=Ft(w.compareAt,a),I===null||I<=L)){q("Compare-at price must be greater than the price");return}}let pe=w.onHand.trim()!==w.initialOnHand.trim(),ye=parseInt(w.onHand,10);if(w.tracked&&pe&&(!Number.isFinite(ye)||ye<0)){q("On-hand quantity must be zero or more");return}try{if(K(!0),w.variant)await t.updateVariant(w.variant.id,{title:w.title.trim()||null,sku:w.sku.trim()||null,...C?{}:{unit_amount:L,compare_at_amount:I},active:w.active}),await t.setVariantInventory(w.variant.id,{tracked:w.tracked,on_hand:w.tracked&&pe?ye:void 0,allow_backorder:w.allowBackorder});else{let ke={};for(let Le of ie){let at=w.optionValues[Le.id];if(!at){q(`Choose a ${Le.title}`),K(!1);return}ke[Le.title]=at}await t.createVariant(e,{title:w.title.trim()||null,sku:w.sku.trim()||null,unit_amount:L,compare_at_amount:I,active:w.active,option_values:ie.length>0?ke:void 0,inventory:w.tracked?{tracked:!0,on_hand:ye,allow_backorder:w.allowBackorder}:{tracked:!1,allow_backorder:w.allowBackorder}})}await v(),l.current&&Z(null)}catch(ke){if(l.current&&q(ke instanceof Error?ke.message:"Failed to save variant"),w.variant)try{let Le=await t.getProduct(e);l.current&&o(Le)}catch{}}finally{l.current&&K(!1)}},Ee=()=>N(async()=>{Q&&(await t.deleteVariant(Q.id),l.current&&G(null))}),Ge=w?.variant?.allow_custom_amount??!1,tt=w?.variant!=null&&w.variant.option_values.length===0&&ie.length>0&&!w.variant.active,Pe=w?.variant?.inventory!=null&&w.variant.inventory.on_hand<0?-w.variant.inventory.on_hand:null;function Tt(C){let L=C.inventory;if(!L||!L.tracked)return(0,T.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let I=L.available??L.on_hand;return I<0?(0,T.jsxs)("span",{children:[-I," backordered"]}):(0,T.jsxs)("span",{children:[I," 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)(ma.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):p?(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:p})}):(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)(_e,{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."})]}),ie.length>0&&(0,T.jsx)("div",{className:"af-space-y-3",children:ie.map(C=>(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:C.title}),(0,T.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>U(C),disabled:h,children:(0,T.jsx)(ma.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,T.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:C.values.map(L=>(0,T.jsxs)(ae,{variant:"secondary",className:"af-gap-1",children:[L.value,(0,T.jsx)("button",{type:"button",onClick:()=>E(C,L.value),className:"af-ml-1 hover:af-text-destructive",disabled:h,title:"Remove value",children:(0,T.jsx)(ma.X,{className:"af-h-3 af-w-3"})})]},L.id))}),(0,T.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,T.jsx)(we,{value:A[C.id]??"",onChange:L=>D(I=>({...I,[C.id]:L.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),P(C))},disabled:h}),(0,T.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>P(C),disabled:h||!(A[C.id]??"").trim(),children:(0,T.jsx)(ma.Plus,{className:"af-h-4 af-w-4"})})]})]},C.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)(_e,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,T.jsx)(we,{id:"new-option-title",value:S,onChange:C=>O(C.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:h})]}),(0,T.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,T.jsx)(_e,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,T.jsx)(we,{id:"new-option-values",value:F,onChange:C=>c(C.target.value),placeholder:"S, M, L",disabled:h})]}),(0,T.jsxs)(_,{type:"button",variant:"outline",onClick:te,disabled:h||!S.trim()||!F.trim(),children:[(0,T.jsx)(ma.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)(_e,{children:"Variants"}),(0,T.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:Re,disabled:h||ie.length===0,children:[(0,T.jsx)(ma.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ie.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."}),J.length===0?(0,T.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,T.jsxs)(Ue,{children:[(0,T.jsx)(Ve,{children:(0,T.jsxs)(he,{children:[(0,T.jsx)(V,{children:"Variant"}),(0,T.jsx)(V,{children:"SKU"}),(0,T.jsx)(V,{children:"Price"}),(0,T.jsx)(V,{children:"Stock"}),(0,T.jsx)(V,{children:"Status"}),(0,T.jsx)(V,{className:"af-text-right",children:"Actions"})]})}),(0,T.jsx)($e,{children:J.map(C=>(0,T.jsxs)(he,{children:[(0,T.jsx)($,{className:"af-font-medium",children:fr(C)}),(0,T.jsx)($,{className:"af-text-muted-foreground",children:C.sku||"-"}),(0,T.jsx)($,{children:C.unit_amount!=null?(0,T.jsxs)("span",{children:[C.compare_at_amount!=null&&(0,T.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:j(C.compare_at_amount,C.currency)}),j(C.unit_amount,C.currency)]}):C.allow_custom_amount?(0,T.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,T.jsx)($,{children:Tt(C)}),(0,T.jsx)($,{children:(0,T.jsx)(ae,{variant:C.active?"success":"secondary",children:C.active?"Active":"Inactive"})}),(0,T.jsx)($,{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)(_,{variant:"ghost",size:"sm",onClick:()=>Qe(C),disabled:h,children:"Edit"}),(0,T.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>G(C),disabled:h,title:"Delete variant",children:(0,T.jsx)(ma.Trash2,{className:"af-h-4 af-w-4"})})]})})]},C.id))})]})]}),y&&(0,T.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:y}),(0,T.jsx)(Aa,{open:w!==null,onOpenChange:C=>{!C&&!de&&Z(null)},children:(0,T.jsxs)(wa,{children:[(0,T.jsxs)(Na,{children:[(0,T.jsx)(_a,{children:w?.variant?"Edit variant":"Add variant"}),(0,T.jsx)(Ra,{children:"Price, markdown, and stock live on the variant."})]}),w&&(0,T.jsxs)("div",{className:"af-space-y-3",children:[w.variant?w.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"}),fr(w.variant)]}):ie.map(C=>(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(_e,{className:"af-text-xs af-text-muted-foreground",children:C.title}),(0,T.jsxs)(ca,{value:w.optionValues[C.id]??"",onValueChange:L=>Z(I=>I&&{...I,optionValues:{...I.optionValues,[C.id]:L}}),children:[(0,T.jsx)(Qt,{children:(0,T.jsx)(ua,{placeholder:`Choose ${C.title}`})}),(0,T.jsx)(Xt,{children:C.values.map(L=>(0,T.jsx)(Je,{value:L.value,children:L.value},L.id))})]})]},C.id)),Ge?(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(_e,{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)(_e,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",a.toUpperCase(),")"]}),(0,T.jsx)(we,{id:"variant-price",type:"number",min:"0",step:n,value:w.unitAmount,onChange:C=>Z(L=>L&&{...L,unitAmount:C.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(_e,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,T.jsx)(we,{id:"variant-compare",type:"number",min:"0",step:n,value:w.compareAt,onChange:C=>Z(L=>L&&{...L,compareAt:C.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,T.jsxs)("div",{className:"af-space-y-1",children:[(0,T.jsx)(_e,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,T.jsx)(we,{id:"variant-sku",value:w.sku,onChange:C=>Z(L=>L&&{...L,sku:C.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:w.tracked,onChange:C=>Z(L=>L&&{...L,tracked:C.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),w.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)(_e,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,T.jsx)(we,{id:"variant-onhand",type:"number",min:"0",step:"1",value:w.onHand,onChange:C=>Z(L=>L&&{...L,onHand:C.target.value}),placeholder:Pe!=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:w.allowBackorder,onChange:C=>Z(L=>L&&{...L,allowBackorder:C.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Pe!=null&&(0,T.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Pe," 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:w.active,onChange:C=>Z(L=>L&&{...L,active:C.target.checked}),className:"af-h-4 af-w-4",disabled:tt}),"Active (buyers can purchase this variant)"]}),tt&&(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."})]}),ee&&(0,T.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:ee})]}),(0,T.jsxs)(Sa,{children:[(0,T.jsx)(_,{variant:"outline",onClick:()=>Z(null),disabled:de,children:"Cancel"}),(0,T.jsxs)(_,{onClick:ot,disabled:de,children:[de?(0,T.jsx)(ma.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,w?.variant?"Save":"Add variant"]})]})]})}),(0,T.jsx)(Aa,{open:Q!==null,onOpenChange:C=>{!C&&!h&&G(null)},children:(0,T.jsxs)(wa,{children:[(0,T.jsxs)(Na,{children:[(0,T.jsx)(_a,{children:"Delete variant?"}),(0,T.jsx)(Ra,{children:Q&&`"${fr(Q)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,T.jsxs)(Sa,{children:[(0,T.jsx)(_,{variant:"outline",onClick:()=>G(null),disabled:h,children:"Cancel"}),(0,T.jsx)(_,{variant:"destructive",onClick:Ee,disabled:h,children:"Delete"})]})]})})]})}var W=require("react/jsx-runtime");function al(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 Xs({productsState:e,product:a,currency:s,onSaved:t,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:g,attachProductFileFromUrl:f}=e,p=!!a,r=a?.currency??s,y=aa(r)?"1":"0.01",x=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[h,u]=Xe.useState(!1),[l,v]=Xe.useState(null),N=Xe.useRef(!0);Xe.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]);let[S,O]=Xe.useState(a?.name??""),[F,c]=Xe.useState(a?.description??""),[A,D]=Xe.useState(a?.allow_custom_amount?"custom":"fixed"),[te,P]=Xe.useState(a?.unit_amount!=null?String(mt(a.unit_amount,r)):""),[E,U]=Xe.useState(a?.min_amount!=null?String(mt(a.min_amount,r)):""),[w,Z]=Xe.useState(a?.max_amount!=null?String(mt(a.max_amount,r)):""),[ee,q]=Xe.useState(String(a?.max_quantity??10)),de=Xe.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(mt(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(mt(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(mt(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[K,Q]=Xe.useState(a?.collect_shipping_address??!1),[G,ie]=Xe.useState(a?.active??!0),[J,Re]=Xe.useState(a?.images??[]),[Qe,ot]=Xe.useState(""),[Ee,Ge]=Xe.useState(a?.fulfillment??null),[tt,Pe]=Xe.useState(!1),[Tt,C]=Xe.useState(""),[L,I]=Xe.useState(null),pe=Xe.useRef(null),ye=h||tt,ke=()=>{let le=Qe.trim();if(le){if(J.includes(le)){v("This image URL is already added");return}Re(Oe=>[...Oe,le]),ot(""),v(null)}},Le=le=>{Re(Oe=>Oe.filter(lt=>lt!==le))},at=async()=>{if(v(null),!S.trim()){v("Product name is required");return}let le=null,Oe=null,lt=null,Jt=!p||A!==de.pricingMode||(A==="fixed"?te!==de.unitAmount:E!==de.minAmount||w!==de.maxAmount),xt=!p||ee!==de.maxQuantity,kt=x||A==="fixed";if(!(x||!Jt))if(A==="fixed"){if(le=Ft(te,r),le===null||le<=0){v("Enter a valid price");return}}else{if(Oe=Ft(E,r),lt=Ft(w,r),Oe===null||lt===null){v("Enter valid minimum and maximum amounts");return}if(lt<Oe){v("Maximum amount must be at least the minimum amount");return}}let $t=parseInt(ee,10);if(kt&&xt&&(!Number.isFinite($t)||$t<1)){v("Max quantity must be at least 1");return}try{u(!0);let qe;if(p&&a){let st={name:S.trim(),description:F.trim()||null,images:J,collect_shipping_address:K,active:G};!x&&Jt&&(st.allow_custom_amount=A==="custom",A==="fixed"?st.unit_amount=le:(st.min_amount=Oe,st.max_amount=lt)),kt&&xt&&(st.max_quantity=$t),qe=await o(a.id,st),de.pricingMode=qe.allow_custom_amount?"custom":"fixed",de.unitAmount=qe.unit_amount!=null?String(mt(qe.unit_amount,r)):"",de.minAmount=qe.min_amount!=null?String(mt(qe.min_amount,r)):"",de.maxAmount=qe.max_amount!=null?String(mt(qe.max_amount,r)):"",de.maxQuantity=String(qe.max_quantity)}else{let st={name:S.trim(),allow_custom_amount:A==="custom",collect_shipping_address:K,active:G};F.trim()&&(st.description=F.trim()),J.length>0&&(st.images=J),A==="fixed"?(st.unit_amount=le,st.max_quantity=$t):(st.min_amount=Oe,st.max_amount=lt),qe=await i(st)}if(!N.current)return;Ge(qe.fulfillment),t?.(qe)}catch(qe){if(!N.current)return;v(qe instanceof Error?qe.message:"Failed to save product")}finally{N.current&&u(!1)}},ze=async le=>{let Oe=le.target.files?.[0];if(!(!Oe||!a))try{Pe(!0),I(null);let lt=await g(a.id,Oe);if(!N.current)return;Ge(lt.fulfillment),t?.(lt)}catch(lt){if(!N.current)return;I(lt instanceof Error?lt.message:"Failed to upload file")}finally{N.current&&(Pe(!1),pe.current&&(pe.current.value=""))}},Ke=async()=>{let le=Tt.trim();if(!(!le||!a))try{Pe(!0),I(null);let Oe=await f(a.id,le);if(!N.current)return;Ge(Oe.fulfillment),C(""),t?.(Oe)}catch(Oe){if(!N.current)return;I(Oe instanceof Error?Oe.message:"Failed to fetch file")}finally{N.current&&Pe(!1)}};return(0,W.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,W.jsxs)("div",{className:"af-space-y-2",children:[(0,W.jsx)(_e,{htmlFor:"product-name",children:"Name"}),(0,W.jsx)(we,{id:"product-name",value:S,onChange:le=>O(le.target.value),placeholder:"My product"})]}),(0,W.jsxs)("div",{className:"af-space-y-2",children:[(0,W.jsx)(_e,{htmlFor:"product-description",children:"Description"}),(0,W.jsx)("textarea",{id:"product-description",value:F,onChange:le=>c(le.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,W.jsxs)("div",{className:"af-space-y-2",children:[(0,W.jsx)(_e,{children:"Pricing"}),x?(0,W.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,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(ca,{value:A,onValueChange:le=>D(le),children:[(0,W.jsx)(Qt,{className:"af-w-[260px]",children:(0,W.jsx)(ua,{})}),(0,W.jsxs)(Xt,{children:[(0,W.jsx)(Je,{value:"fixed",children:"Fixed price"}),(0,W.jsx)(Je,{value:"custom",children:"Buyer chooses the amount"})]})]}),A==="fixed"?(0,W.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,W.jsxs)("div",{className:"af-space-y-1",children:[(0,W.jsxs)(_e,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),(0,W.jsx)(we,{id:"product-price",type:"number",min:"0",step:y,value:te,onChange:le=>P(le.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,W.jsxs)("div",{className:"af-space-y-1",children:[(0,W.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,W.jsxs)("div",{className:"af-space-y-1",children:[(0,W.jsxs)(_e,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),(0,W.jsx)(we,{id:"product-min-amount",type:"number",min:"0",step:y,value:E,onChange:le=>U(le.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,W.jsxs)("div",{className:"af-space-y-1",children:[(0,W.jsxs)(_e,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),(0,W.jsx)(we,{id:"product-max-amount",type:"number",min:"0",step:y,value:w,onChange:le=>Z(le.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,W.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,W.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."]})]}),(x||A==="fixed")&&(0,W.jsxs)("div",{className:"af-space-y-1",children:[(0,W.jsx)(_e,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,W.jsx)(we,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:ee,onChange:le=>q(le.target.value),className:"af-w-[140px]"})]})]}),(0,W.jsxs)("div",{className:"af-space-y-2",children:[(0,W.jsx)(_e,{children:"Images"}),(0,W.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,W.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[J.map(le=>(0,W.jsxs)(ae,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,W.jsx)("span",{className:"af-truncate",children:le}),(0,W.jsx)("button",{type:"button",onClick:()=>Le(le),className:"af-ml-1 hover:af-text-destructive",disabled:h,children:(0,W.jsx)(sa.X,{className:"af-h-3 af-w-3"})})]},le)),J.length===0&&(0,W.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,W.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,W.jsx)(we,{type:"url",value:Qe,onChange:le=>ot(le.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:le=>{le.key==="Enter"&&(le.preventDefault(),ke())},disabled:h}),(0,W.jsx)(_,{type:"button",variant:"outline",onClick:ke,disabled:!Qe.trim()||h,children:(0,W.jsx)(sa.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,W.jsxs)("div",{className:"af-space-y-2",children:[(0,W.jsx)(_e,{children:"Digital File"}),(0,W.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."}),p?(0,W.jsxs)("div",{className:"af-space-y-3",children:[Ee?.type==="download"&&(0,W.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,W.jsx)(sa.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,W.jsx)("span",{className:"af-text-sm",children:Ee.filename}),Ee.size!=null&&(0,W.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",al(Ee.size),")"]})]}),Ee?.type==="redirect"&&Ee.url&&(0,W.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,W.jsx)(sa.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,W.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Ee.url]})]}),(0,W.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,W.jsx)("input",{ref:pe,type:"file",onChange:ze,className:"af-hidden",disabled:ye}),(0,W.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>pe.current?.click(),disabled:ye,children:[tt?(0,W.jsx)(sa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,W.jsx)(sa.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Ee?.type==="download"?"Replace file":"Upload file"]}),(0,W.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,W.jsx)(we,{type:"url",value:Tt,onChange:le=>C(le.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:tt}),(0,W.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:Ke,disabled:!Tt.trim()||ye,children:"Fetch from URL"})]}),L&&(0,W.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:L})]}):(0,W.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,W.jsxs)("div",{className:"af-space-y-2",children:[(0,W.jsx)(_e,{children:"Settings"}),(0,W.jsxs)("div",{className:"af-space-y-2",children:[(0,W.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,W.jsx)("input",{type:"checkbox",checked:K,onChange:le=>Q(le.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,W.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,W.jsx)("input",{type:"checkbox",checked:G,onChange:le=>ie(le.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),p&&a&&(0,W.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,W.jsx)(_e,{children:"Options & Variants"}),(0,W.jsx)(Qs,{productId:a.id,currency:r})]}),l&&(0,W.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),(0,W.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,W.jsxs)(_,{type:"button",onClick:at,disabled:ye,children:[h?(0,W.jsx)(sa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,p?"Save changes":"Create product"]})})]})}var Rt=ce(require("react"),1),ra=require("lucide-react");var ct=ce(require("react"),1);var sl=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function en({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=oe(),[t,n]=ct.useState([]),[i,o]=ct.useState(0),[g,f]=ct.useState(!0),[p,r]=ct.useState(null),[y,x]=ct.useState(0),[h,u]=ct.useState(e),[l,v]=ct.useState(void 0),[N,S]=ct.useState(""),[O,F]=ct.useState(""),[c,A]=ct.useState(""),[D,te]=ct.useState(!1),[P,E]=ct.useState(!1),[U,w]=ct.useState(void 0),Z=U?U.join(","):"",ee=ct.useMemo(()=>{if(!Z)return;let Q=new Set(Z.split(","));return sl.filter(G=>!Q.has(G))},[Z]),q=ct.useRef(0),de=ct.useCallback(async()=>{let Q=++q.current;try{f(!0),r(null);let G={limit:h,offset:y*h};l?G.status=l:ee?G.excludeStatus=ee:D||(G.excludeStatus=["pending","expired"]),N.trim()&&(G.customerEmail=N.trim()),O.trim()&&(G.from=O.trim()),c.trim()&&(G.to=c.trim()),P&&(G.unfulfilledOnly=!0);let ie=await s.getOrders(G);if(Q!==q.current)return;n(ie.orders),o(ie.total)}catch(G){if(Q!==q.current)return;r(G instanceof Error?G:new Error("Failed to fetch orders"))}finally{Q===q.current&&f(!1)}},[s,y,h,l,ee,D,P,N,O,c,a]);ct.useEffect(()=>{de()},[de]);let K=Math.ceil(i/h);return{orders:t,total:i,isLoading:g,error:p,page:y,pageSize:h,hasNextPage:y<K-1,hasPreviousPage:y>0,setPage:x,setPageSize:Q=>{u(Q),x(0)},status:l,setStatus:Q=>{v(Q),x(0)},statusIn:U,setStatusIn:Q=>{w(Q&&Q.length>0?Q:void 0),x(0)},customerEmail:N,setCustomerEmail:Q=>{S(Q),x(0)},from:O,setFrom:Q=>{F(Q),x(0)},to:c,setTo:Q=>{A(Q),x(0)},showAbandoned:D,setShowAbandoned:Q=>{te(Q),x(0)},unfulfilledOnly:P,setUnfulfilledOnly:Q=>{E(Q),x(0)},clearFilters:()=>{v(void 0),w(void 0),te(!1),E(!1),S(""),F(""),A(""),x(0)},refetch:de}}var pt=ce(require("react"),1),Ae=require("lucide-react");var hi=ce(require("react"),1),La=ce(require("@radix-ui/react-popover"),1);var En=require("react/jsx-runtime"),xi=La.Root,wi=La.Trigger;var mr=hi.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>(0,En.jsx)(La.Portal,{children:(0,En.jsx)("div",{className:"aifeatures-admin",children:(0,En.jsx)(La.Content,{ref:n,align:a,sideOffset:s,className:X("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})})}));mr.displayName=La.Content.displayName;var tn=require("react/jsx-runtime"),nl={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function rl(e){return nl[e]??e}function Ni(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 us({status:e,className:a}){return(0,tn.jsx)(ae,{variant:Ni(e),className:a,children:rl(e)})}function as({status:e}){return(0,tn.jsx)(us,{status:e})}function Rs({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,tn.jsx)(ae,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,tn.jsx)(ae,{variant:"warning",className:a,children:"Needs shipping"}):null:null}function ja(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var d=require("react/jsx-runtime"),Pi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ds="af-text-xs af-text-muted-foreground";function pr(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 il(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ci(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 An=24,ol=["paid","partially_refunded"],ll=["paid","partially_refunded","disputed"],cl=/^[A-Za-z0-9 _-]*$/,Si=100;function br(e,a,s,t,n){let i=ol.includes(t);return a==="sent"?{label:"Sent",variant:"success",detail:null}:a==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:a==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:a==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${An} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${An} 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<An&&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<An&&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 _i({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)(ka,{deliveries:[g]}),o&&(0,d.jsx)("div",{className:"af-mt-2",children:o})]});let f=br(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)(ae,{variant:f.variant,className:"af-shrink-0",children:f.label})]}),f.detail&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:f.detail}),o&&(0,d.jsx)("div",{className:"af-mt-2",children:o})]})}function Ri(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=il(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}: ${Ci(n)}`)}function ul(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function yr({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=pt.useState(!1);if(!ul())return null;let g=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},f=i?(0,d.jsx)(Ae.Check,{className:"af-h-3 af-w-3"}):(0,d.jsx)(Ae.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,d.jsx)(_,{variant:"ghost",size:"icon",className:X("af-h-6 af-w-6 af-shrink-0",t),onClick:g,title:a,"aria-label":a,children:f}):(0,d.jsxs)(_,{variant:"outline",size:"sm",className:t,onClick:g,"aria-label":a,children:[i?(0,d.jsx)(Ae.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,d.jsx)(Ae.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function gr({label:e,value:a}){return(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:ds,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)(yr,{value:a,label:`Copy ${e}`})]})]})}function dl({src:e}){let[a,s]=pt.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)(Ae.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 Oa({title:e,action:a,children:s,className:t}){return(0,d.jsxs)("section",{className:X("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:Pi,children:e}),a]}),(0,d.jsx)("div",{className:"af-mt-3",children:s})]})}function jt({label:e,emphasis:a,divider:s,children:t}){return(0,d.jsxs)("div",{className:X("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":ds,children:e}),(0,d.jsx)("span",{className:X("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function vr({onSelect:e,disabled:a,icon:s,children:t}){return(0,d.jsxs)(_,{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 fl(e){let a=[];if(a.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?a.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&a.push({key:"paid",text:`Payment received \u2014 ${j(Tn(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?Cn(s):br("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?Cn(s):br("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 ${j(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 an({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:g=!1,hasNextOrder:f=!1}){let{api:p}=oe(),[r,y]=pt.useState(e),[x,h]=pt.useState(null),[u,l]=pt.useState(null),[v,N]=pt.useState(!1),[S,O]=pt.useState(!1),[F,c]=pt.useState(!1),[A,D]=pt.useState(!1),[te,P]=pt.useState(""),[E,U]=pt.useState(!1),[w,Z]=pt.useState(null),[ee,q]=pt.useState(!1),[de,K]=pt.useState(""),[Q,G]=pt.useState([]),[ie,J]=pt.useState(!1),[Re,Qe]=pt.useState(!1),[ot,Ee]=pt.useState(null);pt.useEffect(()=>{y(e)},[e]);let Ge=k=>{let Be=k.id===r.id&&k.email_deliveries===void 0?{...k,email_deliveries:r.email_deliveries}:k;y(Be),t?.(Be)},tt=Object.entries(r.metadata??{}),Pe=Math.max(0,Tn(r)-r.amount_refunded),Tt=(r.status==="paid"||r.status==="partially_refunded")&&Pe>0,C=r.exclusive_tax_total!=null,L=k=>typeof k.amountNet=="number"?k.amountNet+(k.exclusiveTax??0):(typeof k.unitAmount=="number"?k.unitAmount:0)*(typeof k.quantity=="number"&&k.quantity>0?k.quantity:1),I=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),pe=Q.reduce((k,Be)=>k+L(r.line_items[Be]??{}),0)+(ie?I:0),ye=r.tax_total??0,ke=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((k,Be)=>k+(Be.exclusiveTax??0),0)),Le=C?ie&&I>0?ke:0:r.automatic_tax&&r.tax_behavior==="exclusive"&&ye>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,ye-(r.tax_refunded??0)),Math.round(ye*pe/(r.amount_total+(r.shipping_total??0)))):0,at=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(pe+Le,Pe):pe+Le,ze=Q.length>0||ie,Ke=ze?at:Ft(de,r.currency),le=aa(r.currency)?"1":"0.01",Oe=async()=>{try{N(!0),h(null),l(null),await p.resendOrderReceipt(r.id);let k=await p.getOrder(r.id);Ge(k),l("Receipt email queued.")}catch(k){h(k instanceof Error?k.message:"Failed to resend receipt")}finally{N(!1)}},lt=async()=>{try{O(!0),h(null),l(null);let k=await p.resetOrderDownloads(r.id);Ge(k),c(!1),l("Download count reset.")}catch(k){h(k instanceof Error?k.message:"Failed to reset downloads")}finally{O(!1)}},Jt=r.line_items.some(k=>k.collectShippingAddress===!0&&!k.refunded&&!k.unavailableReason),xt=typeof r.merchant_fulfilled_at=="string",kt=ll.includes(r.status)||r.status==="refunded"&&r.line_items.some(k=>k.collectShippingAddress===!0&&k.amountNet===0&&!k.refunded&&!k.unavailableReason),$t=te.trim(),qe=cl.test($t)&&$t.length<=Si,st=async k=>{try{U(!0),Z(null),l(null);let Be=await p.setOrderFulfillment(r.id,{fulfilled:k,...k&&$t?{trackingNumber:$t}:{}});Ge(Be),P(""),l(k?"Marked as shipped.":"Marked as not shipped.")}catch(Be){Be instanceof Bt&&Be.status===409?Z(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Z(Be instanceof Error?Be.message:"Failed to update the order")}finally{U(!1)}},Ja=()=>{Ee(null),K(String(mt(Pe,r.currency))),G([]),J(!1),q(!0)},Ds=k=>G(Be=>Be.includes(k)?Be.filter(zt=>zt!==k):[...Be,k]),It=async(k,Be)=>{if(s)try{Qe(!0),Ee(null),await s(r,k,Be);let zt=await p.getOrder(r.id);Ge(zt),q(!1),l("Refund issued.")}catch(zt){Ee(zt instanceof Error?zt.message:"Refund failed")}finally{Qe(!1)}},xn=async()=>{if(ze){if(at<=0){Ee("The lines you picked were charged nothing");return}if(at>Pe){Ee(`That selection exceeds the refundable remainder (${j(Pe,r.currency)})`);return}await It(at,{...Q.length>0?{line_items:[...Q].sort((Be,zt)=>Be-zt)}:{},...ie?{shipping:!0}:{}});return}let k=Ft(de,r.currency);if(k===null||k<=0){Ee("Enter a valid refund amount");return}if(k>Pe){Ee(`Amount exceeds the refundable remainder (${j(Pe,r.currency)})`);return}await It(k,{amount:k})},H=()=>It(Pe,{full:!0}),Ze=!r.subscription_history_only&&r.fulfillment_type==="download",z=!r.subscription_history_only&&n&&Jt,Ht=fl(r),Po=r.shipping_address?Ri(r.shipping_address).join(`
4
- `):"",Hr=r.shipping_total!=null,nr=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),zr=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-nr):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,qr=nr>0,Co=zr>0,jr=r.amount_subtotal!=null||Hr||qr||(r.discount_total??0)>0,Ls=[];return r.subscription_history_only||Ls.push((0,d.jsx)(vr,{icon:v?(0,d.jsx)(Ae.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,d.jsx)(Ae.Mail,{className:"af-h-4 af-w-4"}),disabled:v||r.fulfillment_status!=="fulfilled",onSelect:()=>{D(!1),Oe()},children:"Resend receipt"},"resend")),Ze&&Ls.push((0,d.jsx)(vr,{icon:(0,d.jsx)(Ae.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:S,onSelect:()=>{D(!1),c(!0)},children:"Reset download count"},"reset")),Tt&&Ls.push((0,d.jsxs)("div",{children:[(0,d.jsx)(vr,{icon:(0,d.jsx)(Ae.Undo2,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{D(!1),Ja()},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)(_,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,d.jsx)(Ae.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:ja(r)}),(0,d.jsx)(us,{status:r.status}),n&&!r.subscription_history_only&&(0,d.jsx)(Rs,{order:r}),r.is_test&&(0,d.jsx)(ae,{variant:"outline",children:"Test"})]}),(0,d.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",pr(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)(_,{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)(Ae.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,d.jsx)(_,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!f,"aria-label":"Next order",children:(0,d.jsx)(Ae.ChevronRight,{className:"af-h-4 af-w-4"})})]}),z&&(xt?(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 ${pr(r.merchant_fulfilled_at)}`:""]}),kt&&(0,d.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>st(!1),disabled:E,children:[E?(0,d.jsx)(Ae.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(Ae.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):kt?(0,d.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,d.jsx)(we,{value:te,onChange:k=>P(k.target.value),placeholder:"Tracking number (optional)",maxLength:Si,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:E}),(0,d.jsxs)(_,{variant:"default",className:"af-shrink-0",onClick:()=>st(!0),disabled:E||!qe,children:[E?(0,d.jsx)(Ae.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(Ae.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Ls.length>0&&(0,d.jsxs)(xi,{open:A,onOpenChange:D,children:[(0,d.jsx)(wi,{asChild:!0,children:(0,d.jsx)(_,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,d.jsx)(Ae.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,d.jsx)(mr,{children:(0,d.jsx)("div",{className:"af-space-y-0.5",children:Ls})})]})]})]}),z&&!xt&&!qe&&(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."}),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}),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}),x&&(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:x})]}),(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)(Oa,{title:"Items",children:(0,d.jsx)("ul",{className:"af-space-y-3",children:r.line_items.map((k,Be)=>{let zt=typeof k.name=="string"&&k.name?k.name:"Item",Wr=typeof k.quantity=="number"&&k.quantity>0?k.quantity:1,Gr=typeof k.unitAmount=="number";return(0,d.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,d.jsx)(dl,{src:typeof k.imageUrl=="string"&&k.imageUrl?k.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:[zt,typeof k.variantTitle=="string"&&k.variantTitle&&(0,d.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",k.variantTitle]})]}),(0,d.jsxs)("div",{className:ds,children:[Wr," \xD7"," ",Gr?j(k.unitAmount,r.currency):"\u2014"]}),k.unavailableReason==="oversold"&&!k.refunded&&(0,d.jsx)(ae,{variant:"secondary",className:"af-mt-1",children:k.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),k.refunded===!0&&(0,d.jsx)(ae,{variant:"secondary",className:"af-mt-1",children:k.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,d.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof k.amountNet=="number"||Gr?j(k.amountNet??k.unitAmount*Wr,r.currency):"\u2014"})]},Be)})})}),tt.length>0&&(0,d.jsx)(Oa,{title:"Order details",children:(0,d.jsx)("dl",{className:"af-space-y-2",children:tt.map(([k,Be])=>(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{className:X(ds,"af-capitalize"),children:k.replace(/_/g," ")}),(0,d.jsx)("dd",{className:"af-text-sm af-break-words",children:Ci(Be)})]},k))})}),(0,d.jsx)(Oa,{title:"Totals",children:(0,d.jsxs)("div",{className:"af-w-full",children:[jr&&(0,d.jsx)(jt,{label:"Subtotal",children:j(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&(0,d.jsxs)(jt,{label:"Discount",children:["\u2212",j(r.discount_total,r.currency)]}),Hr&&(0,d.jsx)(jt,{label:"Shipping",children:r.shipping_total===0?"Free":j(r.shipping_total??0,r.currency)}),qr&&(0,d.jsx)(jt,{label:"Tax",children:j(nr,r.currency)}),(0,d.jsx)(jt,{label:"Total",emphasis:!0,divider:jr,children:j(Da(r),r.currency)}),(r.credit_applied??0)>0&&(0,d.jsxs)(jt,{label:"Credit applied",children:["\u2212",j(r.credit_applied,r.currency)]}),r.amount_paid!=null&&(0,d.jsx)(jt,{label:"Amount paid",children:j(r.amount_paid,r.currency)}),Co&&(0,d.jsx)(jt,{label:"incl. tax",children:j(zr,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&(0,d.jsxs)(jt,{label:"Your price",children:[j(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)(jt,{label:"Refunded",children:["\u2212",j(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."," ",j(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),(0,d.jsx)(jt,{label:"Net",children:(0,d.jsx)("span",{className:"af-font-medium",children:j(Math.max(0,Tn(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&(0,d.jsxs)(Oa,{title:"Platform fee",children:[r.application_fee_original!=null&&(0,d.jsx)(jt,{label:"Collected",children:j(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&(0,d.jsx)(jt,{label:"Returned",children:j(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&(0,d.jsx)(jt,{label:"Retained",children:j(r.application_fee_retained,r.application_fee_currency??r.currency)}),r.application_fee_state!=="complete"&&(0,d.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:r.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,d.jsx)(Oa,{title:"Timeline",children:(0,d.jsx)("ol",{className:"af-space-y-3",children:Ht.map(k=>(0,d.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,d.jsx)("span",{"aria-hidden":"true",className:X("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",k.tone==="destructive"?"af-bg-destructive":k.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:k.text}),k.at&&(0,d.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:pr(k.at)})]})]},k.key))})})]}),(0,d.jsxs)("div",{className:"af-space-y-6",children:[(0,d.jsx)(Oa,{title:"Customer",children:(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:ds,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)(yr,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:ds,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:ds,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)(ae,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&(0,d.jsx)(Oa,{title:"Ship to",action:(0,d.jsx)(yr,{value:Po,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:Ri(r.shipping_address).map((k,Be)=>(0,d.jsx)("div",{children:k},Be))})}),r.subscription_history_only?(0,d.jsx)(Oa,{title:"Subscription history",children:(0,d.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This renewal had no payment due. No items were fulfilled and no purchase receipt was sent."})}):(0,d.jsxs)(Oa,{title:"Emails",children:[(0,d.jsx)(ka,{deliveries:r.email_deliveries?.filter(k=>!["purchase_receipt","merchant_sale"].includes(k.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,d.jsxs)("div",{className:"af-space-y-4",children:[(0,d.jsx)(_i,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(k=>k.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:(0,d.jsxs)(_,{variant:"outline",size:"sm",onClick:Oe,disabled:v||r.fulfillment_status!=="fulfilled",children:[v?(0,d.jsx)(Ae.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(Ae.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,d.jsx)(_i,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(k=>k.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),Ze&&(0,d.jsx)(Oa,{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)(Ae.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:X(Pi,"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)(gr,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&(0,d.jsx)(gr,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&(0,d.jsx)(gr,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),(0,d.jsx)(Aa,{open:F,onOpenChange:k=>{!k&&!S&&c(!1)},children:(0,d.jsxs)(wa,{children:[(0,d.jsxs)(Na,{children:[(0,d.jsx)(_a,{children:"Reset download count?"}),(0,d.jsx)(Ra,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,d.jsxs)(Sa,{children:[(0,d.jsx)(_,{variant:"outline",onClick:()=>c(!1),disabled:S,children:"Cancel"}),(0,d.jsx)(_,{onClick:lt,disabled:S,children:S?"Resetting...":"Reset"})]})]})}),(0,d.jsx)(Aa,{open:ee,onOpenChange:k=>{!k&&!Re&&q(!1)},children:(0,d.jsxs)(wa,{children:[(0,d.jsxs)(Na,{children:[(0,d.jsx)(_a,{children:"Refund order"}),(0,d.jsxs)(Ra,{children:["Refund up to ",j(Pe,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||I>0)&&(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsx)(_e,{children:"Items"}),(0,d.jsxs)("div",{className:"af-space-y-2",children:[r.line_items.map((k,Be)=>{let zt=k.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:Q.includes(Be),onChange:()=>Ds(Be),disabled:Re||zt||!!k.unavailableReason||L(k)<=0,className:"af-h-4 af-w-4"}),(0,d.jsxs)("span",{className:zt?"af-text-muted-foreground af-line-through":void 0,children:[typeof k.name=="string"&&k.name?k.name:"Item",typeof k.variantTitle=="string"&&k.variantTitle?` \u2014 ${k.variantTitle}`:"",typeof k.quantity=="number"&&k.quantity>1?` \xD7 ${k.quantity}`:""]}),(0,d.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:zt?"Refunded":j(L(k),r.currency)})]},Be)}),I>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:ie,onChange:k=>J(k.target.checked),disabled:Re,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:j(I,r.currency)})]})]})]}),(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)(_e,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),(0,d.jsx)(we,{id:"refund-amount",type:"number",min:"0",step:le,value:ze?String(mt(at,r.currency)):de,onChange:k=>K(k.target.value),disabled:Re||ze}),ze&&(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."})]})]}),ot&&(0,d.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:ot}),(0,d.jsxs)(Sa,{children:[(0,d.jsx)(_,{variant:"outline",onClick:()=>q(!1),disabled:Re,children:"Cancel"}),(0,d.jsx)(_,{variant:"outline",onClick:H,disabled:Re,children:"Refund everything"}),(0,d.jsx)(_,{variant:"destructive",onClick:xn,disabled:Re,children:Re?"Refunding...":Ke!==null&&Ke>0?`Refund ${j(Ke,r.currency)}`:"Refund"})]})]})})]})}var In=ce(require("react"),1),Dn=require("lucide-react");var et=require("react/jsx-runtime");function bt({title:e,onBackToWebsite:a,hideBackButton:s=!1,children:t,className:n}){let i=In.useRef(null);return In.useEffect(()=>{i.current?.focus()},[]),(0,et.jsxs)("div",{className:X("af-bg-background",n),children:[(0,et.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,et.jsx)("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),a&&!s&&(0,et.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:a,className:"af-order-first af-shrink-0",children:[(0,et.jsx)(Dn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,et.jsx)("div",{className:"af-p-4",children:t})]})}function se({className:e}){return(0,et.jsx)("div",{"aria-hidden":"true",className:X("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function nt({label:e,children:a,detail:s,valueClassName:t}){return(0,et.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,et.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,et.jsx)("div",{className:X("af-mt-1 af-text-lg af-font-semibold",t),children:a}),s&&(0,et.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function na({message:e,onRetry:a}){return(0,et.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,et.jsx)("span",{children:e}),(0,et.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:a,children:[(0,et.jsx)(Dn.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Pa({icon:e,children:a}){return(0,et.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,et.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:a})]})}function Ps({icon:e,heading:a,body:s,action:t,className:n,children:i}){return(0,et.jsxs)("div",{className:X("af-px-6 af-py-10 af-text-center",n),children:[(0,et.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,et.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:a}),(0,et.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:s}),t&&(0,et.jsx)(_,{type:"button",className:"af-mt-4",onClick:t.onClick,children:t.label}),i]})}var R=require("react/jsx-runtime"),ml={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Ti={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function ki(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 Ei(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 Ln(e){return e.customer?.name||e.customer_name||null}function pl({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o,maxRows:g,onViewAll:f}){let p=typeof g=="number",{api:r}=oe(),y=en({refreshKey:s}),{orders:x,total:h,isLoading:u,error:l,page:v,pageSize:N,hasNextPage:S,hasPreviousPage:O,setPage:F,setPageSize:c,customerEmail:A,setCustomerEmail:D,setStatusIn:te,from:P,setFrom:E,to:U,setTo:w,showAbandoned:Z,setShowAbandoned:ee,setUnfulfilledOnly:q,refetch:de}=y,[K,Q]=Rt.useState("list"),[G,ie]=Rt.useState(null),[J,Re]=Rt.useState(""),[Qe,ot]=Rt.useState(""),[Ee,Ge]=Rt.useState(!p&&n?"needs_shipping":"all"),[tt,Pe]=Rt.useState(!1),[Tt,C]=Rt.useState(!!t&&!p),[L,I]=Rt.useState(null);Rt.useEffect(()=>{if(!t||p)return;let z=!1;return C(!0),I(null),r.getOrder(t).then(Ht=>{z||(ie(Ht),Q("detail"))}).catch(()=>{z||I("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{z||C(!1)}),()=>{z=!0}},[r,t,p]);let pe=Rt.useCallback(z=>{Ge(z);let Ht=Ti[z];te(Ht.statusIn),q(Ht.unfulfilledOnly)},[te,q]);Rt.useEffect(()=>{n&&!p&&q(!0)},[]);let ye=Rt.useRef(!n);Rt.useEffect(()=>{ye.current||u||(ye.current=!0,x.length===0&&pe("all"))},[u,x.length,pe]);let ke=K==="detail"&&!!G;Rt.useEffect(()=>{o?.(ke)},[ke,o]);let Le=(P?1:0)+(U?1:0)+(Z?1:0),at=Le>0||!!A||!!Qe,ze=!!P&&!!U&&P>U,Ke=!p||!!f,le=z=>{if(p){f?.();return}ie(z),Q("detail")},Oe=()=>{Q("list"),ie(null),de()},lt=z=>{let Ht=z.trim();if(!Ht){ot(""),A&&D("");return}if(Ht.startsWith("#")||/^\d+$/.test(Ht)){ot(Ht),A&&D("");return}ot(""),D(Ht)},Jt=()=>{Re(""),ot(""),D(""),E(""),w(""),ee(!1),Pe(!1)},xt=Qe.replace(/^#/,"").toLowerCase(),kt=xt?x.filter(z=>String(z.order_number??"")===xt||z.id.toLowerCase().startsWith(xt)):x,$t=p?kt.slice(0,g):kt,qe=G?x.findIndex(z=>z.id===G.id):-1,st=qe>0,Ja=qe>=0&&qe<x.length-1;if(Tt)return(0,R.jsx)("div",{className:a,children:(0,R.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,R.jsx)(ra.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(K==="detail"&&G)return(0,R.jsx)("div",{className:a,children:(0,R.jsx)(an,{order:G,onBack:Oe,onRefund:e,onOrderUpdated:z=>ie(z),allowFulfillment:n,onPrevOrder:st?()=>ie(x[qe-1]):void 0,onNextOrder:Ja?()=>ie(x[qe+1]):void 0,hasPrevOrder:st,hasNextOrder:Ja},G.id)});let It=(0,R.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[L&&(0,R.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:L}),(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.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(z=>(0,R.jsx)("button",{type:"button","aria-pressed":Ee===z,onClick:()=>pe(z),className:X("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===z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:ml[z]},z))}),(0,R.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,R.jsx)(ra.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,R.jsx)(we,{type:"text",value:J,onChange:z=>Re(z.target.value),onBlur:()=>lt(J),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),lt(J))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,R.jsxs)(_,{type:"button",variant:Le>0?"secondary":"ghost",size:"sm",onClick:()=>Pe(z=>!z),"aria-expanded":tt,children:[(0,R.jsx)(ra.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Le>0&&(0,R.jsx)(ae,{variant:"secondary",className:"af-ml-2",children:Le})]}),at&&(0,R.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:Jt,children:"Clear filters"})]}),(tt||!!P||!!U)&&(0,R.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,R.jsx)(_e,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,R.jsx)(we,{id:"orders-from",type:"date",value:P,max:U||void 0,onChange:z=>E(z.target.value),className:"af-w-[170px]"}),(0,R.jsx)(_e,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,R.jsx)(we,{id:"orders-to",type:"date",value:U,min:P||void 0,onChange:z=>w(z.target.value),className:"af-w-[170px]"}),!Ti[Ee].statusIn&&(0,R.jsx)(_,{type:"button",variant:Z?"secondary":"ghost",size:"sm",onClick:()=>ee(!Z),"aria-pressed":Z,children:Z?"Hide abandoned":"Show abandoned"})]}),ze&&(0,R.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(u)return(0,R.jsxs)("div",{className:a,children:[p?null:It,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(z=>(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,R.jsx)(se,{className:"af-h-4 af-w-16"}),(0,R.jsx)(se,{className:"af-h-4 af-w-14"})]}),(0,R.jsx)(se,{className:"af-mt-2 af-h-3 af-w-40"}),(0,R.jsx)(se,{className:"af-mt-2 af-h-3 af-w-24"})]},z))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(Ue,{children:[(0,R.jsx)(Ve,{children:(0,R.jsxs)(he,{children:[(0,R.jsx)(V,{children:"Order"}),(0,R.jsx)(V,{children:"Date"}),(0,R.jsx)(V,{children:"Customer"}),(0,R.jsx)(V,{children:"Items"}),(0,R.jsx)(V,{className:"af-text-right",children:"Total"}),(0,R.jsx)(V,{children:"Status"}),(0,R.jsx)(V,{className:"af-w-8"})]})}),(0,R.jsx)($e,{"aria-hidden":"true",children:[0,1,2,3,4].map(z=>(0,R.jsxs)(he,{children:[(0,R.jsx)($,{children:(0,R.jsx)(se,{className:"af-h-4 af-w-14"})}),(0,R.jsx)($,{children:(0,R.jsx)(se,{className:"af-h-4 af-w-24"})}),(0,R.jsx)($,{children:(0,R.jsx)(se,{className:"af-h-4 af-w-40"})}),(0,R.jsx)($,{children:(0,R.jsx)(se,{className:"af-h-4 af-w-32"})}),(0,R.jsx)($,{children:(0,R.jsx)(se,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,R.jsx)($,{children:(0,R.jsx)(se,{className:"af-h-5 af-w-16"})}),(0,R.jsx)($,{})]},z))})]})}),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(l)return(0,R.jsxs)("div",{className:a,children:[p?null:It,(0,R.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,R.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,R.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>de(),children:"Try again"})]})]});let xn=Ee!=="all";if(kt.length===0&&v===0)return at||xn?(0,R.jsxs)("div",{className:a,children:[!p&&It,(0,R.jsx)(Pa,{children:"No orders match these filters."})]}):(0,R.jsx)("div",{className:a,children:(0,R.jsx)(Ps,{icon:ra.Receipt,heading:"No orders yet",body:i??"Orders will appear here when someone buys from your website.",children:!p&&(0,R.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>ee(!0),children:"Show abandoned checkouts"})})});let H=v*N+1,Ze=Math.min((v+1)*N,h);return(0,R.jsxs)("div",{className:a,children:[p?null:It,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:$t.map(z=>(0,R.jsxs)("button",{type:"button",onClick:()=>le(z),disabled:!Ke,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ke?" hover:af-bg-muted/50":""}`,children:[(0,R.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,R.jsx)("span",{className:"af-font-medium",children:ja(z)}),(0,R.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:j(Da(z),z.currency)})]}),(0,R.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,R.jsxs)("div",{className:"af-truncate af-text-sm",children:[z.customer_email||(0,R.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Ln(z)&&(0,R.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Ln(z)]})]}),(0,R.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Ei(z)}),z.amount_refunded>0&&(0,R.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(z.amount_refunded,z.currency)," refunded"]})]}),(0,R.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,R.jsx)(us,{status:z.status}),(0,R.jsx)(Us,{deliveries:z.email_deliveries}),z.is_test&&(0,R.jsx)(ae,{variant:"outline",children:"Test"}),n&&(0,R.jsx)(Rs,{order:z}),(0,R.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:ki(z.created_at)})]})]},z.id))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(Ue,{children:[(0,R.jsx)(Ve,{children:(0,R.jsxs)(he,{children:[(0,R.jsx)(V,{children:"Order"}),(0,R.jsx)(V,{children:"Date"}),(0,R.jsx)(V,{children:"Customer"}),(0,R.jsx)(V,{children:"Items"}),(0,R.jsx)(V,{className:"af-text-right",children:"Total"}),(0,R.jsx)(V,{children:"Status"}),(0,R.jsx)(V,{className:"af-w-8"})]})}),(0,R.jsx)($e,{children:$t.map(z=>(0,R.jsxs)(he,{onClick:Ke?()=>le(z):void 0,className:Ke?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,R.jsxs)($,{className:"af-whitespace-nowrap af-font-medium",children:[(0,R.jsx)("button",{type:"button",onClick:Ht=>{Ht.stopPropagation(),le(z)},disabled:!Ke,"aria-label":`Open order ${ja(z)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ke?" hover:af-underline":""}`,children:ja(z)}),z.is_test&&(0,R.jsx)(ae,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,R.jsx)($,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ki(z.created_at)}),(0,R.jsxs)($,{className:"af-max-w-[220px]",children:[(0,R.jsx)("div",{className:"af-truncate",children:z.customer_email||(0,R.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Ln(z)&&(0,R.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Ln(z)})]}),(0,R.jsx)($,{className:"af-max-w-[220px]",children:(0,R.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:Ei(z)})}),(0,R.jsxs)($,{className:"af-whitespace-nowrap af-text-right",children:[(0,R.jsx)("div",{className:"af-font-medium af-tabular-nums",children:j(Da(z),z.currency)}),z.amount_refunded>0&&(0,R.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(z.amount_refunded,z.currency)," ","refunded"]})]}),(0,R.jsx)($,{children:(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,R.jsx)(us,{status:z.status}),(0,R.jsx)(Us,{deliveries:z.email_deliveries}),n&&(0,R.jsx)(Rs,{order:z})]})}),(0,R.jsx)($,{className:"af-w-8 af-text-right",children:(0,R.jsx)(ra.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},z.id))})]})}),p?null:(0,R.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,R.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,R.jsx)("span",{children:xt?`${kt.length} matching this page`:`Showing ${H}-${Ze} of ${h}`}),(0,R.jsxs)(ca,{value:String(N),onValueChange:z=>c(Number(z)),children:[(0,R.jsx)(Qt,{className:"af-w-[70px] af-h-8",children:(0,R.jsx)(ua,{})}),(0,R.jsxs)(Xt,{children:[(0,R.jsx)(Je,{value:"10",children:"10"}),(0,R.jsx)(Je,{value:"25",children:"25"}),(0,R.jsx)(Je,{value:"50",children:"50"}),(0,R.jsx)(Je,{value:"100",children:"100"})]})]}),(0,R.jsx)("span",{children:"per page"})]}),(0,R.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,R.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>F(v-1),disabled:!O,children:[(0,R.jsx)(ra.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,R.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>F(v+1),disabled:!S,children:["Next",(0,R.jsx)(ra.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function Wa(e){return(0,R.jsx)(pl,{...e},e.maxRows==null?"full":"compact")}var Bn=ce(require("react"),1),Ba=require("lucide-react");var Wt=ce(require("react"),1);function sn({initialPageSize:e=25}={}){let{api:a}=oe(),[s,t]=Wt.useState([]),[n,i]=Wt.useState(0),[o,g]=Wt.useState(!0),[f,p]=Wt.useState(null),[r,y]=Wt.useState(0),[x,h]=Wt.useState(e),[u,l]=Wt.useState(""),v=Wt.useRef(0),N=Wt.useCallback(async()=>{let O=++v.current;try{g(!0),p(null);let F={limit:x,offset:r*x};u.trim()&&(F.email=u.trim());let c=await a.getCustomers(F);if(O!==v.current)return;t(c.customers),i(c.total)}catch(F){if(O!==v.current)return;p(F instanceof Error?F:new Error("Failed to fetch customers"))}finally{O===v.current&&g(!1)}},[a,r,x,u]);Wt.useEffect(()=>{N()},[N]);let S=Math.ceil(n/x);return{customers:s,total:n,isLoading:o,error:f,page:r,pageSize:x,hasNextPage:r<S-1,hasPreviousPage:r>0,setPage:y,setPageSize:O=>{h(O),y(0)},email:u,setEmail:O=>{l(O),y(0)},refetch:N}}var fs=ce(require("react"),1),On=require("lucide-react");var ge=require("react/jsx-runtime");function Ai(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 gl(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 nn({customer:e,onBack:a,className:s}){let{api:t}=oe(),[n,i]=fs.useState(null),[o,g]=fs.useState([]),[f,p]=fs.useState(!0),[r,y]=fs.useState(null);fs.useEffect(()=>{let u=!1;return p(!0),y(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,v])=>{u||(i(l),g(v.orders))}).catch(l=>{u||y(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{u||p(!1)}),()=>{u=!0}},[t,e.id,e.email]);let x=n?.addresses??[],h=n?.order_count??o.length;return(0,ge.jsxs)("div",{className:s,children:[(0,ge.jsxs)("div",{className:"af-mb-6",children:[(0,ge.jsxs)(_,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,ge.jsx)(On.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,ge.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,ge.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Ai(e.created_at)]})]}),f?(0,ge.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ge.jsx)(On.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?(0,ge.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):(0,ge.jsxs)("div",{className:"af-space-y-6",children:[(0,ge.jsx)(ka,{deliveries:n?.email_deliveries}),(0,ge.jsxs)("div",{children:[(0,ge.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,ge.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,ge.jsx)("span",{children:e.email})]}),e.name&&(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,ge.jsx)("span",{children:e.name})]}),e.phone&&(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,ge.jsx)("span",{children:e.phone})]}),(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,ge.jsx)("span",{children:h})]})]})]}),x.length>0&&(0,ge.jsxs)("div",{children:[(0,ge.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,ge.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:x.map(u=>(0,ge.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&(0,ge.jsx)(ae,{variant:"secondary",className:"af-mb-1",children:"Default"}),gl(u).map((l,v)=>(0,ge.jsx)("div",{children:l},v))]},u.id))})]}),(0,ge.jsxs)("div",{children:[(0,ge.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,ge.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,ge.jsxs)(Ue,{children:[(0,ge.jsx)(Ve,{children:(0,ge.jsxs)(he,{children:[(0,ge.jsx)(V,{children:"Date"}),(0,ge.jsx)(V,{children:"Amount"}),(0,ge.jsx)(V,{children:"Status"})]})}),(0,ge.jsx)($e,{children:o.map(u=>(0,ge.jsxs)(he,{children:[(0,ge.jsx)($,{className:"af-text-muted-foreground",children:Ai(u.created_at)}),(0,ge.jsx)($,{children:j(Da(u),u.currency)}),(0,ge.jsx)($,{children:(0,ge.jsx)(as,{status:u.status})})]},u.id))})]})]})]})]})}var ue=require("react/jsx-runtime");function vl(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 rn({className:e}){let{customers:a,total:s,isLoading:t,error:n,page:i,pageSize:o,hasNextPage:g,hasPreviousPage:f,setPage:p,setPageSize:r,email:y,setEmail:x,refetch:h}=sn(),[u,l]=Bn.useState("list"),[v,N]=Bn.useState(null),[S,O]=Bn.useState(""),F=P=>{N(P),l("detail")},c=()=>{l("list"),N(null),h()};if(u==="detail"&&v)return(0,ue.jsx)("div",{className:e,children:(0,ue.jsx)(nn,{customer:v,onBack:c})});let A=(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,ue.jsx)(we,{type:"email",value:S,onChange:P=>O(P.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),x(S.trim()))}}),(0,ue.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>x(S.trim()),children:[(0,ue.jsx)(Ba.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),y&&(0,ue.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{O(""),x("")},children:"Clear"})]});if(t)return(0,ue.jsxs)("div",{className:e,children:[A,(0,ue.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ue.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,ue.jsxs)("div",{className:e,children:[A,(0,ue.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ue.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return(0,ue.jsxs)("div",{className:e,children:[y&&A,(0,ue.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,ue.jsx)(Ba.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ue.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:y?"No customers match that email.":(0,ue.jsxs)(ue.Fragment,{children:["No customers yet.",(0,ue.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let D=i*o+1,te=Math.min((i+1)*o,s);return(0,ue.jsxs)("div",{className:e,children:[A,(0,ue.jsxs)(Ue,{children:[(0,ue.jsx)(Ve,{children:(0,ue.jsxs)(he,{children:[(0,ue.jsx)(V,{children:"Email"}),(0,ue.jsx)(V,{children:"Name"}),(0,ue.jsx)(V,{children:"Customer since"}),(0,ue.jsx)(V,{className:"af-text-right",children:"Actions"})]})}),(0,ue.jsx)($e,{children:a.map(P=>(0,ue.jsxs)(he,{children:[(0,ue.jsx)($,{className:"af-font-medium",children:P.email}),(0,ue.jsx)($,{children:P.name||(0,ue.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ue.jsx)($,{className:"af-text-muted-foreground",children:vl(P.created_at)}),(0,ue.jsx)($,{className:"af-text-right",children:(0,ue.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>F(P),title:"View customer",children:(0,ue.jsx)(Ba.Eye,{className:"af-h-4 af-w-4"})})})]},P.id))})]}),(0,ue.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ue.jsxs)("span",{children:["Showing ",D,"-",te," of ",s]}),(0,ue.jsxs)(ca,{value:String(o),onValueChange:P=>r(Number(P)),children:[(0,ue.jsx)(Qt,{className:"af-w-[70px] af-h-8",children:(0,ue.jsx)(ua,{})}),(0,ue.jsxs)(Xt,{children:[(0,ue.jsx)(Je,{value:"10",children:"10"}),(0,ue.jsx)(Je,{value:"25",children:"25"}),(0,ue.jsx)(Je,{value:"50",children:"50"}),(0,ue.jsx)(Je,{value:"100",children:"100"})]})]}),(0,ue.jsx)("span",{children:"per page"})]}),(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ue.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>p(i-1),disabled:!f,children:[(0,ue.jsx)(Ba.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ue.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>p(i+1),disabled:!g,children:["Next",(0,ue.jsx)(Ba.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Te=ce(require("react"),1),ht=require("lucide-react");var yt=ce(require("react"),1);function ms({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=oe(),[n,i]=yt.useState([]),[o,g]=yt.useState(0),[f,p]=yt.useState(null),[r,y]=yt.useState(!0),[x,h]=yt.useState(null),[u,l]=yt.useState(0),[v,N]=yt.useState(e),[S,O]=yt.useState(void 0),[F,c]=yt.useState(""),[A,D]=yt.useState(""),[te,P]=yt.useState(""),[E,U]=yt.useState(""),[w,Z]=yt.useState(""),ee=S?S.join(","):"",q=yt.useRef(0),de=yt.useCallback(async()=>{let Q=++q.current;y(!0),h(null);try{let G={labels:ee?ee.split(","):void 0,customerEmail:F||void 0,q:A||void 0,from:te||void 0,to:E||void 0,retainerId:w||void 0,includeAggregates:s,limit:v,offset:u*v},ie=await t.getInvoices(G);if(Q!==q.current)return;if(u>0&&u*v>=ie.total){l(Math.max(0,Math.ceil(ie.total/v)-1));return}i(ie.invoices),g(ie.total),s&&p(ie.aggregates??null)}catch(G){if(Q!==q.current)return;h(G instanceof Error?G:new Error("Failed to fetch invoices"))}finally{Q===q.current&&y(!1)}},[t,ee,F,A,te,E,w,u,v,s]);yt.useEffect(()=>{de()},[de,a]);let K=Q=>G=>{l(0),Q(G)};return{invoices:n,total:o,aggregates:f,isLoading:r,error:x,page:u,pageSize:v,hasNextPage:(u+1)*v<o,hasPreviousPage:u>0,setPage:l,setPageSize:K(N),labels:S,setLabels:K(O),customerEmail:F,setCustomerEmail:K(c),q:A,setQ:K(D),from:te,setFrom:K(P),to:E,setTo:K(U),retainerId:w,setRetainerId:K(Z),clearFilters:()=>{l(0),O(void 0),c(""),D(""),P(""),U(""),Z("")},refetch:de}}var m=require("react/jsx-runtime"),bl={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 Nr(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:bl[e.label]??e.label}function yl(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 wr={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},hl={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Ts({invoice:e,className:a}){return(0,m.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,m.jsx)(ae,{variant:yl(e.label),className:a,children:Nr(e)}),e.collection_method==="charge_automatically"&&(0,m.jsx)(ae,{variant:"secondary",children:"Managed in Stripe"})]})}function Un({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,m.jsx)(ae,{variant:s,className:a,children:wr[e.state]??e.state})}function Cs(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ga(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 Ii={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Fn={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 xl(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 hr=100,xr=5e3;async function wl(e,a){let s=[],t=0;for(let n=0;n<xr;n+=hr){let i=await e.getInvoices({...a,limit:hr,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<hr||s.length>=t)break}return{invoices:s.slice(0,xr),total:t,truncated:t>s.length||t>xr}}function Li(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,Cs(t),Nr(t),t.customer_name??"",t.customer_email??"",t.created_at,t.due_at??"",t.paid_at??"",t.currency.toUpperCase(),j(t.amount_subtotal,t.currency),j(t.tax_total,t.currency),j(t.amount_total,t.currency),t.amount_due===null?"":j(t.amount_due,t.currency),t.amount_paid===null?"":j(t.amount_paid,t.currency),j(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?"":j(t.discount_total,t.currency),t.collection_method??""]);return[a,...s].map(t=>t.map(xl).join(",")).join(`
5
- `)}function Nl(e){if(typeof document>"u")return;let a=new Blob([Li(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 Sl({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:g=null,onClearRetainerFilter:f,maxRows:p,onViewAll:r}){let y=typeof p=="number",{api:x}=oe(),{invoices:h,total:u,isLoading:l,error:v,page:N,pageSize:S,hasNextPage:O,hasPreviousPage:F,setPage:c,labels:A,setLabels:D,customerEmail:te,setCustomerEmail:P,q:E,setQ:U,from:w,setFrom:Z,to:ee,setTo:q,retainerId:de,setRetainerId:K,refetch:Q}=ms({refreshKey:a}),[G,ie]=Te.useState(typeof p=="number"?"all":"open"),[J,Re]=Te.useState(""),[Qe,ot]=Te.useState(null),Ee=Te.useRef(0),Ge=!y||!!r,tt=Te.useCallback(H=>{if(y){r?.();return}Ee.current++,Tt(!1),ot(H)},[y,r]),[Pe,Tt]=Te.useState(!1),[C,L]=Te.useState(0),[I,pe]=Te.useState(null),[ye,ke]=Te.useState(!1),[Le,at]=Te.useState(0);Te.useEffect(()=>{ot(H=>{if(!H)return H;let Ze=h.find(z=>z.id===H.id);return Ze&&Ze!==H?Ze:H})},[h]);let[ze,Ke]=Te.useState(!1),[le,Oe]=Te.useState(null),lt=async()=>{if(!ze){Ke(!0),Oe(null);try{let{invoices:H,total:Ze,truncated:z}=await wl(x,{labels:A,customerEmail:te,q:E,from:w,to:ee,retainerId:de});Nl(H),Oe(z?`Exported the first ${H.length.toLocaleString()} of ${Ze.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Oe("Couldn't export \u2014 try again.")}finally{Ke(!1)}}},Jt=!te&&!E&&!w&&!ee&&!de,[xt,kt]=Te.useState(null);Te.useEffect(()=>{if(l||u>0||!Jt||G!=="open")return;let H=!1;return x.getInvoices({limit:1}).then(Ze=>{H||kt(Ze.total>0)}).catch(()=>{H||kt(!0)}),()=>{H=!0}},[x,l,u,Jt,G,a]),Te.useEffect(()=>{D(y?Fn.all:Fn.open)},[]),Te.useEffect(()=>{let H=g?.id??"";H!==de&&(K(H),H&&(ie("all"),D(Fn.all),P(""),U(""),Re(""),Z(""),q("")))},[g?.id]),Te.useEffect(()=>{let H=!1;return ke(!1),x.getInvoiceSettings().then(Ze=>{H||pe({payments_active:Ze.payments_active,blocked:Ze.blocked})}).catch(()=>{H||ke(!0)}),()=>{H=!0}},[x,a,Le]),Te.useEffect(()=>{if(!s||y)return;let H=!1,Ze=Ee.current;return Tt(!1),x.getInvoice(s).then(z=>{!H&&Ze===Ee.current&&ot(z)}).catch(()=>{!H&&Ze===Ee.current&&Tt(!0)}),()=>{H=!0}},[x,s,C,y]),Te.useEffect(()=>{t?.(Qe!==null)},[Qe,t]);let $t=H=>{ie(H),D(Fn[H])},qe=H=>{let Ze=H.trim();if(!Ze){E&&U(""),te&&P("");return}if(Ze.includes("@")){E&&U(""),P(Ze);return}te&&P(""),U(Ze.replace(/^#/,""))},st=h,Ja=y?st.slice(0,p):st,Ds=Pe&&(0,m.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,m.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>L(H=>H+1),children:"Retry opening invoice"})]});if(Qe)return(0,m.jsxs)("div",{className:e,children:[Ds,(0,m.jsx)(Vn,{invoice:Qe,refreshKey:a,onBack:()=>{tt(null),Q()}},Qe.id)]});let It=(0,m.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[ye&&(0,m.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,m.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>at(H=>H+1),children:"Retry setup check"})]}),Ds,I?.blocked&&(0,m.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",I.blocked.reason?`: ${I.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),g&&(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,m.jsxs)(ae,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",g.label]}),f&&(0,m.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:f,children:"Clear schedule filter"})]}),(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,m.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(Ii).map(H=>(0,m.jsx)("button",{type:"button","aria-pressed":G===H,onClick:()=>$t(H),className:X("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",G===H?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ii[H]},H))}),(0,m.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,m.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,m.jsx)(we,{type:"text",value:J,onChange:H=>Re(H.target.value),onBlur:()=>qe(J),onKeyDown:H=>{H.key==="Enter"&&(H.preventDefault(),qe(J))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,m.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,m.jsx)(_e,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,m.jsx)(we,{id:"invoices-from",type:"date",value:w,max:ee||void 0,onChange:H=>Z(H.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,m.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,m.jsx)(_e,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,m.jsx)(we,{id:"invoices-to",type:"date",value:ee,min:w||void 0,onChange:H=>q(H.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,m.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>void lt(),disabled:ze||l||!!v||u===0,"aria-busy":ze,children:[(0,m.jsx)(ht.Download,{className:"af-h-4 af-w-4 af-mr-1"}),ze?"Exporting\u2026":"Export CSV (all matching)"]})]}),le&&(0,m.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:le})]});return l?(0,m.jsxs)("div",{className:e,children:[y?null:It,(0,m.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(H=>(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)(se,{className:"af-h-4 af-w-20"}),(0,m.jsx)(se,{className:"af-h-4 af-w-16"})]}),(0,m.jsx)(se,{className:"af-mt-2 af-h-3 af-w-40"})]},H))})]}):v?(0,m.jsxs)("div",{className:e,children:[y?null:It,(0,m.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,m.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void Q(),children:"Retry"})]})]}):u===0&&Jt&&(G==="all"||xt===!1)&&(G==="open"||G==="all")?I?.blocked?(0,m.jsxs)("div",{className:e,children:[y?null:It,(0,m.jsx)(Mn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,m.jsxs)("div",{className:e,children:[y?null:It,(0,m.jsx)(Mn,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):I&&!I.payments_active?(0,m.jsxs)("div",{className:e,children:[y?null:It,(0,m.jsx)(Mn,{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,m.jsxs)("div",{className:e,children:[y?null:It,(0,m.jsx)(Mn,{heading:"No invoices yet",body:!I||ye?"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,m.jsxs)("div",{className:e,children:[y?null:It,Ja.length===0?(0,m.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,m.jsxs)(m.Fragment,{children:[(0,m.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Ja.map(H=>(0,m.jsxs)("button",{type:"button",onClick:()=>tt(H),disabled:!Ge,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ge?" hover:af-bg-muted/50":""}`,children:[(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,m.jsx)("span",{className:"af-font-medium",children:Cs(H)}),(0,m.jsx)(Ts,{invoice:H})]}),(0,m.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:H.customer_name??H.customer_email??"\u2014"}),H.delivery&&(0,m.jsx)("div",{className:"af-mt-1",children:(0,m.jsx)(Un,{delivery:H.delivery})}),(0,m.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,m.jsx)("span",{children:H.collection_method==="charge_automatically"?"Automatic collection":H.due_at?`Due ${ga(H.due_at)}`:"Due on receipt"}),(0,m.jsx)("span",{className:"af-font-medium af-tabular-nums",children:j(H.amount_due??H.amount_total,H.currency)})]})]},H.id))}),(0,m.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,m.jsxs)(Ue,{children:[(0,m.jsx)(Ve,{children:(0,m.jsxs)(he,{children:[(0,m.jsx)(V,{children:"Invoice"}),(0,m.jsx)(V,{children:"Created"}),(0,m.jsx)(V,{children:"Customer"}),(0,m.jsx)(V,{children:"Due"}),(0,m.jsx)(V,{className:"af-text-right",children:"Amount"}),(0,m.jsx)(V,{children:"Status"}),(0,m.jsx)(V,{children:"Delivery"}),(0,m.jsx)(V,{className:"af-w-8"})]})}),(0,m.jsx)($e,{children:Ja.map(H=>(0,m.jsxs)(he,{className:Ge?"af-cursor-pointer":void 0,onClick:Ge?()=>tt(H):void 0,children:[(0,m.jsx)($,{className:"af-font-medium",children:(0,m.jsx)("button",{type:"button",disabled:!Ge,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ge?" hover:af-underline":""}`,onClick:Ze=>{Ze.stopPropagation(),tt(H)},"aria-label":`Open invoice ${Cs(H)}`,children:Cs(H)})}),(0,m.jsx)($,{children:ga(H.created_at)}),(0,m.jsxs)($,{children:[(0,m.jsx)("div",{children:H.customer_name??"\u2014"}),(0,m.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:H.customer_email})]}),(0,m.jsx)($,{children:H.collection_method==="charge_automatically"?"Automatic":H.due_at?ga(H.due_at):"On receipt"}),(0,m.jsx)($,{className:"af-text-right af-tabular-nums",children:j(H.amount_due??H.amount_total,H.currency)}),(0,m.jsx)($,{children:(0,m.jsx)(Ts,{invoice:H})}),(0,m.jsx)($,{children:(0,m.jsx)(Un,{delivery:H.delivery})}),(0,m.jsx)($,{children:(0,m.jsx)(ht.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},H.id))})]})}),y?null:(0,m.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,m.jsxs)("span",{children:[u," invoice",u===1?"":"s"]}),(0,m.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,m.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(N-1),disabled:!F,"aria-label":"Previous page",children:(0,m.jsx)(ht.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,m.jsxs)("span",{className:"af-tabular-nums",children:[N*S+1,"\u2013",Math.min((N+1)*S,u)]}),(0,m.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(N+1),disabled:!O,"aria-label":"Next page",children:(0,m.jsx)(ht.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Mn({heading:e,body:a,action:s}){return(0,m.jsx)(Ps,{icon:ht.FileText,heading:e,body:a,action:s})}function Ka(e){return(0,m.jsx)(Sl,{...e},e.maxRows==null?"full":"compact")}var Ga="af-text-xs af-text-muted-foreground";function Di(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Vn({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=oe(),i=Te.useRef(null);Te.useEffect(()=>{i.current?.focus()},[e.id]);let[o,g]=Te.useState(!1),[f,p]=Te.useState(null),[r,y]=Te.useState(!1),[x,h]=Te.useState(!1),u=Te.useRef(0),[l,v]=Te.useState(null),[N,S]=Te.useState(!1),[O,F]=Te.useState(0);Te.useEffect(()=>{let w=!1;return S(!1),n.getInvoice(e.id).then(Z=>{w||v({source:e,value:Z})}).catch(()=>{w||S(!0)}),()=>{w=!0}},[n,e,s,O]);let c=l?.source===e?l.value:e,A=c.collection_method==="charge_automatically";Te.useEffect(()=>(u.current++,p(null),y(!1),h(!1),g(!1),()=>{u.current++}),[n,c,s]);let D=w=>w==null?"\u2014":j(w,c.currency),te=async()=>{if(!(!c.pay_url||!Di()))try{await navigator.clipboard.writeText(c.pay_url),g(!0),setTimeout(()=>g(!1),1500)}catch{}},P=async()=>{if(f){p(null);return}let w=++u.current;h(!1),y(!0);try{let Z=await n.getInvoicePreview(c.id);w===u.current&&p(Z)}catch{w===u.current&&h(!0)}finally{w===u.current&&y(!1)}},E=c.bill_to,U=E?[E.company,E.name,E.address?.line1,E.address?.line2,[E.address?.city,E.address?.state,E.address?.postal_code].filter(Boolean).join(", "),E.address?.country,E.tax_id?`${E.tax_id.value}`:null,E.po_number?`PO ${E.po_number}`:null,E.service_period?`Service period: ${E.service_period}`:null].filter(w=>!!w&&w.length>0):[];return(0,m.jsxs)("div",{className:t,children:[(0,m.jsxs)("div",{className:"af-mb-4",children:[(0,m.jsxs)(_,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,m.jsx)(ht.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,m.jsxs)("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",Cs(c)]}),(0,m.jsx)(Ts,{invoice:c}),(0,m.jsx)(Un,{delivery:c.delivery})]}),(0,m.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,m.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,m.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>F(w=>w+1),children:"Retry details"})]}),c.label==="failed"&&(0,m.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,m.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,m.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,m.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,m.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,m.jsxs)(Ue,{children:[(0,m.jsx)(Ve,{children:(0,m.jsxs)(he,{children:[(0,m.jsx)(V,{children:"Description"}),(0,m.jsx)(V,{className:"af-text-right",children:"Qty"}),(0,m.jsx)(V,{className:"af-text-right",children:"Amount"})]})}),(0,m.jsx)($e,{children:c.line_items.map((w,Z)=>(0,m.jsxs)(he,{children:[(0,m.jsx)($,{style:{overflowWrap:"anywhere"},children:w.description}),(0,m.jsx)($,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:w.quantity}),(0,m.jsx)($,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:D(w.amount)})]},Z))})]}),(0,m.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,m.jsx)(ss,{label:"Subtotal",value:D(c.amount_subtotal)}),(c.discount_total??0)>0&&(0,m.jsx)(ss,{label:"Discount",value:`-${D(c.discount_total)}`}),c.tax_total>0&&(0,m.jsx)(ss,{label:c.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:D(c.tax_total)}),(0,m.jsx)(ss,{label:"Total",value:D(c.amount_total),strong:!0}),c.credit_applied>0&&(0,m.jsx)(ss,{label:"Credit applied",value:`-${D(c.credit_applied)}`}),c.amount_due!==null&&c.amount_due!==c.amount_total&&(0,m.jsx)(ss,{label:"Amount due",value:D(c.amount_due),strong:!0}),c.amount_paid!==null&&c.amount_paid>0&&(0,m.jsx)(ss,{label:"Amount paid",value:D(c.amount_paid)}),c.amount_refunded>0&&(0,m.jsx)(ss,{label:"Refunded",value:D(c.amount_refunded)})]}),c.credit_notes?.length>0&&(0,m.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,m.jsx)("div",{className:Ga,children:"Credit notes"}),c.credit_notes.map(w=>(0,m.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,m.jsxs)("span",{className:"af-text-muted-foreground",children:[ga(w.created_at)," \xB7 ",w.origin==="dashboard"?"issued in Stripe":"refund",w.stripe_credit_note_id?"":" \xB7 being created"]}),(0,m.jsxs)("span",{className:"af-tabular-nums",children:["-",j(w.amount,w.currency)]})]},w.id))]})]}),(c.note||c.footer)&&(0,m.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[c.note&&(0,m.jsxs)("div",{children:[(0,m.jsx)("div",{className:Ga,children:"Note"}),(0,m.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:c.note})]}),c.footer&&(0,m.jsxs)("div",{children:[(0,m.jsx)("div",{className:Ga,children:"Footer"}),(0,m.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:c.footer})]})]}),f&&!A&&(0,m.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,m.jsxs)("div",{className:X(Ga,"af-break-words"),children:["Email preview \u2014 ",f.subject]}),(0,m.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,m.jsx)("iframe",{title:"Invoice email preview",srcDoc:f.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,m.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,m.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,m.jsx)(pa,{label:"Created",value:ga(c.created_at)}),(0,m.jsx)(pa,{label:"Due",value:c.collection_method==="charge_automatically"?"Managed in Stripe":c.due_at?ga(c.due_at):"On receipt"}),c.paid_at&&(0,m.jsx)(pa,{label:"Paid",value:ga(c.paid_at)}),c.payment_method&&(0,m.jsx)(pa,{label:"Paid by",value:c.paid_out_of_band?`${c.payment_method} (recorded outside Stripe)`:c.payment_method}),c.payment_state!=="none"&&(0,m.jsx)(pa,{label:"Payment",value:c.payment_state==="processing"?"Processing":c.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),c.delivery&&(0,m.jsx)(pa,{label:"Delivery",value:`${wr[c.delivery.state]} \xB7 ${c.delivery.recipient}`}),c.marked_uncollectible_at&&(0,m.jsx)(pa,{label:"Written off",value:ga(c.marked_uncollectible_at)}),c.correction_reason&&(0,m.jsx)(pa,{label:"Correction",value:c.correction_reason}),c.replaced_by_order_id&&(0,m.jsx)(pa,{label:"Replaced by",value:c.replaced_by_order_id}),c.collection_method==="charge_automatically"?(0,m.jsx)(pa,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):c.retainer_id&&(0,m.jsx)(pa,{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,m.jsx)(pa,{label:"Replaces",value:c.replaces_order_id})]}),(0,m.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,m.jsx)("div",{className:Ga,children:"Reminders"}),A?(0,m.jsx)("div",{children:"View automatic payment reminders in Stripe."}):c.reminders.disabled?(0,m.jsx)("div",{children:"Off for this invoice."}):c.reminders.paused_until?(0,m.jsxs)("div",{children:["Paused until ",ga(c.reminders.paused_until),"."]}):c.reminders.next_at?(0,m.jsxs)("div",{children:["Next on ",ga(c.reminders.next_at),"."]}):c.reminders.final_sent_at?(0,m.jsxs)("div",{children:["Final reminder sent ",ga(c.reminders.final_sent_at),"."]}):(0,m.jsx)("div",{children:"None scheduled."}),!A&&(0,m.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",c.reminders.schedule.length===0?"none":c.reminders.schedule.map(w=>w<0?`${-w}d before`:w===0?"due day":`${w}d after`).join(", ")]})]}),c.communications&&c.communications.length>0&&(0,m.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,m.jsx)("div",{className:Ga,children:"Email delivery history"}),c.communications.map(w=>(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,m.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[hl[w.kind]??w.kind,w.kind==="reminder"&&w.slot!==null?` #${w.slot}`:"",(0,m.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",w.recipient]})]}),(0,m.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[wr[w.state]??w.state," \xB7 ",ga(w.state_at??w.created_at)]})]},w.id))]}),U.length>0&&(0,m.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,m.jsx)("div",{className:Ga,children:"Bill to"}),U.map((w,Z)=>(0,m.jsx)("div",{className:"af-break-words",children:w},Z))]}),(0,m.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[c.pay_url&&(0,m.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void te(),disabled:!Di(),children:[(0,m.jsx)(ht.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":A?"Copy invoice link":"Copy pay link"]}),c.pdf_url&&(0,m.jsx)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,m.jsxs)("a",{href:c.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,m.jsx)(ht.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!A&&(0,m.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void P(),disabled:r,children:[r?(0,m.jsx)(ht.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,m.jsx)(ht.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),f?"Hide email preview":x?"Retry email preview":"Show email preview"]}),x&&!A&&(0,m.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),c.pay_url&&(0,m.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:c.pay_url}),(0,m.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:A?"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 pa({label:e,value:a}){return(0,m.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,m.jsx)("span",{className:X(Ga,"af-shrink-0"),children:e}),(0,m.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function ss({label:e,value:a,strong:s}){return(0,m.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,m.jsx)("dt",{className:X(Ga,s&&"af-font-medium af-text-foreground"),children:e}),(0,m.jsx)("dd",{className:X("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}var Bi=require("lucide-react");var Ie=require("react/jsx-runtime"),_l={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Oi={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Rl(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 Fi(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>Oi[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>Oi[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":_l[e.status]}function Mi(e){let a=e.interval==="year"?"every year":"every month";return`${j(e.amount,e.currency)} ${a}`}function Pl(e){return e.status==="canceled"?`Ended ${$n(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${$n(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 ${$n(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${$n(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function $n(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,Ie.jsx)(ae,{variant:Rl(e.status),className:X("af-max-w-full af-whitespace-normal af-break-words",a),children:Fi(e)})}function ps({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:g=0,isLoadingMore:f=!1,onLoadMore:p,includeEnded:r=!1,onIncludeEndedChange:y,className:x}){let h=!!y;if(!a&&!s&&e.length===0&&!(h&&(r||g>0)))return null;let u=o!==void 0?Math.max(0,o-e.length):0;return(0,Ie.jsxs)("section",{className:X("af-mb-6",x),"aria-label":"Recurring invoices",children:[(0,Ie.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Ie.jsx)(Bi.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,Ie.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,Ie.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."}),h&&(0,Ie.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>y?.(!r),children:r?"Hide ended recurring invoices":g>0&&e.length===0?`Show ended recurring invoices (${g})`:"Show ended recurring invoices"})]}),s?(0,Ie.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,Ie.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?(0,Ie.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(l=>(0,Ie.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,Ie.jsx)(se,{className:"af-h-4 af-w-48"}),(0,Ie.jsx)(se,{className:"af-mt-2 af-h-3 af-w-32"})]},l))}):e.length===0?(0,Ie.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,Ie.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(l=>{let v=i===l.id;return(0,Ie.jsxs)("li",{className:X("af-rounded-md af-border af-p-3",v&&"af-border-primary af-bg-muted/40"),children:[(0,Ie.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,Ie.jsxs)("div",{className:"af-min-w-0",children:[(0,Ie.jsx)("div",{className:"af-truncate af-font-medium",children:l.customer_name??l.customer_email??"\u2014"}),(0,Ie.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:l.description})]}),(0,Ie.jsx)(Hn,{retainer:l})]}),l.collection_method==="charge_automatically"?(0,Ie.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,Ie.jsx)(ae,{variant:"secondary",children:"Managed in Stripe"}),(0,Ie.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,Ie.jsx)("div",{className:"af-mt-2 af-text-sm",children:Mi(l)}),(0,Ie.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,Ie.jsxs)("span",{children:[Pl(l)," \xB7 ",l.cycles.count===0?"no invoices yet":`${l.cycles.paid} paid${l.cycles.open>0?`, ${l.cycles.open} open`:""}`]}),l.cycles.count>0&&(0,Ie.jsx)(_,{type:"button",variant:v?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":v,children:v?"Showing invoices":"View invoices"})]}),l.status==="failed"&&l.operation?.last_error&&(0,Ie.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",l.operation.last_error,". Ask in the chat to try again."]})]},l.id)})}),!a&&!s&&u>0&&p&&(0,Ie.jsx)("div",{className:"af-mt-2",children:(0,Ie.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:p,disabled:f,children:f?"Loading\u2026":`Load more (${u} more)`})})]})}var Ui=ce(require("react"),1),ia=require("lucide-react");var Ne=require("react/jsx-runtime");function on({onConnectStripe:e,onUpgradePlan:a,className:s}){let{status:t,isLoading:n,error:i,refetch:o}=za(),[g,f]=Ui.useState(!1),p=async()=>{f(!0);try{await o()}finally{f(!1)}};return n&&!t?(0,Ne.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ne.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!t?(0,Ne.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ne.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):t.status==="active"?(0,Ne.jsx)("div",{className:s,children:(0,Ne.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,Ne.jsx)(ia.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Ne.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,Ne.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[t.reason==="needs_stripe"&&(0,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ne.jsx)(ia.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Ne.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,Ne.jsxs)(_,{onClick:e,children:[(0,Ne.jsx)(ia.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),t.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Ne.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,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ne.jsx)(ia.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Ne.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,Ne.jsx)(_,{onClick:a,children:"Upgrade plan"}):(0,Ne.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,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.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,Ne.jsx)(ia.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),t.stripe_account_connected?(0,Ne.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,Ne.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,Ne.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&t.stripe_account_connected&&(0,Ne.jsxs)(_,{onClick:e,children:[(0,Ne.jsx)(ia.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Ne.jsxs)(_,{variant:"outline",onClick:p,disabled:g,children:[g?(0,Ne.jsx)(ia.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Ne.jsx)(ia.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var Mt=ce(require("react"),1);function Sr(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function gs({includeStats:e=!1,refreshKey:a}={}){let{api:s}=oe(),[t,n]=Mt.useState([]),[i,o]=Mt.useState(!0),[g,f]=Mt.useState(null),p=Mt.useRef(0),r=Mt.useCallback(async()=>{let v=++p.current;try{o(!0),f(null);let N=await s.getProducts(e?{include:"stats"}:{});if(v!==p.current)return;n(N)}catch(N){if(v!==p.current)return;f(N instanceof Error?N:new Error("Failed to fetch products"))}finally{v===p.current&&o(!1)}},[s,e,a]);Mt.useEffect(()=>{r()},[r]);let y=Mt.useCallback(async v=>{let N=await s.createProduct(v);return n(S=>[N,...S]),N},[s]),x=Mt.useCallback(async(v,N)=>{let S=await s.updateProduct(v,N);return n(O=>Sr(O,v,S)),S},[s]),h=Mt.useCallback(async v=>{await s.deleteProduct(v),n(N=>N.filter(S=>S.id!==v))},[s]),u=Mt.useCallback(async(v,N)=>{let S=await s.attachProductFile(v,N);return n(O=>Sr(O,v,S)),S},[s]),l=Mt.useCallback(async(v,N)=>{let S=await s.attachProductFileFromUrl(v,N);return n(O=>Sr(O,v,S)),S},[s]);return{products:t,isLoading:i,error:g,refetch:r,createProduct:y,updateProduct:x,deleteProduct:h,attachProductFile:u,attachProductFileFromUrl:l}}var Ut=ce(require("react"),1);var Vi=["creating","active","paused","canceling"],Cl=["canceled","failed"];function vs({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=oe(),[n,i]=Ut.useState([]),[o,g]=Ut.useState(0),[f,p]=Ut.useState(0),[r,y]=Ut.useState(!0),[x,h]=Ut.useState(!1),[u,l]=Ut.useState(null),[v,N]=Ut.useState(a),S=Ut.useRef(0),O=Ut.useCallback(async()=>{let c=++S.current;y(!0),h(!1),l(null);try{let A=await t.getRetainers({statuses:v?void 0:Vi,limit:s,offset:0});if(c!==S.current)return;if(i(A.retainers),g(A.total),!v&&A.total===0){let D=await t.getRetainers({statuses:Cl,limit:1,offset:0});if(c!==S.current)return;p(D.total)}else p(0)}catch(A){if(c!==S.current)return;l(A instanceof Error?A:new Error("Failed to fetch retainers"))}finally{c===S.current&&y(!1)}},[t,v,s]);Ut.useEffect(()=>{O()},[O,e]);let F=Ut.useCallback(async()=>{if(r||x||n.length>=o)return;let c=S.current;h(!0);try{let A=await t.getRetainers({statuses:v?void 0:Vi,limit:s,offset:n.length});if(c!==S.current)return;i(D=>{let te=new Set(D.map(P=>P.id));return[...D,...A.retainers.filter(P=>!te.has(P.id))]}),g(A.total)}catch(A){if(c!==S.current)return;l(A instanceof Error?A:new Error("Failed to fetch retainers"))}finally{c===S.current&&h(!1)}},[t,v,s,r,x,n.length,o]);return{retainers:n,total:o,endedTotal:f,hasMore:n.length<o,isLoading:r,isLoadingMore:x,error:u,includeEnded:v,setIncludeEnded:N,loadMore:F,refetch:O}}var be=require("react/jsx-runtime");function _r({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=ks.useState(a),[g,f]=ks.useState("list"),[p,r]=ks.useState(null),y=gs(),{status:x,error:h}=za(),u=x?.currency,l=O=>{r(O),f("edit")},v=()=>{r(null),f("create")},N=()=>{f("list"),r(null)},S=O=>{r(O),f("edit")};return(0,be.jsxs)("div",{className:e,children:[(0,be.jsxs)("div",{className:"af-mb-6",children:[(0,be.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,be.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,be.jsxs)(Rn,{value:i,onValueChange:O=>o(O),children:[(0,be.jsxs)(Bs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,be.jsxs)(ya,{value:"products",className:"af-gap-2",children:[(0,be.jsx)(va.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,be.jsxs)(ya,{value:"orders",className:"af-gap-2",children:[(0,be.jsx)(va.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,be.jsxs)(ya,{value:"invoices",className:"af-gap-2",children:[(0,be.jsx)(va.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,be.jsxs)(ya,{value:"customers",className:"af-gap-2",children:[(0,be.jsx)(va.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,be.jsx)(ya,{value:"promos",children:"Promo codes"}),(0,be.jsxs)(ya,{value:"setup",className:"af-gap-2",children:[(0,be.jsx)(va.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,be.jsx)(ha,{value:"products",children:g==="list"?(0,be.jsx)(Ys,{productsState:y,onSelectProduct:l,onCreateProduct:v}):(0,be.jsxs)("div",{children:[(0,be.jsxs)("div",{className:"af-mb-6",children:[(0,be.jsxs)(_,{variant:"ghost",size:"sm",onClick:N,className:"af-mb-2 af--ml-2",children:[(0,be.jsx)(va.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,be.jsx)("h3",{className:"af-text-lg af-font-semibold",children:g==="create"?"New Product":p?.name})]}),g==="create"&&!u?(0,be.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:h?(0,be.jsxs)("div",{className:"af-text-destructive",children:["Error: ",h.message]}):(0,be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,be.jsx)(Xs,{productsState:y,product:g==="edit"?p:null,currency:u??"usd",onSaved:S},g==="edit"?p?.id??"edit":"new")]})}),(0,be.jsx)(ha,{value:"orders",children:(0,be.jsx)(Wa,{onRefund:t})}),(0,be.jsx)(ha,{value:"invoices",children:(0,be.jsx)(Tl,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:x?.reason==="needs_paid_plan"})}),(0,be.jsx)(ha,{value:"customers",children:(0,be.jsx)(rn,{})}),(0,be.jsx)(ha,{value:"promos",children:(0,be.jsx)(cs,{})}),(0,be.jsx)(ha,{value:"setup",children:(0,be.jsx)(on,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Tl({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=vs(),[n,i]=ks.useState(null),[o,g]=ks.useState(!1);return(0,be.jsxs)(be.Fragment,{children:[!o&&(0,be.jsx)(ps,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:f=>i(p=>p?.id===f.id?null:f),total:t.total,endedTotal:t.endedTotal,isLoadingMore:t.isLoadingMore,onLoadMore:()=>void t.loadMore(),includeEnded:t.includeEnded,onIncludeEndedChange:t.setIncludeEnded}),(0,be.jsx)(Ka,{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 Hi=ce(require("react"),1);var Fa=ce(require("react"),1);function bs({refreshKey:e}={}){let{api:a}=oe(),[s,t]=Fa.useState(null),[n,i]=Fa.useState(!0),[o,g]=Fa.useState(null),f=Fa.useRef(0),p=Fa.useCallback(async()=>{let r=++f.current;try{i(!0),g(null);let y=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==f.current)return;t(y)}catch(y){if(r!==f.current)return;g(y instanceof Error?y:new Error("Failed to fetch summary"))}finally{r===f.current&&i(!1)}},[a,e]);return Fa.useEffect(()=>{p()},[p]),{summary:s,isLoading:n,error:o,refetch:p}}var We=require("react/jsx-runtime");function $i(e,a){if(e.settled.complete)return{headline:j(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:j(s.gross,s.currency),extra:e.totals.slice(1).map(t=>`+ ${j(t.gross,t.currency)} in ${t.currency.toUpperCase()}`)}:{headline:j(0,a),extra:[]}}function Rr({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:g,error:f,refetch:p}=bs({refreshKey:e}),[r,y]=Hi.useState(!1),x=(0,We.jsx)("div",{className:"af-mb-6",children:f&&!o?(0,We.jsx)(na,{message:"Couldn't load your revenue summary.",onRetry:()=>p()}):(0,We.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:g||!o?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(nt,{label:"This week",children:(0,We.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,We.jsx)(nt,{label:"Today",children:(0,We.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,We.jsx)(nt,{label:"Needs attention",children:(0,We.jsx)(se,{className:"af-h-6 af-w-10"})})]}):(0,We.jsx)(We.Fragment,{children:(()=>{let h=$i(o.revenue.d7,o.currency),u=$i(o.revenue.today,o.currency);return(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(nt,{label:"This week",detail:h.extra.length>0?(0,We.jsx)("div",{children:h.extra.map(l=>(0,We.jsx)("div",{children:l},l))}):void 0,children:h.headline}),(0,We.jsx)(nt,{label:"Today",detail:u.extra.length>0?(0,We.jsx)("div",{children:u.extra.map(l=>(0,We.jsx)("div",{children:l},l))}):void 0,children:u.headline}),(0,We.jsx)(nt,{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,We.jsxs)(bt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[x,(0,We.jsx)(Wa,{refreshKey:e,initialOrderId:a,onDetailOpenChange:y,showFulfillment:!0,onRefund:s?t:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Ua=ce(require("react"),1),Es=require("lucide-react");var Ma=ce(require("react"),1),Kn=require("lucide-react");var Pt=require("react/jsx-runtime"),zi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ns="af-text-xs af-text-muted-foreground",zn="af-text-sm af-font-medium af-tabular-nums",kl=3;function El(e){let a=e.pricing,s=a?.currency??e.currency;if(a?.custom_amount??e.allow_custom_amount){let f=e.min_amount??a?.min_amount??null,p=e.max_amount??a?.max_amount??null;return f!==null&&p!==null?{text:`Buyer chooses (${j(f,s)} \u2013 ${j(p,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?j(n,s):`${j(n,s)} \u2013 ${j(i,s)}`,g=a?.compare_at_amount??null;return{text:o,compareAt:g!==null&&g>i?j(g,s):null}}function qn({product:e,className:a}){let s=El(e);return(0,Pt.jsxs)("div",{className:a,children:[(0,Pt.jsx)("span",{className:zn,children:s.text}),s.compareAt&&(0,Pt.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function jn({product:e}){let a=e.inventory;return a?a.tracked?a.out_of_stock?(0,Pt.jsx)(ae,{variant:"destructive",children:"Out of stock"}):a.low_stock?(0,Pt.jsxs)(ae,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?(0,Pt.jsx)(ae,{variant:"secondary",children:"Backorder"}):a.available===null?null:(0,Pt.jsxs)(ae,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?(0,Pt.jsx)(ae,{variant:"warning",children:"Low stock"}):null}function Wn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Gn(e){return e.map(a=>j(a.amount,a.currency)).join(" + ")}function qi(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${j(e.min_amount,e.currency)} \u2013 ${j(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":j(e.unit_amount,e.currency)}function ji({variant:e}){let a=e.inventory;if(!a||!a.tracked)return(0,Pt.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=a.available??0;return a.allow_backorder?(0,Pt.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,Pt.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,s)}),(0,Pt.jsx)(ae,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?(0,Pt.jsx)(ae,{variant:"destructive",children:"Out of stock"}):(0,Pt.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,Pt.jsx)("span",{className:"af-tabular-nums",children:s}),s<=kl&&(0,Pt.jsx)(ae,{variant:"warning",children:"Low"})]})}var Y=require("react/jsx-runtime");function ln({title:e,children:a,className:s}){return(0,Y.jsxs)("section",{className:X("af-rounded-lg af-border af-p-4",s),children:[(0,Y.jsx)("h4",{className:zi,children:e}),(0,Y.jsx)("div",{className:"af-mt-3",children:a})]})}function Wi({src:e,className:a}){let[s,t]=Ma.useState(!1);return Ma.useEffect(()=>t(!1),[e]),!e||s?(0,Y.jsx)("div",{"aria-hidden":"true",className:X("af-flex af-items-center af-justify-center af-bg-muted",a),children:(0,Y.jsx)(Kn.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,Y.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:X("af-object-cover",a)})}function Gi({product:e,showStats:a=!1,onBack:s}){let{api:t}=oe(),[n,i]=Ma.useState(null),[o,g]=Ma.useState(!0),[f,p]=Ma.useState(null),[r,y]=Ma.useState(0),[x,h]=Ma.useState(0);Ma.useEffect(()=>{let c=!1;return g(!0),p(null),t.getProduct(e.id).then(A=>{c||i(A)}).catch(A=>{c||p(A instanceof Error?A:new Error("Failed to load product"))}).finally(()=>{c||g(!1)}),()=>{c=!0}},[t,e.id,r]);let u=n?{...e,...n}:e,l=u.images.length>0?u.images:e.images,v=l[x]??l[0],N=Wn(u),S=a?u.stats:void 0,O=n?.variants??[],F=O.length>1;return(0,Y.jsxs)("div",{children:[(0,Y.jsxs)("div",{className:"af-mb-6",children:[(0,Y.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,Y.jsx)(Kn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,Y.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Y.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),(0,Y.jsx)(ae,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),(0,Y.jsx)(jn,{product:u})]}),(0,Y.jsx)(qn,{product:u,className:"af-mt-1"}),!u.active&&(0,Y.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,Y.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,Y.jsxs)("div",{className:"af-space-y-2",children:[(0,Y.jsx)(Wi,{src:v,className:"af-h-48 af-w-full af-rounded-md af-border"}),l.length>1&&(0,Y.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map((c,A)=>(0,Y.jsx)("button",{type:"button",onClick:()=>h(A),"aria-label":`Show photo ${A+1} of ${l.length}`,"aria-pressed":A===x,className:X("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",A===x?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,Y.jsx)(Wi,{src:c,className:"af-h-12 af-w-12 af-rounded-md"})},`${c}-${A}`))})]}),(0,Y.jsxs)("div",{className:"af-space-y-6",children:[u.description&&(0,Y.jsx)(ln,{title:"Description",children:(0,Y.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?(0,Y.jsxs)(ln,{title:"Variants",children:[(0,Y.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(c=>(0,Y.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,Y.jsx)(se,{className:"af-h-4 af-w-28"}),(0,Y.jsx)(se,{className:"af-h-4 af-w-20"}),(0,Y.jsx)(se,{className:"af-h-4 af-w-16"})]},c))}),(0,Y.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):f?(0,Y.jsx)(na,{message:"Couldn't load this product's variants.",onRetry:()=>y(c=>c+1)}):F?(0,Y.jsx)(ln,{title:`Variants \xB7 ${O.length}`,children:(0,Y.jsx)("div",{className:"af-overflow-x-auto",children:(0,Y.jsxs)(Ue,{children:[(0,Y.jsx)(Ve,{children:(0,Y.jsxs)(he,{children:[(0,Y.jsx)(V,{children:"Variant"}),(0,Y.jsx)(V,{children:"SKU"}),(0,Y.jsx)(V,{className:"af-text-right",children:"Price"}),(0,Y.jsx)(V,{children:"Stock"})]})}),(0,Y.jsx)($e,{children:O.map(c=>(0,Y.jsxs)(he,{children:[(0,Y.jsxs)($,{className:"af-font-medium",children:[c.title||c.option_values.map(A=>A.value).join(" / ")||"\u2014",!c.active&&(0,Y.jsx)(ae,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,Y.jsx)($,{className:"af-text-muted-foreground",children:c.sku?(0,Y.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:c.sku}):"\u2014"}),(0,Y.jsxs)($,{className:"af-whitespace-nowrap af-text-right",children:[(0,Y.jsx)("div",{className:zn,children:qi(c)}),c.compare_at_amount!==null&&c.unit_amount!==null&&c.compare_at_amount>c.unit_amount&&(0,Y.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:j(c.compare_at_amount,c.currency)})]}),(0,Y.jsx)($,{className:"af-text-sm",children:(0,Y.jsx)(ji,{variant:c})})]},c.id))})]})})}):null,(0,Y.jsx)(ln,{title:"Details",children:(0,Y.jsxs)("dl",{className:"af-space-y-2",children:[(0,Y.jsxs)("div",{children:[(0,Y.jsx)("dt",{className:ns,children:"Delivery"}),(0,Y.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,Y.jsxs)("div",{children:[(0,Y.jsx)("dt",{className:ns,children:"Sends buyers to"}),(0,Y.jsx)("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),(0,Y.jsxs)("div",{children:[(0,Y.jsx)("dt",{className:ns,children:"Shipping address"}),(0,Y.jsx)("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,Y.jsxs)("div",{children:[(0,Y.jsx)("dt",{className:ns,children:"Most one buyer can order"}),(0,Y.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),S&&(0,Y.jsx)(ln,{title:"Last 30 days",children:(0,Y.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,Y.jsxs)("div",{children:[(0,Y.jsx)("dt",{className:ns,children:"Units sold"}),(0,Y.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.units_sold})]}),(0,Y.jsxs)("div",{children:[(0,Y.jsx)("dt",{className:ns,children:"Orders"}),(0,Y.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.orders})]}),(0,Y.jsxs)("div",{children:[(0,Y.jsx)("dt",{className:ns,children:"Gross"}),(0,Y.jsx)("dd",{className:zn,children:S.gross.length>0?Gn(S.gross):"\u2014"})]})]})}),(0,Y.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var M=require("react/jsx-runtime"),Al={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Il=["all","active","draft","low_stock","out_of_stock"];function Ki(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function Zi(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Dl(e){return e.inventory?.out_of_stock??!1}function Ll(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Zi(e);case"out_of_stock":return Dl(e);default:return!0}}function Ol({product:e,showStats:a,onOpen:s}){let t=e.images[0],n=a?e.stats:void 0,i=Wn(e),o=e.variant_count??0;return(0,M.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,M.jsx)("img",{src:t,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,M.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,M.jsx)(Es.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,M.jsxs)("div",{className:"af-space-y-2 af-p-3",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)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,M.jsx)(qn,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,M.jsx)(ae,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,M.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,M.jsx)(jn,{product:e}),o>1&&(0,M.jsxs)(ae,{variant:"outline",children:[o," variants"]}),i&&(0,M.jsx)(ae,{variant:"outline",children:i})]}),n&&(0,M.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Gn(n.gross)}`:""," ",(0,M.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Bl(){return(0,M.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,M.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,M.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,M.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,M.jsx)(se,{className:"af-w-32"}),(0,M.jsx)(se,{className:"af-w-16"}),(0,M.jsx)(se,{className:"af-h-5 af-w-24"})]})]},e))})}function Pr({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:g}=gs({includeStats:a,refreshKey:e}),[f,p]=Ua.useState(!1),[r,y]=Ua.useState(null),[x,h]=Ua.useState("all"),[u,l]=Ua.useState(""),[v,N]=Ua.useState("newest"),S=Ua.useMemo(()=>{if(!a)return null;let w=null;for(let Z of n)!Z.stats||Z.stats.units_sold===0||(!w||Z.stats.units_sold>(w.stats?.units_sold??0))&&(w=Z);return w},[n,a]),O=Ua.useMemo(()=>n.filter(Zi).length,[n]),F=u.trim().toLowerCase(),c=Ua.useMemo(()=>{let Z=[...n.filter(ee=>Ll(ee,x)&&(!F||ee.name.toLowerCase().includes(F)))];return v==="name"?Z.sort((ee,q)=>ee.name.localeCompare(q.name)):v==="best_selling"?Z.sort((ee,q)=>(q.stats?.units_sold??0)-(ee.stats?.units_sold??0)):Z.sort((ee,q)=>Ki(q.created_at)-Ki(ee.created_at)),Z},[n,x,F,v]),A=x!=="all"||!!F,D=()=>{h("all"),l("")},te=i||o!==null&&n.length===0,P=(0,M.jsx)("div",{className:"af-mb-6",children:(0,M.jsx)("div",{className:X("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:te?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(nt,{label:"Products",children:(0,M.jsx)(se,{className:"af-h-6 af-w-10"})}),a?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(nt,{label:"Best seller",children:(0,M.jsx)(se,{className:"af-h-6 af-w-28"})}),(0,M.jsx)(nt,{label:"Low stock",children:(0,M.jsx)(se,{className:"af-h-6 af-w-10"})})]}):(0,M.jsx)(nt,{label:"Active",children:(0,M.jsx)(se,{className:"af-h-6 af-w-10"})})]}):(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(nt,{label:"Products",children:n.length}),a?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(nt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:S?`${S.stats?.units_sold??0} sold, last 30 days`:void 0,children:S?(0,M.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:S.name}):(0,M.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,M.jsx)(nt,{label:"Low stock",children:O})]}):(0,M.jsx)(nt,{label:"Active",children:n.filter(w=>w.active).length})]})})}),E=(0,M.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,M.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,M.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:Il.map(w=>(0,M.jsx)("button",{type:"button","aria-pressed":x===w,onClick:()=>h(w),className:X("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",x===w?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Al[w]},w))}),(0,M.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,M.jsx)(Es.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)(we,{type:"text",value:u,onChange:w=>l(w.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,M.jsxs)(ca,{value:v,onValueChange:w=>N(w),children:[(0,M.jsx)(Qt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,M.jsx)(ua,{})}),(0,M.jsxs)(Xt,{children:[(0,M.jsx)(Je,{value:"newest",children:"Newest"}),(0,M.jsx)(Je,{value:"name",children:"Name A\u2013Z"}),a&&(0,M.jsx)(Je,{value:"best_selling",children:"Best selling"})]})]}),A&&(0,M.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:D,children:"Clear filters"})]}),i&&n.length===0?(0,M.jsx)(se,{className:"af-h-4 af-w-28"}):(0,M.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:A?`${c.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${O>0?` \xB7 ${O} low stock`:""}`})]}),U;return r?U=(0,M.jsx)(Gi,{product:r,showStats:a,onBack:()=>{y(null),g()}},r.id):i&&n.length===0?U=(0,M.jsxs)(M.Fragment,{children:[E,(0,M.jsx)(Bl,{}),(0,M.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?U=(0,M.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,M.jsx)(na,{message:"Couldn't load your products.",onRetry:()=>g()})}):n.length===0?U=(0,M.jsxs)(Pa,{icon:(0,M.jsx)(Es.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,M.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):U=(0,M.jsxs)(M.Fragment,{children:[E,o&&(0,M.jsx)("div",{className:"af-mb-4",children:(0,M.jsx)(na,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>g()})}),c.length===0?(0,M.jsxs)(Pa,{children:["No products match these filters.",(0,M.jsx)("br",{}),(0,M.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:D,children:"Show all products"})]}):(0,M.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:c.map(w=>(0,M.jsx)(Ol,{product:w,showStats:a,onOpen:()=>y(w)},w.id))})]}),(0,M.jsx)(bt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:t,children:f?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(_,{variant:"ghost",onClick:()=>p(!1),children:"Back to products"}),(0,M.jsx)(cs,{})]}):(0,M.jsxs)(M.Fragment,{children:[!r&&(0,M.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,M.jsx)(_,{variant:"outline",onClick:()=>p(!0),children:"Promo codes"})}),!r&&P,U]})})}var Ca=ce(require("react"),1),gt=require("lucide-react");var oa=ce(require("react"),1);function cn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=oe(),[t,n]=oa.useState([]),[i,o]=oa.useState(!0),[g,f]=oa.useState(null),[p,r]=oa.useState(0),[y]=oa.useState(e),[x,h]=oa.useState(""),u=oa.useRef(0),l=oa.useCallback(async()=>{let v=++u.current;try{o(!0),f(null);let N={limit:y,offset:p*y};x.trim()&&(N.q=x.trim());let S=await s.getPeople(N);if(v!==u.current)return;n(S.people)}catch(N){if(v!==u.current)return;f(N instanceof Error?N:new Error("Failed to fetch people"))}finally{v===u.current&&o(!1)}},[s,p,y,x,a]);return oa.useEffect(()=>{l()},[l]),{people:t,isLoading:i,error:g,page:p,pageSize:y,hasNextPage:t.length===y,hasPreviousPage:p>0,setPage:r,q:x,setQ:v=>{h(v),r(0)},refetch:l}}var Va=ce(require("react"),1);function un(e,{refreshKey:a}={}){let{api:s}=oe(),[t,n]=Va.useState(null),[i,o]=Va.useState(e!==null),[g,f]=Va.useState(null),p=Va.useRef(0),r=Va.useCallback(async()=>{if(e===null){n(null),o(!1),f(null);return}let y=++p.current;try{o(!0),f(null);let x=await s.getPerson(e);if(y!==p.current)return;n(x)}catch(x){if(y!==p.current)return;f(x instanceof Error?x:new Error("Failed to fetch person"))}finally{y===p.current&&o(!1)}},[s,e,a]);return Va.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:g,refetch:r}}var b=require("react/jsx-runtime"),Cr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Fl="af-text-xs af-text-muted-foreground";function As(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 Tr(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function Ml(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Ul({value:e,label:a}){let[s,t]=Ca.useState(!1);return Ml()?(0,b.jsxs)(_,{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,b.jsx)(gt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,b.jsx)(gt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function Ji(e){return(0,b.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,b.jsxs)(ae,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,b.jsx)(ae,{variant:"secondary",children:"Contact form"})]})}function Yi(e){return e.name?e.name:e.email?e.email:(0,b.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Vl=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,$l=40;function Hl(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>Vl.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=$l).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 zl(e){return e.replace(/_/g," ")}function ql(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function jl({data:e}){let{message:a,rest:s}=Hl(e);return a===null&&s.length===0?(0,b.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,b.jsxs)("div",{className:"af-space-y-3",children:[a!==null&&(0,b.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:a}),s.length>0&&(0,b.jsx)("dl",{className:"af-space-y-1",children:s.map(([t,n])=>(0,b.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,b.jsx)("dt",{className:X(Fl,"af-w-28 af-shrink-0 af-capitalize"),children:zl(t)}),(0,b.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:ql(n)})]},t))})]})}function Qi({formName:e,createdAt:a,data:s}){return(0,b.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,b.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,b.jsx)(ae,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,b.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,b.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:As(a)})]}),(0,b.jsx)(jl,{data:s})]})}function Wl(e){return e.charged_total??e.amount_total}function Gl({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=un(e,{refreshKey:a}),g=Tr(e,t?.submissions[0]?.form_name);return(0,b.jsxs)("div",{children:[(0,b.jsxs)("div",{className:"af-mb-6",children:[(0,b.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,b.jsx)(gt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,b.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,b.jsxs)("div",{className:"af-min-w-0",children:[n?(0,b.jsx)(se,{className:"af-h-7 af-w-48"}):(0,b.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:t?.name||e}),(0,b.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,b.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,b.jsx)(Ul,{value:e,label:"Copy email address"})]})]}),(0,b.jsx)(_,{asChild:!0,children:(0,b.jsxs)("a",{href:g,children:[(0,b.jsx)(gt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?(0,b.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(f=>(0,b.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,b.jsx)(se,{className:"af-w-40"}),(0,b.jsx)(se,{className:"af-mt-2 af-w-64"})]},f)),(0,b.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?(0,b.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,b.jsx)(na,{message:"Couldn't load this person.",onRetry:()=>o()})}):(0,b.jsxs)("div",{className:"af-space-y-6",children:[t.customer&&(0,b.jsxs)("div",{children:[(0,b.jsx)("h4",{className:X(Cr,"af-mb-3"),children:"Customer"}),(0,b.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[t.customer.name&&(0,b.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,b.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,b.jsx)("dd",{children:t.customer.name})]}),t.customer.phone&&(0,b.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,b.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,b.jsx)("dd",{children:t.customer.phone})]}),(0,b.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,b.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,b.jsx)("dd",{children:As(t.customer.created_at)})]})]})]}),t.orders.length>0&&(0,b.jsxs)("div",{children:[(0,b.jsx)("h4",{className:X(Cr,"af-mb-3"),children:"Purchases"}),(0,b.jsx)("div",{className:"af-overflow-x-auto",children:(0,b.jsxs)(Ue,{children:[(0,b.jsx)(Ve,{children:(0,b.jsxs)(he,{children:[(0,b.jsx)(V,{children:"Order"}),(0,b.jsx)(V,{children:"Date"}),(0,b.jsx)(V,{className:"af-text-right",children:"Total"}),(0,b.jsx)(V,{children:"Status"})]})}),(0,b.jsx)($e,{children:t.orders.map(f=>(0,b.jsxs)(he,{children:[(0,b.jsx)($,{className:"af-whitespace-nowrap af-font-medium",children:ja(f)}),(0,b.jsx)($,{className:"af-whitespace-nowrap af-text-muted-foreground",children:As(f.created_at)}),(0,b.jsx)($,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:j(Wl(f),f.currency)}),(0,b.jsx)($,{children:(0,b.jsx)(as,{status:f.status})})]},f.id))})]})}),(0,b.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,b.jsxs)("div",{children:[(0,b.jsx)("h4",{className:X(Cr,"af-mb-3"),children:"Messages"}),(0,b.jsx)("div",{className:"af-space-y-3",children:t.submissions.map(f=>(0,b.jsx)(Qi,{formName:f.form_name,createdAt:f.created_at,data:f.data},f.id))})]})]})]})}function Kl({submissionId:e,onBack:a}){let{api:s}=oe(),[t,n]=Ca.useState(null),[i,o]=Ca.useState(!0),[g,f]=Ca.useState(null),[p,r]=Ca.useState(0);return Ca.useEffect(()=>{let y=!1;return o(!0),f(null),s.getSubmission(e).then(x=>{y||n(x)}).catch(x=>{y||f(x instanceof Error?x:new Error("Failed to load submission"))}).finally(()=>{y||o(!1)}),()=>{y=!0}},[s,e,p]),(0,b.jsxs)("div",{children:[(0,b.jsxs)("div",{className:"af-mb-6",children:[(0,b.jsxs)(_,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,b.jsx)(gt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,b.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,b.jsx)(se,{className:"af-mt-1 af-h-4 af-w-32"}):t&&(0,b.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:As(t.metadata.submitted_at)})]}),i?(0,b.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,b.jsx)(se,{className:"af-w-40"}),(0,b.jsx)(se,{className:"af-mt-2 af-w-64"}),(0,b.jsx)(se,{className:"af-mt-2 af-w-52"}),(0,b.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):g||!t?(0,b.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,b.jsx)(na,{message:"Couldn't load this submission.",onRetry:()=>r(y=>y+1)})}):(0,b.jsxs)("div",{className:"af-space-y-3",children:[(0,b.jsx)(Qi,{formName:null,createdAt:t.metadata.submitted_at,data:t.data}),(0,b.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 Zl={all:"All",customers:"Customers",leads:"Leads"},Jl=["all","customers","leads"];function Yl(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function Ql({refreshKey:e,onBackToWebsite:a,className:s,maxRows:t,onViewAll:n}){let i=typeof t=="number",{people:o,isLoading:g,error:f,page:p,pageSize:r,hasNextPage:y,hasPreviousPage:x,setPage:h,q:u,setQ:l,refetch:v}=cn({refreshKey:e}),[N,S]=Ca.useState({kind:"list"}),[O,F]=Ca.useState(""),[c,A]=Ca.useState("all"),D=!i||!!n,te=ee=>{if(i){n?.();return}ee.email?S({kind:"person",email:ee.email}):ee.submission_id&&S({kind:"submission",submissionId:ee.submission_id})},P=()=>{S({kind:"list"}),v()},E=ee=>{let q=ee.trim();q!==u&&l(q)},U=o.filter(ee=>Yl(ee,c)),w=i?U.slice(0,t):U,Z;if(N.kind==="person")Z=(0,b.jsx)(Gl,{email:N.email,refreshKey:e,onBack:P});else if(N.kind==="submission")Z=(0,b.jsx)(Kl,{submissionId:N.submissionId,onBack:P});else{let ee=(0,b.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,b.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:Jl.map(q=>(0,b.jsx)("button",{type:"button","aria-pressed":c===q,onClick:()=>A(q),className:X("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===q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Zl[q]},q))}),(0,b.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,b.jsx)(gt.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,b.jsx)(we,{type:"text",value:O,onChange:q=>F(q.target.value),onBlur:()=>E(O),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),E(O))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),u&&(0,b.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{F(""),l("")},children:"Clear search"})]});if(g)Z=(0,b.jsxs)("div",{children:[i?null:ee,(0,b.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(q=>(0,b.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,b.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,b.jsx)(se,{className:"af-h-4 af-w-32"}),(0,b.jsx)(se,{className:"af-h-4 af-w-16"})]}),(0,b.jsx)(se,{className:"af-mt-2 af-h-5 af-w-28"}),(0,b.jsx)(se,{className:"af-mt-2 af-h-3 af-w-56"})]},q))}),(0,b.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,b.jsxs)(Ue,{children:[(0,b.jsx)(Ve,{children:(0,b.jsxs)(he,{children:[(0,b.jsx)(V,{children:"Person"}),(0,b.jsx)(V,{children:"Came from"}),(0,b.jsx)(V,{children:"Latest message"}),(0,b.jsx)(V,{children:"Last activity"}),(0,b.jsx)(V,{className:"af-w-8"}),(0,b.jsx)(V,{className:"af-w-8"})]})}),(0,b.jsx)($e,{"aria-hidden":"true",children:[0,1,2,3,4].map(q=>(0,b.jsxs)(he,{children:[(0,b.jsx)($,{children:(0,b.jsx)(se,{className:"af-h-4 af-w-40"})}),(0,b.jsx)($,{children:(0,b.jsx)(se,{className:"af-h-5 af-w-24"})}),(0,b.jsx)($,{children:(0,b.jsx)(se,{className:"af-h-4 af-w-56"})}),(0,b.jsx)($,{children:(0,b.jsx)(se,{className:"af-h-4 af-w-24"})}),(0,b.jsx)($,{}),(0,b.jsx)($,{})]},q))})]})}),(0,b.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(f)Z=(0,b.jsxs)("div",{children:[i?null:ee,(0,b.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,b.jsx)(na,{message:"Couldn't load your leads.",onRetry:()=>v()})})]});else if(w.length===0&&p===0){let q=!!u||c!=="all";Z=(0,b.jsxs)("div",{children:[q&&ee,q?(0,b.jsx)(Pa,{children:u?"Nobody matches that search.":c==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,b.jsx)(Ps,{icon:gt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)Z=(0,b.jsxs)("div",{children:[i?null:ee,(0,b.jsx)(Pa,{children:"No more results."}),(0,b.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,b.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(p-1),children:[(0,b.jsx)(gt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let q=p*r+1,de=p*r+o.length;Z=(0,b.jsxs)("div",{children:[i?null:ee,(0,b.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:w.map((K,Q)=>(0,b.jsxs)("div",{onClick:D?()=>te(K):void 0,className:`af-rounded-md af-border af-p-3${D?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,b.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,b.jsxs)("div",{className:"af-min-w-0",children:[(0,b.jsx)("button",{type:"button",onClick:G=>{G.stopPropagation(),te(K)},disabled:!D,"aria-label":`Open ${K.name||K.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 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${D?" hover:af-underline":""}`,children:Yi(K)}),K.name&&K.email&&(0,b.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:K.email})]}),(0,b.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,b.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:As(K.last_activity_at)}),K.email&&(0,b.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,b.jsx)("a",{href:Tr(K.email),onClick:G=>G.stopPropagation(),"aria-label":`Email ${K.email}`,children:(0,b.jsx)(gt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,b.jsx)("div",{className:"af-mt-2",children:Ji(K)}),K.latest_message_excerpt&&(0,b.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:K.latest_message_excerpt})]},K.email??K.submission_id??Q))}),(0,b.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,b.jsxs)(Ue,{children:[(0,b.jsx)(Ve,{children:(0,b.jsxs)(he,{children:[(0,b.jsx)(V,{children:"Person"}),(0,b.jsx)(V,{children:"Came from"}),(0,b.jsx)(V,{children:"Latest message"}),(0,b.jsx)(V,{children:"Last activity"}),(0,b.jsx)(V,{className:"af-w-8",children:(0,b.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,b.jsx)(V,{className:"af-w-8"})]})}),(0,b.jsx)($e,{children:w.map((K,Q)=>(0,b.jsxs)(he,{onClick:D?()=>te(K):void 0,className:D?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,b.jsxs)($,{className:"af-max-w-[260px] af-font-medium",children:[(0,b.jsx)("button",{type:"button",onClick:G=>{G.stopPropagation(),te(K)},disabled:!D,"aria-label":`Open ${K.name||K.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${D?" hover:af-underline":""}`,children:Yi(K)}),K.name&&K.email&&(0,b.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:K.email})]}),(0,b.jsx)($,{children:Ji(K)}),(0,b.jsx)($,{className:"af-max-w-[320px]",children:K.latest_message_excerpt?(0,b.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:K.latest_message_excerpt}):(0,b.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,b.jsx)($,{className:"af-whitespace-nowrap af-text-muted-foreground",children:As(K.last_activity_at)}),(0,b.jsx)($,{className:"af-w-8",children:K.email&&(0,b.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,b.jsx)("a",{href:Tr(K.email),onClick:G=>G.stopPropagation(),"aria-label":`Email ${K.email}`,children:(0,b.jsx)(gt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,b.jsx)($,{className:"af-w-8 af-text-right",children:(0,b.jsx)(gt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},K.email??K.submission_id??Q))})]})}),!i&&(0,b.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,b.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:c==="all"?`Showing ${q}-${de}`:`${w.length} of ${o.length} on this page`}),(0,b.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,b.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(p-1),disabled:!x,children:[(0,b.jsx)(gt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,b.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(p+1),disabled:!y,children:["Next",(0,b.jsx)(gt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return i?(0,b.jsx)("div",{className:s,children:Z}):(0,b.jsx)(bt,{title:"Leads",onBackToWebsite:a,hideBackButton:N.kind!=="list",className:s,children:Z})}function dn(e){return(0,b.jsx)(Ql,{...e},e.maxRows==null?"full":"compact")}var ys=require("lucide-react");var Gt=ce(require("react"),1);function fn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=oe(),[t,n]=Gt.useState([]),[i,o]=Gt.useState(0),[g,f]=Gt.useState(!0),[p,r]=Gt.useState(null),[y,x]=Gt.useState(0),[h,u]=Gt.useState(e),[l,v]=Gt.useState(void 0),N=Gt.useRef(0),S=Gt.useCallback(async()=>{let F=++N.current;try{f(!0),r(null);let c={limit:h,offset:y*h};l&&(c.status=l);let A=await s.getSubscriptions(c);if(F!==N.current)return;n(A.subscriptions),o(A.total)}catch(c){if(F!==N.current)return;r(c instanceof Error?c:new Error("Failed to fetch subscriptions"))}finally{F===N.current&&f(!1)}},[s,y,h,l,a]);Gt.useEffect(()=>{S()},[S]);let O=Math.ceil(i/h);return{subscriptions:t,total:i,isLoading:g,error:p,page:y,pageSize:h,hasNextPage:y<O-1,hasPreviousPage:y>0,setPage:x,setPageSize:F=>{u(F),x(0)},status:l,setStatus:F=>{v(F),x(0)},refetch:S}}var B=require("react/jsx-runtime");function Xi(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 eo({sub:e}){return e.status==="canceled"?(0,B.jsx)(ae,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,B.jsx)(ae,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,B.jsx)(ae,{variant:"warning",children:"Scheduled to cancel"}):(0,B.jsx)(ae,{variant:"success",children:"Active"}):(0,B.jsx)(ae,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Xl(e,a){let s=j(a,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function to({sub:e}){let a=e.current_amount!==e.plan_amount;return(0,B.jsxs)("div",{children:[(0,B.jsx)("div",{className:"af-font-medium af-tabular-nums",children:Xl(e,e.current_amount)}),a&&(0,B.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",j(e.plan_amount,e.currency)]})]})}function ao(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Xi(e.current_period_end)}`:"Ends at period end":e.current_period_end?Xi(e.current_period_end):"\u2014"}function kr({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:g,pageSize:f,hasNextPage:p,hasPreviousPage:r,setPage:y,refetch:x}=fn({refreshKey:e}),h;if(i)h=(0,B.jsxs)("div",{children:[(0,B.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(u=>(0,B.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,B.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,B.jsx)(se,{className:"af-h-4 af-w-40"}),(0,B.jsx)(se,{className:"af-h-4 af-w-20"})]}),(0,B.jsx)(se,{className:"af-mt-2 af-h-3 af-w-32"}),(0,B.jsx)(se,{className:"af-mt-2 af-h-5 af-w-24"})]},u))}),(0,B.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,B.jsxs)(Ue,{children:[(0,B.jsx)(Ve,{children:(0,B.jsxs)(he,{children:[(0,B.jsx)(V,{children:"Subscriber"}),(0,B.jsx)(V,{children:"Plan"}),(0,B.jsx)(V,{className:"af-text-right",children:"Amount"}),(0,B.jsx)(V,{children:"Renews"}),(0,B.jsx)(V,{children:"Status"})]})}),(0,B.jsx)($e,{"aria-hidden":"true",children:[0,1,2,3,4].map(u=>(0,B.jsxs)(he,{children:[(0,B.jsx)($,{children:(0,B.jsx)(se,{className:"af-h-4 af-w-44"})}),(0,B.jsx)($,{children:(0,B.jsx)(se,{className:"af-h-4 af-w-32"})}),(0,B.jsx)($,{className:"af-text-right",children:(0,B.jsx)(se,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,B.jsx)($,{children:(0,B.jsx)(se,{className:"af-h-4 af-w-24"})}),(0,B.jsx)($,{children:(0,B.jsx)(se,{className:"af-h-5 af-w-20"})})]},u))})]})}),(0,B.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)h=(0,B.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,B.jsx)(na,{message:"Couldn't load your subscriptions.",onRetry:()=>x()})});else if(t.length===0&&g===0)h=(0,B.jsx)(Pa,{icon:(0,B.jsx)(ys.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)h=(0,B.jsxs)("div",{children:[(0,B.jsx)(Pa,{children:"No more results."}),(0,B.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,B.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>y(g-1),children:[(0,B.jsx)(ys.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let u=g*f+1,l=g*f+t.length;h=(0,B.jsxs)("div",{children:[(0,B.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(v=>(0,B.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,B.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,B.jsxs)("div",{className:"af-min-w-0",children:[(0,B.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:v.customer_email||(0,B.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,B.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:v.plan_title||"Untitled plan"})]}),(0,B.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,B.jsx)(to,{sub:v})})]}),(0,B.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,B.jsx)(eo,{sub:v}),v.is_test&&(0,B.jsx)(ae,{variant:"outline",children:"Test"}),(0,B.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:ao(v)})]}),(0,B.jsx)(ka,{deliveries:v.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},v.id))}),(0,B.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,B.jsxs)(Ue,{children:[(0,B.jsx)(Ve,{children:(0,B.jsxs)(he,{children:[(0,B.jsx)(V,{children:"Subscriber"}),(0,B.jsx)(V,{children:"Plan"}),(0,B.jsx)(V,{className:"af-text-right",children:"Amount"}),(0,B.jsx)(V,{children:"Renews"}),(0,B.jsx)(V,{children:"Status"})]})}),(0,B.jsx)($e,{children:t.map(v=>(0,B.jsxs)(he,{children:[(0,B.jsx)($,{className:"af-max-w-[240px]",children:(0,B.jsx)("div",{className:"af-truncate af-font-medium",children:v.customer_email||(0,B.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,B.jsx)($,{className:"af-max-w-[220px]",children:(0,B.jsx)("div",{className:"af-truncate",children:v.plan_title||(0,B.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,B.jsx)($,{className:"af-whitespace-nowrap af-text-right",children:(0,B.jsx)(to,{sub:v})}),(0,B.jsx)($,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ao(v)}),(0,B.jsxs)($,{children:[(0,B.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,B.jsx)(eo,{sub:v}),v.is_test&&(0,B.jsx)(ae,{variant:"outline",children:"Test"})]}),(0,B.jsx)(ka,{deliveries:v.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},v.id))})]})}),(0,B.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,B.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${u}-${l} of ${n}`}),(0,B.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,B.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>y(g-1),disabled:!r,children:[(0,B.jsx)(ys.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,B.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>y(g+1),disabled:!p,children:["Next",(0,B.jsx)(ys.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,B.jsx)(bt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:h})}var Er=ce(require("react"),1);var ut=require("react/jsx-runtime");function Ar({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:g,isLoading:f,error:p,refetch:r}=ms({refreshKey:e,initialPageSize:1,includeAggregates:!0}),y=vs({refreshKey:e}),[x,h]=Er.useState(!1),[u,l]=Er.useState(null),v=(0,ut.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:p||!f&&!g?(0,ut.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,ut.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):f||!g?(0,ut.jsxs)(ut.Fragment,{children:[(0,ut.jsx)(nt,{label:"Outstanding",children:(0,ut.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,ut.jsx)(nt,{label:"Overdue",children:(0,ut.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,ut.jsx)(nt,{label:"Paid this month",children:(0,ut.jsx)(se,{className:"af-h-6 af-w-24"})})]}):(0,ut.jsxs)(ut.Fragment,{children:[(0,ut.jsx)(nt,{label:"Outstanding",detail:`${g.outstanding.count} open`,children:j(g.outstanding.amount,g.currency)}),(0,ut.jsx)(nt,{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:j(g.overdue.amount,g.currency)}),(0,ut.jsx)(nt,{label:"Paid this month",detail:`${g.paid_this_month.count} paid`,children:j(g.paid_this_month.amount,g.currency)})]})});return(0,ut.jsxs)(bt,{title:"Invoices",onBackToWebsite:s,hideBackButton:x,className:o,children:[v,!x&&(0,ut.jsx)(ps,{retainers:y.retainers,isLoading:y.isLoading,error:y.error,onRetry:()=>void y.refetch(),activeRetainerId:u?.id??null,onShowCycles:N=>l(S=>S?.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,ut.jsx)(Ka,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:h,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:()=>l(null)})]})}var St=ce(require("react"),1);var ec=2e3,Et=()=>({data:null,error:null,isLoading:!0});function hs(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=oe(),[i,o]=St.useState(Et),[g,f]=St.useState(Et),[p,r]=St.useState(Et),[y,x]=St.useState(Et),[h,u]=St.useState(Et),l=G=>Object.fromEntries(G.map(ie=>[ie,Et()])),[v,N]=St.useState(()=>l(s)),S=St.useRef(0),O=St.useRef(0),F=St.useRef("idle"),c=s.join(","),A=is()??"",D=JSON.stringify(t),te=`${e}:${c}:${D}:${A}`,[P,E]=St.useState({api:n,fetchIdentity:te});(P.api!==n||P.fetchIdentity!==te)&&(E({api:n,fetchIdentity:te}),S.current+=1,o(Et),f(Et),r(Et),x(Et),N(l(c?c.split(","):[])));let U=`${e}:${String(a??"")}:${A}`,[w,Z]=St.useState({api:n,conversionsIdentity:U});(w.api!==n||w.conversionsIdentity!==U)&&(Z({api:n,conversionsIdentity:U}),O.current+=1,F.current="idle",u(Et));let ee=St.useCallback(async G=>{let ie=++S.current,J=c?c.split(","):[];o(Et),f(Et),r(Et),x(Et),N(Object.fromEntries(J.map(C=>[C,Et()])));let Re=F.current!=="pending"&&(G?.force===!0||F.current==="idle"),Qe=(C,L)=>L.then(I=>{ie===S.current&&C({data:I,error:null,isLoading:!1})},I=>{ie===S.current&&C({data:null,error:I instanceof Error?I:new Error("Failed to fetch report"),isLoading:!1})}),ot=n.getAnalyticsStatus(),Ee=Qe(o,ot),Ge=Symbol("status-timeout"),tt,Pe=await Promise.race([ot.then(C=>C,()=>null),new Promise(C=>{tt=setTimeout(()=>C(Ge),ec)})]);if(clearTimeout(tt),ie!==S.current)return;if(Pe===Ge&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Pe!==null&&Pe!==Ge&&(Pe.collecting!==!0||Pe.first_seen===null&&!Pe.first_seen_unavailable||Pe.first_seen!==null&&Pe.first_seen_in_reports===!1)){let C={data:null,error:null,isLoading:!1};f(C),r(C),x(C),N(Object.fromEntries(J.map(L=>[L,{...C}]))),Re&&(u(C),F.current="done"),await Ee;return}await Promise.all([Pe===Ge?Promise.resolve():Ee,Qe(f,n.getAnalyticsSummary(e,t)),Qe(r,n.getAnalyticsTimeseries(e,t)),Qe(x,n.getAnalyticsChannels(e,t)),Re?(()=>{F.current="pending";let C=++O.current;return u(Et),n.getAnalyticsConversions(e).then(L=>{C===O.current&&(u({data:L,error:null,isLoading:!1}),F.current="done")},L=>{C===O.current&&(u({data:null,error:L instanceof Error?L:new Error("Failed to fetch report"),isLoading:!1}),F.current="done")})})():Promise.resolve(),...J.map(C=>n.getAnalyticsBreakdown(C,e,t).then(L=>{ie===S.current&&N(I=>({...I,[C]:{data:L,error:null,isLoading:!1}}))},L=>{ie===S.current&&N(I=>({...I,[C]:{data:null,error:L instanceof Error?L:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,c,D,U,A]),q=St.useCallback(async()=>{let G=S.current;try{let ie=await n.getAnalyticsStatus();if(G!==S.current)return;o({data:ie,error:null,isLoading:!1})}catch(ie){if(G!==S.current)return;o(J=>({data:J.data,error:ie instanceof Error?ie:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),de=St.useCallback(()=>ee({force:!0}),[ee]);St.useEffect(()=>{ee()},[ee,a]);let K=i.isLoading||g.isLoading||p.isLoading||y.isLoading||h.isLoading||Object.values(v).some(G=>G.isLoading),Q=[p,g,y,h,...Object.values(v)].map(G=>G.data?.status==="ok"?G.data.timezone:void 0).find(G=>G!==void 0);return{status:i,summary:g,timeseries:p,channels:y,conversions:h,breakdowns:v,reportedZone:Q,isLoading:K,refetch:de,refetchStatus:q}}var _t=ce(require("react"),1);var Zn=3e4,Jn=3;function mn(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=oe(),[o,g]=_t.useState(null),[f,p]=_t.useState(null),[r,y]=_t.useState(!1),[x,h]=_t.useState(null),[u,l]=_t.useState(!1),[v,N]=_t.useState(!0),[S,O]=_t.useState(0),F=_t.useRef(0),c=_t.useRef(0),A=_t.useRef(void 0);s!==void 0&&(A.current=s);let D=a?A.current===!0||A.current===void 0&&t:!0,[te,P]=_t.useState({api:i,identity:n}),E=n!==void 0&&n!==te.identity;(te.api!==i||E)&&(A.current=void 0,P({api:i,identity:n}),c.current+=1,F.current=0,g(null),p(null),y(!1),h(null),l(!1),N(!0),O(0));let U=_t.useRef(()=>{}),w=_t.useRef(null),Z=_t.useCallback(async()=>{if(w.current!==null&&w.current===c.current)return;let ee=++c.current;w.current=ee;try{let q=await i.getAnalyticsRealtime();if(ee!==c.current)return;if(q.status==="unreachable"){l(!0),y(!0),N(!1),O(de=>de+1);return}F.current=0,l(!1),g(q.data.current_visitors),p(q.as_of),y(!1),h(null),N(!1),O(de=>de+1)}catch(q){if(ee!==c.current)return;F.current+=1,N(!1),O(de=>de+1),y(!0),F.current>=Jn&&h(q instanceof Error?q:new Error("Realtime unavailable"))}finally{w.current===ee&&(w.current=null)}},[i]);return U.current=()=>void Z(),_t.useEffect(()=>{let ee,q=()=>{ee===void 0&&(ee=setInterval(()=>U.current(),Zn))},de=()=>{ee!==void 0&&(clearInterval(ee),ee=void 0)},K=()=>{typeof document<"u"&&document.hidden?de():(U.current(),q())};return D?((typeof document>"u"||!document.hidden)&&(U.current(),q()),document?.addEventListener("visibilitychange",K),()=>{de(),document?.removeEventListener("visibilitychange",K),c.current+=1}):()=>{document?.removeEventListener("visibilitychange",K)}},[te.api,te.identity,D]),{currentVisitors:o,asOf:f,isStale:r,error:x,isUnreachable:u,isInitialLoad:v,polls:S}}var it=ce(require("react"),1);var so=ce(require("react"),1);var xs=require("react/jsx-runtime");function tc(){try{let e=Intl.supportedValuesOf?.("timeZone");if(e&&e.length>0)return e.includes("UTC")?e:["UTC",...e]}catch{}return["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Madrid","Africa/Johannesburg","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Tokyo","Australia/Sydney"]}function Ir({value:e,chosen:a,onChange:s}){let t=Os(),n=a===null&&t!==null&&e===t,i=so.useMemo(()=>{let o=tc();return o.includes(e)?o:[e,...o]},[e]);return(0,xs.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,xs.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,xs.jsxs)("select",{value:n?"":e,onChange:o=>s(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[(0,xs.jsx)("option",{value:"",children:t?`${t.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),i.map(o=>(0,xs.jsx)("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var Yn=(e,{published:a}={})=>{let s=a===!1,t=e!=null&&(!e.collecting||s&&e.first_seen===null&&!e.first_seen_unavailable),n=!t&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,i=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=n||i;return{notCollecting:t,awaitingFirstVisit:n,firstVisitTooRecent:i,holdingForFirstData:o,nothingToReport:t||o}};var pn=ce(require("react"),1),ac=3e4;function Qn({status:e,holdingForFirstData:a,refetchStatus:s,refetch:t}){pn.useEffect(()=>{if(!a)return;let i,o=()=>{i===void 0&&(i=setInterval(()=>void s(),ac))},g=()=>{i!==void 0&&(clearInterval(i),i=void 0)},f=()=>{typeof document<"u"&&document.hidden?g():(s(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",f),()=>{g(),document?.removeEventListener("visibilitychange",f)}},[a,s]);let n=pn.useRef(void 0);pn.useEffect(()=>{if(!e){n.current=void 0;return}let i=n.current;n.current=a,i===!0&&!a&&t()},[e,a,t])}var ws=ce(require("react"),1);var sc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Vt(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?Vt(o*t):`${o}${n}`}return String(e)}function Is(e){return`${(e*100).toFixed(1)}%`}function gn(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 ro(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`:gn(a)}function io(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function oo(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 vn(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function lo(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 Dr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${sc[a-1]} ${s}`}function no(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function nc(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function co(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=no(e.to,s);for(let o=no(e.from,s);o<i;o=nc(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 uo(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 la=require("react/jsx-runtime");function fo({what:e="This report",onRetry:a,collecting:s}){return(0,la.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,la.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,la.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,la.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 Xn({what:e="No data"}){return(0,la.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 Za({sourced:e,error:a,isLoading:s,what:t,onRetry:n,collecting:i,children:o}){return s?(0,la.jsx)("div",{role:"status","aria-label":`Loading ${t}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):a?(0,la.jsx)(fo,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?(0,la.jsx)(fo,{what:t,onRetry:n,collecting:i}):(0,la.jsx)(la.Fragment,{children:o(e.data)})}var Ye=require("react/jsx-runtime");function Lr({rows:e,dimension:a,metric:s,metricLabel:t,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:g,maxRows:f=9}){let[p,r]=ws.useState(!1);if(e.length===0)return(0,Ye.jsx)(Xn,{what:i});let y=e.reduce((u,l)=>Math.max(u,Number(l[s]??0)),0)||1,x=Math.max(0,e.length-f),h=p?e:e.slice(0,f);return(0,Ye.jsxs)(Ye.Fragment,{children:[(0,Ye.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Ye.jsx)("thead",{children:(0,Ye.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:a==="pathname"?"Page":"Name"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:t})]})}),(0,Ye.jsx)("tbody",{children:h.map((u,l)=>{let v=Number(u[s]??0),N=u[a]??null,S=vn(N),O=n?u[n]:null,F=N!==null&&(g?g(N,O):!0);return(0,Ye.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,Ye.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,Ye.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,v/y*100)}%`}}),N!==null&&o&&F?(0,Ye.jsx)("button",{type:"button",onClick:()=>o(N,O),title:`Filter by ${S}`,"aria-label":`Filter by ${S}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:S}):(0,Ye.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:S}),O?(0,Ye.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:O}):null]}),(0,Ye.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(v)})]},`${S}-${O??""}-${l}`)})})]}),x>0?(0,Ye.jsx)("button",{type:"button",onClick:()=>r(u=>!u),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:p?"Show fewer":`Show all ${e.length}`}):null]})}function bn({title:e,tabs:a,defaultTabId:s,headerRight:t}){let[n,i]=ws.useState(s),o=a.find(h=>h.id===n)??a[0],g=ws.useId(),f=h=>`${g}-tab-${h}`,p=h=>`${g}-panel-${h}`,r=ws.useRef(null),y=(h,u)=>{h.preventDefault();let l=(u+a.length)%a.length;i(a[l].id),r.current?.querySelectorAll('[role="tab"]')?.[l]?.focus()};return(0,Ye.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,Ye.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,Ye.jsx)("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:h=>{let u=a.findIndex(l=>l.id===n);h.key==="ArrowRight"&&y(h,u+1),h.key==="ArrowLeft"&&y(h,u-1),h.key==="Home"&&y(h,0),h.key==="End"&&y(h,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(h=>(0,Ye.jsx)("button",{id:f(h.id),role:"tab",type:"button","aria-selected":h.id===n,"aria-controls":p(h.id),tabIndex:h.id===n?0:-1,onClick:()=>i(h.id),className:h.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:h.label},h.id))}),t]}),o?(0,Ye.jsx)("div",{id:p(o.id),role:"tabpanel","aria-labelledby":f(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var Kt=ce(require("react"),1),rs=ce(require("@radix-ui/react-popover"),1);var Ns=3,Ss=100;var De=require("react/jsx-runtime"),yn={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"},rc=Object.keys(yn);function mo(e){let a=yn[e.dimension],s=e.operator==="is_not"?"is not":"is",t=e.values.map(n=>vn(n)).join(" or ");return`${a} ${s} ${t}`}function Or(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 ic(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 po(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 oc(e){return{dimension:e,operator:"is",search:"",picked:[]}}function go(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=ic(e.byDimension,s);for(let[i,o]of Object.entries(t)){let g=e.foldsByLabel.get(i)??new Set;for(let f of o)g.add(f);e.foldsByLabel.set(i,g)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function vo(e){let{filters:a,onChange:s}=e,t=a.length>=3;return Kt.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,De.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[a.map((n,i)=>(0,De.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,De.jsx)("span",{className:"af-text-foreground",children:mo(n)}),(0,De.jsx)("button",{type:"button","aria-label":`Remove filter ${mo(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,De.jsx)(lc,{...e,disabled:t}),a.length>0?(0,De.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 lc({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,g]=Kt.useState(!1),f=Kt.useRef(null),[p,r]=Kt.useState(null);Kt.useEffect(()=>{r(f.current?.closest(".aifeatures-admin")??null)},[]);let[y,x]=Kt.useState(null),[h,u]=Kt.useState("is"),[l,v]=Kt.useState(""),[N,S]=Kt.useState([]);Kt.useEffect(()=>{o||(x(null),u("is"),v(""),S([]))},[o]);let O=Kt.useRef(t);O.current!==t&&(O.current=t,o&&g(!1),y!==null&&x(null),N.length>0&&S([]),l!==""&&v(""),h!=="is"&&u("is"));let F=E=>{let U=oc(E);x(U.dimension),S(U.picked),v(U.search),u(U.operator)},A=(y?s[y]??[]:[]).filter(E=>E.toLowerCase().includes(l.trim().toLowerCase())),D=y===null||N.length===0?null:Or(e,{dimension:y,operator:h,values:i?i(y,N):N}),te=D!==null&&D!==e,P=()=>{let E=D;!E||E===e||(a(E),g(!1))};return(0,De.jsxs)(rs.Root,{open:o,onOpenChange:g,children:[(0,De.jsx)(rs.Trigger,{asChild:!0,children:(0,De.jsx)("button",{ref:f,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,De.jsx)(rs.Portal,{container:p,children:(0,De.jsx)(rs.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,De.jsxs)("div",{children:[(0,De.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,De.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:rc.filter(E=>s[E]!==void 0).map(E=>{let U=s[E]?.length??0,w=!e.some(Z=>Z.dimension===E)&&e.length>=3;return(0,De.jsxs)("button",{type:"button",onClick:()=>F(E),disabled:U===0||w,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,De.jsx)("span",{children:yn[E]}),(0,De.jsx)("span",{className:"af-text-muted-foreground",children:U===0?"no data":w?"no room":U})]},E)})})]}):(0,De.jsxs)("div",{children:[(0,De.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,De.jsx)("button",{type:"button",onClick:()=>F(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,De.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:yn[y]}),(0,De.jsxs)("select",{"aria-label":"Operator",value:h,onChange:E=>u(E.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,De.jsx)("option",{value:"is",children:"is"}),(0,De.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,De.jsx)("input",{type:"text",value:l,onChange:E=>v(E.target.value),placeholder:"Search\u2026","aria-label":`Search ${yn[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,De.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:A.length===0?(0,De.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",l,"\u201D."]}):A.map(E=>(0,De.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,De.jsx)("input",{type:"checkbox",checked:N.includes(E),disabled:!N.includes(E)&&N.length>=100,onChange:U=>S(w=>U.target.checked?[...w,E]:w.filter(Z=>Z!==E))}),(0,De.jsx)("span",{className:"af-break-all",children:vn(E)})]},E))}),(0,De.jsx)("button",{type:"button",onClick:P,disabled:!te,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 rt=require("react/jsx-runtime"),cc=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Vt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Vt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Vt,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:Is,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:gn,chart:"visit_duration_seconds"}];function uc({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,rt.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 bo({summary:e,selected:a,onSelect:s}){return(0,rt.jsx)("div",{className:"af-@container",children:(0,rt.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:cc.map(t=>{let n=t.chart===a,i=s!==void 0,o=(0,rt.jsxs)(rt.Fragment,{children:[(0,rt.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:t.label}),(0,rt.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,rt.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,rt.jsx)(uc,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?(0,rt.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,rt.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},t.key)})})})}function Br({currentVisitors:e,asOf:a,isStale:s,isUnreachable:t,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!t)return(0,rt.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,rt.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,rt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return(0,rt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?lo(a):"freshness unknown",g=i?" across the whole site, not the current filter,":"",f=s?`${e} current visitors${g} ${o} (not updating)`:`${e} current visitors${g} ${o}`;return(0,rt.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:f,children:[(0,rt.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,rt.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,rt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),(0,rt.jsx)("span",{className:"af-sr-only",children:f})]})}var yo=ce(require("react"),1),ho=require("lucide-react");var Fe=require("react/jsx-runtime");function er(e,a){return!a||e.goal!==a.goal?!1:a.implicit===void 0||e.implicit===a.implicit}function tr({rows:e,denominator:a,windowPrecedesCollection:s=!1,coverageUnknown:t=!1,emptyCopy:n="No conversions in this period",maxRows:i=9,primaryConversion:o}){let[g,f]=yo.useState(!1),p=e.filter(v=>!v.implicit||v.visitors>0||v.events>0||er(v,o)),r=s?(0,Fe.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This period starts before we began collecting for this site, so these counts cover less time than the dates suggest."}):t?(0,Fe.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null;if(p.length===0)return(0,Fe.jsxs)(Fe.Fragment,{children:[(0,Fe.jsx)(Xn,{what:n}),r]});let y=p.slice(0,i),x=o?p.find(v=>er(v,o)):void 0,h=x&&!y.includes(x)?p.filter(v=>y.includes(v)||v===x).slice(0,Math.max(0,i-1)).concat(x):y,u=g?e:h,l=Math.max(0,e.length-h.length);return(0,Fe.jsxs)(Fe.Fragment,{children:[(0,Fe.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Fe.jsx)("thead",{children:(0,Fe.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Fe.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,Fe.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,Fe.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,Fe.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,Fe.jsx)("tbody",{children:u.map((v,N)=>(0,Fe.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":er(v,o)?"true":void 0,children:[(0,Fe.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:er(v,o)?(0,Fe.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,Fe.jsx)(ho.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,Fe.jsx)("span",{className:"af-font-medium af-text-foreground",children:v.goal}),(0,Fe.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):v.goal}),(0,Fe.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(v.visitors)}),(0,Fe.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(v.events)}),(0,Fe.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:v.conversion_rate===null?(0,Fe.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Is(v.conversion_rate)})]},`${v.goal}-${N}`))})]}),l>0?(0,Fe.jsx)("button",{type:"button",onClick:()=>f(v=>!v),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:g?"Show fewer":`Show all ${e.length} goals`}):null,(0,Fe.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Vt(a)," ",a===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),r]})}var Zt=require("recharts");var dt=require("react/jsx-runtime"),ar={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Mr={visitors:Vt,visits:Vt,pageviews:Vt,views_per_visit:e=>e.toFixed(2),bounce_rate:Is,visit_duration_seconds:gn},dc=31,fc=new Set(["visitors","visits","pageviews"]),mc={...Mr,bounce_rate:io,visit_duration_seconds:ro},Fr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],pc=[5,10,15,30,60,120,300,600,900,1800,3600,7200],gc=[.01,.02,.05,.1,.2,.25,.5,1],vc=[.25,.5,1,2,5,10,25,50],bc={visitors:Fr,visits:Fr,pageviews:Fr,views_per_visit:vc,bounce_rate:gc,visit_duration_seconds:pc};function yc({active:e,payload:a,label:s,metric:t}){if(!e||!a||a.length===0)return null;let n=a[0].payload;return(0,dt.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,dt.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:ar[t]}),(0,dt.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,dt.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,dt.jsx)("span",{className:"af-text-muted-foreground",children:uo(String(s))}),(0,dt.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Mr[t](Number(n[t]??0))})]})]})}function sr({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=co(a,e,t),o=Mr[s],g=mc[s],f=oo(i.reduce((r,y)=>Math.max(r,Number(y[s]??0)),0),bc[s]),p=`${ar[s]} by day: ${i.map(r=>`${Dr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return(0,dt.jsxs)("figure",{"aria-label":`${ar[s]} over time`,className:"af-m-0",children:[(0,dt.jsx)(Zt.ResponsiveContainer,{width:"100%",height:n,children:(0,dt.jsxs)(Zt.AreaChart,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,dt.jsx)("defs",{children:(0,dt.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,dt.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,dt.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,dt.jsx)(Zt.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,dt.jsx)(Zt.XAxis,{dataKey:"date",tickFormatter:Dr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,dt.jsx)(Zt.YAxis,{allowDecimals:!fc.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...f?{ticks:f,domain:[0,f[f.length-1]]}:{},tickFormatter:r=>g(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,dt.jsx)(Zt.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,dt.jsx)(yc,{metric:s})}),(0,dt.jsx)(Zt.Area,{type:"linear",dataKey:s,name:ar[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:i.length<=dc?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,dt.jsx)("figcaption",{className:"af-sr-only",children:p})]})}var ne=require("react/jsx-runtime"),hc="2026-08-13",xc=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],wc=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function xo({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,primaryConversion:n,className:i,published:o,lastPublishedAt:g}){let[f,p]=it.useState(30),[r,y]=it.useState(()=>or()),x=e!==void 0&&a!==void 0,[h,u]=it.useState(e??[]),{api:l}=oe(),[v,N]=it.useState(l);v!==l&&(N(l),!x&&h.length>0&&u([]));let S=x?e:h,O=it.useCallback(I=>{a&&a(I),x||u(I)},[a,x]),F=it.useCallback((I,pe,ye)=>{let ke=Array.isArray(pe)?pe:[pe];if(ke.length===0)return null;let Le=Or(S,{dimension:I,operator:"is",values:ke});if(ye&&(!ye.value||(Le=po(Le,{dimension:ye.dimension,operator:"is",values:[ye.value]}),!Le.find(Ke=>Ke.dimension===ye.dimension&&Ke.operator!=="is_not")?.values.includes(ye.value))))return null;let at=Le.find(ze=>ze.dimension===I&&ze.operator!=="is_not");return ke.every(ze=>at?.values.includes(ze))?JSON.stringify(Le)===JSON.stringify(S)?null:Le:null},[S]),c=it.useCallback((I,pe,ye)=>F(I,pe,ye)!==null,[F]),A=it.useCallback((I,pe,ye)=>{let ke=F(I,pe,ye);ke&&O(ke)},[F,O]),[D,te]=it.useState("visitors"),P=hs(f,{refreshKey:s,breakdowns:wc,filters:S}),E=P.status.data,U=P.reportedZone??E?.timezone,w=U??r??Os()??"UTC",{notCollecting:Z,awaitingFirstVisit:ee,firstVisitTooRecent:q,holdingForFirstData:de}=Yn(E,{published:o}),K=o===!1,Q=mn({collecting:ee||Z?!1:E?.collecting,statusFailed:P.status.error!=null,identity:E?.analytics_id}),G=it.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),ie=it.useMemo(()=>{let I=P.breakdowns.sources?.data,pe={};if(!I||I.status!=="ok")return pe;for(let ye of I.data){let ke=ye.source,Le=ye.sources;typeof ke=="string"&&Array.isArray(Le)&&Le.length>0&&(pe[ke]=Le)}return pe},[P.breakdowns.sources?.data]),J=it.useMemo(()=>{let I=(ke,Le)=>{let at=P.breakdowns[ke]?.data;return!at||at.status!=="ok"?[]:[...new Set(at.data.map(ze=>ze[Le]).filter(ze=>typeof ze=="string"&&ze!==""))]};return{channel:P.channels.data?.status==="ok"?[...new Set(P.channels.data.data.map(ke=>ke.channel))]:[],source:I("sources","source"),campaign:I("utm/campaign","campaign"),page:I("pages","pathname"),entry_page:I("entry-pages","pathname"),exit_page:I("exit-pages","pathname"),country:I("countries","country"),browser:I("browsers","browser"),os:I("operating-systems","os"),device:I("devices","device")}},[P.breakdowns,P.channels.data]),[Re,Qe]=it.useState({}),ot=JSON.stringify(J),[Ee,Ge]=it.useState(new Map),tt=JSON.stringify(ie);it.useEffect(()=>{let{suggestions:I,folds:pe}=go(G.current,{api:l,period:f},JSON.parse(ot),JSON.parse(tt));Qe(I),Ge(pe)},[ot,tt,l,f]);let Pe=it.useCallback((I,pe)=>I!=="source"?pe:[...new Set(pe.flatMap(ye=>{let ke=[...Ee.get(ye)??[],...ie[ye]??[]];return ke.length>0?ke:[ye]}))],[Ee,ie]),Tt=it.useMemo(()=>{let I=P.conversions.error;return I instanceof Bt&&I.details?.code==="goals_exceed_report_budget"?I.message:null},[P.conversions.error]),C=it.useMemo(()=>{let I=[P.summary,P.timeseries,P.channels,...Object.values(P.breakdowns)];for(let pe of I){let ye=pe?.error;if(ye instanceof Bt&&ye.details?.code==="filter_unsupported")return ye.message}return null},[P.summary,P.timeseries,P.channels,P.breakdowns]),L=(I,pe,ye,ke,Le,at,ze,Ke,le)=>()=>{let Oe=P.breakdowns[I];return(0,ne.jsx)(Za,{sourced:Oe?.data??null,error:Oe?.error,isLoading:Oe?.isLoading,what:pe,collecting:E?.collecting,onRetry:P.refetch,children:lt=>{let Jt=xt=>Ke?Pe(Ke,[xt]):xt;return(0,ne.jsx)(Lr,{rows:lt,dimension:ye,metric:ke,metricLabel:Le,secondary:at,emptyCopy:S.length>0?"No data for this filter":ze,canFilter:Ke?(xt,kt)=>c(Ke,Jt(xt),le?{dimension:le,value:kt}:void 0):()=>!1,onFilter:Ke?(xt,kt)=>A(Ke,Jt(xt),le?{dimension:le,value:kt}:void 0):void 0})}})};if(Qn({status:E,holdingForFirstData:de,refetchStatus:P.refetchStatus,refetch:P.refetch}),Z){let I=!!g&&String(g).slice(0,10)<hc;return(0,ne.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:i,children:(0,ne.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,ne.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:K?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":I?"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 ee?(0,ne.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:i,children:(0,ne.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,ne.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."})]})}):q?(0,ne.jsxs)(bt,{title:"Analytics",onBackToWebsite:t,className:i,children:[(0,ne.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,ne.jsx)(Ir,{value:w,chosen:r,onChange:I=>{lr(I),y(I)}})}),(0,ne.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,ne.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,ne.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,ne.jsx)(Br,{currentVisitors:Q.currentVisitors,asOf:Q.asOf,isStale:Q.isStale,isUnreachable:Q.isUnreachable||Q.error!==null,isInitialLoad:Q.isInitialLoad})})]})]}):(0,ne.jsx)(bt,{title:"Analytics",onBackToWebsite:t,className:i,children:(0,ne.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,ne.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,ne.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:xc.map(I=>(0,ne.jsx)("button",{type:"button","aria-pressed":I.value===f,onClick:()=>p(I.value),className:I.value===f?"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:I.label},I.value))}),(0,ne.jsx)(Ir,{value:w,chosen:r,onChange:I=>{lr(I),y(I)}}),(0,ne.jsx)(Br,{currentVisitors:Q.currentVisitors,asOf:Q.asOf,isStale:Q.isStale,isUnreachable:Q.isUnreachable||Q.error!==null,isInitialLoad:Q.isInitialLoad,scopeIsSiteWide:S.length>0})]}),(0,ne.jsx)(vo,{filters:S,onChange:O,suggestions:Re,expandValues:Pe,resetKey:l}),C?(0,ne.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,ne.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:C}),(0,ne.jsx)("button",{type:"button",onClick:()=>O([]),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,!C&&E?.timezone_defaulted?(0,ne.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,C?null:(0,ne.jsxs)(ne.Fragment,{children:[(0,ne.jsx)(Za,{sourced:P.summary.data,error:P.summary.error,isLoading:P.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:P.refetch,children:I=>(0,ne.jsxs)(ne.Fragment,{children:[(0,ne.jsx)(bo,{summary:I,selected:D,onSelect:te}),I.previous_unavailable?(0,ne.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[I.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,ne.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,ne.jsx)(Za,{sourced:P.timeseries.data,error:P.timeseries.error,isLoading:P.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:P.refetch,children:I=>{let pe=P.timeseries.data?.status==="ok"?P.timeseries.data.window:{from:"",to:""};return(0,ne.jsx)(sr,{rows:I,window:pe,metric:D,timeZone:U??"UTC"})}})}),(0,ne.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,ne.jsx)(bn,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,ne.jsx)(Za,{sourced:P.channels.data,error:P.channels.error,isLoading:P.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:P.refetch,children:I=>(0,ne.jsx)(Lr,{rows:I,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:S.length>0?"No data for this filter":"No data for this period",canFilter:pe=>c("channel",pe),onFilter:pe=>A("channel",pe)})})},{id:"sources",label:"Sources",render:L("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:L("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,ne.jsx)(bn,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:L("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:L("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:L("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,ne.jsx)(bn,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:L("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:L("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:L("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,ne.jsx)(bn,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:L("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:L("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:L("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,ne.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,ne.jsx)("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,ne.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,ne.jsxs)("div",{className:"af-px-3 af-py-2",children:[S.length>0?(0,ne.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",S.length===1?"filter":"filters"," above."]}):null,Tt!==null?(0,ne.jsxs)("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[(0,ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,ne.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:Tt})]}):(0,ne.jsx)(Za,{sourced:P.conversions.data,error:P.conversions.error,isLoading:P.conversions.isLoading,what:"Conversions",collecting:E?.collecting,onRetry:P.refetch,children:I=>{let pe=P.conversions.data?.status==="ok"?P.conversions.data:null;return(0,ne.jsx)(ne.Fragment,{children:(0,ne.jsx)(tr,{rows:I,primaryConversion:n,denominator:pe?.denominator??0,windowPrecedesCollection:pe?.window_precedes_collection??!1,coverageUnknown:pe?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var At=require("lucide-react"),hn=require("react/jsx-runtime");function Nc(e){let a=[e];e.startsWith("//")?a.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||a.push(`https://${e}`);for(let s of a)try{let{hostname:t}=new URL(s);if(t)return t.toLowerCase().replace(/^www\./,"")}catch{}return null}function Sc(e){if(Ur(e,"whatsapp"))return!0;let a=Nc(e);return a===null?!1:["wa.me","whatsapp.com"].some(s=>a===s||a.endsWith(`.${s}`))}function Ur(e,a){return e.slice(0,a.length+1).toLowerCase()===`${a}:`}var wo=[{goal:"Contact",target:e=>Ur(e,"tel"),icon:At.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Ur(e,"mailto"),icon:At.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:At.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Sc(e),icon:At.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:At.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:At.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:At.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:At.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:At.Download,line:"This site is set up to get your file downloaded."}];function No(e){let{goal:a,target:s}=e;return e.implicit!==!0?null:(s?wo.find(n=>n.goal===a&&n.target?.(s)):void 0)??wo.find(n=>n.goal===a&&!n.target)??null}function _c(e){return No(e)?.icon??At.Target}function So({primaryConversion:e}){if(!e?.goal)return null;let a=No(e),s=e.label?.trim(),t=_c(e),n=s?`Your main conversion is ${s}.`:a?.line??`Your main conversion is ${e.goal}.`;return(0,hn.jsxs)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,hn.jsx)(t,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,hn.jsx)("span",{children:n})]})}var Ot=require("react/jsx-runtime");function _o({refreshKey:e,onViewAll:a,primaryConversion:s}){let t=hs(7,{refreshKey:e,breakdowns:[]}),n=t.status.data??void 0,{nothingToReport:i,notCollecting:o,holdingForFirstData:g}=Yn(n);return Qn({status:n,holdingForFirstData:g,refetchStatus:t.refetchStatus,refetch:t.refetch}),(0,Ot.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Ot.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Ot.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),a&&(0,Ot.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:a,children:"View all analytics"})]}),i?(0,Ot.jsx)("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:o?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):(0,Ot.jsxs)(Ot.Fragment,{children:[(0,Ot.jsx)(Za,{sourced:t.timeseries.data,error:t.timeseries.error,isLoading:t.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:t.refetch,children:f=>{let p=t.timeseries.data?.status==="ok"?t.timeseries.data:null;return(0,Ot.jsx)(sr,{rows:f,window:p?.window??{from:"",to:""},metric:"visitors",timeZone:p?.timezone,height:140})}}),(0,Ot.jsxs)("div",{className:"af-mt-3",children:[(0,Ot.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,Ot.jsx)(Za,{sourced:t.conversions.data,error:t.conversions.error,isLoading:t.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:t.refetch,children:f=>{let p=t.conversions.data?.status==="ok"?t.conversions.data:null;return(0,Ot.jsx)(tr,{rows:f,primaryConversion:s,denominator:p?.denominator??0,windowPrecedesCollection:p?.window_precedes_collection??!1,coverageUnknown:p?.first_seen_unavailable??!1})}})]})]})]})}var Ct=require("react/jsx-runtime"),Vr=5;function $r({title:e,viewAllLabel:a,onViewAll:s}){return(0,Ct.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Ct.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),s&&(0,Ct.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:s,children:a})]})}function Ro({refreshKey:e,onBackToWebsite:a,primaryConversion:s,onOpenSurface:t,needsPaidPlan:n,onUpgradePlan:i,onConnectStripe:o}){let g=bs({refreshKey:e}),f=(g.summary?.products.count??0)>0||(g.summary?.commerce?.storefront_orders??!1),p=f||(g.summary?.commerce?.invoicing??!1);return(0,Ct.jsx)(bt,{title:"Dashboard",onBackToWebsite:a,children:(0,Ct.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,Ct.jsx)(So,{primaryConversion:s}),(0,Ct.jsx)(_o,{refreshKey:e,onViewAll:t&&(()=>t("analytics")),primaryConversion:s}),(0,Ct.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Ct.jsx)($r,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:t&&(()=>t("leads"))}),(0,Ct.jsx)(dn,{refreshKey:e,maxRows:Vr,onViewAll:t&&(()=>t("leads"))})]}),f&&(0,Ct.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Ct.jsx)($r,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:t&&(()=>t("orders"))}),(0,Ct.jsx)(Wa,{refreshKey:e,maxRows:Vr,onViewAll:t&&(()=>t("orders"))})]}),p&&(0,Ct.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Ct.jsx)($r,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:t&&(()=>t("invoices"))}),(0,Ct.jsx)(Ka,{refreshKey:e,maxRows:Vr,onViewAll:t&&(()=>t("invoices")),needsPaidPlan:n,onUpgradePlan:i,onConnectStripe:o})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,DashboardView,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,PromosPanel,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 Fo=Object.create;var Pn=Object.defineProperty;var Mo=Object.getOwnPropertyDescriptor;var $o=Object.getOwnPropertyNames;var Uo=Object.getPrototypeOf,Vo=Object.prototype.hasOwnProperty;var Ho=(e,t)=>{for(var s in t)Pn(e,s,{get:t[s],enumerable:!0})},ei=(e,t,s,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of $o(t))!Vo.call(e,n)&&n!==s&&Pn(e,n,{get:()=>t[n],enumerable:!(a=Mo(t,n))||a.enumerable});return e};var le=(e,t,s)=>(s=e!=null?Fo(Uo(e)):{},ei(t||!e||!e.__esModule?Pn(s,"default",{value:e,enumerable:!0}):s,e)),zo=e=>ei(Pn({},"__esModule",{value:!0}),e);var Fc={};Ho(Fc,{AifeaturesApiError:()=>It,AifeaturesProvider:()=>si,AnalyticsView:()=>_o,CustomerDetail:()=>un,CustomersList:()=>dn,DashboardView:()=>Lo,FormSettings:()=>Xs,FormSubmissions:()=>Ws,FormsDashboard:()=>yr,FormsList:()=>zs,InvoiceDetail:()=>Wn,InvoiceLabelBadge:()=>Ds,InvoicesList:()=>Qa,InvoicesView:()=>Fr,LeadsView:()=>vn,MAX_ANALYTICS_FILTERS:()=>Ps,MAX_ANALYTICS_FILTER_VALUES:()=>Cs,OrderDetail:()=>ln,OrderStatusBadge:()=>os,OrdersList:()=>Ja,OrdersView:()=>Ar,PaymentsDashboard:()=>Er,PaymentsSetup:()=>fn,ProductSettings:()=>sn,ProductsList:()=>tn,ProductsView:()=>Ir,PromosPanel:()=>ms,REALTIME_FAILURES_BEFORE_ERROR:()=>sr,REALTIME_POLL_MS:()=>ar,RetainerStatusBadge:()=>Zn,RetainersPanel:()=>ys,SubmissionDetail:()=>Gs,SubscriptionsView:()=>Or,VariantsEditor:()=>an,ViewShell:()=>yt,WebhookDeliveries:()=>Ys,WebhookSettings:()=>Qs,chargedTotal:()=>Ba,createApiClient:()=>Tn,formatPrice:()=>W,isZeroDecimalCurrency:()=>sa,toMajorUnits:()=>pt,toMinorUnits:()=>Mt,useAifeatures:()=>ne,useAifeaturesContext:()=>ne,useAnalytics:()=>Ss,useBusinessSummary:()=>ws,useCustomers:()=>cn,useEventDestinations:()=>Zs,useForms:()=>ds,useInvoices:()=>bs,useOrders:()=>nn,usePaymentsStatus:()=>Wa,usePeople:()=>pn,usePerson:()=>gn,useProducts:()=>hs,useRealtimeVisitors:()=>yn,useRetainers:()=>xs,useSubmissions:()=>js,useSubscriptions:()=>bn});module.exports=zo(Fc);var ns=le(require("react"),1);var fr="aifeatures:analytics:timezone",mr;function Us(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function ti(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function as(){return pr()??Us()}function pr(){if(mr!==void 0)return mr;try{let e=window.localStorage.getItem(fr);return ti(e)?e:null}catch{return null}}function gr(e){if(!(e!==null&&!ti(e))){mr=e;try{e===null?window.localStorage.removeItem(fr):window.localStorage.setItem(fr,e)}catch{}}}function Cn(e,t){let s=new URLSearchParams({period:String(e)}),a=as();return a&&s.set("timezone",a),t&&t.length>0&&s.set("filters",JSON.stringify(t)),s.toString()}var It=class extends Error{constructor(s,a,n){super(s);this.status=a;this.details=n;this.name="AifeaturesApiError"}};function vr(e,t){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${t}`}function Tn(e,t="https://aifeatures.dev"){async function s(a,n={}){let i=`${t}${a}`,o=await fetch(i,{...n,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...n.headers}});if(!o.ok){let d;try{d=await o.json()}catch{}throw new It(vr(d?.error,o.status),o.status,d)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(a){return s(`/api/v1/forms/${a}`)},async createForm(a){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,n){return s(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteForm(a){await s(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,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(),d=`/api/v1/forms/${a}/submissions${o?`?${o}`:""}`;return s(d)},async getSubmission(a){return s(`/api/v1/submissions/${a}`)},async deleteSubmission(a){await s(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,n){let i=typeof n=="string"?{name:n}:n,o=i.name,d=i.id??i.name,f=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(d)}`,u=await fetch(f,{headers:{Authorization:`Bearer ${e}`}});if(!u.ok){let b;try{b=await u.json()}catch{}throw new It(vr(b?.error,u.status),u.status,b)}let r=await u.blob(),v=URL.createObjectURL(r),x=document.createElement("a");x.href=v,x.download=o,document.body.appendChild(x),x.click(),document.body.removeChild(x),URL.revokeObjectURL(v)},async getPaymentsStatus(){return s("/api/v1/payments/status")},getPromos(a){let n=new URLSearchParams({limit:"10"});return a&&n.set("cursor",a),s(`/api/v1/promos?${n}`)},getPromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return s("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,n){return s(`/api/v1/promos/${encodeURIComponent(a)}/replace`,{method:"POST",body:JSON.stringify(n)})},async getProducts(a={}){let n=new URLSearchParams;a.include&&n.set("include",a.include);let i=n.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(a){return s(`/api/v1/products/${a}`)},async createProduct(a){return s("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,n){return s(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteProduct(a){await s(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,n){let i=new FormData;i.append("file",n);let o=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!o.ok){let d;try{d=await o.json()}catch{}throw new It(vr(d?.error,o.status),o.status,d)}return o.json()},async attachProductFileFromUrl(a,n){return s(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:n})})},async createOption(a,n){return s(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(n)})},async updateOption(a,n){return s(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteOption(a){await s(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,n){return s(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(n)})},async updateVariant(a,n){return s(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteVariant(a){await s(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,n){return s(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(n)})},async adjustVariantInventory(a,n){return s(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(n)})},async getCustomers(a={}){let n=new URLSearchParams;a.email?n.set("email",a.email):a.q&&n.set("q",a.q),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(a){return s(`/api/v1/customers/${a}`)},async getOrders(a={}){let n=new URLSearchParams;a.status&&n.set("status",a.status),a.source&&n.set("source",a.source),a.excludeStatus?.length&&n.set("exclude_status",a.excludeStatus.join(",")),a.customerEmail&&n.set("customer_email",a.customerEmail),a.from&&n.set("from",a.from),a.to&&n.set("to",a.to),a.unfulfilledOnly&&n.set("unfulfilled_only","true"),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(a){return s(`/api/v1/orders/${a}`)},async getInvoices(a={}){let n=new URLSearchParams;a.labels?.length&&n.set("label",a.labels.join(",")),a.customerEmail&&n.set("customer_email",a.customerEmail),a.customerId&&n.set("customer_id",a.customerId),a.q&&n.set("q",a.q),a.from&&n.set("from",a.from),a.to&&n.set("to",a.to),a.includeAggregates&&n.set("include","aggregates"),a.retainerId&&n.set("retainer_id",a.retainerId),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(a){return s(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return s(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(a={}){let n=new URLSearchParams;a.statuses?.length&&n.set("status",a.statuses.join(",")),a.customerEmail&&n.set("customer_email",a.customerEmail),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/retainers${i?`?${i}`:""}`)},async getRetainer(a){return s(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await s(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return s(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,n){return s(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:n.fulfilled,...n.trackingNumber!==void 0?{tracking_number:n.trackingNumber}:{}})})},async getSubscriptions(a={}){let n=new URLSearchParams;a.status&&n.set("status",a.status),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getAnalyticsStatus(){let a=new URLSearchParams,n=as();n&&a.set("timezone",n);let i=a.toString();return s(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(a,n){return s(`/api/v1/analytics/summary?${Cn(a,n)}`)},async getAnalyticsTimeseries(a,n){return s(`/api/v1/analytics/timeseries?${Cn(a,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,n){return s(`/api/v1/analytics/channels?${Cn(a,n)}`)},async getAnalyticsConversions(a){return s((()=>{let n=new URLSearchParams({period:String(a)}),i=as();return i&&n.set("timezone",i),`/api/v1/analytics/conversions?${n.toString()}`})())},async getAnalyticsGoalTargets(a,n,i){let o=new URLSearchParams({goal:a,period:String(n)}),d=as();return d&&o.set("timezone",d),i!==void 0&&o.set("limit",String(i)),s(`/api/v1/analytics/conversions/targets?${o.toString()}`)},async getAnalyticsBreakdown(a,n,i){let o=a.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${Cn(n,i)}`)},async getBusinessSummary(a){let n=new URLSearchParams;n.set("tz_offset_minutes",String(a.tzOffsetMinutes));let i=as();return i&&n.set("timezone",i),s(`/api/v1/summary?${n.toString()}`)},async getPeople(a={}){let n=new URLSearchParams;a.since&&n.set("since",a.since),a.q&&n.set("q",a.q),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/people${i?`?${i}`:""}`)},async getPerson(a){return s(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(a){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,n){return s(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteEventDestination(a){await s(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return s(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await s(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,n){let i=n===void 0?"":`?limit=${n}`;return(await s(`/api/v1/event-destinations/${a}/deliveries${i}`)).deliveries},async retryEventDelivery(a,n){return s(`/api/v1/event-destinations/${a}/deliveries/${n}/retry`,{method:"POST"})}}}var ss=require("react/jsx-runtime"),ai=ns.createContext(null);function qo(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 si({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:s=!1,className:a,children:n}){let i=ns.useMemo(()=>qo(e),[e]),o=ns.useMemo(()=>Tn(e,t),[e,t]),d=ns.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return i?(0,ss.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:(0,ss.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,ss.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,ss.jsx)("p",{className:"af-text-sm af-text-destructive",children:i})]})}):(0,ss.jsx)(ai.Provider,{value:d,children:(0,ss.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:n})})}function ne(){let e=ns.useContext(ai);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var Ga=le(require("react"),1),ks=require("lucide-react");var kn=le(require("react"),1),wa=le(require("@radix-ui/react-tabs"),1);var ni=require("clsx"),ri=require("tailwind-merge"),jo=(0,ri.extendTailwindMerge)({prefix:"af-"});function te(...e){return jo((0,ni.clsx)(e))}var An=require("react/jsx-runtime"),En=wa.Root,Vs=kn.forwardRef(({className:e,...t},s)=>(0,An.jsx)(wa.List,{ref:s,className:te("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));Vs.displayName=wa.List.displayName;var Na=kn.forwardRef(({className:e,...t},s)=>(0,An.jsx)(wa.Trigger,{ref:s,className:te("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));Na.displayName=wa.Trigger.displayName;var Sa=kn.forwardRef(({className:e,...t},s)=>(0,An.jsx)(wa.Content,{ref:s,className:te("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));Sa.displayName=wa.Content.displayName;var ii=le(require("react"),1),oi=require("@radix-ui/react-slot"),li=require("class-variance-authority");var ci=require("react/jsx-runtime"),Go=(0,li.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"}}),_=ii.forwardRef(({className:e,variant:t,size:s,asChild:a=!1,...n},i)=>(0,ci.jsx)(a?oi.Slot:"button",{className:te(Go({variant:t,size:s,className:e})),ref:i,...n}));_.displayName="Button";var Hs=require("lucide-react");var qa=le(require("react"),1);var Ia=require("react/jsx-runtime"),Ue=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,Ia.jsx)("table",{ref:s,className:te("af-w-full af-caption-bottom af-text-sm",e),...t})}));Ue.displayName="Table";var Ve=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("thead",{ref:s,className:te("[&_tr]:af-border-b",e),...t}));Ve.displayName="TableHeader";var He=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("tbody",{ref:s,className:te("[&_tr:last-child]:af-border-0",e),...t}));He.displayName="TableBody";var Wo=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("tfoot",{ref:s,className:te("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Wo.displayName="TableFooter";var xe=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("tr",{ref:s,className:te("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));xe.displayName="TableRow";var H=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("th",{ref:s,className:te("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));H.displayName="TableHead";var z=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("td",{ref:s,className:te("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));z.displayName="TableCell";var Ko=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("caption",{ref:s,className:te("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Ko.displayName="TableCaption";var _a=le(require("react"),1);function ds(){let{api:e}=ne(),[t,s]=_a.useState([]),[a,n]=_a.useState(!0),[i,o]=_a.useState(null),d=_a.useCallback(async()=>{try{n(!0),o(null);let v=await e.getForms();s(v)}catch(v){o(v instanceof Error?v:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);_a.useEffect(()=>{d()},[d]);let f=_a.useCallback(async v=>{let x=await e.createForm(v);return s(b=>[...b,x]),x},[e]),u=_a.useCallback(async(v,x)=>{let b=await e.updateForm(v,x);return s(c=>c.map(l=>l.id===v?b:l)),b},[e]),r=_a.useCallback(async v=>{await e.deleteForm(v),s(x=>x.filter(b=>b.id!==v))},[e]);return{forms:t,isLoading:a,error:i,refetch:d,createForm:f,updateForm:u,deleteForm:r}}var Je=require("react/jsx-runtime");function zs({onSelectForm:e,className:t}){let{forms:s,isLoading:a,error:n}=ds();return a?(0,Je.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Je.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,Je.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Je.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?(0,Je.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,Je.jsx)(Hs.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Je.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Je.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Je.jsx)("div",{className:t,children:(0,Je.jsxs)(Ue,{children:[(0,Je.jsx)(Ve,{children:(0,Je.jsxs)(xe,{children:[(0,Je.jsx)(H,{children:"Name"}),(0,Je.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,Je.jsx)(He,{children:s.map(i=>(0,Je.jsxs)(xe,{children:[(0,Je.jsx)(z,{className:"af-font-medium",children:i.name}),(0,Je.jsx)(z,{className:"af-text-right",children:(0,Je.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Je.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[(0,Je.jsx)(Hs.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Je.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[(0,Je.jsx)(Hs.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}var fi=require("lucide-react");var ui=require("class-variance-authority");var di=require("react/jsx-runtime"),Zo=(0,ui.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 ae({className:e,variant:t,...s}){return(0,di.jsx)("div",{className:te(Zo({variant:t}),e),...s})}var Qt=require("react/jsx-runtime"),Jo={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 In(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 br(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function Yo(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 qs({deliveries:e,label:t="Email needs attention"}){return br(e)?(0,Qt.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,Qt.jsx)(fi.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Da({deliveries:e,problemsOnly:t=!1,className:s=""}){let a=(e??[]).filter(n=>!t||br([n]));return a.length?(0,Qt.jsx)("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:a.map(n=>{let i=In(n),o=Yo(n);return(0,Qt.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Qt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Qt.jsx)("span",{className:"af-font-medium",children:Jo[n.kind]??"Email notification"}),(0,Qt.jsx)(ae,{variant:i.variant,children:i.label})]}),(0,Qt.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&&br([n])&&(0,Qt.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,Qt.jsx)("p",{className:"af-mt-1",children:i.detail}),o&&(0,Qt.jsx)("p",{className:"af-mt-1",children:o})]},n.id)})}):null}var Ts=le(require("react"),1),pa=require("lucide-react");var rs=le(require("react"),1),Te=le(require("@radix-ui/react-select"),1),fs=require("lucide-react");var mt=require("react/jsx-runtime"),da=Te.Root;var fa=Te.Value,Xt=rs.forwardRef(({className:e,children:t,...s},a)=>(0,mt.jsxs)(Te.Trigger,{ref:a,className:te("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[t,(0,mt.jsx)(Te.Icon,{asChild:!0,children:(0,mt.jsx)(fs.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Xt.displayName=Te.Trigger.displayName;var mi=rs.forwardRef(({className:e,...t},s)=>(0,mt.jsx)(Te.ScrollUpButton,{ref:s,className:te("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,mt.jsx)(fs.ChevronUp,{className:"af-h-4 af-w-4"})}));mi.displayName=Te.ScrollUpButton.displayName;var pi=rs.forwardRef(({className:e,...t},s)=>(0,mt.jsx)(Te.ScrollDownButton,{ref:s,className:te("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,mt.jsx)(fs.ChevronDown,{className:"af-h-4 af-w-4"})}));pi.displayName=Te.ScrollDownButton.displayName;var ea=rs.forwardRef(({className:e,children:t,position:s="popper",...a},n)=>(0,mt.jsx)(Te.Portal,{children:(0,mt.jsxs)(Te.Content,{ref:n,className:te("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...a,children:[(0,mt.jsx)(mi,{}),(0,mt.jsx)(Te.Viewport,{className:te("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,mt.jsx)(pi,{})]})}));ea.displayName=Te.Content.displayName;var Qo=rs.forwardRef(({className:e,...t},s)=>(0,mt.jsx)(Te.Label,{ref:s,className:te("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));Qo.displayName=Te.Label.displayName;var Ye=rs.forwardRef(({className:e,children:t,...s},a)=>(0,mt.jsxs)(Te.Item,{ref:a,className:te("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,mt.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,mt.jsx)(Te.ItemIndicator,{children:(0,mt.jsx)(fs.Check,{className:"af-h-4 af-w-4"})})}),(0,mt.jsx)(Te.ItemText,{children:t})]}));Ye.displayName=Te.Item.displayName;var Xo=rs.forwardRef(({className:e,...t},s)=>(0,mt.jsx)(Te.Separator,{ref:s,className:te("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));Xo.displayName=Te.Separator.displayName;var ma=le(require("react"),1);function js({formId:e,initialPageSize:t=25}){let{api:s}=ne(),[a,n]=ma.useState([]),[i,o]=ma.useState(0),[d,f]=ma.useState(!0),[u,r]=ma.useState(null),[v,x]=ma.useState(0),[b,c]=ma.useState(t),l=ma.useCallback(async()=>{if(e)try{f(!0),r(null);let S={limit:b,offset:v*b},O=await s.getSubmissions(e,S);n(O.submissions),o(O.total)}catch(S){r(S instanceof Error?S:new Error("Failed to fetch submissions"))}finally{f(!1)}},[s,e,v,b]);ma.useEffect(()=>{l()},[l]);let y=ma.useCallback(async S=>{await s.deleteSubmission(S),n(O=>O.filter(M=>M.id!==S)),o(O=>O-1)},[s]),N=Math.ceil(i/b);return{submissions:a,total:i,isLoading:d,error:u,page:v,pageSize:b,hasNextPage:v<N-1,hasPreviousPage:v>0,setPage:x,setPageSize:S=>{c(S),x(0)},refetch:l,deleteSubmission:y}}var vi=le(require("react"),1),Ot=require("lucide-react");var we=require("react/jsx-runtime");function gi(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function el(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,a)).toFixed(1))} ${s[a]}`}function Gs({submission:e,onBack:t}){let{api:s}=ne(),[a,n]=vi.useState(null),i=f=>f.id??f.name,o=async f=>{n(i(f));try{await s.downloadAttachment(e.id,f)}catch(u){console.error("Download failed:",u)}finally{n(null)}},d=Object.entries(e.data).filter(([f])=>!f.startsWith("_"));return(0,we.jsxs)("div",{children:[(0,we.jsxs)("div",{className:"af-mb-6",children:[(0,we.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,we.jsx)(Ot.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,we.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,we.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",gi(e.metadata.submitted_at)]})]}),(0,we.jsxs)("div",{className:"af-space-y-6",children:[(0,we.jsx)(Da,{deliveries:e.email_deliveries}),(0,we.jsxs)("div",{children:[(0,we.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,we.jsxs)("div",{className:"af-space-y-3",children:[d.map(([f,u])=>(0,we.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,we.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:f.replace(/_/g," ")}),(0,we.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof u=="string"&&u.includes(`
3
+ `)?(0,we.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:u}):String(u)})]},f)),d.length===0&&(0,we.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,we.jsxs)("div",{children:[(0,we.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,we.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((f,u)=>(0,we.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,we.jsx)(Ot.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,we.jsx)("span",{className:"af-text-sm",children:f.name}),(0,we.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",el(f.size),")"]})]}),(0,we.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>o(f),disabled:a===i(f),children:[a===i(f)?(0,we.jsx)(Ot.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,we.jsx)(Ot.Download,{className:"af-h-4 af-w-4 af-mr-1"}),a===i(f)?"Downloading...":"Download"]})]},u))})]}),(0,we.jsxs)("div",{children:[(0,we.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,we.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,we.jsx)(Ot.Clock,{className:"af-h-4 af-w-4"}),(0,we.jsx)("span",{children:gi(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,we.jsx)(Ot.Globe,{className:"af-h-4 af-w-4"}),(0,we.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,we.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,we.jsx)(Ot.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,we.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,we.jsx)(Ot.Mail,{className:"af-h-4 af-w-4"}),(0,we.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var ue=require("react/jsx-runtime");function tl(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function al(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let s of t)if(typeof e[s]=="string")return e[s];return null}var sl=["message","comments","comment","inquiry","question","details","body","notes"];function nl(e){let t=Object.entries(e).filter(([i,o])=>!i.startsWith("_")&&!i.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),s=new Map(t.map(([i,o])=>[i.toLowerCase(),o])),n=(sl.map(i=>s.get(i)).find(Boolean)??t.reduce((i,[,o])=>o.length>i.length?o:i,"")).trim().replace(/\s+/g," ");return n.length>80?n.slice(0,80)+"\u2026":n}function Ws({formId:e,className:t,defaultSubmissionId:s,submissionId:a,onSelectSubmission:n}){let{api:i}=ne(),{submissions:o,total:d,isLoading:f,error:u,page:r,pageSize:v,hasNextPage:x,hasPreviousPage:b,setPage:c,setPageSize:l}=js({formId:e}),[y,N]=Ts.useState(s??null),S=n?a??null:y,O=n??N,M=F=>!!F&&F.id===S&&F.form_id===e,m=o.find(M),[R,T]=Ts.useState(null),D=M(R)?R:null,[P,A]=Ts.useState(null);if(Ts.useEffect(()=>{if(A(null),!S||m||D)return;let F=!1;return i.getSubmission(S).then(X=>{if(!F){if(X.form_id!==e){A("This submission could not be found.");return}T(X)}}).catch(()=>{F||A("This submission could not be found.")}),()=>{F=!0}},[i,e,S,m,D]),S){let F=m??D;return F?(0,ue.jsx)("div",{className:t,children:(0,ue.jsx)(Gs,{submission:F,onBack:()=>O(null)})}):P?(0,ue.jsxs)("div",{className:t,children:[(0,ue.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>O(null),className:"af-mb-2 af--ml-2",children:[(0,ue.jsx)(pa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,ue.jsx)("p",{className:"af-text-sm af-text-destructive",children:P})]}):(0,ue.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ue.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(f)return(0,ue.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ue.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(u)return(0,ue.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ue.jsxs)("div",{className:"af-text-destructive",children:["Error: ",u.message]})});if(o.length===0&&r===0)return(0,ue.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,ue.jsx)(pa.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ue.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,ue.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let U=r*v+1,w=Math.min((r+1)*v,d);return(0,ue.jsxs)("div",{className:t,children:[(0,ue.jsxs)(Ue,{children:[(0,ue.jsx)(Ve,{children:(0,ue.jsxs)(xe,{children:[(0,ue.jsx)(H,{children:"Email"}),(0,ue.jsx)(H,{children:"Preview"}),(0,ue.jsx)(H,{children:"Date"}),(0,ue.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,ue.jsx)(He,{children:o.map(F=>{let X=al(F.data),q=nl(F.data);return(0,ue.jsxs)(xe,{children:[(0,ue.jsxs)(z,{className:"af-font-medium",children:[(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[X||(0,ue.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),F.attachments.length>0&&(0,ue.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${F.attachments.length} attachment(s)`,children:[(0,ue.jsx)(pa.Paperclip,{className:"af-h-3 af-w-3"}),(0,ue.jsx)("span",{className:"af-text-xs",children:F.attachments.length})]})]}),(0,ue.jsx)(qs,{deliveries:F.email_deliveries,label:"Notification email needs attention"})]}),(0,ue.jsx)(z,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:q||(0,ue.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,ue.jsx)(z,{className:"af-text-muted-foreground",children:tl(F.metadata.submitted_at)}),(0,ue.jsx)(z,{className:"af-text-right",children:(0,ue.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>O(F.id),title:"View details",children:(0,ue.jsx)(pa.Eye,{className:"af-h-4 af-w-4"})})})]},F.id)})})]}),(0,ue.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ue.jsxs)("span",{children:["Showing ",U,"-",w," of ",d]}),(0,ue.jsxs)(da,{value:String(v),onValueChange:F=>l(Number(F)),children:[(0,ue.jsx)(Xt,{className:"af-w-[70px] af-h-8",children:(0,ue.jsx)(fa,{})}),(0,ue.jsxs)(ea,{children:[(0,ue.jsx)(Ye,{value:"10",children:"10"}),(0,ue.jsx)(Ye,{value:"25",children:"25"}),(0,ue.jsx)(Ye,{value:"50",children:"50"}),(0,ue.jsx)(Ye,{value:"100",children:"100"})]})]}),(0,ue.jsx)("span",{children:"per page"})]}),(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ue.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>c(r-1),disabled:!b,children:[(0,ue.jsx)(pa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ue.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>c(r+1),disabled:!x,children:["Next",(0,ue.jsx)(pa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var aa=le(require("react"),1),is=require("lucide-react");var bi=le(require("react"),1);var yi=require("react/jsx-runtime"),Ne=bi.forwardRef(({className:e,type:t,...s},a)=>(0,yi.jsx)("input",{type:t,className:te("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:a,...s}));Ne.displayName="Input";var hi=le(require("react"),1),xi=require("class-variance-authority");var wi=require("react/jsx-runtime"),rl=(0,xi.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Re=hi.forwardRef(({className:e,...t},s)=>(0,wi.jsx)("label",{ref:s,className:te(rl(),e),...t}));Re.displayName="Label";var ga=le(require("react"),1),Bt=require("lucide-react");var Ks=le(require("react"),1),Nt=le(require("@radix-ui/react-dialog"),1),Ni=require("lucide-react");var jt=require("react/jsx-runtime"),La=Nt.Root;var il=Nt.Portal;var Si=Ks.forwardRef(({className:e,...t},s)=>(0,jt.jsx)(Nt.Overlay,{ref:s,className:te("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Si.displayName=Nt.Overlay.displayName;var Ra=Ks.forwardRef(({className:e,children:t,...s},a)=>(0,jt.jsx)(il,{children:(0,jt.jsxs)("div",{className:"aifeatures-admin",children:[(0,jt.jsx)(Si,{}),(0,jt.jsxs)(Nt.Content,{ref:a,className:te("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[t,(0,jt.jsxs)(Nt.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,jt.jsx)(Ni.X,{className:"af-h-4 af-w-4"}),(0,jt.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Ra.displayName=Nt.Content.displayName;var Pa=({className:e,...t})=>(0,jt.jsx)("div",{className:te("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Pa.displayName="DialogHeader";var Ca=({className:e,...t})=>(0,jt.jsx)("div",{className:te("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ca.displayName="DialogFooter";var Ta=Ks.forwardRef(({className:e,...t},s)=>(0,jt.jsx)(Nt.Title,{ref:s,className:te("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Ta.displayName=Nt.Title.displayName;var ka=Ks.forwardRef(({className:e,...t},s)=>(0,jt.jsx)(Nt.Description,{ref:s,className:te("af-text-sm af-text-muted-foreground",e),...t}));ka.displayName=Nt.Description.displayName;var ta=le(require("react"),1);function Zs(){let{api:e}=ne(),[t,s]=ta.useState([]),[a,n]=ta.useState(!0),[i,o]=ta.useState(null),d=ta.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(b){o(b instanceof Error?b:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);ta.useEffect(()=>{d()},[d]);let f=ta.useCallback(async b=>{let c=await e.createEventDestination(b);return s(l=>[c,...l]),c},[e]),u=ta.useCallback(async(b,c)=>{let l=await e.updateEventDestination(b,c);return s(y=>y.map(N=>N.id===b?l:N)),l},[e]),r=ta.useCallback(async b=>{await e.deleteEventDestination(b),s(c=>c.filter(l=>l.id!==b))},[e]),v=ta.useCallback(async b=>{let c=await e.rotateEventDestinationSecret(b);return s(l=>l.map(y=>y.id===b?c:y)),c},[e]),x=ta.useCallback(b=>e.getEventDestinationSecret(b),[e]);return{destinations:t,isLoading:a,error:i,refetch:d,createDestination:f,updateDestination:u,deleteDestination:r,rotateSecret:v,getSecret:x}}var ja=le(require("react"),1),Js=require("lucide-react");var St=require("react/jsx-runtime");function Ys({destinationId:e,limit:t=25,className:s}){let{api:a}=ne(),[n,i]=ja.useState([]),[o,d]=ja.useState(!0),[f,u]=ja.useState(null),[r,v]=ja.useState(null),x=ja.useCallback(async()=>{try{d(!0),u(null),i(await a.getEventDeliveries(e,t))}catch(c){u(c instanceof Error?c.message:"Failed to load deliveries")}finally{d(!1)}},[a,e,t]);ja.useEffect(()=>{x()},[x]);let b=async c=>{try{v(c.id),u(null);let l=await a.retryEventDelivery(e,c.id);i(y=>y.map(N=>N.id===c.id?l:N))}catch(l){u(l instanceof Error?l.message:"Retry failed")}finally{v(null)}};return o?(0,St.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,St.jsx)(Js.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):f?(0,St.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:f}):n.length===0?(0,St.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,St.jsx)("div",{className:s,children:(0,St.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(c=>{let l=c.delivered_at!==null;return(0,St.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,St.jsxs)("div",{className:"af-min-w-0",children:[(0,St.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[l?(0,St.jsx)(ae,{variant:"secondary",children:c.last_status??200}):(0,St.jsx)(ae,{variant:"destructive",children:c.last_status??"failed"}),(0,St.jsx)("span",{className:"af-text-sm af-truncate",children:c.type})]}),(0,St.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[c.event_id," \xB7 ",c.created_at,c.attempts>0&&` \xB7 ${c.attempts} failed ${c.attempts===1?"attempt":"attempts"}`]}),!l&&c.last_error&&(0,St.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:c.last_error})]}),(0,St.jsx)(_,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===c.id,onClick:()=>b(c),children:r===c.id?(0,St.jsx)(Js.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,St.jsx)(Js.RotateCw,{className:"af-h-4 af-w-4"})})]},c.id)})})})}var me=require("react/jsx-runtime");function Qs({formId:e,topics:t,description:s,className:a}){let{destinations:n,isLoading:i,error:o,createDestination:d,updateDestination:f,deleteDestination:u,rotateSecret:r,getSecret:v}=Zs(),[x,b]=ga.useState(""),[c,l]=ga.useState(!1),[y,N]=ga.useState(null),[S,O]=ga.useState(null),[M,m]=ga.useState(null),[R,T]=ga.useState(!1),[D,P]=ga.useState(null),[A,U]=ga.useState(null),[w,F]=ga.useState(null),X=ga.useMemo(()=>n.filter(Y=>Y.form_id===e),[n,e]),q=async()=>{let Y=x.trim();if(Y){if(!Y.startsWith("https://")){N("Webhook URLs must start with https://");return}try{l(!0),N(null),await d({url:Y,form_id:e,...t&&t.length>0?{topics:t}:{}}),b("")}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to add webhook")}finally{l(!1)}}},fe=async Y=>{try{U(Y.id),N(null),await r(Y.id),T(!1),m(await v(Y.id))}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to rotate secret")}finally{U(null)}},J=async Y=>{try{U(Y.id),N(null),await f(Y.id,{status:"active"})}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to re-enable")}finally{U(null)}},ee=async()=>{if(D)try{U(D.id),await u(D.id),P(null)}catch(Y){N(Y instanceof Error?Y.message:"Failed to delete")}finally{U(null)}},Z=async Y=>{if(S===Y.id){O(null),m(null);return}try{U(Y.id),N(null),T(!1),O(Y.id),m(await v(Y.id))}catch(Pe){O(null),N(Pe instanceof Error?Pe.message:"Failed to read secret")}finally{U(null)}},oe=async()=>{if(M)try{await navigator.clipboard.writeText(M),T(!0)}catch{}};return(0,me.jsxs)("div",{className:a,children:[(0,me.jsxs)("div",{className:"af-space-y-1",children:[(0,me.jsx)(Re,{children:"Webhooks"}),(0,me.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,me.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,me.jsx)(Ne,{value:x,placeholder:"https://hooks.zapier.com/...",onChange:Y=>b(Y.target.value),onKeyDown:Y=>{Y.key==="Enter"&&(Y.preventDefault(),q())},disabled:c}),(0,me.jsxs)(_,{onClick:q,disabled:c||!x.trim(),children:[c?(0,me.jsx)(Bt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,me.jsx)(Bt.Plus,{className:"af-h-4 af-w-4"}),(0,me.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(y||o)&&(0,me.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:y||o?.message}),(0,me.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[i&&(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,me.jsx)(Bt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&X.length===0&&(0,me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),X.map(Y=>(0,me.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,me.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,me.jsxs)("div",{className:"af-min-w-0",children:[(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,me.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:Y.url}),Y.status==="disabled"?(0,me.jsx)(ae,{variant:"destructive",children:"Disabled"}):(0,me.jsx)(ae,{variant:"secondary",children:"Active"})]}),(0,me.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:Y.topics.includes("*")?"All events":Y.topics.join(", ")})]}),(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,me.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>F(w===Y.id?null:Y.id),children:w===Y.id?"Hide log":"Deliveries"}),(0,me.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>Z(Y),disabled:A===Y.id,children:S===Y.id?"Hide secret":"Show secret"}),(0,me.jsx)(_,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:A===Y.id,onClick:()=>P(Y),children:(0,me.jsx)(Bt.Trash2,{className:"af-h-4 af-w-4"})})]})]}),Y.status==="disabled"&&(0,me.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,me.jsx)(Bt.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,me.jsxs)("div",{className:"af-text-sm",children:[(0,me.jsxs)("p",{children:["We stopped sending after repeated failures."," ",Y.disabled_reason]}),(0,me.jsx)(_,{variant:"outline",size:"sm",className:"af-mt-2",disabled:A===Y.id,onClick:()=>J(Y),children:"Re-enable"})]})]}),S===Y.id&&M&&(0,me.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,me.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,me.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,me.jsx)(Ne,{readOnly:!0,value:M,className:"af-font-mono"}),(0,me.jsx)(_,{variant:"outline",title:"Copy signing secret",onClick:oe,children:R?(0,me.jsx)(Bt.Check,{className:"af-h-4 af-w-4"}):(0,me.jsx)(Bt.Copy,{className:"af-h-4 af-w-4"})}),(0,me.jsx)(_,{variant:"outline",title:"Rotate signing secret",disabled:A===Y.id,onClick:()=>fe(Y),children:A===Y.id?(0,me.jsx)(Bt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,me.jsx)(Bt.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),w===Y.id&&(0,me.jsx)(Ys,{destinationId:Y.id})]},Y.id))]}),(0,me.jsx)(La,{open:!!D,onOpenChange:Y=>{!Y&&!A&&P(null)},children:(0,me.jsxs)(Ra,{children:[(0,me.jsxs)(Pa,{children:[(0,me.jsx)(Ta,{children:"Delete this webhook?"}),(0,me.jsxs)(ka,{children:["New submissions will stop being sent to ",D?.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,me.jsxs)(Ca,{children:[(0,me.jsx)(_,{variant:"outline",onClick:()=>P(null),disabled:!!A,children:"Cancel"}),(0,me.jsx)(_,{variant:"destructive",onClick:ee,disabled:!!A,children:A?"Deleting...":"Delete"})]})]})})]})}var _e=require("react/jsx-runtime");function Xs({form:e,onSaved:t,className:s}){let{updateForm:a}=ds(),[n,i]=aa.useState(!1),[o,d]=aa.useState(null),[f,u]=aa.useState(null),[r,v]=aa.useState(e.name),[x,b]=aa.useState(e.redirect_url||""),[c,l]=aa.useState(e.email_recipients),[y,N]=aa.useState("");aa.useEffect(()=>{v(e.name),b(e.redirect_url||""),l(e.email_recipients),u(null)},[e]);let S=aa.useCallback(async T=>{try{i(!0),u(null);let D=await a(e.id,T);d(new Date),t?.(D)}catch(D){u(D instanceof Error?D.message:"Failed to save")}finally{i(!1)}},[e.id,a,t]);aa.useEffect(()=>{if(o){let T=setTimeout(()=>d(null),2e3);return()=>clearTimeout(T)}},[o]);let O=async()=>{let T=y.trim().toLowerCase();if(!T)return;if(!T.includes("@")){u("Please enter a valid email address");return}if(c.includes(T)){u("This email is already added");return}let D=[...c,T];l(D),N(""),u(null),await S({email_recipients:D})},M=async T=>{let D=c.filter(P=>P!==T);l(D),await S({email_recipients:D})},m=async()=>{r!==e.name&&await S({name:r})},R=async()=>{let T=x||null;T!==e.redirect_url&&await S({redirect_url:T})};return(0,_e.jsxs)("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&(0,_e.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,_e.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,_e.jsx)(is.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,_e.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,_e.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,_e.jsx)(is.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,_e.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{htmlFor:"form-name",children:"Form Name"}),(0,_e.jsx)(Ne,{id:"form-name",value:r,onChange:T=>v(T.target.value),onBlur:m,placeholder:"Contact Form"}),(0,_e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{children:"Email Recipients"}),(0,_e.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,_e.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[c.map(T=>(0,_e.jsxs)(ae,{variant:"secondary",className:"af-gap-1",children:[T,(0,_e.jsx)("button",{type:"button",onClick:()=>M(T),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,_e.jsx)(is.X,{className:"af-h-3 af-w-3"})})]},T)),c.length===0&&(0,_e.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)(Ne,{type:"email",value:y,onChange:T=>N(T.target.value),placeholder:"Add email address",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),O())},disabled:n}),(0,_e.jsx)(_,{type:"button",variant:"outline",onClick:O,disabled:!y.trim()||n,children:(0,_e.jsx)(is.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,_e.jsx)(Ne,{id:"redirect-url",value:x,onChange:T=>b(T.target.value),onBlur:R,placeholder:"/thank-you"}),(0,_e.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,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{children:"Form Endpoint"}),(0,_e.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,_e.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,_e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{children:"Captcha Protection"}),(0,_e.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,_e.jsx)(ae,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,_e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,_e.jsx)(Qs,{formId:e.id}),f&&(0,_e.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f})]})}var We=require("react/jsx-runtime");function yr({className:e,location:t,onNavigate:s,submissionId:a}){let{api:n}=ne(),[i,o]=Ga.useState({submissionId:a});Ga.useEffect(()=>{a&&o({submissionId:a})},[a]);let d=s?t??{}:i,f=s??o,[u,r]=Ga.useState(null),v=`${d.formId??""}|${d.submissionId??""}`,[x,b]=Ga.useState(null),c=x?.key===v?x.message:null,l=d.formId??(u&&u.submissionId===d.submissionId?u.formId:void 0);Ga.useEffect(()=>{let T=d.submissionId;if(!T||d.formId)return;let D=!1;return n.getSubmission(T).then(P=>{D||(b(null),r({submissionId:T,formId:P.form_id}))}).catch(()=>{D||b({key:v,message:"This submission could not be found."})}),()=>{D=!0}},[n,d.submissionId,d.formId,v]);let[y,N]=Ga.useState(null);Ga.useEffect(()=>{if(!l||y?.id===l)return;let T=!1;return n.getForm(l).then(D=>{T||(b(null),N(D))}).catch(()=>{T||b({key:v,message:"This form could not be found."})}),()=>{T=!0}},[n,l,y?.id,v]);let S=(T,D)=>{N(T),f({formId:T.id,tab:D})},O=()=>f({});if(!d.formId&&!d.submissionId)return(0,We.jsxs)("div",{className:e,children:[(0,We.jsxs)("div",{className:"af-mb-6",children:[(0,We.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,We.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,We.jsx)(zs,{onSelectForm:S})]});let m=(0,We.jsxs)(_,{variant:"ghost",size:"sm",onClick:O,className:"af-mb-2 af--ml-2",children:[(0,We.jsx)(ks.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(c)return(0,We.jsxs)("div",{className:e,children:[m,(0,We.jsx)("p",{className:"af-text-sm af-text-destructive",children:c})]});if(!l||y?.id!==l)return(0,We.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,We.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let R=d.submissionId?"submissions":d.tab??"submissions";return(0,We.jsxs)("div",{className:e,children:[(0,We.jsxs)("div",{className:"af-mb-6",children:[m,(0,We.jsx)("h2",{className:"af-text-lg af-font-semibold",children:y.name})]}),(0,We.jsxs)(En,{value:R,onValueChange:T=>f({formId:l,tab:T}),children:[(0,We.jsxs)(Vs,{className:"af-mb-4",children:[(0,We.jsxs)(Na,{value:"submissions",className:"af-gap-2",children:[(0,We.jsx)(ks.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,We.jsxs)(Na,{value:"settings",className:"af-gap-2",children:[(0,We.jsx)(ks.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,We.jsx)(Sa,{value:"submissions",children:(0,We.jsx)(Ws,{formId:l,submissionId:d.submissionId,onSelectSubmission:T=>f({formId:l,tab:"submissions",submissionId:T??void 0})})}),(0,We.jsx)(Sa,{value:"settings",children:(0,We.jsx)(Xs,{form:y,onSaved:N})})]})]})}var $e=le(require("react"),1);var Oa=le(require("react"),1);function Wa(){let{api:e}=ne(),[t,s]=Oa.useState(null),[a,n]=Oa.useState(!0),[i,o]=Oa.useState(null),d=Oa.useRef(0),f=Oa.useCallback(async()=>{let u=++d.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(u!==d.current)return;s(r)}catch(r){if(u!==d.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{u===d.current&&n(!1)}},[e]);return Oa.useEffect(()=>{f()},[f]),{status:t,isLoading:a,error:i,refetch:f}}var ol=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function sa(e){return ol.has(e.toLowerCase())}function W(e,t,s){let a=sa(t)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:t.toUpperCase()}).format(a)}catch{return`${a} ${t.toUpperCase()}`}}function Ba(e){let t=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+t}function Mt(e,t){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let a=sa(t)?s:s*100;return Math.round(a)}function pt(e,t){return sa(t)?e:e/100}function Dn(e){return e.amount_paid??Math.max(0,Ba(e)-(e.credit_applied??0))}var ie=require("react/jsx-runtime");function en(e){return e instanceof It&&e.status===404?"Promo management is not available yet. Try again after the service is updated.":e instanceof Error?e.message:"Could not complete the request."}function _i(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${W(e.amount_off,e.currency)} off`:"Discount unavailable"}function ms(){let{api:e,siteToken:t}=ne();return(0,ie.jsx)(ll,{api:e},t)}function ll({api:e}){let{status:t,error:s}=Wa(),[a,n]=$e.useState([]),[i,o]=$e.useState(null),[d,f]=$e.useState(null),[u,r]=$e.useState(!1),[v,x]=$e.useState(!1),[b,c]=$e.useState(""),[l,y]=$e.useState(null),[N,S]=$e.useState(null),[O,M]=$e.useState(!1),m=$e.useRef(0),R=$e.useCallback(async P=>{let A=++m.current;r(!0),c("");try{let U=await e.getPromos(P);if(A!==m.current)return;n(w=>P?[...w,...U.promos.filter(F=>!w.some(X=>X.id===F.id))]:U.promos),o(U.next_cursor),f(U.checkout_enabled)}catch(U){A===m.current&&c(en(U))}finally{A===m.current&&r(!1)}},[e]);$e.useEffect(()=>(R(),()=>{m.current++}),[R]);async function T(P){let A=++m.current;r(!0),c(""),M(!1);try{let U=await e.getPromo(P);A===m.current&&y(U)}catch(U){A===m.current&&c(en(U))}finally{A===m.current&&r(!1)}}async function D(){if(l){x(!0),r(!0),c("");try{let P=await e.disablePromo(l.id);if(y(P),!["inactive","expired","exhausted"].includes(P.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");M(!1),await R()}catch(P){c(en(P))}finally{x(!1),r(!1)}}}return N?(0,ie.jsx)(cl,{currency:t?.currency??void 0,replaces:N.replaces,onCancel:()=>S(null),onSave:async P=>{let A=N.replaces?await e.replacePromo(N.replaces.id,P):await e.createPromo(P),U=await e.getPromo(A.id);if(U.status==="pending"||U.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");y(U),S(null),await R()}}):(0,ie.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,ie.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,ie.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,ie.jsx)(_,{disabled:u||!t?.currency,onClick:()=>{c(""),S({})},children:"Create promo code"})]}),(0,ie.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),d===!1&&(0,ie.jsx)("p",{role:"status",className:"af-rounded-md af-border af-p-3 af-text-sm",children:"Checkout code entry is not enabled yet. You can prepare codes, but buyers cannot enter them in our checkout until it is enabled."}),!t?.currency&&(0,ie.jsx)("p",{className:"af-text-sm",children:s?en(s):"Connect Stripe and set the payment currency before creating codes."}),b&&(0,ie.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[b," ",(0,ie.jsx)(_,{variant:"outline",disabled:u,onClick:()=>l?void T(l.id):void R(),children:"Refresh"})]}),l?(0,ie.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,ie.jsx)(_,{variant:"ghost",disabled:v,onClick:()=>{y(null),M(!1),R()},children:"Back to codes"}),(0,ie.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),(0,ie.jsxs)("p",{children:[_i(l)," \xB7 ",l.status]}),(0,ie.jsxs)("p",{className:"af-text-sm",children:[l.times_redeemed==null?"Usage unavailable":`${l.times_redeemed} redemptions`,l.max_redemptions!=null?` / ${l.max_redemptions} maximum`:""]}),(0,ie.jsxs)("p",{className:"af-text-sm",children:[l.minimum_amount!=null&&l.currency?`Minimum order: ${W(l.minimum_amount,l.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,ie.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",l.duration==="repeating"?`${l.duration_in_months} months`:l.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,ie.jsx)("p",{className:"af-text-sm",children:l.expires_at?`Expires ${new Date(l.expires_at).toLocaleString()}`:"No expiry"}),(0,ie.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ie.jsx)(_,{variant:"outline",disabled:u,onClick:()=>void T(l.id),children:"Refresh details"}),(0,ie.jsx)(_,{variant:"outline",disabled:u||l.status==="pending"||l.status==="unavailable"||!t?.currency,onClick:()=>S({replaces:l}),children:"Replace with new code"}),(0,ie.jsx)(_,{variant:"outline",disabled:u||!["active","pending","unavailable"].includes(l.status),onClick:()=>M(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),O&&(0,ie.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,ie.jsxs)("p",{className:"af-text-sm",children:[l.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${l.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,ie.jsx)(_,{disabled:u,onClick:()=>void D(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,ie.jsx)(_,{variant:"ghost",disabled:u,onClick:()=>M(!1),children:"Cancel"})]})]}):(0,ie.jsxs)(ie.Fragment,{children:[a.map(P=>(0,ie.jsxs)("button",{type:"button",disabled:u,onClick:()=>void T(P.id),className:"af-w-full af-rounded-lg af-border af-p-4 af-text-left hover:af-bg-muted focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[(0,ie.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,ie.jsx)("span",{className:"af-font-semibold af-break-all",children:P.code}),(0,ie.jsx)("span",{className:"af-text-sm",children:P.status})]}),(0,ie.jsxs)("div",{className:"af-text-sm",children:[_i(P)," \xB7"," ",P.times_redeemed==null?"Usage unavailable":`${P.times_redeemed} redemptions`]})]},P.id)),!u&&!b&&a.length===0&&(0,ie.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),u&&(0,ie.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),i&&(0,ie.jsx)(_,{variant:"outline",disabled:u,onClick:()=>void R(i),children:"Load more"})]})]})}function cl({currency:e,replaces:t,onCancel:s,onSave:a}){let[n,i]=$e.useState(""),[o,d]=$e.useState(t?.name??""),[f,u]=$e.useState(t?.amount_off!=null?"fixed":"percent"),[r,v]=$e.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(pt(t.amount_off,e)):"")),[x,b]=$e.useState(t?.minimum_amount!=null&&e?String(pt(t.minimum_amount,e)):""),[c,l]=$e.useState(()=>{if(!t?.expires_at)return"";let J=new Date(t.expires_at);return Number.isFinite(J.getTime())?new Date(J.getTime()-J.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[y,N]=$e.useState(t?.max_redemptions?.toString()??""),[S,O]=$e.useState(t?.duration??"once"),[M,m]=$e.useState(t?.duration_in_months?.toString()??"3"),[R,T]=$e.useState(null),[D,P]=$e.useState(!1),[A,U]=$e.useState(""),w=$e.useRef(!1),F=e&&sa(e)?"1":"0.01";async function X(J){if(J.preventDefault(),w.current)return;U("");let ee=R;if(!ee){if(!e){U("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){U("Choose a different code for the replacement.");return}let Z=Mt(r,e),oe=x?Mt(x,e):null;if(f==="fixed"&&(!Z||Z>999999999999)||x&&(!oe||oe>999999999999)){U("Enter a positive amount within the supported range.");return}if(c&&new Date(c).getTime()<=Date.now()){U("Choose a future expiry.");return}ee={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:S,...f==="percent"?{percent_off:Number(r)}:{amount_off:Z,currency:e},...x?{minimum_amount:oe,currency:e}:{},...c?{expires_at:new Date(c).toISOString()}:{},...y?{max_redemptions:Number(y)}:{},...S==="repeating"?{duration_in_months:Number(M)}:{}},T(ee)}w.current=!0,P(!0);try{await a(ee)}catch(Z){U(en(Z)),Z instanceof It&&Z.status>=400&&Z.status<500&&Z.details?.retryable!==!0&&T(null)}finally{w.current=!1,P(!1)}}let q=(J,ee,Z,oe={})=>(0,ie.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[J,(0,ie.jsx)(Ne,{"aria-label":J,value:ee,onChange:Y=>Z(Y.target.value),...oe})]}),fe="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,ie.jsxs)("form",{onSubmit:X,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,ie.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,ie.jsx)("p",{className:"af-text-sm",children:"Use a different code. The old code will be disabled only after the replacement is created. Existing subscription discounts continue."}),(0,ie.jsxs)("fieldset",{disabled:D||!!R,className:"af-grid af-gap-4",children:[q("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),q("Name",o,d,{required:!0,maxLength:40}),(0,ie.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,ie.jsxs)("select",{"aria-label":"Discount type",className:fe,value:f,onChange:J=>u(J.target.value),children:[(0,ie.jsx)("option",{value:"percent",children:"Percentage"}),(0,ie.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),q("Discount",r,v,{type:"number",required:!0,min:f==="percent"?"0.01":F,max:f==="percent"?"100":void 0,step:f==="percent"?"0.01":F}),q("Minimum order amount",x,b,{type:"number",min:F,step:F,placeholder:e?.toUpperCase()}),(0,ie.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),q("Expires at (local time)",c,l,{type:"datetime-local",step:1}),q("Maximum redemptions",y,N,{type:"number",min:1,max:1e6,step:1}),(0,ie.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,ie.jsxs)("select",{"aria-label":"Subscription duration",className:fe,value:S,onChange:J=>O(J.target.value),children:[(0,ie.jsx)("option",{value:"once",children:"First invoice only"}),(0,ie.jsx)("option",{value:"forever",children:"Every invoice"}),(0,ie.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),S==="repeating"&&q("Months",M,m,{type:"number",required:!0,min:1,max:36,step:1})]}),A&&(0,ie.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:A}),R&&!D&&(0,ie.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,ie.jsx)("span",{className:"af-break-all",children:R.request_id})]}),(0,ie.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ie.jsx)(_,{type:"submit",disabled:D,children:D?"Saving\u2026":R?"Retry same request":t?"Create replacement":"Create code"}),(0,ie.jsx)(_,{type:"button",variant:"ghost",disabled:D||!!R,onClick:s,children:"Cancel"})]})]})}var Ls=le(require("react"),1),ha=require("lucide-react");var Ln=le(require("react"),1),Ka=require("lucide-react");var be=require("react/jsx-runtime");function ul(e){if(e.allow_custom_amount){let t=e.min_amount!==null?W(e.min_amount,e.currency):"?",s=e.max_amount!==null?W(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${s})`}return e.unit_amount===null?"Varies by variant":W(e.unit_amount,e.currency)}function dl(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function tn({productsState:e,onSelectProduct:t,onCreateProduct:s,className:a}){let{products:n,isLoading:i,error:o,deleteProduct:d}=e,[f,u]=Ln.useState(null),[r,v]=Ln.useState(!1),[x,b]=Ln.useState(null),c=async()=>{if(f)try{v(!0),b(null),await d(f.id),u(null)}catch(l){b(l instanceof Error?l.message:"Failed to delete product")}finally{v(!1)}};return i?(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,be.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?(0,be.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[(0,be.jsx)(Ka.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,be.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,be.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,be.jsxs)(_,{variant:"outline",onClick:()=>s?.(),children:[(0,be.jsx)(Ka.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,be.jsxs)("div",{className:a,children:[(0,be.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,be.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[(0,be.jsx)(Ka.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,be.jsxs)(Ue,{children:[(0,be.jsx)(Ve,{children:(0,be.jsxs)(xe,{children:[(0,be.jsx)(H,{children:"Name"}),(0,be.jsx)(H,{children:"Price"}),(0,be.jsx)(H,{children:"Fulfillment"}),(0,be.jsx)(H,{children:"Status"}),(0,be.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,be.jsx)(He,{children:n.map(l=>(0,be.jsxs)(xe,{children:[(0,be.jsx)(z,{className:"af-font-medium",children:l.name}),(0,be.jsx)(z,{children:ul(l)}),(0,be.jsx)(z,{className:"af-text-muted-foreground",children:dl(l)}),(0,be.jsx)(z,{children:(0,be.jsx)(ae,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),(0,be.jsx)(z,{className:"af-text-right",children:(0,be.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,be.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>t?.(l),children:[(0,be.jsx)(Ka.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,be.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>{b(null),u(l)},children:[(0,be.jsx)(Ka.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),(0,be.jsx)(La,{open:!!f,onOpenChange:l=>{!l&&!r&&u(null)},children:(0,be.jsxs)(Ra,{children:[(0,be.jsxs)(Pa,{children:[(0,be.jsx)(Ta,{children:"Delete product?"}),(0,be.jsxs)(ka,{children:['"',f?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),x&&(0,be.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:x}),(0,be.jsxs)(Ca,{children:[(0,be.jsx)(_,{variant:"outline",onClick:()=>u(null),disabled:r,children:"Cancel"}),(0,be.jsx)(_,{variant:"destructive",onClick:c,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}var et=le(require("react"),1),na=require("lucide-react");var bt=le(require("react"),1),va=require("lucide-react");var E=require("react/jsx-runtime");function hr(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function an({productId:e,currency:t,className:s}){let{api:a}=ne(),n=sa(t)?"1":"0.01",[i,o]=bt.useState(null),[d,f]=bt.useState(!0),[u,r]=bt.useState(null),[v,x]=bt.useState(null),[b,c]=bt.useState(!1),l=bt.useRef(!0);bt.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let y=bt.useCallback(async()=>{try{let k=await a.getProduct(e);if(!l.current)return;o(k)}catch(k){if(!l.current)return;r(k instanceof Error?k.message:"Failed to load product")}finally{l.current&&f(!1)}},[a,e]);bt.useEffect(()=>{y()},[y]);let N=async k=>{x(null),c(!0);try{await k(),await y()}catch(B){l.current&&x(B instanceof Error?B.message:"Something went wrong")}finally{l.current&&c(!1)}},[S,O]=bt.useState(""),[M,m]=bt.useState(""),[R,T]=bt.useState({}),D=()=>N(async()=>{let k=S.trim(),B=M.split(",").map(L=>L.trim()).filter(Boolean);if(!k)throw new Error("Option name is required");if(B.length===0)throw new Error("Add at least one value");await a.createOption(e,{title:k,values:B}),l.current&&(O(""),m(""))}),P=k=>N(async()=>{let B=(R[k.id]??"").trim();if(!B)throw new Error("Enter a value");await a.updateOption(k.id,{add_values:[B]}),l.current&&T(L=>({...L,[k.id]:""}))}),A=(k,B)=>N(()=>a.updateOption(k.id,{remove_values:[B]})),U=k=>N(()=>a.deleteOption(k.id)),[w,F]=bt.useState(null),[X,q]=bt.useState(null),[fe,J]=bt.useState(!1),[ee,Z]=bt.useState(null),oe=i?.options??[],Y=i?.variants??[],Pe=()=>{q(null),F({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(oe.map(k=>[k.id,k.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Xe=k=>{q(null);let B=k.inventory?.on_hand??0,L=B<0?"":String(B);F({variant:k,title:k.title??"",sku:k.sku??"",unitAmount:k.unit_amount!=null?String(pt(k.unit_amount,t)):"",compareAt:k.compare_at_amount!=null?String(pt(k.compare_at_amount,t)):"",active:k.active,optionValues:{},tracked:k.inventory?.tracked??!1,onHand:L,initialOnHand:L,allowBackorder:k.inventory?.allow_backorder??!1})},lt=async()=>{if(!w)return;q(null);let k=w.variant?.allow_custom_amount??!1,B=null,L=null;if(!k){if(B=Mt(w.unitAmount,t),B===null||B<=0){q("Enter a valid price");return}if(w.compareAt.trim()&&(L=Mt(w.compareAt,t),L===null||L<=B)){q("Compare-at price must be greater than the price");return}}let pe=w.onHand.trim()!==w.initialOnHand.trim(),he=parseInt(w.onHand,10);if(w.tracked&&pe&&(!Number.isFinite(he)||he<0)){q("On-hand quantity must be zero or more");return}try{if(J(!0),w.variant)await a.updateVariant(w.variant.id,{title:w.title.trim()||null,sku:w.sku.trim()||null,...k?{}:{unit_amount:B,compare_at_amount:L},active:w.active}),await a.setVariantInventory(w.variant.id,{tracked:w.tracked,on_hand:w.tracked&&pe?he:void 0,allow_backorder:w.allowBackorder});else{let Ee={};for(let Oe of oe){let st=w.optionValues[Oe.id];if(!st){q(`Choose a ${Oe.title}`),J(!1);return}Ee[Oe.title]=st}await a.createVariant(e,{title:w.title.trim()||null,sku:w.sku.trim()||null,unit_amount:B,compare_at_amount:L,active:w.active,option_values:oe.length>0?Ee:void 0,inventory:w.tracked?{tracked:!0,on_hand:he,allow_backorder:w.allowBackorder}:{tracked:!1,allow_backorder:w.allowBackorder}})}await y(),l.current&&F(null)}catch(Ee){if(l.current&&q(Ee instanceof Error?Ee.message:"Failed to save variant"),w.variant)try{let Oe=await a.getProduct(e);l.current&&o(Oe)}catch{}}finally{l.current&&J(!1)}},Ae=()=>N(async()=>{ee&&(await a.deleteVariant(ee.id),l.current&&Z(null))}),Ge=w?.variant?.allow_custom_amount??!1,at=w?.variant!=null&&w.variant.option_values.length===0&&oe.length>0&&!w.variant.active,Ce=w?.variant?.inventory!=null&&w.variant.inventory.on_hand<0?-w.variant.inventory.on_hand:null;function Et(k){let B=k.inventory;if(!B||!B.tracked)return(0,E.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let L=B.available??B.on_hand;return L<0?(0,E.jsxs)("span",{children:[-L," backordered"]}):(0,E.jsxs)("span",{children:[L," in stock",B.allow_backorder&&(0,E.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return d?(0,E.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:(0,E.jsx)(va.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):u?(0,E.jsx)("div",{className:s,children:(0,E.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})}):(0,E.jsxs)("div",{className:`af-space-y-6 ${s||""}`,children:[(0,E.jsxs)("div",{className:"af-space-y-3",children:[(0,E.jsxs)("div",{children:[(0,E.jsx)(Re,{children:"Options"}),(0,E.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."})]}),oe.length>0&&(0,E.jsx)("div",{className:"af-space-y-3",children:oe.map(k=>(0,E.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,E.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,E.jsx)("span",{className:"af-text-sm af-font-medium",children:k.title}),(0,E.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>U(k),disabled:b,children:(0,E.jsx)(va.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,E.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:k.values.map(B=>(0,E.jsxs)(ae,{variant:"secondary",className:"af-gap-1",children:[B.value,(0,E.jsx)("button",{type:"button",onClick:()=>A(k,B.value),className:"af-ml-1 hover:af-text-destructive",disabled:b,title:"Remove value",children:(0,E.jsx)(va.X,{className:"af-h-3 af-w-3"})})]},B.id))}),(0,E.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,E.jsx)(Ne,{value:R[k.id]??"",onChange:B=>T(L=>({...L,[k.id]:B.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),P(k))},disabled:b}),(0,E.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>P(k),disabled:b||!(R[k.id]??"").trim(),children:(0,E.jsx)(va.Plus,{className:"af-h-4 af-w-4"})})]})]},k.id))}),(0,E.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,E.jsx)(Ne,{id:"new-option-title",value:S,onChange:k=>O(k.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:b})]}),(0,E.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,E.jsx)(Re,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,E.jsx)(Ne,{id:"new-option-values",value:M,onChange:k=>m(k.target.value),placeholder:"S, M, L",disabled:b})]}),(0,E.jsxs)(_,{type:"button",variant:"outline",onClick:D,disabled:b||!S.trim()||!M.trim(),children:[(0,E.jsx)(va.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,E.jsxs)("div",{className:"af-space-y-3",children:[(0,E.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,E.jsx)(Re,{children:"Variants"}),(0,E.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:Pe,disabled:b||oe.length===0,children:[(0,E.jsx)(va.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),oe.length===0&&(0,E.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),Y.length===0?(0,E.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,E.jsxs)(Ue,{children:[(0,E.jsx)(Ve,{children:(0,E.jsxs)(xe,{children:[(0,E.jsx)(H,{children:"Variant"}),(0,E.jsx)(H,{children:"SKU"}),(0,E.jsx)(H,{children:"Price"}),(0,E.jsx)(H,{children:"Stock"}),(0,E.jsx)(H,{children:"Status"}),(0,E.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,E.jsx)(He,{children:Y.map(k=>(0,E.jsxs)(xe,{children:[(0,E.jsx)(z,{className:"af-font-medium",children:hr(k)}),(0,E.jsx)(z,{className:"af-text-muted-foreground",children:k.sku||"-"}),(0,E.jsx)(z,{children:k.unit_amount!=null?(0,E.jsxs)("span",{children:[k.compare_at_amount!=null&&(0,E.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,E.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,E.jsx)(z,{children:Et(k)}),(0,E.jsx)(z,{children:(0,E.jsx)(ae,{variant:k.active?"success":"secondary",children:k.active?"Active":"Inactive"})}),(0,E.jsx)(z,{className:"af-text-right",children:(0,E.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,E.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>Xe(k),disabled:b,children:"Edit"}),(0,E.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>Z(k),disabled:b,title:"Delete variant",children:(0,E.jsx)(va.Trash2,{className:"af-h-4 af-w-4"})})]})})]},k.id))})]})]}),v&&(0,E.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),(0,E.jsx)(La,{open:w!==null,onOpenChange:k=>{!k&&!fe&&F(null)},children:(0,E.jsxs)(Ra,{children:[(0,E.jsxs)(Pa,{children:[(0,E.jsx)(Ta,{children:w?.variant?"Edit variant":"Add variant"}),(0,E.jsx)(ka,{children:"Price, markdown, and stock live on the variant."})]}),w&&(0,E.jsxs)("div",{className:"af-space-y-3",children:[w.variant?w.variant.option_values.length>0&&(0,E.jsxs)("div",{className:"af-text-sm",children:[(0,E.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),hr(w.variant)]}):oe.map(k=>(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:k.title}),(0,E.jsxs)(da,{value:w.optionValues[k.id]??"",onValueChange:B=>F(L=>L&&{...L,optionValues:{...L.optionValues,[k.id]:B}}),children:[(0,E.jsx)(Xt,{children:(0,E.jsx)(fa,{placeholder:`Choose ${k.title}`})}),(0,E.jsx)(ea,{children:k.values.map(B=>(0,E.jsx)(Ye,{value:B.value,children:B.value},B.id))})]})]},k.id)),Ge?(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,E.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,E.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsxs)(Re,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,E.jsx)(Ne,{id:"variant-price",type:"number",min:"0",step:n,value:w.unitAmount,onChange:k=>F(B=>B&&{...B,unitAmount:k.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,E.jsx)(Ne,{id:"variant-compare",type:"number",min:"0",step:n,value:w.compareAt,onChange:k=>F(B=>B&&{...B,compareAt:k.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,E.jsx)(Ne,{id:"variant-sku",value:w.sku,onChange:k=>F(B=>B&&{...B,sku:k.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,E.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,E.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,E.jsx)("input",{type:"checkbox",checked:w.tracked,onChange:k=>F(B=>B&&{...B,tracked:k.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),w.tracked&&(0,E.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,E.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,E.jsx)(Ne,{id:"variant-onhand",type:"number",min:"0",step:"1",value:w.onHand,onChange:k=>F(B=>B&&{...B,onHand:k.target.value}),placeholder:Ce!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,E.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,E.jsx)("input",{type:"checkbox",checked:w.allowBackorder,onChange:k=>F(B=>B&&{...B,allowBackorder:k.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Ce!=null&&(0,E.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Ce," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,E.jsx)("input",{type:"checkbox",checked:w.active,onChange:k=>F(B=>B&&{...B,active:k.target.checked}),className:"af-h-4 af-w-4",disabled:at}),"Active (buyers can purchase this variant)"]}),at&&(0,E.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."})]}),X&&(0,E.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:X})]}),(0,E.jsxs)(Ca,{children:[(0,E.jsx)(_,{variant:"outline",onClick:()=>F(null),disabled:fe,children:"Cancel"}),(0,E.jsxs)(_,{onClick:lt,disabled:fe,children:[fe?(0,E.jsx)(va.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,w?.variant?"Save":"Add variant"]})]})]})}),(0,E.jsx)(La,{open:ee!==null,onOpenChange:k=>{!k&&!b&&Z(null)},children:(0,E.jsxs)(Ra,{children:[(0,E.jsxs)(Pa,{children:[(0,E.jsx)(Ta,{children:"Delete variant?"}),(0,E.jsx)(ka,{children:ee&&`"${hr(ee)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,E.jsxs)(Ca,{children:[(0,E.jsx)(_,{variant:"outline",onClick:()=>Z(null),disabled:b,children:"Cancel"}),(0,E.jsx)(_,{variant:"destructive",onClick:Ae,disabled:b,children:"Delete"})]})]})})]})}var K=require("react/jsx-runtime");function fl(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,a)).toFixed(1))} ${s[a]}`}function sn({productsState:e,product:t,currency:s,onSaved:a,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:d,attachProductFileFromUrl:f}=e,u=!!t,r=t?.currency??s,v=sa(r)?"1":"0.01",x=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[b,c]=et.useState(!1),[l,y]=et.useState(null),N=et.useRef(!0);et.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]);let[S,O]=et.useState(t?.name??""),[M,m]=et.useState(t?.description??""),[R,T]=et.useState(t?.allow_custom_amount?"custom":"fixed"),[D,P]=et.useState(t?.unit_amount!=null?String(pt(t.unit_amount,r)):""),[A,U]=et.useState(t?.min_amount!=null?String(pt(t.min_amount,r)):""),[w,F]=et.useState(t?.max_amount!=null?String(pt(t.max_amount,r)):""),[X,q]=et.useState(String(t?.max_quantity??10)),fe=et.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(pt(t.unit_amount,r)):"",minAmount:t?.min_amount!=null?String(pt(t.min_amount,r)):"",maxAmount:t?.max_amount!=null?String(pt(t.max_amount,r)):"",maxQuantity:String(t?.max_quantity??10)}).current,[J,ee]=et.useState(t?.collect_shipping_address??!1),[Z,oe]=et.useState(t?.active??!0),[Y,Pe]=et.useState(t?.images??[]),[Xe,lt]=et.useState(""),[Ae,Ge]=et.useState(t?.fulfillment??null),[at,Ce]=et.useState(!1),[Et,k]=et.useState(""),[B,L]=et.useState(null),pe=et.useRef(null),he=b||at,Ee=()=>{let ce=Xe.trim();if(ce){if(Y.includes(ce)){y("This image URL is already added");return}Pe(Be=>[...Be,ce]),lt(""),y(null)}},Oe=ce=>{Pe(Be=>Be.filter(ct=>ct!==ce))},st=async()=>{if(y(null),!S.trim()){y("Product name is required");return}let ce=null,Be=null,ct=null,Yt=!u||R!==fe.pricingMode||(R==="fixed"?D!==fe.unitAmount:A!==fe.minAmount||w!==fe.maxAmount),wt=!u||X!==fe.maxQuantity,At=x||R==="fixed";if(!(x||!Yt))if(R==="fixed"){if(ce=Mt(D,r),ce===null||ce<=0){y("Enter a valid price");return}}else{if(Be=Mt(A,r),ct=Mt(w,r),Be===null||ct===null){y("Enter valid minimum and maximum amounts");return}if(ct<Be){y("Maximum amount must be at least the minimum amount");return}}let Ht=parseInt(X,10);if(At&&wt&&(!Number.isFinite(Ht)||Ht<1)){y("Max quantity must be at least 1");return}try{c(!0);let qe;if(u&&t){let nt={name:S.trim(),description:M.trim()||null,images:Y,collect_shipping_address:J,active:Z};!x&&Yt&&(nt.allow_custom_amount=R==="custom",R==="fixed"?nt.unit_amount=ce:(nt.min_amount=Be,nt.max_amount=ct)),At&&wt&&(nt.max_quantity=Ht),qe=await o(t.id,nt),fe.pricingMode=qe.allow_custom_amount?"custom":"fixed",fe.unitAmount=qe.unit_amount!=null?String(pt(qe.unit_amount,r)):"",fe.minAmount=qe.min_amount!=null?String(pt(qe.min_amount,r)):"",fe.maxAmount=qe.max_amount!=null?String(pt(qe.max_amount,r)):"",fe.maxQuantity=String(qe.max_quantity)}else{let nt={name:S.trim(),allow_custom_amount:R==="custom",collect_shipping_address:J,active:Z};M.trim()&&(nt.description=M.trim()),Y.length>0&&(nt.images=Y),R==="fixed"?(nt.unit_amount=ce,nt.max_quantity=Ht):(nt.min_amount=Be,nt.max_amount=ct),qe=await i(nt)}if(!N.current)return;Ge(qe.fulfillment),a?.(qe)}catch(qe){if(!N.current)return;y(qe instanceof Error?qe.message:"Failed to save product")}finally{N.current&&c(!1)}},ze=async ce=>{let Be=ce.target.files?.[0];if(!(!Be||!t))try{Ce(!0),L(null);let ct=await d(t.id,Be);if(!N.current)return;Ge(ct.fulfillment),a?.(ct)}catch(ct){if(!N.current)return;L(ct instanceof Error?ct.message:"Failed to upload file")}finally{N.current&&(Ce(!1),pe.current&&(pe.current.value=""))}},Ke=async()=>{let ce=Et.trim();if(!(!ce||!t))try{Ce(!0),L(null);let Be=await f(t.id,ce);if(!N.current)return;Ge(Be.fulfillment),k(""),a?.(Be)}catch(Be){if(!N.current)return;L(Be instanceof Error?Be.message:"Failed to fetch file")}finally{N.current&&Ce(!1)}};return(0,K.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{htmlFor:"product-name",children:"Name"}),(0,K.jsx)(Ne,{id:"product-name",value:S,onChange:ce=>O(ce.target.value),placeholder:"My product"})]}),(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{htmlFor:"product-description",children:"Description"}),(0,K.jsx)("textarea",{id:"product-description",value:M,onChange:ce=>m(ce.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,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{children:"Pricing"}),x?(0,K.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,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(da,{value:R,onValueChange:ce=>T(ce),children:[(0,K.jsx)(Xt,{className:"af-w-[260px]",children:(0,K.jsx)(fa,{})}),(0,K.jsxs)(ea,{children:[(0,K.jsx)(Ye,{value:"fixed",children:"Fixed price"}),(0,K.jsx)(Ye,{value:"custom",children:"Buyer chooses the amount"})]})]}),R==="fixed"?(0,K.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,K.jsxs)("div",{className:"af-space-y-1",children:[(0,K.jsxs)(Re,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),(0,K.jsx)(Ne,{id:"product-price",type:"number",min:"0",step:v,value:D,onChange:ce=>P(ce.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,K.jsxs)("div",{className:"af-space-y-1",children:[(0,K.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,K.jsxs)("div",{className:"af-space-y-1",children:[(0,K.jsxs)(Re,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),(0,K.jsx)(Ne,{id:"product-min-amount",type:"number",min:"0",step:v,value:A,onChange:ce=>U(ce.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,K.jsxs)("div",{className:"af-space-y-1",children:[(0,K.jsxs)(Re,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),(0,K.jsx)(Ne,{id:"product-max-amount",type:"number",min:"0",step:v,value:w,onChange:ce=>F(ce.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,K.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,K.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."]})]}),(x||R==="fixed")&&(0,K.jsxs)("div",{className:"af-space-y-1",children:[(0,K.jsx)(Re,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,K.jsx)(Ne,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:X,onChange:ce=>q(ce.target.value),className:"af-w-[140px]"})]})]}),(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{children:"Images"}),(0,K.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,K.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[Y.map(ce=>(0,K.jsxs)(ae,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,K.jsx)("span",{className:"af-truncate",children:ce}),(0,K.jsx)("button",{type:"button",onClick:()=>Oe(ce),className:"af-ml-1 hover:af-text-destructive",disabled:b,children:(0,K.jsx)(na.X,{className:"af-h-3 af-w-3"})})]},ce)),Y.length===0&&(0,K.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,K.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,K.jsx)(Ne,{type:"url",value:Xe,onChange:ce=>lt(ce.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:ce=>{ce.key==="Enter"&&(ce.preventDefault(),Ee())},disabled:b}),(0,K.jsx)(_,{type:"button",variant:"outline",onClick:Ee,disabled:!Xe.trim()||b,children:(0,K.jsx)(na.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{children:"Digital File"}),(0,K.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."}),u?(0,K.jsxs)("div",{className:"af-space-y-3",children:[Ae?.type==="download"&&(0,K.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,K.jsx)(na.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,K.jsx)("span",{className:"af-text-sm",children:Ae.filename}),Ae.size!=null&&(0,K.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",fl(Ae.size),")"]})]}),Ae?.type==="redirect"&&Ae.url&&(0,K.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,K.jsx)(na.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,K.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Ae.url]})]}),(0,K.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,K.jsx)("input",{ref:pe,type:"file",onChange:ze,className:"af-hidden",disabled:he}),(0,K.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>pe.current?.click(),disabled:he,children:[at?(0,K.jsx)(na.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,K.jsx)(na.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Ae?.type==="download"?"Replace file":"Upload file"]}),(0,K.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,K.jsx)(Ne,{type:"url",value:Et,onChange:ce=>k(ce.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:at}),(0,K.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:Ke,disabled:!Et.trim()||he,children:"Fetch from URL"})]}),B&&(0,K.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:B})]}):(0,K.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{children:"Settings"}),(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,K.jsx)("input",{type:"checkbox",checked:J,onChange:ce=>ee(ce.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,K.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,K.jsx)("input",{type:"checkbox",checked:Z,onChange:ce=>oe(ce.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),u&&t&&(0,K.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,K.jsx)(Re,{children:"Options & Variants"}),(0,K.jsx)(an,{productId:t.id,currency:r})]}),l&&(0,K.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),(0,K.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,K.jsxs)(_,{type:"button",onClick:st,disabled:he,children:[b?(0,K.jsx)(na.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,u?"Save changes":"Create product"]})})]})}var Pt=le(require("react"),1),ia=require("lucide-react");var ut=le(require("react"),1);var ml=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function nn({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=ne(),[a,n]=ut.useState([]),[i,o]=ut.useState(0),[d,f]=ut.useState(!0),[u,r]=ut.useState(null),[v,x]=ut.useState(0),[b,c]=ut.useState(e),[l,y]=ut.useState(void 0),[N,S]=ut.useState(""),[O,M]=ut.useState(""),[m,R]=ut.useState(""),[T,D]=ut.useState(!1),[P,A]=ut.useState(!1),[U,w]=ut.useState(void 0),F=U?U.join(","):"",X=ut.useMemo(()=>{if(!F)return;let ee=new Set(F.split(","));return ml.filter(Z=>!ee.has(Z))},[F]),q=ut.useRef(0),fe=ut.useCallback(async()=>{let ee=++q.current;try{f(!0),r(null);let Z={limit:b,offset:v*b};l?Z.status=l:X?Z.excludeStatus=X:T||(Z.excludeStatus=["pending","expired"]),N.trim()&&(Z.customerEmail=N.trim()),O.trim()&&(Z.from=O.trim()),m.trim()&&(Z.to=m.trim()),P&&(Z.unfulfilledOnly=!0);let oe=await s.getOrders(Z);if(ee!==q.current)return;n(oe.orders),o(oe.total)}catch(Z){if(ee!==q.current)return;r(Z instanceof Error?Z:new Error("Failed to fetch orders"))}finally{ee===q.current&&f(!1)}},[s,v,b,l,X,T,P,N,O,m,t]);ut.useEffect(()=>{fe()},[fe]);let J=Math.ceil(i/b);return{orders:a,total:i,isLoading:d,error:u,page:v,pageSize:b,hasNextPage:v<J-1,hasPreviousPage:v>0,setPage:x,setPageSize:ee=>{c(ee),x(0)},status:l,setStatus:ee=>{y(ee),x(0)},statusIn:U,setStatusIn:ee=>{w(ee&&ee.length>0?ee:void 0),x(0)},customerEmail:N,setCustomerEmail:ee=>{S(ee),x(0)},from:O,setFrom:ee=>{M(ee),x(0)},to:m,setTo:ee=>{R(ee),x(0)},showAbandoned:T,setShowAbandoned:ee=>{D(ee),x(0)},unfulfilledOnly:P,setUnfulfilledOnly:ee=>{A(ee),x(0)},clearFilters:()=>{y(void 0),w(void 0),D(!1),A(!1),S(""),M(""),R(""),x(0)},refetch:fe}}var gt=le(require("react"),1),Ie=require("lucide-react");var Ri=le(require("react"),1),Fa=le(require("@radix-ui/react-popover"),1);var On=require("react/jsx-runtime"),Bn=Fa.Root,Fn=Fa.Trigger;var rn=Ri.forwardRef(({className:e,align:t="end",sideOffset:s=4,...a},n)=>(0,On.jsx)(Fa.Portal,{children:(0,On.jsx)("div",{className:"aifeatures-admin",children:(0,On.jsx)(Fa.Content,{ref:n,align:t,sideOffset:s,className:te("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...a})})}));rn.displayName=Fa.Content.displayName;var on=require("react/jsx-runtime"),pl={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function gl(e){return pl[e]??e}function Pi(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 ps({status:e,className:t}){return(0,on.jsx)(ae,{variant:Pi(e),className:t,children:gl(e)})}function os({status:e}){return(0,on.jsx)(ps,{status:e})}function Es({order:e,className:t}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,on.jsx)(ae,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,on.jsx)(ae,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Za(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var p=require("react/jsx-runtime"),Ei="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",gs="af-text-xs af-text-muted-foreground";function xr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function vl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ai(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 Mn=24,bl=["paid","partially_refunded"],yl=["paid","partially_refunded","disputed"],hl=/^[A-Za-z0-9 _-]*$/,Ci=100;function Sr(e,t,s,a,n){let i=bl.includes(a);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${Mn} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${Mn} tries used). Nothing is being retried while the order is ${a.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?s<Mn&&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<Mn&&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.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${a==="refunded"?"because the order was refunded":a==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function Ti({title:e,recipient:t,status:s,attempts:a,side:n,orderStatus:i,action:o,delivery:d}){if(d)return(0,p.jsxs)("div",{children:[(0,p.jsx)(Da,{deliveries:[d]}),o&&(0,p.jsx)("div",{className:"af-mt-2",children:o})]});let f=Sr(n,s,a,i,t);return(0,p.jsxs)("div",{children:[(0,p.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,p.jsxs)("div",{className:"af-min-w-0",children:[(0,p.jsx)("div",{className:"af-text-sm",children:e}),t&&(0,p.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,p.jsx)(ae,{variant:f.variant,className:"af-shrink-0",children:f.label})]}),f.detail&&(0,p.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:f.detail}),o&&(0,p.jsx)("div",{className:"af-mt-2",children:o})]})}function ki(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let s=vl(e.address)?e.address:null;if(s){for(let n of["line1","line2"]){let i=s[n];typeof i=="string"&&i&&t.push(i)}let a=["city","state","postal_code"].map(n=>s[n]).filter(n=>typeof n=="string"&&!!n).join(", ");a&&t.push(a),typeof s.country=="string"&&s.country&&t.push(s.country)}return t.length>0?t:Object.entries(e).map(([a,n])=>`${a}: ${Ai(n)}`)}function xl(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function _r({value:e,label:t,children:s,className:a,size:n="icon"}){let[i,o]=gt.useState(!1);if(!xl())return null;let d=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},f=i?(0,p.jsx)(Ie.Check,{className:"af-h-3 af-w-3"}):(0,p.jsx)(Ie.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,p.jsx)(_,{variant:"ghost",size:"icon",className:te("af-h-6 af-w-6 af-shrink-0",a),onClick:d,title:t,"aria-label":t,children:f}):(0,p.jsxs)(_,{variant:"outline",size:"sm",className:a,onClick:d,"aria-label":t,children:[i?(0,p.jsx)(Ie.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,p.jsx)(Ie.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function wr({label:e,value:t}){return(0,p.jsxs)("div",{children:[(0,p.jsx)("div",{className:gs,children:e}),(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,p.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,p.jsx)(_r,{value:t,label:`Copy ${e}`})]})]})}function wl({src:e}){let[t,s]=gt.useState(!1);return!e||t?(0,p.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,p.jsx)(Ie.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,p.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 Ma({title:e,action:t,children:s,className:a}){return(0,p.jsxs)("section",{className:te("af-rounded-lg af-border af-p-4",a),children:[(0,p.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,p.jsx)("h4",{className:Ei,children:e}),t]}),(0,p.jsx)("div",{className:"af-mt-3",children:s})]})}function Gt({label:e,emphasis:t,divider:s,children:a}){return(0,p.jsxs)("div",{className:te("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[(0,p.jsx)("span",{className:t?"af-text-base af-font-semibold":gs,children:e}),(0,p.jsx)("span",{className:te("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:a})]})}function Nr({onSelect:e,disabled:t,icon:s,children:a}){return(0,p.jsxs)(_,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,p.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),a]})}function Nl(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?t.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${W(Dn(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),a=s?In(s):Sr("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${a.label.toLowerCase()}`,at:null,tone:a.variant==="destructive"?"destructive":a.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),a=s?In(s):Sr("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.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 ${a.label.toLowerCase()}`,at:null,tone:a.variant==="destructive"?"destructive":a.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${W(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function ln({order:e,onBack:t,onRefund:s,onOrderUpdated:a,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:d=!1,hasNextOrder:f=!1}){let{api:u}=ne(),[r,v]=gt.useState(e),[x,b]=gt.useState(null),[c,l]=gt.useState(null),[y,N]=gt.useState(!1),[S,O]=gt.useState(!1),[M,m]=gt.useState(!1),[R,T]=gt.useState(!1),[D,P]=gt.useState(""),[A,U]=gt.useState(!1),[w,F]=gt.useState(null),[X,q]=gt.useState(!1),[fe,J]=gt.useState(""),[ee,Z]=gt.useState([]),[oe,Y]=gt.useState(!1),[Pe,Xe]=gt.useState(!1),[lt,Ae]=gt.useState(null);gt.useEffect(()=>{v(e)},[e]);let Ge=I=>{let Fe=I.id===r.id&&I.email_deliveries===void 0?{...I,email_deliveries:r.email_deliveries}:I;v(Fe),a?.(Fe)},at=Object.entries(r.metadata??{}),Ce=Math.max(0,Dn(r)-r.amount_refunded),Et=(r.status==="paid"||r.status==="partially_refunded")&&Ce>0,k=r.exclusive_tax_total!=null,B=I=>typeof I.amountNet=="number"?I.amountNet+(I.exclusiveTax??0):(typeof I.unitAmount=="number"?I.unitAmount:0)*(typeof I.quantity=="number"&&I.quantity>0?I.quantity:1),L=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),pe=ee.reduce((I,Fe)=>I+B(r.line_items[Fe]??{}),0)+(oe?L:0),he=r.tax_total??0,Ee=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((I,Fe)=>I+(Fe.exclusiveTax??0),0)),Oe=k?oe&&L>0?Ee:0:r.automatic_tax&&r.tax_behavior==="exclusive"&&he>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,he-(r.tax_refunded??0)),Math.round(he*pe/(r.amount_total+(r.shipping_total??0)))):0,st=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(pe+Oe,Ce):pe+Oe,ze=ee.length>0||oe,Ke=ze?st:Mt(fe,r.currency),ce=sa(r.currency)?"1":"0.01",Be=async()=>{try{N(!0),b(null),l(null),await u.resendOrderReceipt(r.id);let I=await u.getOrder(r.id);Ge(I),l("Receipt email queued.")}catch(I){b(I instanceof Error?I.message:"Failed to resend receipt")}finally{N(!1)}},ct=async()=>{try{O(!0),b(null),l(null);let I=await u.resetOrderDownloads(r.id);Ge(I),m(!1),l("Download count reset.")}catch(I){b(I instanceof Error?I.message:"Failed to reset downloads")}finally{O(!1)}},Yt=r.line_items.some(I=>I.collectShippingAddress===!0&&!I.refunded&&!I.unavailableReason),wt=typeof r.merchant_fulfilled_at=="string",At=yl.includes(r.status)||r.status==="refunded"&&r.line_items.some(I=>I.collectShippingAddress===!0&&I.amountNet===0&&!I.refunded&&!I.unavailableReason),Ht=D.trim(),qe=hl.test(Ht)&&Ht.length<=Ci,nt=async I=>{try{U(!0),F(null),l(null);let Fe=await u.setOrderFulfillment(r.id,{fulfilled:I,...I&&Ht?{trackingNumber:Ht}:{}});Ge(Fe),P(""),l(I?"Marked as shipped.":"Marked as not shipped.")}catch(Fe){Fe instanceof It&&Fe.status===409?F(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):F(Fe instanceof Error?Fe.message:"Failed to update the order")}finally{U(!1)}},ts=()=>{Ae(null),J(String(pt(Ce,r.currency))),Z([]),Y(!1),q(!0)},Ms=I=>Z(Fe=>Fe.includes(I)?Fe.filter(qt=>qt!==I):[...Fe,I]),Lt=async(I,Fe)=>{if(s)try{Xe(!0),Ae(null),await s(r,I,Fe);let qt=await u.getOrder(r.id);Ge(qt),q(!1),l("Refund issued.")}catch(qt){Ae(qt instanceof Error?qt.message:"Refund failed")}finally{Xe(!1)}},Rn=async()=>{if(ze){if(st<=0){Ae("The lines you picked were charged nothing");return}if(st>Ce){Ae(`That selection exceeds the refundable remainder (${W(Ce,r.currency)})`);return}await Lt(st,{...ee.length>0?{line_items:[...ee].sort((Fe,qt)=>Fe-qt)}:{},...oe?{shipping:!0}:{}});return}let I=Mt(fe,r.currency);if(I===null||I<=0){Ae("Enter a valid refund amount");return}if(I>Ce){Ae(`Amount exceeds the refundable remainder (${W(Ce,r.currency)})`);return}await Lt(I,{amount:I})},j=()=>Lt(Ce,{full:!0}),Ze=!r.subscription_history_only&&r.fulfillment_type==="download",G=!r.subscription_history_only&&n&&Yt,zt=Nl(r),Oo=r.shipping_address?ki(r.shipping_address).join(`
4
+ `):"",Kr=r.shipping_total!=null,dr=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),Zr=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-dr):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,Jr=dr>0,Bo=Zr>0,Yr=r.amount_subtotal!=null||Kr||Jr||(r.discount_total??0)>0,$s=[];return r.subscription_history_only||$s.push((0,p.jsx)(Nr,{icon:y?(0,p.jsx)(Ie.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,p.jsx)(Ie.Mail,{className:"af-h-4 af-w-4"}),disabled:y||r.fulfillment_status!=="fulfilled",onSelect:()=>{T(!1),Be()},children:"Resend receipt"},"resend")),Ze&&$s.push((0,p.jsx)(Nr,{icon:(0,p.jsx)(Ie.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:S,onSelect:()=>{T(!1),m(!0)},children:"Reset download count"},"reset")),Et&&$s.push((0,p.jsxs)("div",{children:[(0,p.jsx)(Nr,{icon:(0,p.jsx)(Ie.Undo2,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{T(!1),ts()},children:"Refund\u2026"}),!s&&(0,p.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,p.jsxs)("div",{children:[(0,p.jsxs)("div",{className:"af-mb-6",children:[(0,p.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,p.jsx)(Ie.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,p.jsxs)("div",{className:"af-min-w-0",children:[(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)("h3",{className:"af-text-xl af-font-semibold",children:Za(r)}),(0,p.jsx)(ps,{status:r.status}),n&&!r.subscription_history_only&&(0,p.jsx)(Es,{order:r}),r.is_test&&(0,p.jsx)(ae,{variant:"outline",children:"Test"})]}),(0,p.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",xr(r.created_at)]}),r.is_test&&(0,p.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,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&(0,p.jsxs)("div",{className:"af-flex af-items-center",children:[(0,p.jsx)(_,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!d,"aria-label":"Previous order",children:(0,p.jsx)(Ie.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,p.jsx)(_,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!f,"aria-label":"Next order",children:(0,p.jsx)(Ie.ChevronRight,{className:"af-h-4 af-w-4"})})]}),G&&(wt?(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,p.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${xr(r.merchant_fulfilled_at)}`:""]}),At&&(0,p.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>nt(!1),disabled:A,children:[A?(0,p.jsx)(Ie.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,p.jsx)(Ie.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):At?(0,p.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,p.jsx)(Ne,{value:D,onChange:I=>P(I.target.value),placeholder:"Tracking number (optional)",maxLength:Ci,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:A}),(0,p.jsxs)(_,{variant:"default",className:"af-shrink-0",onClick:()=>nt(!0),disabled:A||!qe,children:[A?(0,p.jsx)(Ie.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,p.jsx)(Ie.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),$s.length>0&&(0,p.jsxs)(Bn,{open:R,onOpenChange:T,children:[(0,p.jsx)(Fn,{asChild:!0,children:(0,p.jsx)(_,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,p.jsx)(Ie.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,p.jsx)(rn,{children:(0,p.jsx)("div",{className:"af-space-y-0.5",children:$s})})]})]})]}),G&&!wt&&!qe&&(0,p.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."}),w&&(0,p.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}),c&&(0,p.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:c}),x&&(0,p.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:x})]}),(0,p.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,p.jsxs)("div",{className:"af-space-y-6",children:[r.line_items.length>0&&(0,p.jsx)(Ma,{title:"Items",children:(0,p.jsx)("ul",{className:"af-space-y-3",children:r.line_items.map((I,Fe)=>{let qt=typeof I.name=="string"&&I.name?I.name:"Item",Qr=typeof I.quantity=="number"&&I.quantity>0?I.quantity:1,Xr=typeof I.unitAmount=="number";return(0,p.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,p.jsx)(wl,{src:typeof I.imageUrl=="string"&&I.imageUrl?I.imageUrl:void 0}),(0,p.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,p.jsxs)("div",{className:"af-text-sm af-font-medium",children:[qt,typeof I.variantTitle=="string"&&I.variantTitle&&(0,p.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",I.variantTitle]})]}),(0,p.jsxs)("div",{className:gs,children:[Qr," \xD7"," ",Xr?W(I.unitAmount,r.currency):"\u2014"]}),I.unavailableReason==="oversold"&&!I.refunded&&(0,p.jsx)(ae,{variant:"secondary",className:"af-mt-1",children:I.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),I.refunded===!0&&(0,p.jsx)(ae,{variant:"secondary",className:"af-mt-1",children:I.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,p.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof I.amountNet=="number"||Xr?W(I.amountNet??I.unitAmount*Qr,r.currency):"\u2014"})]},Fe)})})}),at.length>0&&(0,p.jsx)(Ma,{title:"Order details",children:(0,p.jsx)("dl",{className:"af-space-y-2",children:at.map(([I,Fe])=>(0,p.jsxs)("div",{children:[(0,p.jsx)("dt",{className:te(gs,"af-capitalize"),children:I.replace(/_/g," ")}),(0,p.jsx)("dd",{className:"af-text-sm af-break-words",children:Ai(Fe)})]},I))})}),(0,p.jsx)(Ma,{title:"Totals",children:(0,p.jsxs)("div",{className:"af-w-full",children:[Yr&&(0,p.jsx)(Gt,{label:"Subtotal",children:W(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&(0,p.jsxs)(Gt,{label:"Discount",children:["\u2212",W(r.discount_total,r.currency)]}),Kr&&(0,p.jsx)(Gt,{label:"Shipping",children:r.shipping_total===0?"Free":W(r.shipping_total??0,r.currency)}),Jr&&(0,p.jsx)(Gt,{label:"Tax",children:W(dr,r.currency)}),(0,p.jsx)(Gt,{label:"Total",emphasis:!0,divider:Yr,children:W(Ba(r),r.currency)}),(r.credit_applied??0)>0&&(0,p.jsxs)(Gt,{label:"Credit applied",children:["\u2212",W(r.credit_applied,r.currency)]}),r.amount_paid!=null&&(0,p.jsx)(Gt,{label:"Amount paid",children:W(r.amount_paid,r.currency)}),Bo&&(0,p.jsx)(Gt,{label:"incl. tax",children:W(Zr,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&(0,p.jsxs)(Gt,{label:"Your price",children:[W(r.base_amount_total,r.base_currency),(0,p.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(Gt,{label:"Refunded",children:["\u2212",W(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&(0,p.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",W(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),(0,p.jsx)(Gt,{label:"Net",children:(0,p.jsx)("span",{className:"af-font-medium",children:W(Math.max(0,Dn(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&(0,p.jsxs)(Ma,{title:"Platform fee",children:[r.application_fee_original!=null&&(0,p.jsx)(Gt,{label:"Collected",children:W(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&(0,p.jsx)(Gt,{label:"Returned",children:W(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&(0,p.jsx)(Gt,{label:"Retained",children:W(r.application_fee_retained,r.application_fee_currency??r.currency)}),r.application_fee_state!=="complete"&&(0,p.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:r.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,p.jsx)(Ma,{title:"Timeline",children:(0,p.jsx)("ol",{className:"af-space-y-3",children:zt.map(I=>(0,p.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,p.jsx)("span",{"aria-hidden":"true",className:te("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",I.tone==="destructive"?"af-bg-destructive":I.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,p.jsxs)("div",{className:"af-min-w-0",children:[(0,p.jsx)("div",{className:"af-text-sm af-break-words",children:I.text}),I.at&&(0,p.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:xr(I.at)})]})]},I.key))})})]}),(0,p.jsxs)("div",{className:"af-space-y-6",children:[(0,p.jsx)(Ma,{title:"Customer",children:(0,p.jsxs)("div",{className:"af-space-y-2",children:[(0,p.jsxs)("div",{children:[(0,p.jsx)("div",{className:gs,children:"Email"}),(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,p.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||(0,p.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&(0,p.jsx)(_r,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&(0,p.jsxs)("div",{children:[(0,p.jsx)("div",{className:gs,children:"Name"}),(0,p.jsx)("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&(0,p.jsxs)("div",{children:[(0,p.jsx)("div",{className:gs,children:"Customer record"}),(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),(0,p.jsx)(ae,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&(0,p.jsx)(Ma,{title:"Ship to",action:(0,p.jsx)(_r,{value:Oo,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,p.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:ki(r.shipping_address).map((I,Fe)=>(0,p.jsx)("div",{children:I},Fe))})}),r.subscription_history_only?(0,p.jsx)(Ma,{title:"Subscription history",children:(0,p.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This renewal had no payment due. No items were fulfilled and no purchase receipt was sent."})}):(0,p.jsxs)(Ma,{title:"Emails",children:[(0,p.jsx)(Da,{deliveries:r.email_deliveries?.filter(I=>!["purchase_receipt","merchant_sale"].includes(I.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,p.jsxs)("div",{className:"af-space-y-4",children:[(0,p.jsx)(Ti,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(I=>I.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:(0,p.jsxs)(_,{variant:"outline",size:"sm",onClick:Be,disabled:y||r.fulfillment_status!=="fulfilled",children:[y?(0,p.jsx)(Ie.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,p.jsx)(Ie.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,p.jsx)(Ti,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(I=>I.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),Ze&&(0,p.jsx)(Ma,{title:"Download",children:(0,p.jsxs)("div",{className:"af-space-y-2",children:[(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,p.jsx)(Ie.Download,{className:"af-h-4 af-w-4"}),(0,p.jsxs)("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&(0,p.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,p.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,p.jsx)("summary",{className:te(Ei,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,p.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,p.jsx)(wr,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&(0,p.jsx)(wr,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&(0,p.jsx)(wr,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),(0,p.jsx)(La,{open:M,onOpenChange:I=>{!I&&!S&&m(!1)},children:(0,p.jsxs)(Ra,{children:[(0,p.jsxs)(Pa,{children:[(0,p.jsx)(Ta,{children:"Reset download count?"}),(0,p.jsx)(ka,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,p.jsxs)(Ca,{children:[(0,p.jsx)(_,{variant:"outline",onClick:()=>m(!1),disabled:S,children:"Cancel"}),(0,p.jsx)(_,{onClick:ct,disabled:S,children:S?"Resetting...":"Reset"})]})]})}),(0,p.jsx)(La,{open:X,onOpenChange:I=>{!I&&!Pe&&q(!1)},children:(0,p.jsxs)(Ra,{children:[(0,p.jsxs)(Pa,{children:[(0,p.jsx)(Ta,{children:"Refund order"}),(0,p.jsxs)(ka,{children:["Refund up to ",W(Ce,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,p.jsxs)("div",{className:"af-space-y-4",children:[(r.line_items.length>0||L>0)&&(0,p.jsxs)("div",{className:"af-space-y-2",children:[(0,p.jsx)(Re,{children:"Items"}),(0,p.jsxs)("div",{className:"af-space-y-2",children:[r.line_items.map((I,Fe)=>{let qt=I.refunded===!0;return(0,p.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,p.jsx)("input",{type:"checkbox",checked:ee.includes(Fe),onChange:()=>Ms(Fe),disabled:Pe||qt||!!I.unavailableReason||B(I)<=0,className:"af-h-4 af-w-4"}),(0,p.jsxs)("span",{className:qt?"af-text-muted-foreground af-line-through":void 0,children:[typeof I.name=="string"&&I.name?I.name:"Item",typeof I.variantTitle=="string"&&I.variantTitle?` \u2014 ${I.variantTitle}`:"",typeof I.quantity=="number"&&I.quantity>1?` \xD7 ${I.quantity}`:""]}),(0,p.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:qt?"Refunded":W(B(I),r.currency)})]},Fe)}),L>0&&(0,p.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,p.jsx)("input",{type:"checkbox",checked:oe,onChange:I=>Y(I.target.checked),disabled:Pe,className:"af-h-4 af-w-4"}),(0,p.jsx)("span",{children:"Shipping"}),(0,p.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:W(L,r.currency)})]})]})]}),(0,p.jsxs)("div",{className:"af-space-y-2",children:[(0,p.jsxs)(Re,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),(0,p.jsx)(Ne,{id:"refund-amount",type:"number",min:"0",step:ce,value:ze?String(pt(st,r.currency)):fe,onChange:I=>J(I.target.value),disabled:Pe||ze}),ze&&(0,p.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),lt&&(0,p.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:lt}),(0,p.jsxs)(Ca,{children:[(0,p.jsx)(_,{variant:"outline",onClick:()=>q(!1),disabled:Pe,children:"Cancel"}),(0,p.jsx)(_,{variant:"outline",onClick:j,disabled:Pe,children:"Refund everything"}),(0,p.jsx)(_,{variant:"destructive",onClick:Rn,disabled:Pe,children:Pe?"Refunding...":Ke!==null&&Ke>0?`Refund ${W(Ke,r.currency)}`:"Refund"})]})]})})]})}var $n=le(require("react"),1),Un=require("lucide-react");var tt=require("react/jsx-runtime");function yt({title:e,onBackToWebsite:t,hideBackButton:s=!1,children:a,className:n}){let i=$n.useRef(null);return $n.useEffect(()=>{i.current?.focus()},[]),(0,tt.jsxs)("div",{className:te("af-bg-background",n),children:[(0,tt.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,tt.jsx)("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!s&&(0,tt.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,tt.jsx)(Un.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,tt.jsx)("div",{className:"af-p-4",children:a})]})}function se({className:e}){return(0,tt.jsx)("div",{"aria-hidden":"true",className:te("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function rt({label:e,children:t,detail:s,valueClassName:a}){return(0,tt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,tt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,tt.jsx)("div",{className:te("af-mt-1 af-text-lg af-font-semibold",a),children:t}),s&&(0,tt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function ra({message:e,onRetry:t}){return(0,tt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,tt.jsx)("span",{children:e}),(0,tt.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,tt.jsx)(Un.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Ea({icon:e,children:t}){return(0,tt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,tt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function As({icon:e,heading:t,body:s,action:a,className:n,children:i}){return(0,tt.jsxs)("div",{className:te("af-px-6 af-py-10 af-text-center",n),children:[(0,tt.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,tt.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,tt.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:s}),a&&(0,tt.jsx)(_,{type:"button",className:"af-mt-4",onClick:a.onClick,children:a.label}),i]})}var C=require("react/jsx-runtime"),Sl={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Ii={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Di(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Li(e){let t=Array.isArray(e.line_items)?e.line_items:[],s=t[0];if(!s)return"\u2014";let a=typeof s.name=="string"&&s.name?s.name:"Item",n=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,i=n>1?`${a} \xD7${n}`:a;return t.length>1?`${i} +${t.length-1} more`:i}function Vn(e){return e.customer?.name||e.customer_name||null}function _l({onRefund:e,className:t,refreshKey:s,initialOrderId:a,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o,maxRows:d,onViewAll:f}){let u=typeof d=="number",{api:r}=ne(),v=nn({refreshKey:s}),{orders:x,total:b,isLoading:c,error:l,page:y,pageSize:N,hasNextPage:S,hasPreviousPage:O,setPage:M,setPageSize:m,customerEmail:R,setCustomerEmail:T,setStatusIn:D,from:P,setFrom:A,to:U,setTo:w,showAbandoned:F,setShowAbandoned:X,setUnfulfilledOnly:q,refetch:fe}=v,[J,ee]=Pt.useState("list"),[Z,oe]=Pt.useState(null),[Y,Pe]=Pt.useState(""),[Xe,lt]=Pt.useState(""),[Ae,Ge]=Pt.useState(!u&&n?"needs_shipping":"all"),[at,Ce]=Pt.useState(!1),[Et,k]=Pt.useState(!!a&&!u),[B,L]=Pt.useState(null);Pt.useEffect(()=>{if(!a||u)return;let G=!1;return k(!0),L(null),r.getOrder(a).then(zt=>{G||(oe(zt),ee("detail"))}).catch(()=>{G||L("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{G||k(!1)}),()=>{G=!0}},[r,a,u]);let pe=Pt.useCallback(G=>{Ge(G);let zt=Ii[G];D(zt.statusIn),q(zt.unfulfilledOnly)},[D,q]);Pt.useEffect(()=>{n&&!u&&q(!0)},[]);let he=Pt.useRef(!n);Pt.useEffect(()=>{he.current||c||(he.current=!0,x.length===0&&pe("all"))},[c,x.length,pe]);let Ee=J==="detail"&&!!Z;Pt.useEffect(()=>{o?.(Ee)},[Ee,o]);let Oe=(P?1:0)+(U?1:0)+(F?1:0),st=Oe>0||!!R||!!Xe,ze=!!P&&!!U&&P>U,Ke=!u||!!f,ce=G=>{if(u){f?.();return}oe(G),ee("detail")},Be=()=>{ee("list"),oe(null),fe()},ct=G=>{let zt=G.trim();if(!zt){lt(""),R&&T("");return}if(zt.startsWith("#")||/^\d+$/.test(zt)){lt(zt),R&&T("");return}lt(""),T(zt)},Yt=()=>{Pe(""),lt(""),T(""),A(""),w(""),X(!1),Ce(!1)},wt=Xe.replace(/^#/,"").toLowerCase(),At=wt?x.filter(G=>String(G.order_number??"")===wt||G.id.toLowerCase().startsWith(wt)):x,Ht=u?At.slice(0,d):At,qe=Z?x.findIndex(G=>G.id===Z.id):-1,nt=qe>0,ts=qe>=0&&qe<x.length-1;if(Et)return(0,C.jsx)("div",{className:t,children:(0,C.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,C.jsx)(ia.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(J==="detail"&&Z)return(0,C.jsx)("div",{className:t,children:(0,C.jsx)(ln,{order:Z,onBack:Be,onRefund:e,onOrderUpdated:G=>oe(G),allowFulfillment:n,onPrevOrder:nt?()=>oe(x[qe-1]):void 0,onNextOrder:ts?()=>oe(x[qe+1]):void 0,hasPrevOrder:nt,hasNextOrder:ts},Z.id)});let Lt=(0,C.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[B&&(0,C.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:B}),(0,C.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,C.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(G=>(0,C.jsx)("button",{type:"button","aria-pressed":Ae===G,onClick:()=>pe(G),className:te("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",Ae===G?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Sl[G]},G))}),(0,C.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,C.jsx)(ia.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,C.jsx)(Ne,{type:"text",value:Y,onChange:G=>Pe(G.target.value),onBlur:()=>ct(Y),onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),ct(Y))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,C.jsxs)(_,{type:"button",variant:Oe>0?"secondary":"ghost",size:"sm",onClick:()=>Ce(G=>!G),"aria-expanded":at,children:[(0,C.jsx)(ia.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Oe>0&&(0,C.jsx)(ae,{variant:"secondary",className:"af-ml-2",children:Oe})]}),st&&(0,C.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:Yt,children:"Clear filters"})]}),(at||!!P||!!U)&&(0,C.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,C.jsx)(Re,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,C.jsx)(Ne,{id:"orders-from",type:"date",value:P,max:U||void 0,onChange:G=>A(G.target.value),className:"af-w-[170px]"}),(0,C.jsx)(Re,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,C.jsx)(Ne,{id:"orders-to",type:"date",value:U,min:P||void 0,onChange:G=>w(G.target.value),className:"af-w-[170px]"}),!Ii[Ae].statusIn&&(0,C.jsx)(_,{type:"button",variant:F?"secondary":"ghost",size:"sm",onClick:()=>X(!F),"aria-pressed":F,children:F?"Hide abandoned":"Show abandoned"})]}),ze&&(0,C.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(c)return(0,C.jsxs)("div",{className:t,children:[u?null:Lt,(0,C.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(G=>(0,C.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,C.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,C.jsx)(se,{className:"af-h-4 af-w-16"}),(0,C.jsx)(se,{className:"af-h-4 af-w-14"})]}),(0,C.jsx)(se,{className:"af-mt-2 af-h-3 af-w-40"}),(0,C.jsx)(se,{className:"af-mt-2 af-h-3 af-w-24"})]},G))}),(0,C.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,C.jsxs)(Ue,{children:[(0,C.jsx)(Ve,{children:(0,C.jsxs)(xe,{children:[(0,C.jsx)(H,{children:"Order"}),(0,C.jsx)(H,{children:"Date"}),(0,C.jsx)(H,{children:"Customer"}),(0,C.jsx)(H,{children:"Items"}),(0,C.jsx)(H,{className:"af-text-right",children:"Total"}),(0,C.jsx)(H,{children:"Status"}),(0,C.jsx)(H,{className:"af-w-8"})]})}),(0,C.jsx)(He,{"aria-hidden":"true",children:[0,1,2,3,4].map(G=>(0,C.jsxs)(xe,{children:[(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-4 af-w-14"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-4 af-w-24"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-4 af-w-40"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-4 af-w-32"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-5 af-w-16"})}),(0,C.jsx)(z,{})]},G))})]})}),(0,C.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(l)return(0,C.jsxs)("div",{className:t,children:[u?null:Lt,(0,C.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,C.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,C.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>fe(),children:"Try again"})]})]});let Rn=Ae!=="all";if(At.length===0&&y===0)return st||Rn?(0,C.jsxs)("div",{className:t,children:[!u&&Lt,(0,C.jsx)(Ea,{children:"No orders match these filters."})]}):(0,C.jsx)("div",{className:t,children:(0,C.jsx)(As,{icon:ia.Receipt,heading:"No orders yet",body:i??"Orders will appear here when someone buys from your website.",children:!u&&(0,C.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>X(!0),children:"Show abandoned checkouts"})})});let j=y*N+1,Ze=Math.min((y+1)*N,b);return(0,C.jsxs)("div",{className:t,children:[u?null:Lt,(0,C.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Ht.map(G=>(0,C.jsxs)("button",{type:"button",onClick:()=>ce(G),disabled:!Ke,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ke?" hover:af-bg-muted/50":""}`,children:[(0,C.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,C.jsx)("span",{className:"af-font-medium",children:Za(G)}),(0,C.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:W(Ba(G),G.currency)})]}),(0,C.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,C.jsxs)("div",{className:"af-truncate af-text-sm",children:[G.customer_email||(0,C.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Vn(G)&&(0,C.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Vn(G)]})]}),(0,C.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Li(G)}),G.amount_refunded>0&&(0,C.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",W(G.amount_refunded,G.currency)," refunded"]})]}),(0,C.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,C.jsx)(ps,{status:G.status}),(0,C.jsx)(qs,{deliveries:G.email_deliveries}),G.is_test&&(0,C.jsx)(ae,{variant:"outline",children:"Test"}),n&&(0,C.jsx)(Es,{order:G}),(0,C.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Di(G.created_at)})]})]},G.id))}),(0,C.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,C.jsxs)(Ue,{children:[(0,C.jsx)(Ve,{children:(0,C.jsxs)(xe,{children:[(0,C.jsx)(H,{children:"Order"}),(0,C.jsx)(H,{children:"Date"}),(0,C.jsx)(H,{children:"Customer"}),(0,C.jsx)(H,{children:"Items"}),(0,C.jsx)(H,{className:"af-text-right",children:"Total"}),(0,C.jsx)(H,{children:"Status"}),(0,C.jsx)(H,{className:"af-w-8"})]})}),(0,C.jsx)(He,{children:Ht.map(G=>(0,C.jsxs)(xe,{onClick:Ke?()=>ce(G):void 0,className:Ke?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,C.jsxs)(z,{className:"af-whitespace-nowrap af-font-medium",children:[(0,C.jsx)("button",{type:"button",onClick:zt=>{zt.stopPropagation(),ce(G)},disabled:!Ke,"aria-label":`Open order ${Za(G)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ke?" hover:af-underline":""}`,children:Za(G)}),G.is_test&&(0,C.jsx)(ae,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,C.jsx)(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Di(G.created_at)}),(0,C.jsxs)(z,{className:"af-max-w-[220px]",children:[(0,C.jsx)("div",{className:"af-truncate",children:G.customer_email||(0,C.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Vn(G)&&(0,C.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Vn(G)})]}),(0,C.jsx)(z,{className:"af-max-w-[220px]",children:(0,C.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:Li(G)})}),(0,C.jsxs)(z,{className:"af-whitespace-nowrap af-text-right",children:[(0,C.jsx)("div",{className:"af-font-medium af-tabular-nums",children:W(Ba(G),G.currency)}),G.amount_refunded>0&&(0,C.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",W(G.amount_refunded,G.currency)," ","refunded"]})]}),(0,C.jsx)(z,{children:(0,C.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,C.jsx)(ps,{status:G.status}),(0,C.jsx)(qs,{deliveries:G.email_deliveries}),n&&(0,C.jsx)(Es,{order:G})]})}),(0,C.jsx)(z,{className:"af-w-8 af-text-right",children:(0,C.jsx)(ia.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},G.id))})]})}),u?null:(0,C.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,C.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,C.jsx)("span",{children:wt?`${At.length} matching this page`:`Showing ${j}-${Ze} of ${b}`}),(0,C.jsxs)(da,{value:String(N),onValueChange:G=>m(Number(G)),children:[(0,C.jsx)(Xt,{className:"af-w-[70px] af-h-8",children:(0,C.jsx)(fa,{})}),(0,C.jsxs)(ea,{children:[(0,C.jsx)(Ye,{value:"10",children:"10"}),(0,C.jsx)(Ye,{value:"25",children:"25"}),(0,C.jsx)(Ye,{value:"50",children:"50"}),(0,C.jsx)(Ye,{value:"100",children:"100"})]})]}),(0,C.jsx)("span",{children:"per page"})]}),(0,C.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,C.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>M(y-1),disabled:!O,children:[(0,C.jsx)(ia.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,C.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>M(y+1),disabled:!S,children:["Next",(0,C.jsx)(ia.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function Ja(e){return(0,C.jsx)(_l,{...e},e.maxRows==null?"full":"compact")}var zn=le(require("react"),1),$a=require("lucide-react");var Wt=le(require("react"),1);function cn({initialPageSize:e=25}={}){let{api:t}=ne(),[s,a]=Wt.useState([]),[n,i]=Wt.useState(0),[o,d]=Wt.useState(!0),[f,u]=Wt.useState(null),[r,v]=Wt.useState(0),[x,b]=Wt.useState(e),[c,l]=Wt.useState(""),y=Wt.useRef(0),N=Wt.useCallback(async()=>{let O=++y.current;try{d(!0),u(null);let M={limit:x,offset:r*x};c.trim()&&(M.email=c.trim());let m=await t.getCustomers(M);if(O!==y.current)return;a(m.customers),i(m.total)}catch(M){if(O!==y.current)return;u(M instanceof Error?M:new Error("Failed to fetch customers"))}finally{O===y.current&&d(!1)}},[t,r,x,c]);Wt.useEffect(()=>{N()},[N]);let S=Math.ceil(n/x);return{customers:s,total:n,isLoading:o,error:f,page:r,pageSize:x,hasNextPage:r<S-1,hasPreviousPage:r>0,setPage:v,setPageSize:O=>{b(O),v(0)},email:c,setEmail:O=>{l(O),v(0)},refetch:N}}var vs=le(require("react"),1),Hn=require("lucide-react");var ge=require("react/jsx-runtime");function Oi(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Rl(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&t.push(s),e.country&&t.push(e.country),t}function un({customer:e,onBack:t,className:s}){let{api:a}=ne(),[n,i]=vs.useState(null),[o,d]=vs.useState([]),[f,u]=vs.useState(!0),[r,v]=vs.useState(null);vs.useEffect(()=>{let c=!1;return u(!0),v(null),Promise.all([a.getCustomer(e.id),a.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,y])=>{c||(i(l),d(y.orders))}).catch(l=>{c||v(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{c||u(!1)}),()=>{c=!0}},[a,e.id,e.email]);let x=n?.addresses??[],b=n?.order_count??o.length;return(0,ge.jsxs)("div",{className:s,children:[(0,ge.jsxs)("div",{className:"af-mb-6",children:[(0,ge.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,ge.jsx)(Hn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,ge.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,ge.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Oi(e.created_at)]})]}),f?(0,ge.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ge.jsx)(Hn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?(0,ge.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):(0,ge.jsxs)("div",{className:"af-space-y-6",children:[(0,ge.jsx)(Da,{deliveries:n?.email_deliveries}),(0,ge.jsxs)("div",{children:[(0,ge.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,ge.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,ge.jsx)("span",{children:e.email})]}),e.name&&(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,ge.jsx)("span",{children:e.name})]}),e.phone&&(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,ge.jsx)("span",{children:e.phone})]}),(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,ge.jsx)("span",{children:b})]})]})]}),x.length>0&&(0,ge.jsxs)("div",{children:[(0,ge.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,ge.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:x.map(c=>(0,ge.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[c.is_default&&(0,ge.jsx)(ae,{variant:"secondary",className:"af-mb-1",children:"Default"}),Rl(c).map((l,y)=>(0,ge.jsx)("div",{children:l},y))]},c.id))})]}),(0,ge.jsxs)("div",{children:[(0,ge.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,ge.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,ge.jsxs)(Ue,{children:[(0,ge.jsx)(Ve,{children:(0,ge.jsxs)(xe,{children:[(0,ge.jsx)(H,{children:"Date"}),(0,ge.jsx)(H,{children:"Amount"}),(0,ge.jsx)(H,{children:"Status"})]})}),(0,ge.jsx)(He,{children:o.map(c=>(0,ge.jsxs)(xe,{children:[(0,ge.jsx)(z,{className:"af-text-muted-foreground",children:Oi(c.created_at)}),(0,ge.jsx)(z,{children:W(Ba(c),c.currency)}),(0,ge.jsx)(z,{children:(0,ge.jsx)(os,{status:c.status})})]},c.id))})]})]})]})]})}var de=require("react/jsx-runtime");function Pl(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function dn({className:e}){let{customers:t,total:s,isLoading:a,error:n,page:i,pageSize:o,hasNextPage:d,hasPreviousPage:f,setPage:u,setPageSize:r,email:v,setEmail:x,refetch:b}=cn(),[c,l]=zn.useState("list"),[y,N]=zn.useState(null),[S,O]=zn.useState(""),M=P=>{N(P),l("detail")},m=()=>{l("list"),N(null),b()};if(c==="detail"&&y)return(0,de.jsx)("div",{className:e,children:(0,de.jsx)(un,{customer:y,onBack:m})});let R=(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,de.jsx)(Ne,{type:"email",value:S,onChange:P=>O(P.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),x(S.trim()))}}),(0,de.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>x(S.trim()),children:[(0,de.jsx)($a.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),v&&(0,de.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{O(""),x("")},children:"Clear"})]});if(a)return(0,de.jsxs)("div",{className:e,children:[R,(0,de.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,de.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,de.jsxs)("div",{className:e,children:[R,(0,de.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,de.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&i===0)return(0,de.jsxs)("div",{className:e,children:[v&&R,(0,de.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,de.jsx)($a.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,de.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:v?"No customers match that email.":(0,de.jsxs)(de.Fragment,{children:["No customers yet.",(0,de.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let T=i*o+1,D=Math.min((i+1)*o,s);return(0,de.jsxs)("div",{className:e,children:[R,(0,de.jsxs)(Ue,{children:[(0,de.jsx)(Ve,{children:(0,de.jsxs)(xe,{children:[(0,de.jsx)(H,{children:"Email"}),(0,de.jsx)(H,{children:"Name"}),(0,de.jsx)(H,{children:"Customer since"}),(0,de.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,de.jsx)(He,{children:t.map(P=>(0,de.jsxs)(xe,{children:[(0,de.jsx)(z,{className:"af-font-medium",children:P.email}),(0,de.jsx)(z,{children:P.name||(0,de.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,de.jsx)(z,{className:"af-text-muted-foreground",children:Pl(P.created_at)}),(0,de.jsx)(z,{className:"af-text-right",children:(0,de.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>M(P),title:"View customer",children:(0,de.jsx)($a.Eye,{className:"af-h-4 af-w-4"})})})]},P.id))})]}),(0,de.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,de.jsxs)("span",{children:["Showing ",T,"-",D," of ",s]}),(0,de.jsxs)(da,{value:String(o),onValueChange:P=>r(Number(P)),children:[(0,de.jsx)(Xt,{className:"af-w-[70px] af-h-8",children:(0,de.jsx)(fa,{})}),(0,de.jsxs)(ea,{children:[(0,de.jsx)(Ye,{value:"10",children:"10"}),(0,de.jsx)(Ye,{value:"25",children:"25"}),(0,de.jsx)(Ye,{value:"50",children:"50"}),(0,de.jsx)(Ye,{value:"100",children:"100"})]})]}),(0,de.jsx)("span",{children:"per page"})]}),(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,de.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>u(i-1),disabled:!f,children:[(0,de.jsx)($a.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,de.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>u(i+1),disabled:!d,children:["Next",(0,de.jsx)($a.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var ke=le(require("react"),1),xt=require("lucide-react");var ht=le(require("react"),1);function bs({initialPageSize:e=25,refreshKey:t,includeAggregates:s=!1}={}){let{api:a}=ne(),[n,i]=ht.useState([]),[o,d]=ht.useState(0),[f,u]=ht.useState(null),[r,v]=ht.useState(!0),[x,b]=ht.useState(null),[c,l]=ht.useState(0),[y,N]=ht.useState(e),[S,O]=ht.useState(void 0),[M,m]=ht.useState(""),[R,T]=ht.useState(""),[D,P]=ht.useState(""),[A,U]=ht.useState(""),[w,F]=ht.useState(""),X=S?S.join(","):"",q=ht.useRef(0),fe=ht.useCallback(async()=>{let ee=++q.current;v(!0),b(null);try{let Z={labels:X?X.split(","):void 0,customerEmail:M||void 0,q:R||void 0,from:D||void 0,to:A||void 0,retainerId:w||void 0,includeAggregates:s,limit:y,offset:c*y},oe=await a.getInvoices(Z);if(ee!==q.current)return;if(c>0&&c*y>=oe.total){l(Math.max(0,Math.ceil(oe.total/y)-1));return}i(oe.invoices),d(oe.total),s&&u(oe.aggregates??null)}catch(Z){if(ee!==q.current)return;b(Z instanceof Error?Z:new Error("Failed to fetch invoices"))}finally{ee===q.current&&v(!1)}},[a,X,M,R,D,A,w,c,y,s]);ht.useEffect(()=>{fe()},[fe,t]);let J=ee=>Z=>{l(0),ee(Z)};return{invoices:n,total:o,aggregates:f,isLoading:r,error:x,page:c,pageSize:y,hasNextPage:(c+1)*y<o,hasPreviousPage:c>0,setPage:l,setPageSize:J(N),labels:S,setLabels:J(O),customerEmail:M,setCustomerEmail:J(m),q:R,setQ:J(T),from:D,setFrom:J(P),to:A,setTo:J(U),retainerId:w,setRetainerId:J(F),clearFilters:()=>{l(0),O(void 0),m(""),T(""),P(""),U(""),F("")},refetch:fe}}var g=require("react/jsx-runtime"),Cl={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 Tr(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Cl[e.label]??e.label}function Tl(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 Cr={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},kl={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Ds({invoice:e,className:t}){return(0,g.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,g.jsx)(ae,{variant:Tl(e.label),className:t,children:Tr(e)}),e.collection_method==="charge_automatically"&&(0,g.jsx)(ae,{variant:"secondary",children:"Managed in Stripe"})]})}function Gn({delivery:e,className:t}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,g.jsx)(ae,{variant:s,className:t,children:Cr[e.state]??e.state})}function Is(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ya(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Bi={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},qn={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 El(e){let t=e==null?"":String(e),s=/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),a=s?`'${t}`:t;return s||/[",;\r\n]/.test(a)?`"${a.replace(/"/g,'""')}"`:a}var Rr=100,Pr=5e3;async function Al(e,t){let s=[],a=0;for(let n=0;n<Pr;n+=Rr){let i=await e.getInvoices({...t,limit:Rr,offset:n});if(a=i.total,s.push(...i.invoices),i.invoices.length<Rr||s.length>=a)break}return{invoices:s.slice(0,Pr),total:a,truncated:a>s.length||a>Pr}}function Mi(e){let t=["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(a=>[a.id,Is(a),Tr(a),a.customer_name??"",a.customer_email??"",a.created_at,a.due_at??"",a.paid_at??"",a.currency.toUpperCase(),W(a.amount_subtotal,a.currency),W(a.tax_total,a.currency),W(a.amount_total,a.currency),a.amount_due===null?"":W(a.amount_due,a.currency),a.amount_paid===null?"":W(a.amount_paid,a.currency),W(a.amount_refunded,a.currency),a.payment_method??"",a.pay_url??"",a.retainer_id??"",a.replaces_order_id??"",a.replaced_by_order_id??"",a.tax_behavior??"",a.discount_total===void 0?"":W(a.discount_total,a.currency),a.collection_method??""]);return[t,...s].map(a=>a.map(El).join(",")).join(`
5
+ `)}function Il(e){if(typeof document>"u")return;let t=new Blob([Mi(e)],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(t),a=document.createElement("a");a.href=s,a.download=`invoices-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(s)}function Dl({className:e,refreshKey:t,initialInvoiceId:s,onDetailOpenChange:a,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:d=null,onClearRetainerFilter:f,maxRows:u,onViewAll:r}){let v=typeof u=="number",{api:x}=ne(),{invoices:b,total:c,isLoading:l,error:y,page:N,pageSize:S,hasNextPage:O,hasPreviousPage:M,setPage:m,labels:R,setLabels:T,customerEmail:D,setCustomerEmail:P,q:A,setQ:U,from:w,setFrom:F,to:X,setTo:q,retainerId:fe,setRetainerId:J,refetch:ee}=bs({refreshKey:t}),[Z,oe]=ke.useState(typeof u=="number"?"all":"open"),[Y,Pe]=ke.useState(""),[Xe,lt]=ke.useState(null),Ae=ke.useRef(0),Ge=!v||!!r,at=ke.useCallback(j=>{if(v){r?.();return}Ae.current++,Et(!1),lt(j)},[v,r]),[Ce,Et]=ke.useState(!1),[k,B]=ke.useState(0),[L,pe]=ke.useState(null),[he,Ee]=ke.useState(!1),[Oe,st]=ke.useState(0);ke.useEffect(()=>{lt(j=>{if(!j)return j;let Ze=b.find(G=>G.id===j.id);return Ze&&Ze!==j?Ze:j})},[b]);let[ze,Ke]=ke.useState(!1),[ce,Be]=ke.useState(null),ct=async()=>{if(!ze){Ke(!0),Be(null);try{let{invoices:j,total:Ze,truncated:G}=await Al(x,{labels:R,customerEmail:D,q:A,from:w,to:X,retainerId:fe});Il(j),Be(G?`Exported the first ${j.length.toLocaleString()} of ${Ze.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Be("Couldn't export \u2014 try again.")}finally{Ke(!1)}}},Yt=!D&&!A&&!w&&!X&&!fe,[wt,At]=ke.useState(null);ke.useEffect(()=>{if(l||c>0||!Yt||Z!=="open")return;let j=!1;return x.getInvoices({limit:1}).then(Ze=>{j||At(Ze.total>0)}).catch(()=>{j||At(!0)}),()=>{j=!0}},[x,l,c,Yt,Z,t]),ke.useEffect(()=>{T(v?qn.all:qn.open)},[]),ke.useEffect(()=>{let j=d?.id??"";j!==fe&&(J(j),j&&(oe("all"),T(qn.all),P(""),U(""),Pe(""),F(""),q("")))},[d?.id]),ke.useEffect(()=>{let j=!1;return Ee(!1),x.getInvoiceSettings().then(Ze=>{j||pe({payments_active:Ze.payments_active,blocked:Ze.blocked})}).catch(()=>{j||Ee(!0)}),()=>{j=!0}},[x,t,Oe]),ke.useEffect(()=>{if(!s||v)return;let j=!1,Ze=Ae.current;return Et(!1),x.getInvoice(s).then(G=>{!j&&Ze===Ae.current&&lt(G)}).catch(()=>{!j&&Ze===Ae.current&&Et(!0)}),()=>{j=!0}},[x,s,k,v]),ke.useEffect(()=>{a?.(Xe!==null)},[Xe,a]);let Ht=j=>{oe(j),T(qn[j])},qe=j=>{let Ze=j.trim();if(!Ze){A&&U(""),D&&P("");return}if(Ze.includes("@")){A&&U(""),P(Ze);return}D&&P(""),U(Ze.replace(/^#/,""))},nt=b,ts=v?nt.slice(0,u):nt,Ms=Ce&&(0,g.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,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>B(j=>j+1),children:"Retry opening invoice"})]});if(Xe)return(0,g.jsxs)("div",{className:e,children:[Ms,(0,g.jsx)(Wn,{invoice:Xe,refreshKey:t,onBack:()=>{at(null),ee()}},Xe.id)]});let Lt=(0,g.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[he&&(0,g.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>st(j=>j+1),children:"Retry setup check"})]}),Ms,L?.blocked&&(0,g.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",L.blocked.reason?`: ${L.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),d&&(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,g.jsxs)(ae,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",d.label]}),f&&(0,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:f,children:"Clear schedule filter"})]}),(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,g.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(Bi).map(j=>(0,g.jsx)("button",{type:"button","aria-pressed":Z===j,onClick:()=>Ht(j),className:te("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",Z===j?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Bi[j]},j))}),(0,g.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,g.jsx)(xt.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,g.jsx)(Ne,{type:"text",value:Y,onChange:j=>Pe(j.target.value),onBlur:()=>qe(Y),onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),qe(Y))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,g.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,g.jsx)(Re,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,g.jsx)(Ne,{id:"invoices-from",type:"date",value:w,max:X||void 0,onChange:j=>F(j.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,g.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,g.jsx)(Re,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,g.jsx)(Ne,{id:"invoices-to",type:"date",value:X,min:w||void 0,onChange:j=>q(j.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,g.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>void ct(),disabled:ze||l||!!y||c===0,"aria-busy":ze,children:[(0,g.jsx)(xt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),ze?"Exporting\u2026":"Export CSV (all matching)"]})]}),ce&&(0,g.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:ce})]});return l?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(j=>(0,g.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,g.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,g.jsx)(se,{className:"af-h-4 af-w-20"}),(0,g.jsx)(se,{className:"af-h-4 af-w-16"})]}),(0,g.jsx)(se,{className:"af-mt-2 af-h-3 af-w-40"})]},j))})]}):y?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void ee(),children:"Retry"})]})]}):c===0&&Yt&&(Z==="all"||wt===!1)&&(Z==="open"||Z==="all")?L?.blocked?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)(jn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)(jn,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):L&&!L.payments_active?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)(jn,{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,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)(jn,{heading:"No invoices yet",body:!L||he?"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,g.jsxs)("div",{className:e,children:[v?null:Lt,ts.length===0?(0,g.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,g.jsxs)(g.Fragment,{children:[(0,g.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ts.map(j=>(0,g.jsxs)("button",{type:"button",onClick:()=>at(j),disabled:!Ge,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ge?" hover:af-bg-muted/50":""}`,children:[(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,g.jsx)("span",{className:"af-font-medium",children:Is(j)}),(0,g.jsx)(Ds,{invoice:j})]}),(0,g.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:j.customer_name??j.customer_email??"\u2014"}),j.delivery&&(0,g.jsx)("div",{className:"af-mt-1",children:(0,g.jsx)(Gn,{delivery:j.delivery})}),(0,g.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,g.jsx)("span",{children:j.collection_method==="charge_automatically"?"Automatic collection":j.due_at?`Due ${ya(j.due_at)}`:"Due on receipt"}),(0,g.jsx)("span",{className:"af-font-medium af-tabular-nums",children:W(j.amount_due??j.amount_total,j.currency)})]})]},j.id))}),(0,g.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,g.jsxs)(Ue,{children:[(0,g.jsx)(Ve,{children:(0,g.jsxs)(xe,{children:[(0,g.jsx)(H,{children:"Invoice"}),(0,g.jsx)(H,{children:"Created"}),(0,g.jsx)(H,{children:"Customer"}),(0,g.jsx)(H,{children:"Due"}),(0,g.jsx)(H,{className:"af-text-right",children:"Amount"}),(0,g.jsx)(H,{children:"Status"}),(0,g.jsx)(H,{children:"Delivery"}),(0,g.jsx)(H,{className:"af-w-8"})]})}),(0,g.jsx)(He,{children:ts.map(j=>(0,g.jsxs)(xe,{className:Ge?"af-cursor-pointer":void 0,onClick:Ge?()=>at(j):void 0,children:[(0,g.jsx)(z,{className:"af-font-medium",children:(0,g.jsx)("button",{type:"button",disabled:!Ge,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ge?" hover:af-underline":""}`,onClick:Ze=>{Ze.stopPropagation(),at(j)},"aria-label":`Open invoice ${Is(j)}`,children:Is(j)})}),(0,g.jsx)(z,{children:ya(j.created_at)}),(0,g.jsxs)(z,{children:[(0,g.jsx)("div",{children:j.customer_name??"\u2014"}),(0,g.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:j.customer_email})]}),(0,g.jsx)(z,{children:j.collection_method==="charge_automatically"?"Automatic":j.due_at?ya(j.due_at):"On receipt"}),(0,g.jsx)(z,{className:"af-text-right af-tabular-nums",children:W(j.amount_due??j.amount_total,j.currency)}),(0,g.jsx)(z,{children:(0,g.jsx)(Ds,{invoice:j})}),(0,g.jsx)(z,{children:(0,g.jsx)(Gn,{delivery:j.delivery})}),(0,g.jsx)(z,{children:(0,g.jsx)(xt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},j.id))})]})}),v?null:(0,g.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,g.jsxs)("span",{children:[c," invoice",c===1?"":"s"]}),(0,g.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,g.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>m(N-1),disabled:!M,"aria-label":"Previous page",children:(0,g.jsx)(xt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,g.jsxs)("span",{className:"af-tabular-nums",children:[N*S+1,"\u2013",Math.min((N+1)*S,c)]}),(0,g.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>m(N+1),disabled:!O,"aria-label":"Next page",children:(0,g.jsx)(xt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function jn({heading:e,body:t,action:s}){return(0,g.jsx)(As,{icon:xt.FileText,heading:e,body:t,action:s})}function Qa(e){return(0,g.jsx)(Dl,{...e},e.maxRows==null?"full":"compact")}var Ya="af-text-xs af-text-muted-foreground";function Fi(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Wn({invoice:e,onBack:t,refreshKey:s,className:a}){let{api:n}=ne(),i=ke.useRef(null);ke.useEffect(()=>{i.current?.focus()},[e.id]);let[o,d]=ke.useState(!1),[f,u]=ke.useState(null),[r,v]=ke.useState(!1),[x,b]=ke.useState(!1),c=ke.useRef(0),[l,y]=ke.useState(null),[N,S]=ke.useState(!1),[O,M]=ke.useState(0);ke.useEffect(()=>{let w=!1;return S(!1),n.getInvoice(e.id).then(F=>{w||y({source:e,value:F})}).catch(()=>{w||S(!0)}),()=>{w=!0}},[n,e,s,O]);let m=l?.source===e?l.value:e,R=m.collection_method==="charge_automatically";ke.useEffect(()=>(c.current++,u(null),v(!1),b(!1),d(!1),()=>{c.current++}),[n,m,s]);let T=w=>w==null?"\u2014":W(w,m.currency),D=async()=>{if(!(!m.pay_url||!Fi()))try{await navigator.clipboard.writeText(m.pay_url),d(!0),setTimeout(()=>d(!1),1500)}catch{}},P=async()=>{if(f){u(null);return}let w=++c.current;b(!1),v(!0);try{let F=await n.getInvoicePreview(m.id);w===c.current&&u(F)}catch{w===c.current&&b(!0)}finally{w===c.current&&v(!1)}},A=m.bill_to,U=A?[A.company,A.name,A.address?.line1,A.address?.line2,[A.address?.city,A.address?.state,A.address?.postal_code].filter(Boolean).join(", "),A.address?.country,A.tax_id?`${A.tax_id.value}`:null,A.po_number?`PO ${A.po_number}`:null,A.service_period?`Service period: ${A.service_period}`:null].filter(w=>!!w&&w.length>0):[];return(0,g.jsxs)("div",{className:a,children:[(0,g.jsxs)("div",{className:"af-mb-4",children:[(0,g.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,g.jsx)(xt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,g.jsxs)("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",Is(m)]}),(0,g.jsx)(Ds,{invoice:m}),(0,g.jsx)(Gn,{delivery:m.delivery})]}),(0,g.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[m.customer_name??m.customer_email,m.customer_name&&m.customer_email?` \xB7 ${m.customer_email}`:""]})]}),N&&(0,g.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,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>M(w=>w+1),children:"Retry details"})]}),m.label==="failed"&&(0,g.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."}),m.label==="creating"&&(0,g.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,g.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,g.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,g.jsxs)(Ue,{children:[(0,g.jsx)(Ve,{children:(0,g.jsxs)(xe,{children:[(0,g.jsx)(H,{children:"Description"}),(0,g.jsx)(H,{className:"af-text-right",children:"Qty"}),(0,g.jsx)(H,{className:"af-text-right",children:"Amount"})]})}),(0,g.jsx)(He,{children:m.line_items.map((w,F)=>(0,g.jsxs)(xe,{children:[(0,g.jsx)(z,{style:{overflowWrap:"anywhere"},children:w.description}),(0,g.jsx)(z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:w.quantity}),(0,g.jsx)(z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:T(w.amount)})]},F))})]}),(0,g.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,g.jsx)(ls,{label:"Subtotal",value:T(m.amount_subtotal)}),(m.discount_total??0)>0&&(0,g.jsx)(ls,{label:"Discount",value:`-${T(m.discount_total)}`}),m.tax_total>0&&(0,g.jsx)(ls,{label:m.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:T(m.tax_total)}),(0,g.jsx)(ls,{label:"Total",value:T(m.amount_total),strong:!0}),m.credit_applied>0&&(0,g.jsx)(ls,{label:"Credit applied",value:`-${T(m.credit_applied)}`}),m.amount_due!==null&&m.amount_due!==m.amount_total&&(0,g.jsx)(ls,{label:"Amount due",value:T(m.amount_due),strong:!0}),m.amount_paid!==null&&m.amount_paid>0&&(0,g.jsx)(ls,{label:"Amount paid",value:T(m.amount_paid)}),m.amount_refunded>0&&(0,g.jsx)(ls,{label:"Refunded",value:T(m.amount_refunded)})]}),m.credit_notes?.length>0&&(0,g.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,g.jsx)("div",{className:Ya,children:"Credit notes"}),m.credit_notes.map(w=>(0,g.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,g.jsxs)("span",{className:"af-text-muted-foreground",children:[ya(w.created_at)," \xB7 ",w.origin==="dashboard"?"issued in Stripe":"refund",w.stripe_credit_note_id?"":" \xB7 being created"]}),(0,g.jsxs)("span",{className:"af-tabular-nums",children:["-",W(w.amount,w.currency)]})]},w.id))]})]}),(m.note||m.footer)&&(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[m.note&&(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:Ya,children:"Note"}),(0,g.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:m.note})]}),m.footer&&(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:Ya,children:"Footer"}),(0,g.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:m.footer})]})]}),f&&!R&&(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,g.jsxs)("div",{className:te(Ya,"af-break-words"),children:["Email preview \u2014 ",f.subject]}),(0,g.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,g.jsx)("iframe",{title:"Invoice email preview",srcDoc:f.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,g.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,g.jsx)(ba,{label:"Created",value:ya(m.created_at)}),(0,g.jsx)(ba,{label:"Due",value:m.collection_method==="charge_automatically"?"Managed in Stripe":m.due_at?ya(m.due_at):"On receipt"}),m.paid_at&&(0,g.jsx)(ba,{label:"Paid",value:ya(m.paid_at)}),m.payment_method&&(0,g.jsx)(ba,{label:"Paid by",value:m.paid_out_of_band?`${m.payment_method} (recorded outside Stripe)`:m.payment_method}),m.payment_state!=="none"&&(0,g.jsx)(ba,{label:"Payment",value:m.payment_state==="processing"?"Processing":m.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),m.delivery&&(0,g.jsx)(ba,{label:"Delivery",value:`${Cr[m.delivery.state]} \xB7 ${m.delivery.recipient}`}),m.marked_uncollectible_at&&(0,g.jsx)(ba,{label:"Written off",value:ya(m.marked_uncollectible_at)}),m.correction_reason&&(0,g.jsx)(ba,{label:"Correction",value:m.correction_reason}),m.replaced_by_order_id&&(0,g.jsx)(ba,{label:"Replaced by",value:m.replaced_by_order_id}),m.collection_method==="charge_automatically"?(0,g.jsx)(ba,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):m.retainer_id&&(0,g.jsx)(ba,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),m.replaces_order_id&&(0,g.jsx)(ba,{label:"Replaces",value:m.replaces_order_id})]}),(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,g.jsx)("div",{className:Ya,children:"Reminders"}),R?(0,g.jsx)("div",{children:"View automatic payment reminders in Stripe."}):m.reminders.disabled?(0,g.jsx)("div",{children:"Off for this invoice."}):m.reminders.paused_until?(0,g.jsxs)("div",{children:["Paused until ",ya(m.reminders.paused_until),"."]}):m.reminders.next_at?(0,g.jsxs)("div",{children:["Next on ",ya(m.reminders.next_at),"."]}):m.reminders.final_sent_at?(0,g.jsxs)("div",{children:["Final reminder sent ",ya(m.reminders.final_sent_at),"."]}):(0,g.jsx)("div",{children:"None scheduled."}),!R&&(0,g.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",m.reminders.schedule.length===0?"none":m.reminders.schedule.map(w=>w<0?`${-w}d before`:w===0?"due day":`${w}d after`).join(", ")]})]}),m.communications&&m.communications.length>0&&(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,g.jsx)("div",{className:Ya,children:"Email delivery history"}),m.communications.map(w=>(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,g.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[kl[w.kind]??w.kind,w.kind==="reminder"&&w.slot!==null?` #${w.slot}`:"",(0,g.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",w.recipient]})]}),(0,g.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Cr[w.state]??w.state," \xB7 ",ya(w.state_at??w.created_at)]})]},w.id))]}),U.length>0&&(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,g.jsx)("div",{className:Ya,children:"Bill to"}),U.map((w,F)=>(0,g.jsx)("div",{className:"af-break-words",children:w},F))]}),(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[m.pay_url&&(0,g.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void D(),disabled:!Fi(),children:[(0,g.jsx)(xt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":R?"Copy invoice link":"Copy pay link"]}),m.pdf_url&&(0,g.jsx)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,g.jsxs)("a",{href:m.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,g.jsx)(xt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!R&&(0,g.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void P(),disabled:r,children:[r?(0,g.jsx)(xt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,g.jsx)(xt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),f?"Hide email preview":x?"Retry email preview":"Show email preview"]}),x&&!R&&(0,g.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),m.pay_url&&(0,g.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:m.pay_url}),(0,g.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:R?"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 ba({label:e,value:t}){return(0,g.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,g.jsx)("span",{className:te(Ya,"af-shrink-0"),children:e}),(0,g.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function ls({label:e,value:t,strong:s}){return(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,g.jsx)("dt",{className:te(Ya,s&&"af-font-medium af-text-foreground"),children:e}),(0,g.jsx)("dd",{className:te("af-tabular-nums",s&&"af-font-semibold"),children:t})]})}var Ui=require("lucide-react");var De=require("react/jsx-runtime"),Ll={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},$i={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Ol(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 Vi(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>$i[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>$i[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Ll[e.status]}function Hi(e){let t=e.interval==="year"?"every year":"every month";return`${W(e.amount,e.currency)} ${t}`}function Bl(e){return e.status==="canceled"?`Ended ${Kn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Kn(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 ${Kn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Kn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Kn(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(t);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Zn({retainer:e,className:t}){return(0,De.jsx)(ae,{variant:Ol(e.status),className:te("af-max-w-full af-whitespace-normal af-break-words",t),children:Vi(e)})}function ys({retainers:e,isLoading:t,error:s,onRetry:a,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:d=0,isLoadingMore:f=!1,onLoadMore:u,includeEnded:r=!1,onIncludeEndedChange:v,className:x}){let b=!!v;if(!t&&!s&&e.length===0&&!(b&&(r||d>0)))return null;let c=o!==void 0?Math.max(0,o-e.length):0;return(0,De.jsxs)("section",{className:te("af-mb-6",x),"aria-label":"Recurring invoices",children:[(0,De.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,De.jsx)(Ui.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,De.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,De.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."}),b&&(0,De.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>v?.(!r),children:r?"Hide ended recurring invoices":d>0&&e.length===0?`Show ended recurring invoices (${d})`:"Show ended recurring invoices"})]}),s?(0,De.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,De.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:a,children:"Retry"})]}):t?(0,De.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(l=>(0,De.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,De.jsx)(se,{className:"af-h-4 af-w-48"}),(0,De.jsx)(se,{className:"af-mt-2 af-h-3 af-w-32"})]},l))}):e.length===0?(0,De.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,De.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(l=>{let y=i===l.id;return(0,De.jsxs)("li",{className:te("af-rounded-md af-border af-p-3",y&&"af-border-primary af-bg-muted/40"),children:[(0,De.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,De.jsxs)("div",{className:"af-min-w-0",children:[(0,De.jsx)("div",{className:"af-truncate af-font-medium",children:l.customer_name??l.customer_email??"\u2014"}),(0,De.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:l.description})]}),(0,De.jsx)(Zn,{retainer:l})]}),l.collection_method==="charge_automatically"?(0,De.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,De.jsx)(ae,{variant:"secondary",children:"Managed in Stripe"}),(0,De.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,De.jsx)("div",{className:"af-mt-2 af-text-sm",children:Hi(l)}),(0,De.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,De.jsxs)("span",{children:[Bl(l)," \xB7 ",l.cycles.count===0?"no invoices yet":`${l.cycles.paid} paid${l.cycles.open>0?`, ${l.cycles.open} open`:""}`]}),l.cycles.count>0&&(0,De.jsx)(_,{type:"button",variant:y?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":y,children:y?"Showing invoices":"View invoices"})]}),l.status==="failed"&&l.operation?.last_error&&(0,De.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",l.operation.last_error,". Ask in the chat to try again."]})]},l.id)})}),!t&&!s&&c>0&&u&&(0,De.jsx)("div",{className:"af-mt-2",children:(0,De.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:u,disabled:f,children:f?"Loading\u2026":`Load more (${c} more)`})})]})}var zi=le(require("react"),1),oa=require("lucide-react");var Se=require("react/jsx-runtime");function fn({onConnectStripe:e,onUpgradePlan:t,className:s}){let{status:a,isLoading:n,error:i,refetch:o}=Wa(),[d,f]=zi.useState(!1),u=async()=>{f(!0);try{await o()}finally{f(!1)}};return n&&!a?(0,Se.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Se.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!a?(0,Se.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Se.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):a.status==="active"?(0,Se.jsx)("div",{className:s,children:(0,Se.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,Se.jsx)(oa.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Se.jsxs)("div",{children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Se.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",a.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,Se.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[a.reason==="needs_stripe"&&(0,Se.jsxs)("div",{className:"af-space-y-3",children:[(0,Se.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Se.jsx)(oa.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Se.jsxs)("div",{children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Se.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,Se.jsxs)(_,{onClick:e,children:[(0,Se.jsx)(oa.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),a.reason==="needs_paid_plan"&&(0,Se.jsxs)("div",{className:"af-space-y-3",children:[(0,Se.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Se.jsx)(oa.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Se.jsxs)("div",{children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Se.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."})]})]}),t?(0,Se.jsx)(_,{onClick:t,children:"Upgrade plan"}):(0,Se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),a.reason==="account_disabled"&&(0,Se.jsxs)("div",{className:"af-space-y-3",children:[(0,Se.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,Se.jsx)(oa.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Se.jsxs)("div",{children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?(0,Se.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,Se.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,Se.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&(0,Se.jsxs)(_,{onClick:e,children:[(0,Se.jsx)(oa.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Se.jsxs)(_,{variant:"outline",onClick:u,disabled:d,children:[d?(0,Se.jsx)(oa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Se.jsx)(oa.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var $t=le(require("react"),1);function kr(e,t,s){return e.map(a=>a.id===t?{...a,...s}:a)}function hs({includeStats:e=!1,refreshKey:t}={}){let{api:s}=ne(),[a,n]=$t.useState([]),[i,o]=$t.useState(!0),[d,f]=$t.useState(null),u=$t.useRef(0),r=$t.useCallback(async()=>{let y=++u.current;try{o(!0),f(null);let N=await s.getProducts(e?{include:"stats"}:{});if(y!==u.current)return;n(N)}catch(N){if(y!==u.current)return;f(N instanceof Error?N:new Error("Failed to fetch products"))}finally{y===u.current&&o(!1)}},[s,e,t]);$t.useEffect(()=>{r()},[r]);let v=$t.useCallback(async y=>{let N=await s.createProduct(y);return n(S=>[N,...S]),N},[s]),x=$t.useCallback(async(y,N)=>{let S=await s.updateProduct(y,N);return n(O=>kr(O,y,S)),S},[s]),b=$t.useCallback(async y=>{await s.deleteProduct(y),n(N=>N.filter(S=>S.id!==y))},[s]),c=$t.useCallback(async(y,N)=>{let S=await s.attachProductFile(y,N);return n(O=>kr(O,y,S)),S},[s]),l=$t.useCallback(async(y,N)=>{let S=await s.attachProductFileFromUrl(y,N);return n(O=>kr(O,y,S)),S},[s]);return{products:a,isLoading:i,error:d,refetch:r,createProduct:v,updateProduct:x,deleteProduct:b,attachProductFile:c,attachProductFileFromUrl:l}}var Ut=le(require("react"),1);var qi=["creating","active","paused","canceling"],Fl=["canceled","failed"];function xs({refreshKey:e,includeEnded:t=!1,limit:s=50}={}){let{api:a}=ne(),[n,i]=Ut.useState([]),[o,d]=Ut.useState(0),[f,u]=Ut.useState(0),[r,v]=Ut.useState(!0),[x,b]=Ut.useState(!1),[c,l]=Ut.useState(null),[y,N]=Ut.useState(t),S=Ut.useRef(0),O=Ut.useCallback(async()=>{let m=++S.current;v(!0),b(!1),l(null);try{let R=await a.getRetainers({statuses:y?void 0:qi,limit:s,offset:0});if(m!==S.current)return;if(i(R.retainers),d(R.total),!y&&R.total===0){let T=await a.getRetainers({statuses:Fl,limit:1,offset:0});if(m!==S.current)return;u(T.total)}else u(0)}catch(R){if(m!==S.current)return;l(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{m===S.current&&v(!1)}},[a,y,s]);Ut.useEffect(()=>{O()},[O,e]);let M=Ut.useCallback(async()=>{if(r||x||n.length>=o)return;let m=S.current;b(!0);try{let R=await a.getRetainers({statuses:y?void 0:qi,limit:s,offset:n.length});if(m!==S.current)return;i(T=>{let D=new Set(T.map(P=>P.id));return[...T,...R.retainers.filter(P=>!D.has(P.id))]}),d(R.total)}catch(R){if(m!==S.current)return;l(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{m===S.current&&b(!1)}},[a,y,s,r,x,n.length,o]);return{retainers:n,total:o,endedTotal:f,hasMore:n.length<o,isLoading:r,isLoadingMore:x,error:c,includeEnded:y,setIncludeEnded:N,loadMore:M,refetch:O}}var ye=require("react/jsx-runtime");function Er({className:e,defaultTab:t="products",onConnectStripe:s,onRefund:a,onUpgradePlan:n}){let[i,o]=Ls.useState(t),[d,f]=Ls.useState("list"),[u,r]=Ls.useState(null),v=hs(),{status:x,error:b}=Wa(),c=x?.currency,l=O=>{r(O),f("edit")},y=()=>{r(null),f("create")},N=()=>{f("list"),r(null)},S=O=>{r(O),f("edit")};return(0,ye.jsxs)("div",{className:e,children:[(0,ye.jsxs)("div",{className:"af-mb-6",children:[(0,ye.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,ye.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,ye.jsxs)(En,{value:i,onValueChange:O=>o(O),children:[(0,ye.jsxs)(Vs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,ye.jsxs)(Na,{value:"products",className:"af-gap-2",children:[(0,ye.jsx)(ha.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,ye.jsxs)(Na,{value:"orders",className:"af-gap-2",children:[(0,ye.jsx)(ha.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,ye.jsxs)(Na,{value:"invoices",className:"af-gap-2",children:[(0,ye.jsx)(ha.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,ye.jsxs)(Na,{value:"customers",className:"af-gap-2",children:[(0,ye.jsx)(ha.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,ye.jsx)(Na,{value:"promos",children:"Promo codes"}),(0,ye.jsxs)(Na,{value:"setup",className:"af-gap-2",children:[(0,ye.jsx)(ha.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,ye.jsx)(Sa,{value:"products",children:d==="list"?(0,ye.jsx)(tn,{productsState:v,onSelectProduct:l,onCreateProduct:y}):(0,ye.jsxs)("div",{children:[(0,ye.jsxs)("div",{className:"af-mb-6",children:[(0,ye.jsxs)(_,{variant:"ghost",size:"sm",onClick:N,className:"af-mb-2 af--ml-2",children:[(0,ye.jsx)(ha.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,ye.jsx)("h3",{className:"af-text-lg af-font-semibold",children:d==="create"?"New Product":u?.name})]}),d==="create"&&!c?(0,ye.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:b?(0,ye.jsxs)("div",{className:"af-text-destructive",children:["Error: ",b.message]}):(0,ye.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,ye.jsx)(sn,{productsState:v,product:d==="edit"?u:null,currency:c??"usd",onSaved:S},d==="edit"?u?.id??"edit":"new")]})}),(0,ye.jsx)(Sa,{value:"orders",children:(0,ye.jsx)(Ja,{onRefund:a})}),(0,ye.jsx)(Sa,{value:"invoices",children:(0,ye.jsx)(Ml,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:x?.reason==="needs_paid_plan"})}),(0,ye.jsx)(Sa,{value:"customers",children:(0,ye.jsx)(dn,{})}),(0,ye.jsx)(Sa,{value:"promos",children:(0,ye.jsx)(ms,{})}),(0,ye.jsx)(Sa,{value:"setup",children:(0,ye.jsx)(fn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Ml({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s}){let a=xs(),[n,i]=Ls.useState(null),[o,d]=Ls.useState(!1);return(0,ye.jsxs)(ye.Fragment,{children:[!o&&(0,ye.jsx)(ys,{retainers:a.retainers,isLoading:a.isLoading,error:a.error,onRetry:()=>void a.refetch(),activeRetainerId:n?.id??null,onShowCycles:f=>i(u=>u?.id===f.id?null:f),total:a.total,endedTotal:a.endedTotal,isLoadingMore:a.isLoadingMore,onLoadMore:()=>void a.loadMore(),includeEnded:a.includeEnded,onIncludeEndedChange:a.setIncludeEnded}),(0,ye.jsx)(Qa,{onDetailOpenChange:d,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>i(null)})]})}var Gi=le(require("react"),1);var Ua=le(require("react"),1);function ws({refreshKey:e}={}){let{api:t}=ne(),[s,a]=Ua.useState(null),[n,i]=Ua.useState(!0),[o,d]=Ua.useState(null),f=Ua.useRef(0),u=Ua.useCallback(async()=>{let r=++f.current;try{i(!0),d(null);let v=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==f.current)return;a(v)}catch(v){if(r!==f.current)return;d(v instanceof Error?v:new Error("Failed to fetch summary"))}finally{r===f.current&&i(!1)}},[t,e]);return Ua.useEffect(()=>{u()},[u]),{summary:s,isLoading:n,error:o,refetch:u}}var je=require("react/jsx-runtime");function ji(e,t){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(a=>`+ ${W(a.gross,a.currency)} in ${a.currency.toUpperCase()}`)}:{headline:W(0,t),extra:[]}}function Ar({refreshKey:e,initialOrderId:t,isOwner:s=!1,onRefund:a,onBackToWebsite:n,className:i}){let{summary:o,isLoading:d,error:f,refetch:u}=ws({refreshKey:e}),[r,v]=Gi.useState(!1),x=(0,je.jsx)("div",{className:"af-mb-6",children:f&&!o?(0,je.jsx)(ra,{message:"Couldn't load your revenue summary.",onRetry:()=>u()}):(0,je.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:d||!o?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(rt,{label:"This week",children:(0,je.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,je.jsx)(rt,{label:"Today",children:(0,je.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,je.jsx)(rt,{label:"Needs attention",children:(0,je.jsx)(se,{className:"af-h-6 af-w-10"})})]}):(0,je.jsx)(je.Fragment,{children:(()=>{let b=ji(o.revenue.d7,o.currency),c=ji(o.revenue.today,o.currency);return(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(rt,{label:"This week",detail:b.extra.length>0?(0,je.jsx)("div",{children:b.extra.map(l=>(0,je.jsx)("div",{children:l},l))}):void 0,children:b.headline}),(0,je.jsx)(rt,{label:"Today",detail:c.extra.length>0?(0,je.jsx)("div",{children:c.extra.map(l=>(0,je.jsx)("div",{children:l},l))}):void 0,children:c.headline}),(0,je.jsx)(rt,{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,je.jsxs)(yt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[x,(0,je.jsx)(Ja,{refreshKey:e,initialOrderId:t,onDetailOpenChange:v,showFulfillment:!0,onRefund:s?a:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Ha=le(require("react"),1),Os=require("lucide-react");var Va=le(require("react"),1),tr=require("lucide-react");var Ct=require("react/jsx-runtime"),Wi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",cs="af-text-xs af-text-muted-foreground",Jn="af-text-sm af-font-medium af-tabular-nums",$l=3;function Ul(e){let t=e.pricing,s=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let f=e.min_amount??t?.min_amount??null,u=e.max_amount??t?.max_amount??null;return f!==null&&u!==null?{text:`Buyer chooses (${W(f,s)} \u2013 ${W(u,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,i=t?.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)}`,d=t?.compare_at_amount??null;return{text:o,compareAt:d!==null&&d>i?W(d,s):null}}function Yn({product:e,className:t}){let s=Ul(e);return(0,Ct.jsxs)("div",{className:t,children:[(0,Ct.jsx)("span",{className:Jn,children:s.text}),s.compareAt&&(0,Ct.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function Qn({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,Ct.jsx)(ae,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,Ct.jsxs)(ae,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,Ct.jsx)(ae,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,Ct.jsxs)(ae,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,Ct.jsx)(ae,{variant:"warning",children:"Low stock"}):null}function Xn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function er(e){return e.map(t=>W(t.amount,t.currency)).join(" + ")}function Ki(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 Zi({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,Ct.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=t.available??0;return t.allow_backorder?(0,Ct.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,Ct.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,s)}),(0,Ct.jsx)(ae,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?(0,Ct.jsx)(ae,{variant:"destructive",children:"Out of stock"}):(0,Ct.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,Ct.jsx)("span",{className:"af-tabular-nums",children:s}),s<=$l&&(0,Ct.jsx)(ae,{variant:"warning",children:"Low"})]})}var Q=require("react/jsx-runtime");function mn({title:e,children:t,className:s}){return(0,Q.jsxs)("section",{className:te("af-rounded-lg af-border af-p-4",s),children:[(0,Q.jsx)("h4",{className:Wi,children:e}),(0,Q.jsx)("div",{className:"af-mt-3",children:t})]})}function Ji({src:e,className:t}){let[s,a]=Va.useState(!1);return Va.useEffect(()=>a(!1),[e]),!e||s?(0,Q.jsx)("div",{"aria-hidden":"true",className:te("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,Q.jsx)(tr.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,Q.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>a(!0),className:te("af-object-cover",t)})}function Yi({product:e,showStats:t=!1,onBack:s}){let{api:a}=ne(),[n,i]=Va.useState(null),[o,d]=Va.useState(!0),[f,u]=Va.useState(null),[r,v]=Va.useState(0),[x,b]=Va.useState(0);Va.useEffect(()=>{let m=!1;return d(!0),u(null),a.getProduct(e.id).then(R=>{m||i(R)}).catch(R=>{m||u(R instanceof Error?R:new Error("Failed to load product"))}).finally(()=>{m||d(!1)}),()=>{m=!0}},[a,e.id,r]);let c=n?{...e,...n}:e,l=c.images.length>0?c.images:e.images,y=l[x]??l[0],N=Xn(c),S=t?c.stats:void 0,O=n?.variants??[],M=O.length>1;return(0,Q.jsxs)("div",{children:[(0,Q.jsxs)("div",{className:"af-mb-6",children:[(0,Q.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,Q.jsx)(tr.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,Q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Q.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:c.name}),(0,Q.jsx)(ae,{variant:c.active?"success":"secondary",children:c.active?"Active":"Draft"}),(0,Q.jsx)(Qn,{product:c})]}),(0,Q.jsx)(Yn,{product:c,className:"af-mt-1"}),!c.active&&(0,Q.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,Q.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,Q.jsxs)("div",{className:"af-space-y-2",children:[(0,Q.jsx)(Ji,{src:y,className:"af-h-48 af-w-full af-rounded-md af-border"}),l.length>1&&(0,Q.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map((m,R)=>(0,Q.jsx)("button",{type:"button",onClick:()=>b(R),"aria-label":`Show photo ${R+1} of ${l.length}`,"aria-pressed":R===x,className:te("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",R===x?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,Q.jsx)(Ji,{src:m,className:"af-h-12 af-w-12 af-rounded-md"})},`${m}-${R}`))})]}),(0,Q.jsxs)("div",{className:"af-space-y-6",children:[c.description&&(0,Q.jsx)(mn,{title:"Description",children:(0,Q.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:c.description})}),o?(0,Q.jsxs)(mn,{title:"Variants",children:[(0,Q.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(m=>(0,Q.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,Q.jsx)(se,{className:"af-h-4 af-w-28"}),(0,Q.jsx)(se,{className:"af-h-4 af-w-20"}),(0,Q.jsx)(se,{className:"af-h-4 af-w-16"})]},m))}),(0,Q.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):f?(0,Q.jsx)(ra,{message:"Couldn't load this product's variants.",onRetry:()=>v(m=>m+1)}):M?(0,Q.jsx)(mn,{title:`Variants \xB7 ${O.length}`,children:(0,Q.jsx)("div",{className:"af-overflow-x-auto",children:(0,Q.jsxs)(Ue,{children:[(0,Q.jsx)(Ve,{children:(0,Q.jsxs)(xe,{children:[(0,Q.jsx)(H,{children:"Variant"}),(0,Q.jsx)(H,{children:"SKU"}),(0,Q.jsx)(H,{className:"af-text-right",children:"Price"}),(0,Q.jsx)(H,{children:"Stock"})]})}),(0,Q.jsx)(He,{children:O.map(m=>(0,Q.jsxs)(xe,{children:[(0,Q.jsxs)(z,{className:"af-font-medium",children:[m.title||m.option_values.map(R=>R.value).join(" / ")||"\u2014",!m.active&&(0,Q.jsx)(ae,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,Q.jsx)(z,{className:"af-text-muted-foreground",children:m.sku?(0,Q.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:m.sku}):"\u2014"}),(0,Q.jsxs)(z,{className:"af-whitespace-nowrap af-text-right",children:[(0,Q.jsx)("div",{className:Jn,children:Ki(m)}),m.compare_at_amount!==null&&m.unit_amount!==null&&m.compare_at_amount>m.unit_amount&&(0,Q.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:W(m.compare_at_amount,m.currency)})]}),(0,Q.jsx)(z,{className:"af-text-sm",children:(0,Q.jsx)(Zi,{variant:m})})]},m.id))})]})})}):null,(0,Q.jsx)(mn,{title:"Details",children:(0,Q.jsxs)("dl",{className:"af-space-y-2",children:[(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Delivery"}),(0,Q.jsx)("dd",{className:"af-text-sm",children:N==="Digital download"?c.fulfillment.filename??"Digital download":N??"Nothing to deliver"})]}),c.fulfillment.type==="redirect"&&c.fulfillment.url&&(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Sends buyers to"}),(0,Q.jsx)("dd",{className:"af-break-all af-text-sm",children:c.fulfillment.url})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Shipping address"}),(0,Q.jsx)("dd",{className:"af-text-sm",children:c.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Most one buyer can order"}),(0,Q.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:c.max_quantity})]})]})}),S&&(0,Q.jsx)(mn,{title:"Last 30 days",children:(0,Q.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Units sold"}),(0,Q.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.units_sold})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Orders"}),(0,Q.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.orders})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Gross"}),(0,Q.jsx)("dd",{className:Jn,children:S.gross.length>0?er(S.gross):"\u2014"})]})]})}),(0,Q.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"),Vl={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Hl=["all","active","draft","low_stock","out_of_stock"];function Qi(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t).getTime();return Number.isNaN(s)?0:s}function Xi(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function zl(e){return e.inventory?.out_of_stock??!1}function ql(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Xi(e);case"out_of_stock":return zl(e);default:return!0}}function jl({product:e,showStats:t,onOpen:s}){let a=e.images[0],n=t?e.stats:void 0,i=Xn(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:[a?(0,V.jsx)("img",{src:a,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)(Os.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)(Yn,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,V.jsx)(ae,{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)(Qn,{product:e}),o>1&&(0,V.jsxs)(ae,{variant:"outline",children:[o," variants"]}),i&&(0,V.jsx)(ae,{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 ${er(n.gross)}`:""," ",(0,V.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Gl(){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)(se,{className:"af-w-32"}),(0,V.jsx)(se,{className:"af-w-16"}),(0,V.jsx)(se,{className:"af-h-5 af-w-24"})]})]},e))})}function Ir({refreshKey:e,showStats:t=!1,onBackToWebsite:s,className:a}){let{products:n,isLoading:i,error:o,refetch:d}=hs({includeStats:t,refreshKey:e}),[f,u]=Ha.useState(!1),[r,v]=Ha.useState(null),[x,b]=Ha.useState("all"),[c,l]=Ha.useState(""),[y,N]=Ha.useState("newest"),S=Ha.useMemo(()=>{if(!t)return null;let w=null;for(let F of n)!F.stats||F.stats.units_sold===0||(!w||F.stats.units_sold>(w.stats?.units_sold??0))&&(w=F);return w},[n,t]),O=Ha.useMemo(()=>n.filter(Xi).length,[n]),M=c.trim().toLowerCase(),m=Ha.useMemo(()=>{let F=[...n.filter(X=>ql(X,x)&&(!M||X.name.toLowerCase().includes(M)))];return y==="name"?F.sort((X,q)=>X.name.localeCompare(q.name)):y==="best_selling"?F.sort((X,q)=>(q.stats?.units_sold??0)-(X.stats?.units_sold??0)):F.sort((X,q)=>Qi(q.created_at)-Qi(X.created_at)),F},[n,x,M,y]),R=x!=="all"||!!M,T=()=>{b("all"),l("")},D=i||o!==null&&n.length===0,P=(0,V.jsx)("div",{className:"af-mb-6",children:(0,V.jsx)("div",{className:te("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:D?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(rt,{label:"Products",children:(0,V.jsx)(se,{className:"af-h-6 af-w-10"})}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(rt,{label:"Best seller",children:(0,V.jsx)(se,{className:"af-h-6 af-w-28"})}),(0,V.jsx)(rt,{label:"Low stock",children:(0,V.jsx)(se,{className:"af-h-6 af-w-10"})})]}):(0,V.jsx)(rt,{label:"Active",children:(0,V.jsx)(se,{className:"af-h-6 af-w-10"})})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(rt,{label:"Products",children:n.length}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(rt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:S?`${S.stats?.units_sold??0} sold, last 30 days`:void 0,children:S?(0,V.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:S.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)(rt,{label:"Low stock",children:O})]}):(0,V.jsx)(rt,{label:"Active",children:n.filter(w=>w.active).length})]})})}),A=(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:Hl.map(w=>(0,V.jsx)("button",{type:"button","aria-pressed":x===w,onClick:()=>b(w),className:te("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",x===w?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Vl[w]},w))}),(0,V.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,V.jsx)(Os.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)(Ne,{type:"text",value:c,onChange:w=>l(w.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,V.jsxs)(da,{value:y,onValueChange:w=>N(w),children:[(0,V.jsx)(Xt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,V.jsx)(fa,{})}),(0,V.jsxs)(ea,{children:[(0,V.jsx)(Ye,{value:"newest",children:"Newest"}),(0,V.jsx)(Ye,{value:"name",children:"Name A\u2013Z"}),t&&(0,V.jsx)(Ye,{value:"best_selling",children:"Best selling"})]})]}),R&&(0,V.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:T,children:"Clear filters"})]}),i&&n.length===0?(0,V.jsx)(se,{className:"af-h-4 af-w-28"}):(0,V.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:R?`${m.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${O>0?` \xB7 ${O} low stock`:""}`})]}),U;return r?U=(0,V.jsx)(Yi,{product:r,showStats:t,onBack:()=>{v(null),d()}},r.id):i&&n.length===0?U=(0,V.jsxs)(V.Fragment,{children:[A,(0,V.jsx)(Gl,{}),(0,V.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?U=(0,V.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,V.jsx)(ra,{message:"Couldn't load your products.",onRetry:()=>d()})}):n.length===0?U=(0,V.jsxs)(Ea,{icon:(0,V.jsx)(Os.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."]}):U=(0,V.jsxs)(V.Fragment,{children:[A,o&&(0,V.jsx)("div",{className:"af-mb-4",children:(0,V.jsx)(ra,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>d()})}),m.length===0?(0,V.jsxs)(Ea,{children:["No products match these filters.",(0,V.jsx)("br",{}),(0,V.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:T,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:m.map(w=>(0,V.jsx)(jl,{product:w,showStats:t,onOpen:()=>v(w)},w.id))})]}),(0,V.jsx)(yt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:a,children:f?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(_,{variant:"ghost",onClick:()=>u(!1),children:"Back to products"}),(0,V.jsx)(ms,{})]}):(0,V.jsxs)(V.Fragment,{children:[!r&&(0,V.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,V.jsx)(_,{variant:"outline",onClick:()=>u(!0),children:"Promo codes"})}),!r&&P,U]})})}var Aa=le(require("react"),1),vt=require("lucide-react");var la=le(require("react"),1);function pn({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=ne(),[a,n]=la.useState([]),[i,o]=la.useState(!0),[d,f]=la.useState(null),[u,r]=la.useState(0),[v]=la.useState(e),[x,b]=la.useState(""),c=la.useRef(0),l=la.useCallback(async()=>{let y=++c.current;try{o(!0),f(null);let N={limit:v,offset:u*v};x.trim()&&(N.q=x.trim());let S=await s.getPeople(N);if(y!==c.current)return;n(S.people)}catch(N){if(y!==c.current)return;f(N instanceof Error?N:new Error("Failed to fetch people"))}finally{y===c.current&&o(!1)}},[s,u,v,x,t]);return la.useEffect(()=>{l()},[l]),{people:a,isLoading:i,error:d,page:u,pageSize:v,hasNextPage:a.length===v,hasPreviousPage:u>0,setPage:r,q:x,setQ:y=>{b(y),r(0)},refetch:l}}var za=le(require("react"),1);function gn(e,{refreshKey:t}={}){let{api:s}=ne(),[a,n]=za.useState(null),[i,o]=za.useState(e!==null),[d,f]=za.useState(null),u=za.useRef(0),r=za.useCallback(async()=>{if(e===null){n(null),o(!1),f(null);return}let v=++u.current;try{o(!0),f(null);let x=await s.getPerson(e);if(v!==u.current)return;n(x)}catch(x){if(v!==u.current)return;f(x instanceof Error?x:new Error("Failed to fetch person"))}finally{v===u.current&&o(!1)}},[s,e,t]);return za.useEffect(()=>{r()},[r]),{person:a,isLoading:i,error:d,refetch:r}}var h=require("react/jsx-runtime"),Dr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Wl="af-text-xs af-text-muted-foreground";function Bs(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Lr(e,t){let s=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function Kl(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Zl({value:e,label:t}){let[s,a]=Aa.useState(!1);return Kl()?(0,h.jsxs)(_,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),a(!0),setTimeout(()=>a(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[s?(0,h.jsx)(vt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,h.jsx)(vt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function eo(e){return(0,h.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,h.jsxs)(ae,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,h.jsx)(ae,{variant:"secondary",children:"Contact form"})]})}function to(e){return e.name?e.name:e.email?e.email:(0,h.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Jl=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Yl=40;function Ql(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),a=t.find(([n,i])=>Jl.test(n)&&typeof i=="string"&&i.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=Yl).sort((n,i)=>String(i[1]).trim().length-String(n[1]).trim().length)[0];return a?{message:String(a[1]),rest:t.filter(([n])=>n!==a[0])}:{message:null,rest:t}}function Xl(e){return e.replace(/_/g," ")}function ec(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function tc({data:e}){let{message:t,rest:s}=Ql(e);return t===null&&s.length===0?(0,h.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,h.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,h.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),s.length>0&&(0,h.jsx)("dl",{className:"af-space-y-1",children:s.map(([a,n])=>(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,h.jsx)("dt",{className:te(Wl,"af-w-28 af-shrink-0 af-capitalize"),children:Xl(a)}),(0,h.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:ec(n)})]},a))})]})}function ao({formName:e,createdAt:t,data:s}){return(0,h.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,h.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)(ae,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,h.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,h.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Bs(t)})]}),(0,h.jsx)(tc,{data:s})]})}function ac(e){return e.charged_total??e.amount_total}function sc({email:e,refreshKey:t,onBack:s}){let{person:a,isLoading:n,error:i,refetch:o}=gn(e,{refreshKey:t}),d=Lr(e,a?.submissions[0]?.form_name);return(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-mb-6",children:[(0,h.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,h.jsx)(vt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,h.jsxs)("div",{className:"af-min-w-0",children:[n?(0,h.jsx)(se,{className:"af-h-7 af-w-48"}):(0,h.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:a?.name||e}),(0,h.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,h.jsx)(Zl,{value:e,label:"Copy email address"})]})]}),(0,h.jsx)(_,{asChild:!0,children:(0,h.jsxs)("a",{href:d,children:[(0,h.jsx)(vt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?(0,h.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(f=>(0,h.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,h.jsx)(se,{className:"af-w-40"}),(0,h.jsx)(se,{className:"af-mt-2 af-w-64"})]},f)),(0,h.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!a?(0,h.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,h.jsx)(ra,{message:"Couldn't load this person.",onRetry:()=>o()})}):(0,h.jsxs)("div",{className:"af-space-y-6",children:[a.customer&&(0,h.jsxs)("div",{children:[(0,h.jsx)("h4",{className:te(Dr,"af-mb-3"),children:"Customer"}),(0,h.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[a.customer.name&&(0,h.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,h.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,h.jsx)("dd",{children:a.customer.name})]}),a.customer.phone&&(0,h.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,h.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,h.jsx)("dd",{children:a.customer.phone})]}),(0,h.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,h.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,h.jsx)("dd",{children:Bs(a.customer.created_at)})]})]})]}),a.orders.length>0&&(0,h.jsxs)("div",{children:[(0,h.jsx)("h4",{className:te(Dr,"af-mb-3"),children:"Purchases"}),(0,h.jsx)("div",{className:"af-overflow-x-auto",children:(0,h.jsxs)(Ue,{children:[(0,h.jsx)(Ve,{children:(0,h.jsxs)(xe,{children:[(0,h.jsx)(H,{children:"Order"}),(0,h.jsx)(H,{children:"Date"}),(0,h.jsx)(H,{className:"af-text-right",children:"Total"}),(0,h.jsx)(H,{children:"Status"})]})}),(0,h.jsx)(He,{children:a.orders.map(f=>(0,h.jsxs)(xe,{children:[(0,h.jsx)(z,{className:"af-whitespace-nowrap af-font-medium",children:Za(f)}),(0,h.jsx)(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Bs(f.created_at)}),(0,h.jsx)(z,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:W(ac(f),f.currency)}),(0,h.jsx)(z,{children:(0,h.jsx)(os,{status:f.status})})]},f.id))})]})}),(0,h.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."})]}),a.submissions.length>0&&(0,h.jsxs)("div",{children:[(0,h.jsx)("h4",{className:te(Dr,"af-mb-3"),children:"Messages"}),(0,h.jsx)("div",{className:"af-space-y-3",children:a.submissions.map(f=>(0,h.jsx)(ao,{formName:f.form_name,createdAt:f.created_at,data:f.data},f.id))})]})]})]})}function nc({submissionId:e,onBack:t}){let{api:s}=ne(),[a,n]=Aa.useState(null),[i,o]=Aa.useState(!0),[d,f]=Aa.useState(null),[u,r]=Aa.useState(0);return Aa.useEffect(()=>{let v=!1;return o(!0),f(null),s.getSubmission(e).then(x=>{v||n(x)}).catch(x=>{v||f(x instanceof Error?x:new Error("Failed to load submission"))}).finally(()=>{v||o(!1)}),()=>{v=!0}},[s,e,u]),(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-mb-6",children:[(0,h.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,h.jsx)(vt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,h.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,h.jsx)(se,{className:"af-mt-1 af-h-4 af-w-32"}):a&&(0,h.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Bs(a.metadata.submitted_at)})]}),i?(0,h.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,h.jsx)(se,{className:"af-w-40"}),(0,h.jsx)(se,{className:"af-mt-2 af-w-64"}),(0,h.jsx)(se,{className:"af-mt-2 af-w-52"}),(0,h.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):d||!a?(0,h.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,h.jsx)(ra,{message:"Couldn't load this submission.",onRetry:()=>r(v=>v+1)})}):(0,h.jsxs)("div",{className:"af-space-y-3",children:[(0,h.jsx)(ao,{formName:null,createdAt:a.metadata.submitted_at,data:a.data}),(0,h.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 rc={all:"All",customers:"Customers",leads:"Leads"},ic=["all","customers","leads"];function oc(e,t){return t==="customers"?e.sources.includes("customer"):t==="leads"?e.sources.includes("lead"):!0}function lc({refreshKey:e,onBackToWebsite:t,className:s,maxRows:a,onViewAll:n}){let i=typeof a=="number",{people:o,isLoading:d,error:f,page:u,pageSize:r,hasNextPage:v,hasPreviousPage:x,setPage:b,q:c,setQ:l,refetch:y}=pn({refreshKey:e}),[N,S]=Aa.useState({kind:"list"}),[O,M]=Aa.useState(""),[m,R]=Aa.useState("all"),T=!i||!!n,D=X=>{if(i){n?.();return}X.email?S({kind:"person",email:X.email}):X.submission_id&&S({kind:"submission",submissionId:X.submission_id})},P=()=>{S({kind:"list"}),y()},A=X=>{let q=X.trim();q!==c&&l(q)},U=o.filter(X=>oc(X,m)),w=i?U.slice(0,a):U,F;if(N.kind==="person")F=(0,h.jsx)(sc,{email:N.email,refreshKey:e,onBack:P});else if(N.kind==="submission")F=(0,h.jsx)(nc,{submissionId:N.submissionId,onBack:P});else{let X=(0,h.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.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:ic.map(q=>(0,h.jsx)("button",{type:"button","aria-pressed":m===q,onClick:()=>R(q),className:te("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",m===q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:rc[q]},q))}),(0,h.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,h.jsx)(vt.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,h.jsx)(Ne,{type:"text",value:O,onChange:q=>M(q.target.value),onBlur:()=>A(O),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),A(O))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),c&&(0,h.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{M(""),l("")},children:"Clear search"})]});if(d)F=(0,h.jsxs)("div",{children:[i?null:X,(0,h.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(q=>(0,h.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,h.jsx)(se,{className:"af-h-4 af-w-32"}),(0,h.jsx)(se,{className:"af-h-4 af-w-16"})]}),(0,h.jsx)(se,{className:"af-mt-2 af-h-5 af-w-28"}),(0,h.jsx)(se,{className:"af-mt-2 af-h-3 af-w-56"})]},q))}),(0,h.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,h.jsxs)(Ue,{children:[(0,h.jsx)(Ve,{children:(0,h.jsxs)(xe,{children:[(0,h.jsx)(H,{children:"Person"}),(0,h.jsx)(H,{children:"Came from"}),(0,h.jsx)(H,{children:"Latest message"}),(0,h.jsx)(H,{children:"Last activity"}),(0,h.jsx)(H,{className:"af-w-8"}),(0,h.jsx)(H,{className:"af-w-8"})]})}),(0,h.jsx)(He,{"aria-hidden":"true",children:[0,1,2,3,4].map(q=>(0,h.jsxs)(xe,{children:[(0,h.jsx)(z,{children:(0,h.jsx)(se,{className:"af-h-4 af-w-40"})}),(0,h.jsx)(z,{children:(0,h.jsx)(se,{className:"af-h-5 af-w-24"})}),(0,h.jsx)(z,{children:(0,h.jsx)(se,{className:"af-h-4 af-w-56"})}),(0,h.jsx)(z,{children:(0,h.jsx)(se,{className:"af-h-4 af-w-24"})}),(0,h.jsx)(z,{}),(0,h.jsx)(z,{})]},q))})]})}),(0,h.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(f)F=(0,h.jsxs)("div",{children:[i?null:X,(0,h.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,h.jsx)(ra,{message:"Couldn't load your leads.",onRetry:()=>y()})})]});else if(w.length===0&&u===0){let q=!!c||m!=="all";F=(0,h.jsxs)("div",{children:[q&&X,q?(0,h.jsx)(Ea,{children:c?"Nobody matches that search.":m==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,h.jsx)(As,{icon:vt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)F=(0,h.jsxs)("div",{children:[i?null:X,(0,h.jsx)(Ea,{children:"No more results."}),(0,h.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,h.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>b(u-1),children:[(0,h.jsx)(vt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let q=u*r+1,fe=u*r+o.length;F=(0,h.jsxs)("div",{children:[i?null:X,(0,h.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:w.map((J,ee)=>(0,h.jsxs)("div",{onClick:T?()=>D(J):void 0,className:`af-rounded-md af-border af-p-3${T?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,h.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsx)("button",{type:"button",onClick:Z=>{Z.stopPropagation(),D(J)},disabled:!T,"aria-label":`Open ${J.name||J.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 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${T?" hover:af-underline":""}`,children:to(J)}),J.name&&J.email&&(0,h.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:J.email})]}),(0,h.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,h.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:Bs(J.last_activity_at)}),J.email&&(0,h.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,h.jsx)("a",{href:Lr(J.email),onClick:Z=>Z.stopPropagation(),"aria-label":`Email ${J.email}`,children:(0,h.jsx)(vt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,h.jsx)("div",{className:"af-mt-2",children:eo(J)}),J.latest_message_excerpt&&(0,h.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:J.latest_message_excerpt})]},J.email??J.submission_id??ee))}),(0,h.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,h.jsxs)(Ue,{children:[(0,h.jsx)(Ve,{children:(0,h.jsxs)(xe,{children:[(0,h.jsx)(H,{children:"Person"}),(0,h.jsx)(H,{children:"Came from"}),(0,h.jsx)(H,{children:"Latest message"}),(0,h.jsx)(H,{children:"Last activity"}),(0,h.jsx)(H,{className:"af-w-8",children:(0,h.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,h.jsx)(H,{className:"af-w-8"})]})}),(0,h.jsx)(He,{children:w.map((J,ee)=>(0,h.jsxs)(xe,{onClick:T?()=>D(J):void 0,className:T?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,h.jsxs)(z,{className:"af-max-w-[260px] af-font-medium",children:[(0,h.jsx)("button",{type:"button",onClick:Z=>{Z.stopPropagation(),D(J)},disabled:!T,"aria-label":`Open ${J.name||J.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${T?" hover:af-underline":""}`,children:to(J)}),J.name&&J.email&&(0,h.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:J.email})]}),(0,h.jsx)(z,{children:eo(J)}),(0,h.jsx)(z,{className:"af-max-w-[320px]",children:J.latest_message_excerpt?(0,h.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:J.latest_message_excerpt}):(0,h.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,h.jsx)(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Bs(J.last_activity_at)}),(0,h.jsx)(z,{className:"af-w-8",children:J.email&&(0,h.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,h.jsx)("a",{href:Lr(J.email),onClick:Z=>Z.stopPropagation(),"aria-label":`Email ${J.email}`,children:(0,h.jsx)(vt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,h.jsx)(z,{className:"af-w-8 af-text-right",children:(0,h.jsx)(vt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},J.email??J.submission_id??ee))})]})}),!i&&(0,h.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,h.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:m==="all"?`Showing ${q}-${fe}`:`${w.length} of ${o.length} on this page`}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,h.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>b(u-1),disabled:!x,children:[(0,h.jsx)(vt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,h.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>b(u+1),disabled:!v,children:["Next",(0,h.jsx)(vt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return i?(0,h.jsx)("div",{className:s,children:F}):(0,h.jsx)(yt,{title:"Leads",onBackToWebsite:t,hideBackButton:N.kind!=="list",className:s,children:F})}function vn(e){return(0,h.jsx)(lc,{...e},e.maxRows==null?"full":"compact")}var Ns=require("lucide-react");var Kt=le(require("react"),1);function bn({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=ne(),[a,n]=Kt.useState([]),[i,o]=Kt.useState(0),[d,f]=Kt.useState(!0),[u,r]=Kt.useState(null),[v,x]=Kt.useState(0),[b,c]=Kt.useState(e),[l,y]=Kt.useState(void 0),N=Kt.useRef(0),S=Kt.useCallback(async()=>{let M=++N.current;try{f(!0),r(null);let m={limit:b,offset:v*b};l&&(m.status=l);let R=await s.getSubscriptions(m);if(M!==N.current)return;n(R.subscriptions),o(R.total)}catch(m){if(M!==N.current)return;r(m instanceof Error?m:new Error("Failed to fetch subscriptions"))}finally{M===N.current&&f(!1)}},[s,v,b,l,t]);Kt.useEffect(()=>{S()},[S]);let O=Math.ceil(i/b);return{subscriptions:a,total:i,isLoading:d,error:u,page:v,pageSize:b,hasNextPage:v<O-1,hasPreviousPage:v>0,setPage:x,setPageSize:M=>{c(M),x(0)},status:l,setStatus:M=>{y(M),x(0)},refetch:S}}var $=require("react/jsx-runtime");function so(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function no({sub:e}){return e.status==="canceled"?(0,$.jsx)(ae,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,$.jsx)(ae,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,$.jsx)(ae,{variant:"warning",children:"Scheduled to cancel"}):(0,$.jsx)(ae,{variant:"success",children:"Active"}):(0,$.jsx)(ae,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function cc(e,t){let s=W(t,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function ro({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,$.jsxs)("div",{children:[(0,$.jsx)("div",{className:"af-font-medium af-tabular-nums",children:cc(e,e.current_amount)}),t&&(0,$.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",W(e.plan_amount,e.currency)]})]})}function io(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${so(e.current_period_end)}`:"Ends at period end":e.current_period_end?so(e.current_period_end):"\u2014"}function Or({refreshKey:e,onBackToWebsite:t,className:s}){let{subscriptions:a,total:n,isLoading:i,error:o,page:d,pageSize:f,hasNextPage:u,hasPreviousPage:r,setPage:v,refetch:x}=bn({refreshKey:e}),b;if(i)b=(0,$.jsxs)("div",{children:[(0,$.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(c=>(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)(se,{className:"af-h-4 af-w-40"}),(0,$.jsx)(se,{className:"af-h-4 af-w-20"})]}),(0,$.jsx)(se,{className:"af-mt-2 af-h-3 af-w-32"}),(0,$.jsx)(se,{className:"af-mt-2 af-h-5 af-w-24"})]},c))}),(0,$.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,$.jsxs)(Ue,{children:[(0,$.jsx)(Ve,{children:(0,$.jsxs)(xe,{children:[(0,$.jsx)(H,{children:"Subscriber"}),(0,$.jsx)(H,{children:"Plan"}),(0,$.jsx)(H,{className:"af-text-right",children:"Amount"}),(0,$.jsx)(H,{children:"Renews"}),(0,$.jsx)(H,{children:"Status"})]})}),(0,$.jsx)(He,{"aria-hidden":"true",children:[0,1,2,3,4].map(c=>(0,$.jsxs)(xe,{children:[(0,$.jsx)(z,{children:(0,$.jsx)(se,{className:"af-h-4 af-w-44"})}),(0,$.jsx)(z,{children:(0,$.jsx)(se,{className:"af-h-4 af-w-32"})}),(0,$.jsx)(z,{className:"af-text-right",children:(0,$.jsx)(se,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,$.jsx)(z,{children:(0,$.jsx)(se,{className:"af-h-4 af-w-24"})}),(0,$.jsx)(z,{children:(0,$.jsx)(se,{className:"af-h-5 af-w-20"})})]},c))})]})}),(0,$.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)b=(0,$.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,$.jsx)(ra,{message:"Couldn't load your subscriptions.",onRetry:()=>x()})});else if(a.length===0&&d===0)b=(0,$.jsx)(Ea,{icon:(0,$.jsx)(Ns.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(a.length===0)b=(0,$.jsxs)("div",{children:[(0,$.jsx)(Ea,{children:"No more results."}),(0,$.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,$.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>v(d-1),children:[(0,$.jsx)(Ns.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let c=d*f+1,l=d*f+a.length;b=(0,$.jsxs)("div",{children:[(0,$.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:a.map(y=>(0,$.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,$.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,$.jsxs)("div",{className:"af-min-w-0",children:[(0,$.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:y.customer_email||(0,$.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,$.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:y.plan_title||"Untitled plan"})]}),(0,$.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,$.jsx)(ro,{sub:y})})]}),(0,$.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,$.jsx)(no,{sub:y}),y.is_test&&(0,$.jsx)(ae,{variant:"outline",children:"Test"}),(0,$.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:io(y)})]}),(0,$.jsx)(Da,{deliveries:y.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},y.id))}),(0,$.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,$.jsxs)(Ue,{children:[(0,$.jsx)(Ve,{children:(0,$.jsxs)(xe,{children:[(0,$.jsx)(H,{children:"Subscriber"}),(0,$.jsx)(H,{children:"Plan"}),(0,$.jsx)(H,{className:"af-text-right",children:"Amount"}),(0,$.jsx)(H,{children:"Renews"}),(0,$.jsx)(H,{children:"Status"})]})}),(0,$.jsx)(He,{children:a.map(y=>(0,$.jsxs)(xe,{children:[(0,$.jsx)(z,{className:"af-max-w-[240px]",children:(0,$.jsx)("div",{className:"af-truncate af-font-medium",children:y.customer_email||(0,$.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,$.jsx)(z,{className:"af-max-w-[220px]",children:(0,$.jsx)("div",{className:"af-truncate",children:y.plan_title||(0,$.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,$.jsx)(z,{className:"af-whitespace-nowrap af-text-right",children:(0,$.jsx)(ro,{sub:y})}),(0,$.jsx)(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:io(y)}),(0,$.jsxs)(z,{children:[(0,$.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,$.jsx)(no,{sub:y}),y.is_test&&(0,$.jsx)(ae,{variant:"outline",children:"Test"})]}),(0,$.jsx)(Da,{deliveries:y.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},y.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,$.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${c}-${l} of ${n}`}),(0,$.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,$.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>v(d-1),disabled:!r,children:[(0,$.jsx)(Ns.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,$.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>v(d+1),disabled:!u,children:["Next",(0,$.jsx)(Ns.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,$.jsx)(yt,{title:"Subscriptions",onBackToWebsite:t,className:s,children:b})}var Br=le(require("react"),1);var dt=require("react/jsx-runtime");function Fr({refreshKey:e,initialInvoiceId:t,onBackToWebsite:s,onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:d,isLoading:f,error:u,refetch:r}=bs({refreshKey:e,initialPageSize:1,includeAggregates:!0}),v=xs({refreshKey:e}),[x,b]=Br.useState(!1),[c,l]=Br.useState(null),y=(0,dt.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:u||!f&&!d?(0,dt.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,dt.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):f||!d?(0,dt.jsxs)(dt.Fragment,{children:[(0,dt.jsx)(rt,{label:"Outstanding",children:(0,dt.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,dt.jsx)(rt,{label:"Overdue",children:(0,dt.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,dt.jsx)(rt,{label:"Paid this month",children:(0,dt.jsx)(se,{className:"af-h-6 af-w-24"})})]}):(0,dt.jsxs)(dt.Fragment,{children:[(0,dt.jsx)(rt,{label:"Outstanding",detail:`${d.outstanding.count} open`,children:W(d.outstanding.amount,d.currency)}),(0,dt.jsx)(rt,{label:"Overdue",detail:d.overdue.count===0?"Nothing overdue":`${d.overdue.count} overdue`,valueClassName:d.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:W(d.overdue.amount,d.currency)}),(0,dt.jsx)(rt,{label:"Paid this month",detail:`${d.paid_this_month.count} paid`,children:W(d.paid_this_month.amount,d.currency)})]})});return(0,dt.jsxs)(yt,{title:"Invoices",onBackToWebsite:s,hideBackButton:x,className:o,children:[y,!x&&(0,dt.jsx)(ys,{retainers:v.retainers,isLoading:v.isLoading,error:v.error,onRetry:()=>void v.refetch(),activeRetainerId:c?.id??null,onShowCycles:N=>l(S=>S?.id===N.id?null:N),total:v.total,endedTotal:v.endedTotal,isLoadingMore:v.isLoadingMore,onLoadMore:()=>void v.loadMore(),includeEnded:v.includeEnded,onIncludeEndedChange:v.setIncludeEnded}),(0,dt.jsx)(Qa,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:b,onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:c?{id:c.id,label:`${c.customer_name??c.customer_email??"Recurring invoices"} \u2014 ${c.description}`}:null,onClearRetainerFilter:()=>l(null)})]})}var _t=le(require("react"),1);var uc=2e3,Dt=()=>({data:null,error:null,isLoading:!0});function Ss(e,{refreshKey:t,breakdowns:s=[],filters:a=[]}={}){let{api:n}=ne(),[i,o]=_t.useState(Dt),[d,f]=_t.useState(Dt),[u,r]=_t.useState(Dt),[v,x]=_t.useState(Dt),[b,c]=_t.useState(Dt),l=Z=>Object.fromEntries(Z.map(oe=>[oe,Dt()])),[y,N]=_t.useState(()=>l(s)),S=_t.useRef(0),O=_t.useRef(0),M=_t.useRef("idle"),m=s.join(","),R=as()??"",T=JSON.stringify(a),D=`${e}:${m}:${T}:${R}`,[P,A]=_t.useState({api:n,fetchIdentity:D});(P.api!==n||P.fetchIdentity!==D)&&(A({api:n,fetchIdentity:D}),S.current+=1,o(Dt),f(Dt),r(Dt),x(Dt),N(l(m?m.split(","):[])));let U=`${e}:${String(t??"")}:${R}`,[w,F]=_t.useState({api:n,conversionsIdentity:U});(w.api!==n||w.conversionsIdentity!==U)&&(F({api:n,conversionsIdentity:U}),O.current+=1,M.current="idle",c(Dt));let X=_t.useCallback(async Z=>{let oe=++S.current,Y=m?m.split(","):[];o(Dt),f(Dt),r(Dt),x(Dt),N(Object.fromEntries(Y.map(k=>[k,Dt()])));let Pe=M.current!=="pending"&&(Z?.force===!0||M.current==="idle"),Xe=(k,B)=>B.then(L=>{oe===S.current&&k({data:L,error:null,isLoading:!1})},L=>{oe===S.current&&k({data:null,error:L instanceof Error?L:new Error("Failed to fetch report"),isLoading:!1})}),lt=n.getAnalyticsStatus(),Ae=Xe(o,lt),Ge=Symbol("status-timeout"),at,Ce=await Promise.race([lt.then(k=>k,()=>null),new Promise(k=>{at=setTimeout(()=>k(Ge),uc)})]);if(clearTimeout(at),oe!==S.current)return;if(Ce===Ge&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Ce!==null&&Ce!==Ge&&(Ce.collecting!==!0||Ce.first_seen===null&&!Ce.first_seen_unavailable||Ce.first_seen!==null&&Ce.first_seen_in_reports===!1)){let k={data:null,error:null,isLoading:!1};f(k),r(k),x(k),N(Object.fromEntries(Y.map(B=>[B,{...k}]))),Pe&&(c(k),M.current="done"),await Ae;return}await Promise.all([Ce===Ge?Promise.resolve():Ae,Xe(f,n.getAnalyticsSummary(e,a)),Xe(r,n.getAnalyticsTimeseries(e,a)),Xe(x,n.getAnalyticsChannels(e,a)),Pe?(()=>{M.current="pending";let k=++O.current;return c(Dt),n.getAnalyticsConversions(e).then(B=>{k===O.current&&(c({data:B,error:null,isLoading:!1}),M.current="done")},B=>{k===O.current&&(c({data:null,error:B instanceof Error?B:new Error("Failed to fetch report"),isLoading:!1}),M.current="done")})})():Promise.resolve(),...Y.map(k=>n.getAnalyticsBreakdown(k,e,a).then(B=>{oe===S.current&&N(L=>({...L,[k]:{data:B,error:null,isLoading:!1}}))},B=>{oe===S.current&&N(L=>({...L,[k]:{data:null,error:B instanceof Error?B:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,m,T,U,R]),q=_t.useCallback(async()=>{let Z=S.current;try{let oe=await n.getAnalyticsStatus();if(Z!==S.current)return;o({data:oe,error:null,isLoading:!1})}catch(oe){if(Z!==S.current)return;o(Y=>({data:Y.data,error:oe instanceof Error?oe:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),fe=_t.useCallback(()=>X({force:!0}),[X]);_t.useEffect(()=>{X()},[X,t]);let J=i.isLoading||d.isLoading||u.isLoading||v.isLoading||b.isLoading||Object.values(y).some(Z=>Z.isLoading),ee=[u,d,v,b,...Object.values(y)].map(Z=>Z.data?.status==="ok"?Z.data.timezone:void 0).find(Z=>Z!==void 0);return{status:i,summary:d,timeseries:u,channels:v,conversions:b,breakdowns:y,reportedZone:ee,isLoading:J,refetch:fe,refetchStatus:q}}var Rt=le(require("react"),1);var ar=3e4,sr=3;function yn(e={}){let t="collecting"in e,{collecting:s,statusFailed:a=!1,identity:n}=e,{api:i}=ne(),[o,d]=Rt.useState(null),[f,u]=Rt.useState(null),[r,v]=Rt.useState(!1),[x,b]=Rt.useState(null),[c,l]=Rt.useState(!1),[y,N]=Rt.useState(!0),[S,O]=Rt.useState(0),M=Rt.useRef(0),m=Rt.useRef(0),R=Rt.useRef(void 0);s!==void 0&&(R.current=s);let T=t?R.current===!0||R.current===void 0&&a:!0,[D,P]=Rt.useState({api:i,identity:n}),A=n!==void 0&&n!==D.identity;(D.api!==i||A)&&(R.current=void 0,P({api:i,identity:n}),m.current+=1,M.current=0,d(null),u(null),v(!1),b(null),l(!1),N(!0),O(0));let U=Rt.useRef(()=>{}),w=Rt.useRef(null),F=Rt.useCallback(async()=>{if(w.current!==null&&w.current===m.current)return;let X=++m.current;w.current=X;try{let q=await i.getAnalyticsRealtime();if(X!==m.current)return;if(q.status==="unreachable"){l(!0),v(!0),N(!1),O(fe=>fe+1);return}M.current=0,l(!1),d(q.data.current_visitors),u(q.as_of),v(!1),b(null),N(!1),O(fe=>fe+1)}catch(q){if(X!==m.current)return;M.current+=1,N(!1),O(fe=>fe+1),v(!0),M.current>=sr&&b(q instanceof Error?q:new Error("Realtime unavailable"))}finally{w.current===X&&(w.current=null)}},[i]);return U.current=()=>void F(),Rt.useEffect(()=>{let X,q=()=>{X===void 0&&(X=setInterval(()=>U.current(),ar))},fe=()=>{X!==void 0&&(clearInterval(X),X=void 0)},J=()=>{typeof document<"u"&&document.hidden?fe():(U.current(),q())};return T?((typeof document>"u"||!document.hidden)&&(U.current(),q()),document?.addEventListener("visibilitychange",J),()=>{fe(),document?.removeEventListener("visibilitychange",J),m.current+=1}):()=>{document?.removeEventListener("visibilitychange",J)}},[D.api,D.identity,T]),{currentVisitors:o,asOf:f,isStale:r,error:x,isUnreachable:c,isInitialLoad:y,polls:S}}var ot=le(require("react"),1);var oo=le(require("react"),1);var _s=require("react/jsx-runtime");function dc(){try{let e=Intl.supportedValuesOf?.("timeZone");if(e&&e.length>0)return e.includes("UTC")?e:["UTC",...e]}catch{}return["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Madrid","Africa/Johannesburg","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Tokyo","Australia/Sydney"]}function Mr({value:e,chosen:t,onChange:s}){let a=Us(),n=t===null&&a!==null&&e===a,i=oo.useMemo(()=>{let o=dc();return o.includes(e)?o:[e,...o]},[e]);return(0,_s.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,_s.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,_s.jsxs)("select",{value:n?"":e,onChange:o=>s(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[(0,_s.jsx)("option",{value:"",children:a?`${a.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),i.map(o=>(0,_s.jsx)("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var nr=(e,{published:t}={})=>{let s=t===!1,a=e!=null&&(!e.collecting||s&&e.first_seen===null&&!e.first_seen_unavailable),n=!a&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,i=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=n||i;return{notCollecting:a,awaitingFirstVisit:n,firstVisitTooRecent:i,holdingForFirstData:o,nothingToReport:a||o}};var hn=le(require("react"),1),fc=3e4;function rr({status:e,holdingForFirstData:t,refetchStatus:s,refetch:a}){hn.useEffect(()=>{if(!t)return;let i,o=()=>{i===void 0&&(i=setInterval(()=>void s(),fc))},d=()=>{i!==void 0&&(clearInterval(i),i=void 0)},f=()=>{typeof document<"u"&&document.hidden?d():(s(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",f),()=>{d(),document?.removeEventListener("visibilitychange",f)}},[t,s]);let n=hn.useRef(void 0);hn.useEffect(()=>{if(!e){n.current=void 0;return}let i=n.current;n.current=t,i===!0&&!t&&a()},[e,t,a])}var Rs=le(require("react"),1);var mc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Vt(e){let t=Math.abs(e);if(t<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[a,n]of s)if(t>=a){let i=e/a,o=Math.abs(i)<10?Math.round(i*10)/10:Math.round(i);return Math.abs(o)>=1e3&&a!==1e9?Vt(o*a):`${o}${n}`}return String(e)}function Fs(e){return`${(e*100).toFixed(1)}%`}function xn(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function co(e){let t=Math.max(0,Math.round(e));return t>=3600&&t%3600===0?`${t/3600}h`:t>=60&&t%60===0?`${t/60}m`:xn(t)}function uo(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function fo(e,t){if(!(!Number.isFinite(e)||e<=0))for(let s of t){let a=Math.ceil(e/s);if(a<=5)return Array.from({length:a+1},(n,i)=>Number((i*s).toPrecision(12)))}}function wn(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function mo(e){let t=new Date(e);return Number.isNaN(t.getTime())?"as of an unknown time":`as of ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function $r(e){let t=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${mc[t-1]} ${s}`}function lo(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function pc(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function po(e,t,s="UTC"){let a=new Map(t.map(o=>[o.date,o])),n=[],i=lo(e.to,s);for(let o=lo(e.from,s);o<i;o=pc(o))n.push(a.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function go(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=new Date(`${e}T00:00:00Z`);if(Number.isNaN(a.getTime()))return e;let n=String(a.getUTCDate()).padStart(2,"0");return`${t[a.getUTCDay()]}, ${n} ${s[a.getUTCMonth()]}`}var ca=require("react/jsx-runtime");function vo({what:e="This report",onRetry:t,collecting:s}){return(0,ca.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,ca.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,ca.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.`}),t?(0,ca.jsx)("button",{type:"button",onClick:t,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 ir({what:e="No data"}){return(0,ca.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 Xa({sourced:e,error:t,isLoading:s,what:a,onRetry:n,collecting:i,children:o}){return s?(0,ca.jsx)("div",{role:"status","aria-label":`Loading ${a}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,ca.jsx)(vo,{what:a,onRetry:n,collecting:i}):!e||e.status==="unreachable"?(0,ca.jsx)(vo,{what:a,onRetry:n,collecting:i}):(0,ca.jsx)(ca.Fragment,{children:o(e.data)})}var Qe=require("react/jsx-runtime");function Ur({rows:e,dimension:t,metric:s,metricLabel:a,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:d,maxRows:f=9}){let[u,r]=Rs.useState(!1);if(e.length===0)return(0,Qe.jsx)(ir,{what:i});let v=e.reduce((c,l)=>Math.max(c,Number(l[s]??0)),0)||1,x=Math.max(0,e.length-f),b=u?e:e.slice(0,f);return(0,Qe.jsxs)(Qe.Fragment,{children:[(0,Qe.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Qe.jsx)("thead",{children:(0,Qe.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Qe.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,Qe.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:a})]})}),(0,Qe.jsx)("tbody",{children:b.map((c,l)=>{let y=Number(c[s]??0),N=c[t]??null,S=wn(N),O=n?c[n]:null,M=N!==null&&(d?d(N,O):!0);return(0,Qe.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,Qe.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,Qe.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,y/v*100)}%`}}),N!==null&&o&&M?(0,Qe.jsx)("button",{type:"button",onClick:()=>o(N,O),title:`Filter by ${S}`,"aria-label":`Filter by ${S}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:S}):(0,Qe.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:S}),O?(0,Qe.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:O}):null]}),(0,Qe.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(y)})]},`${S}-${O??""}-${l}`)})})]}),x>0?(0,Qe.jsx)("button",{type:"button",onClick:()=>r(c=>!c),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:u?"Show fewer":`Show all ${e.length}`}):null]})}function Nn({title:e,tabs:t,defaultTabId:s,headerRight:a}){let[n,i]=Rs.useState(s),o=t.find(b=>b.id===n)??t[0],d=Rs.useId(),f=b=>`${d}-tab-${b}`,u=b=>`${d}-panel-${b}`,r=Rs.useRef(null),v=(b,c)=>{b.preventDefault();let l=(c+t.length)%t.length;i(t[l].id),r.current?.querySelectorAll('[role="tab"]')?.[l]?.focus()};return(0,Qe.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,Qe.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,Qe.jsx)("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:b=>{let c=t.findIndex(l=>l.id===n);b.key==="ArrowRight"&&v(b,c+1),b.key==="ArrowLeft"&&v(b,c-1),b.key==="Home"&&v(b,0),b.key==="End"&&v(b,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(b=>(0,Qe.jsx)("button",{id:f(b.id),role:"tab",type:"button","aria-selected":b.id===n,"aria-controls":u(b.id),tabIndex:b.id===n?0:-1,onClick:()=>i(b.id),className:b.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:b.label},b.id))}),a]}),o?(0,Qe.jsx)("div",{id:u(o.id),role:"tabpanel","aria-labelledby":f(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var Zt=le(require("react"),1),us=le(require("@radix-ui/react-popover"),1);var Ps=3,Cs=100;var Le=require("react/jsx-runtime"),Sn={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"},gc=Object.keys(Sn);function bo(e){let t=Sn[e.dimension],s=e.operator==="is_not"?"is not":"is",a=e.values.map(n=>wn(n)).join(" or ");return`${t} ${s} ${a}`}function Vr(e,t){let s=e.findIndex(a=>a.dimension===t.dimension&&(a.operator??"is")===(t.operator??"is"));if(s>=0){let a=[...new Set([...e[s].values,...t.values])];return a.length>100||a.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:a}:n)}return t.values.length>100||e.length>=3?e:[...e,t]}function vc(e,t){let s={};for(let[a,n]of Object.entries(t)){let i=e.get(a)??new Set;for(let o of n)i.add(o);e.set(a,i),s[a]=[...i]}return s}function yo(e,t){let s=e.findIndex(a=>a.dimension===t.dimension&&(a.operator??"is")===(t.operator??"is"));return s>=0?e.map((a,n)=>n===s?t:a):t.values.length>100||e.length>=3?e:[...e,t]}function bc(e){return{dimension:e,operator:"is",search:"",picked:[]}}function ho(e,t,s,a={}){if(e.api!==t.api||e.period!==t.period)return e.api=t.api,e.period=t.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=vc(e.byDimension,s);for(let[i,o]of Object.entries(a)){let d=e.foldsByLabel.get(i)??new Set;for(let f of o)d.add(f);e.foldsByLabel.set(i,d)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function xo(e){let{filters:t,onChange:s}=e,a=t.length>=3;return Zt.useEffect(()=>{if(t.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)},[t.length,s]),(0,Le.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,i)=>(0,Le.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,Le.jsx)("span",{className:"af-text-foreground",children:bo(n)}),(0,Le.jsx)("button",{type:"button","aria-label":`Remove filter ${bo(n)}`,onClick:()=>s(t.filter((o,d)=>d!==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,Le.jsx)(yc,{...e,disabled:a}),t.length>0?(0,Le.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 yc({filters:e,onChange:t,suggestions:s,resetKey:a,disabled:n,expandValues:i}){let[o,d]=Zt.useState(!1),f=Zt.useRef(null),[u,r]=Zt.useState(null);Zt.useEffect(()=>{r(f.current?.closest(".aifeatures-admin")??null)},[]);let[v,x]=Zt.useState(null),[b,c]=Zt.useState("is"),[l,y]=Zt.useState(""),[N,S]=Zt.useState([]);Zt.useEffect(()=>{o||(x(null),c("is"),y(""),S([]))},[o]);let O=Zt.useRef(a);O.current!==a&&(O.current=a,o&&d(!1),v!==null&&x(null),N.length>0&&S([]),l!==""&&y(""),b!=="is"&&c("is"));let M=A=>{let U=bc(A);x(U.dimension),S(U.picked),y(U.search),c(U.operator)},R=(v?s[v]??[]:[]).filter(A=>A.toLowerCase().includes(l.trim().toLowerCase())),T=v===null||N.length===0?null:Vr(e,{dimension:v,operator:b,values:i?i(v,N):N}),D=T!==null&&T!==e,P=()=>{let A=T;!A||A===e||(t(A),d(!1))};return(0,Le.jsxs)(us.Root,{open:o,onOpenChange:d,children:[(0,Le.jsx)(us.Trigger,{asChild:!0,children:(0,Le.jsx)("button",{ref:f,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,Le.jsx)(us.Portal,{container:u,children:(0,Le.jsx)(us.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:v===null?(0,Le.jsxs)("div",{children:[(0,Le.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Le.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:gc.filter(A=>s[A]!==void 0).map(A=>{let U=s[A]?.length??0,w=!e.some(F=>F.dimension===A)&&e.length>=3;return(0,Le.jsxs)("button",{type:"button",onClick:()=>M(A),disabled:U===0||w,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,Le.jsx)("span",{children:Sn[A]}),(0,Le.jsx)("span",{className:"af-text-muted-foreground",children:U===0?"no data":w?"no room":U})]},A)})})]}):(0,Le.jsxs)("div",{children:[(0,Le.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Le.jsx)("button",{type:"button",onClick:()=>M(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Le.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Sn[v]}),(0,Le.jsxs)("select",{"aria-label":"Operator",value:b,onChange:A=>c(A.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,Le.jsx)("option",{value:"is",children:"is"}),(0,Le.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Le.jsx)("input",{type:"text",value:l,onChange:A=>y(A.target.value),placeholder:"Search\u2026","aria-label":`Search ${Sn[v]}`,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,Le.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:R.length===0?(0,Le.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",l,"\u201D."]}):R.map(A=>(0,Le.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,Le.jsx)("input",{type:"checkbox",checked:N.includes(A),disabled:!N.includes(A)&&N.length>=100,onChange:U=>S(w=>U.target.checked?[...w,A]:w.filter(F=>F!==A))}),(0,Le.jsx)("span",{className:"af-break-all",children:wn(A)})]},A))}),(0,Le.jsx)("button",{type:"button",onClick:P,disabled:!D,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 it=require("react/jsx-runtime"),hc=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Vt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Vt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Vt,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:Fs,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:xn,chart:"visit_duration_seconds"}];function xc({current:e,previous:t,downIsGood:s}){if(t===0)return null;let a=(e-t)/t;if(Math.abs(a)<5e-4)return null;let n=a>0,i=s?!n:n,o=`${n?"+":""}${(a*100).toFixed(1)}%`;return(0,it.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 wo({summary:e,selected:t,onSelect:s}){return(0,it.jsx)("div",{className:"af-@container",children:(0,it.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:hc.map(a=>{let n=a.chart===t,i=s!==void 0,o=(0,it.jsxs)(it.Fragment,{children:[(0,it.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:a.label}),(0,it.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,it.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:a.format(a.get(e.current))}),e.previous?(0,it.jsx)(xc,{current:a.get(e.current),previous:a.get(e.previous),downIsGood:a.downIsGood}):null]})]});return i?(0,it.jsx)("button",{type:"button","aria-pressed":n,onClick:()=>s(a.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},a.key):(0,it.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},a.key)})})})}function Hr({currentVisitors:e,asOf:t,isStale:s,isUnreachable:a,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!a)return(0,it.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,it.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,it.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(a||e===null)return(0,it.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?mo(t):"freshness unknown",d=i?" across the whole site, not the current filter,":"",f=s?`${e} current visitors${d} ${o} (not updating)`:`${e} current visitors${d} ${o}`;return(0,it.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:f,children:[(0,it.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,it.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,it.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),(0,it.jsx)("span",{className:"af-sr-only",children:f})]})}var No=le(require("react"),1),So=require("lucide-react");var Me=require("react/jsx-runtime");function or(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function lr({rows:e,denominator:t,windowPrecedesCollection:s=!1,coverageUnknown:a=!1,emptyCopy:n="No conversions in this period",maxRows:i=9,primaryConversion:o}){let[d,f]=No.useState(!1),u=e.filter(y=>!y.implicit||y.visitors>0||y.events>0||or(y,o)),r=s?(0,Me.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This period starts before we began collecting for this site, so these counts cover less time than the dates suggest."}):a?(0,Me.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null;if(u.length===0)return(0,Me.jsxs)(Me.Fragment,{children:[(0,Me.jsx)(ir,{what:n}),r]});let v=u.slice(0,i),x=o?u.find(y=>or(y,o)):void 0,b=x&&!v.includes(x)?u.filter(y=>v.includes(y)||y===x).slice(0,Math.max(0,i-1)).concat(x):v,c=d?e:b,l=Math.max(0,e.length-b.length);return(0,Me.jsxs)(Me.Fragment,{children:[(0,Me.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Me.jsx)("thead",{children:(0,Me.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Me.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,Me.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,Me.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,Me.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,Me.jsx)("tbody",{children:c.map((y,N)=>(0,Me.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":or(y,o)?"true":void 0,children:[(0,Me.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:or(y,o)?(0,Me.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,Me.jsx)(So.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,Me.jsx)("span",{className:"af-font-medium af-text-foreground",children:y.goal}),(0,Me.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):y.goal}),(0,Me.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(y.visitors)}),(0,Me.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(y.events)}),(0,Me.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:y.conversion_rate===null?(0,Me.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Fs(y.conversion_rate)})]},`${y.goal}-${N}`))})]}),l>0?(0,Me.jsx)("button",{type:"button",onClick:()=>f(y=>!y),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:d?"Show fewer":`Show all ${e.length} goals`}):null,(0,Me.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Vt(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),r]})}var Jt=require("recharts");var ft=require("react/jsx-runtime"),cr={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},qr={visitors:Vt,visits:Vt,pageviews:Vt,views_per_visit:e=>e.toFixed(2),bounce_rate:Fs,visit_duration_seconds:xn},wc=31,Nc=new Set(["visitors","visits","pageviews"]),Sc={...qr,bounce_rate:uo,visit_duration_seconds:co},zr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],_c=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Rc=[.01,.02,.05,.1,.2,.25,.5,1],Pc=[.25,.5,1,2,5,10,25,50],Cc={visitors:zr,visits:zr,pageviews:zr,views_per_visit:Pc,bounce_rate:Rc,visit_duration_seconds:_c};function Tc({active:e,payload:t,label:s,metric:a}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return(0,ft.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,ft.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:cr[a]}),(0,ft.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,ft.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,ft.jsx)("span",{className:"af-text-muted-foreground",children:go(String(s))}),(0,ft.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:qr[a](Number(n[a]??0))})]})]})}function ur({rows:e,window:t,metric:s,timeZone:a="UTC",height:n=260}){let i=po(t,e,a),o=qr[s],d=Sc[s],f=fo(i.reduce((r,v)=>Math.max(r,Number(v[s]??0)),0),Cc[s]),u=`${cr[s]} by day: ${i.map(r=>`${$r(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return(0,ft.jsxs)("figure",{"aria-label":`${cr[s]} over time`,className:"af-m-0",children:[(0,ft.jsx)(Jt.ResponsiveContainer,{width:"100%",height:n,children:(0,ft.jsxs)(Jt.AreaChart,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,ft.jsx)("defs",{children:(0,ft.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,ft.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,ft.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,ft.jsx)(Jt.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,ft.jsx)(Jt.XAxis,{dataKey:"date",tickFormatter:$r,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,ft.jsx)(Jt.YAxis,{allowDecimals:!Nc.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...f?{ticks:f,domain:[0,f[f.length-1]]}:{},tickFormatter:r=>d(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,ft.jsx)(Jt.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,ft.jsx)(Tc,{metric:s})}),(0,ft.jsx)(Jt.Area,{type:"linear",dataKey:s,name:cr[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:i.length<=wc?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,ft.jsx)("figcaption",{className:"af-sr-only",children:u})]})}var re=require("react/jsx-runtime"),kc="2026-08-13",Ec=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Ac=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function _o({filters:e,onFiltersChange:t,refreshKey:s,onBackToWebsite:a,primaryConversion:n,className:i,published:o,lastPublishedAt:d}){let[f,u]=ot.useState(30),[r,v]=ot.useState(()=>pr()),x=e!==void 0&&t!==void 0,[b,c]=ot.useState(e??[]),{api:l}=ne(),[y,N]=ot.useState(l);y!==l&&(N(l),!x&&b.length>0&&c([]));let S=x?e:b,O=ot.useCallback(L=>{t&&t(L),x||c(L)},[t,x]),M=ot.useCallback((L,pe,he)=>{let Ee=Array.isArray(pe)?pe:[pe];if(Ee.length===0)return null;let Oe=Vr(S,{dimension:L,operator:"is",values:Ee});if(he&&(!he.value||(Oe=yo(Oe,{dimension:he.dimension,operator:"is",values:[he.value]}),!Oe.find(Ke=>Ke.dimension===he.dimension&&Ke.operator!=="is_not")?.values.includes(he.value))))return null;let st=Oe.find(ze=>ze.dimension===L&&ze.operator!=="is_not");return Ee.every(ze=>st?.values.includes(ze))?JSON.stringify(Oe)===JSON.stringify(S)?null:Oe:null},[S]),m=ot.useCallback((L,pe,he)=>M(L,pe,he)!==null,[M]),R=ot.useCallback((L,pe,he)=>{let Ee=M(L,pe,he);Ee&&O(Ee)},[M,O]),[T,D]=ot.useState("visitors"),P=Ss(f,{refreshKey:s,breakdowns:Ac,filters:S}),A=P.status.data,U=P.reportedZone??A?.timezone,w=U??r??Us()??"UTC",{notCollecting:F,awaitingFirstVisit:X,firstVisitTooRecent:q,holdingForFirstData:fe}=nr(A,{published:o}),J=o===!1,ee=yn({collecting:X||F?!1:A?.collecting,statusFailed:P.status.error!=null,identity:A?.analytics_id}),Z=ot.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),oe=ot.useMemo(()=>{let L=P.breakdowns.sources?.data,pe={};if(!L||L.status!=="ok")return pe;for(let he of L.data){let Ee=he.source,Oe=he.sources;typeof Ee=="string"&&Array.isArray(Oe)&&Oe.length>0&&(pe[Ee]=Oe)}return pe},[P.breakdowns.sources?.data]),Y=ot.useMemo(()=>{let L=(Ee,Oe)=>{let st=P.breakdowns[Ee]?.data;return!st||st.status!=="ok"?[]:[...new Set(st.data.map(ze=>ze[Oe]).filter(ze=>typeof ze=="string"&&ze!==""))]};return{channel:P.channels.data?.status==="ok"?[...new Set(P.channels.data.data.map(Ee=>Ee.channel))]:[],source:L("sources","source"),campaign:L("utm/campaign","campaign"),page:L("pages","pathname"),entry_page:L("entry-pages","pathname"),exit_page:L("exit-pages","pathname"),country:L("countries","country"),browser:L("browsers","browser"),os:L("operating-systems","os"),device:L("devices","device")}},[P.breakdowns,P.channels.data]),[Pe,Xe]=ot.useState({}),lt=JSON.stringify(Y),[Ae,Ge]=ot.useState(new Map),at=JSON.stringify(oe);ot.useEffect(()=>{let{suggestions:L,folds:pe}=ho(Z.current,{api:l,period:f},JSON.parse(lt),JSON.parse(at));Xe(L),Ge(pe)},[lt,at,l,f]);let Ce=ot.useCallback((L,pe)=>L!=="source"?pe:[...new Set(pe.flatMap(he=>{let Ee=[...Ae.get(he)??[],...oe[he]??[]];return Ee.length>0?Ee:[he]}))],[Ae,oe]),Et=ot.useMemo(()=>{let L=P.conversions.error;return L instanceof It&&L.details?.code==="goals_exceed_report_budget"?L.message:null},[P.conversions.error]),k=ot.useMemo(()=>{let L=[P.summary,P.timeseries,P.channels,...Object.values(P.breakdowns)];for(let pe of L){let he=pe?.error;if(he instanceof It&&he.details?.code==="filter_unsupported")return he.message}return null},[P.summary,P.timeseries,P.channels,P.breakdowns]),B=(L,pe,he,Ee,Oe,st,ze,Ke,ce)=>()=>{let Be=P.breakdowns[L];return(0,re.jsx)(Xa,{sourced:Be?.data??null,error:Be?.error,isLoading:Be?.isLoading,what:pe,collecting:A?.collecting,onRetry:P.refetch,children:ct=>{let Yt=wt=>Ke?Ce(Ke,[wt]):wt;return(0,re.jsx)(Ur,{rows:ct,dimension:he,metric:Ee,metricLabel:Oe,secondary:st,emptyCopy:S.length>0?"No data for this filter":ze,canFilter:Ke?(wt,At)=>m(Ke,Yt(wt),ce?{dimension:ce,value:At}:void 0):()=>!1,onFilter:Ke?(wt,At)=>R(Ke,Yt(wt),ce?{dimension:ce,value:At}:void 0):void 0})}})};if(rr({status:A,holdingForFirstData:fe,refetchStatus:P.refetchStatus,refetch:P.refetch}),F){let L=!!d&&String(d).slice(0,10)<kc;return(0,re.jsx)(yt,{title:"Analytics",onBackToWebsite:a,className:i,children:(0,re.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,re.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:J?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":L?"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 X?(0,re.jsx)(yt,{title:"Analytics",onBackToWebsite:a,className:i,children:(0,re.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,re.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."})]})}):q?(0,re.jsxs)(yt,{title:"Analytics",onBackToWebsite:a,className:i,children:[(0,re.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,re.jsx)(Mr,{value:w,chosen:r,onChange:L=>{gr(L),v(L)}})}),(0,re.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,re.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",A?.timezone?` ${A.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,re.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,re.jsx)(Hr,{currentVisitors:ee.currentVisitors,asOf:ee.asOf,isStale:ee.isStale,isUnreachable:ee.isUnreachable||ee.error!==null,isInitialLoad:ee.isInitialLoad})})]})]}):(0,re.jsx)(yt,{title:"Analytics",onBackToWebsite:a,className:i,children:(0,re.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,re.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,re.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Ec.map(L=>(0,re.jsx)("button",{type:"button","aria-pressed":L.value===f,onClick:()=>u(L.value),className:L.value===f?"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:L.label},L.value))}),(0,re.jsx)(Mr,{value:w,chosen:r,onChange:L=>{gr(L),v(L)}}),(0,re.jsx)(Hr,{currentVisitors:ee.currentVisitors,asOf:ee.asOf,isStale:ee.isStale,isUnreachable:ee.isUnreachable||ee.error!==null,isInitialLoad:ee.isInitialLoad,scopeIsSiteWide:S.length>0})]}),(0,re.jsx)(xo,{filters:S,onChange:O,suggestions:Pe,expandValues:Ce,resetKey:l}),k?(0,re.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,re.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:k}),(0,re.jsx)("button",{type:"button",onClick:()=>O([]),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,!k&&A?.timezone_defaulted?(0,re.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,k?null:(0,re.jsxs)(re.Fragment,{children:[(0,re.jsx)(Xa,{sourced:P.summary.data,error:P.summary.error,isLoading:P.summary.isLoading,what:"The traffic summary",collecting:A?.collecting,onRetry:P.refetch,children:L=>(0,re.jsxs)(re.Fragment,{children:[(0,re.jsx)(wo,{summary:L,selected:T,onSelect:D}),L.previous_unavailable?(0,re.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[L.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,re.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,re.jsx)(Xa,{sourced:P.timeseries.data,error:P.timeseries.error,isLoading:P.timeseries.isLoading,what:"The visitors chart",collecting:A?.collecting,onRetry:P.refetch,children:L=>{let pe=P.timeseries.data?.status==="ok"?P.timeseries.data.window:{from:"",to:""};return(0,re.jsx)(ur,{rows:L,window:pe,metric:T,timeZone:U??"UTC"})}})}),(0,re.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,re.jsx)(Nn,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,re.jsx)(Xa,{sourced:P.channels.data,error:P.channels.error,isLoading:P.channels.isLoading,what:"Channels",collecting:A?.collecting,onRetry:P.refetch,children:L=>(0,re.jsx)(Ur,{rows:L,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:S.length>0?"No data for this filter":"No data for this period",canFilter:pe=>m("channel",pe),onFilter:pe=>R("channel",pe)})})},{id:"sources",label:"Sources",render:B("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:B("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,re.jsx)(Nn,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:B("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:B("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:B("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,re.jsx)(Nn,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:B("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:B("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:B("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,re.jsx)(Nn,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:B("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:B("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:B("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,re.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,re.jsx)("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,re.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,re.jsxs)("div",{className:"af-px-3 af-py-2",children:[S.length>0?(0,re.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",S.length===1?"filter":"filters"," above."]}):null,Et!==null?(0,re.jsxs)("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[(0,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,re.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:Et})]}):(0,re.jsx)(Xa,{sourced:P.conversions.data,error:P.conversions.error,isLoading:P.conversions.isLoading,what:"Conversions",collecting:A?.collecting,onRetry:P.refetch,children:L=>{let pe=P.conversions.data?.status==="ok"?P.conversions.data:null;return(0,re.jsx)(re.Fragment,{children:(0,re.jsx)(lr,{rows:L,primaryConversion:n,denominator:pe?.denominator??0,windowPrecedesCollection:pe?.window_precedes_collection??!1,coverageUnknown:pe?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var Eo=le(require("react"),1),Tt=require("lucide-react");var xa=le(require("react"),1),es=require("lucide-react");var ve=require("react/jsx-runtime"),Ro=90,Po=100;function Ic(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Co(e){return!!e.label&&e.label!==e.target}function Dc(e,t,s){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:a,with_a_value:n}=t;return a===0?e===0?"Nothing specific has converted here yet.":null:n===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":n<a?s?`These cover ${n.toLocaleString()} of ${a.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${n.toLocaleString()} of ${a.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function _n(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function To({current:e,onChange:t,onClose:s}){let{api:a}=ne(),[n,i]=xa.useState(null),[o,d]=xa.useState(!1),[f,u]=xa.useState({at:"goals"}),[r,v]=xa.useState(null),[x,b]=xa.useState(null),[c,l]=xa.useState(!1),[y,N]=xa.useState(null),S=xa.useRef(0);xa.useEffect(()=>{let R=!0;return i(null),d(!1),u({at:"goals"}),v(null),b(null),l(!1),N(null),S.current+=1,a.getAnalyticsConversions(Ro).then(T=>{if(R){if(T.status!=="ok"){d(!0);return}i(T.data)}}).catch(()=>{R&&d(!0)}),()=>{R=!1}},[a]);let O=R=>{u({at:"targets",row:R}),v(null),b(null),l(!1),N(null);let T=++S.current;a.getAnalyticsGoalTargets(R.goal,Ro,Po).then(D=>{if(T===S.current){if(D.status!=="ok"){b("failed");return}v(D.data),l(D.truncated===!0),N(D.coverage??null)}}).catch(D=>{if(T!==S.current)return;let P=D instanceof It?D.details?.code:void 0;b(P==="goal_has_no_targets"?"no-values":"failed")})},M=R=>{t(R),s()};if(o)return(0,ve.jsx)("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,ve.jsx)(es.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,ve.jsx)("span",{children:"Loading your conversions\u2026"})]});if(f.at==="targets"){let R=f.row,T=new Map;for(let D of r??[])T.set(D.label,(T.get(D.label)??0)+1);return(0,ve.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[(0,ve.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,ve.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({at:"goals"}),children:[(0,ve.jsx)(es.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,ve.jsx)("span",{children:"All conversions"})]})}),(0,ve.jsxs)("button",{type:"button","aria-current":e&&_n(R,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>M({goal:R.goal,implicit:R.implicit}),children:[e&&_n(R,e)&&!e.target&&(0,ve.jsx)(es.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ve.jsxs)("span",{children:["Any ",R.goal.toLowerCase()]})]}),x==="no-values"&&(0,ve.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),x==="failed"&&(0,ve.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,ve.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,ve.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(R),children:"Try again"})]}),!r&&x===null&&(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,ve.jsx)(es.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,ve.jsx)("span",{children:"Loading\u2026"})]}),r&&(0,ve.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Dc(r.length,y,c)}),c&&(0,ve.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Po,". If what you want isn\u2019t here, pick the conversion itself instead."]}),r?.some(Co)&&(0,ve.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),r?.map(D=>{let P=!!(e&&_n(R,e)&&e.target===D.target),A=T.get(D.label)>1;return Co(D)?(0,ve.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-3 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,ve.jsxs)("span",{className:"af-min-w-0",children:[(0,ve.jsx)("span",{className:"af-block af-truncate",children:D.label}),A&&(0,ve.jsx)("span",{className:"af-block af-truncate af-text-xs",children:D.target})]}),(0,ve.jsx)("span",{className:"af-shrink-0 af-text-xs",children:D.visitors.toLocaleString()})]},D.target):(0,ve.jsxs)("button",{type:"button","aria-current":P?"true":void 0,className:"af-flex af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>M({goal:R.goal,implicit:R.implicit,target:D.target,...D.label&&D.label!==D.target?{label:D.label}:{}}),children:[(0,ve.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[P&&(0,ve.jsx)(es.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ve.jsxs)("span",{className:"af-min-w-0",children:[(0,ve.jsx)("span",{className:"af-block af-truncate",children:D.label}),A&&(0,ve.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:D.target})]})]}),(0,ve.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:D.visitors.toLocaleString()})]},D.target)})]})}let m=e?.goal&&!n.some(R=>_n(R,e));return(0,ve.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[m&&(0,ve.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&(0,ve.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(R=>{let T=e?_n(R,e):!1;return(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,ve.jsxs)("button",{type:"button","aria-current":T?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>M({goal:R.goal,implicit:R.implicit}),children:[(0,ve.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[T&&(0,ve.jsx)(es.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ve.jsx)("span",{className:"af-truncate",children:R.goal})]}),(0,ve.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:R.visitors.toLocaleString()})]}),Ic(R)&&(0,ve.jsx)(_,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${R.goal}`,onClick:()=>O(R),children:"Narrow"})]},R.goal)}),e?.goal&&(0,ve.jsx)("button",{type:"button",className:"af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm af-text-muted-foreground hover:af-bg-accent",onClick:()=>M(null),children:"No main conversion"})]})}var ua=require("react/jsx-runtime");function Lc(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let s of t)try{let{hostname:a}=new URL(s);if(a)return a.toLowerCase().replace(/^www\./,"")}catch{}return null}function Oc(e){if(jr(e,"whatsapp"))return!0;let t=Lc(e);return t===null?!1:["wa.me","whatsapp.com"].some(s=>t===s||t.endsWith(`.${s}`))}function jr(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var ko=[{goal:"Contact",target:e=>jr(e,"tel"),icon:Tt.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>jr(e,"mailto"),icon:Tt.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:Tt.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Oc(e),icon:Tt.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:Tt.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Tt.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Tt.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:Tt.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:Tt.Download,line:"This site is set up to get your file downloaded."}];function Ao(e){let{goal:t,target:s}=e;return e.implicit!==!0?null:(s?ko.find(n=>n.goal===t&&n.target?.(s)):void 0)??ko.find(n=>n.goal===t&&!n.target)??null}function Bc(e){return Ao(e)?.icon??Tt.Target}function Io({primaryConversion:e,onChange:t}){let[s,a]=Eo.useState(!1);if(!!!e?.goal&&!t)return null;let i=e?Ao(e):null,o=e?.label?.trim(),d=e?Bc(e):Tt.Target,f=e?.goal?o?`Your main conversion is ${o}.`:i?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",u=(0,ua.jsxs)(ua.Fragment,{children:[(0,ua.jsx)(d,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ua.jsx)("span",{children:f})]});return t?(0,ua.jsxs)(Bn,{open:s,onOpenChange:a,children:[(0,ua.jsx)(Fn,{asChild:!0,children:(0,ua.jsx)("button",{type:"button",className:"af-flex af-items-center af-gap-2 af-rounded af-text-left af-text-sm af-text-muted-foreground hover:af-text-foreground focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:u})}),(0,ua.jsx)(rn,{align:"start",className:"af-w-80 af-p-1",children:s&&(0,ua.jsx)(To,{current:e,onChange:t,onClose:()=>a(!1)})})]}):(0,ua.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:u})}var Ft=require("react/jsx-runtime");function Do({refreshKey:e,onViewAll:t,primaryConversion:s}){let a=Ss(7,{refreshKey:e,breakdowns:[]}),n=a.status.data??void 0,{nothingToReport:i,notCollecting:o,holdingForFirstData:d}=nr(n);return rr({status:n,holdingForFirstData:d,refetchStatus:a.refetchStatus,refetch:a.refetch}),(0,Ft.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Ft.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Ft.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,Ft.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),i?(0,Ft.jsx)("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:o?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):(0,Ft.jsxs)(Ft.Fragment,{children:[(0,Ft.jsx)(Xa,{sourced:a.timeseries.data,error:a.timeseries.error,isLoading:a.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:a.refetch,children:f=>{let u=a.timeseries.data?.status==="ok"?a.timeseries.data:null;return(0,Ft.jsx)(ur,{rows:f,window:u?.window??{from:"",to:""},metric:"visitors",timeZone:u?.timezone,height:140})}}),(0,Ft.jsxs)("div",{className:"af-mt-3",children:[(0,Ft.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,Ft.jsx)(Xa,{sourced:a.conversions.data,error:a.conversions.error,isLoading:a.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:a.refetch,children:f=>{let u=a.conversions.data?.status==="ok"?a.conversions.data:null;return(0,Ft.jsx)(lr,{rows:f,primaryConversion:s,denominator:u?.denominator??0,windowPrecedesCollection:u?.window_precedes_collection??!1,coverageUnknown:u?.first_seen_unavailable??!1})}})]})]})]})}var kt=require("react/jsx-runtime"),Gr=5;function Wr({title:e,viewAllLabel:t,onViewAll:s}){return(0,kt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,kt.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),s&&(0,kt.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:s,children:t})]})}function Lo({refreshKey:e,onBackToWebsite:t,primaryConversion:s,onChangePrimaryConversion:a,onOpenSurface:n,needsPaidPlan:i,onUpgradePlan:o,onConnectStripe:d}){let f=ws({refreshKey:e}),u=(f.summary?.products.count??0)>0||(f.summary?.commerce?.storefront_orders??!1),r=u||(f.summary?.commerce?.invoicing??!1);return(0,kt.jsx)(yt,{title:"Dashboard",onBackToWebsite:t,children:(0,kt.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,kt.jsx)(Io,{primaryConversion:s,onChange:a}),(0,kt.jsx)(Do,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:s}),(0,kt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,kt.jsx)(Wr,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),(0,kt.jsx)(vn,{refreshKey:e,maxRows:Gr,onViewAll:n&&(()=>n("leads"))})]}),u&&(0,kt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,kt.jsx)(Wr,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),(0,kt.jsx)(Ja,{refreshKey:e,maxRows:Gr,onViewAll:n&&(()=>n("orders"))})]}),r&&(0,kt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,kt.jsx)(Wr,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),(0,kt.jsx)(Qa,{refreshKey:e,maxRows:Gr,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:i,onUpgradePlan:o,onConnectStripe:d})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,DashboardView,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,PromosPanel,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});