@aifeatures/admin-react 0.20.0 → 0.22.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 ql=Object.create;var Qs=Object.defineProperty;var jl=Object.getOwnPropertyDescriptor;var Gl=Object.getOwnPropertyNames;var Wl=Object.getPrototypeOf,Kl=Object.prototype.hasOwnProperty;var Zl=(e,t)=>{for(var n in t)Qs(e,n,{get:t[n],enumerable:!0})},$i=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Gl(t))!Kl.call(e,a)&&a!==n&&Qs(e,a,{get:()=>t[a],enumerable:!(s=jl(t,a))||s.enumerable});return e};var oe=(e,t,n)=>(n=e!=null?ql(Wl(e)):{},$i(t||!e||!e.__esModule?Qs(n,"default",{value:e,enumerable:!0}):n,e)),Jl=e=>$i(Qs({},"__esModule",{value:!0}),e);var Yu={};Zl(Yu,{AifeaturesApiError:()=>ht,AifeaturesProvider:()=>ji,AnalyticsView:()=>Al,CustomerDetail:()=>Fs,CustomersList:()=>Us,DashboardView:()=>Hl,ExportCsvButton:()=>Bt,FormSettings:()=>Cs,FormSubmissions:()=>ws,FormsDashboard:()=>Yr,FormsList:()=>vs,InvoiceDetail:()=>Sr,InvoiceLabelBadge:()=>as,InvoiceSettingsPanel:()=>js,InvoicesList:()=>mn,InvoicesView:()=>_i,LeadsView:()=>Hs,MAX_ANALYTICS_FILTERS:()=>Kn,MAX_ANALYTICS_FILTER_VALUES:()=>Zn,NotificationRecipientsSettings:()=>Ni,OrderDetail:()=>Os,OrderStatusBadge:()=>_n,OrdersList:()=>dn,OrdersView:()=>di,PaymentsDashboard:()=>ui,PaymentsSetup:()=>Un,ProductSettings:()=>Is,ProductsList:()=>ks,ProductsView:()=>fi,PromosPanel:()=>An,REALTIME_FAILURES_BEFORE_ERROR:()=>Or,REALTIME_POLL_MS:()=>Lr,RetainerStatusBadge:()=>_r,RetainersPanel:()=>Fn,StoreSettings:()=>Si,SubmissionDetail:()=>hs,SubscriptionsView:()=>gi,VariantsEditor:()=>Es,ViewShell:()=>wt,WebhookDeliveries:()=>Rs,WebhookSettings:()=>Ps,chargedTotal:()=>Za,createApiClient:()=>ar,formatPrice:()=>Z,isZeroDecimalCurrency:()=>da,toMajorUnits:()=>at,toMinorUnits:()=>It,useAifeatures:()=>ae,useAifeaturesContext:()=>ae,useAnalytics:()=>jn,useBusinessSummary:()=>Vn,useCsvExport:()=>xs,useCustomers:()=>Bs,useEventDestinations:()=>Ns,useForms:()=>kn,useInvoices:()=>Bn,useOrders:()=>As,usePaymentsStatus:()=>ln,usePeople:()=>$s,usePerson:()=>Vs,useProducts:()=>Mn,useRealtimeVisitors:()=>Gs,useRetainers:()=>$n,useSiteSettings:()=>pn,useSubmissions:()=>ys,useSubscriptions:()=>zs});module.exports=Jl(Yu);var xn=oe(require("react"),1);var Gr="aifeatures:analytics:timezone",Wr;function fs(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function Vi(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function yn(){return Kr()??fs()}function Kr(){if(Wr!==void 0)return Wr;try{let e=window.localStorage.getItem(Gr);return Vi(e)?e:null}catch{return null}}function Zr(e){if(!(e!==null&&!Vi(e))){Wr=e;try{e===null?window.localStorage.removeItem(Gr):window.localStorage.setItem(Gr,e)}catch{}}}function er(e,t){let n=new URLSearchParams({period:String(e)}),s=yn();return s&&n.set("timezone",s),t&&t.length>0&&n.set("filters",JSON.stringify(t)),n.toString()}var ht=class extends Error{constructor(n,s,a){super(n);this.status=s;this.details=a;this.name="AifeaturesApiError"}};function tr(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 ms(e,t){let n=t.toString();return n?`${e}?${n}`:e}function Hi(e){let t=new URLSearchParams;return e.status&&t.set("status",e.status),e.source&&t.set("source",e.source),e.excludeStatus?.length&&t.set("exclude_status",e.excludeStatus.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),e.from&&t.set("from",e.from),e.to&&t.set("to",e.to),e.unfulfilledOnly&&t.set("unfulfilled_only","true"),t}function zi(e){let t=new URLSearchParams;return e.statuses?.length&&t.set("status",e.statuses.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),t}function ar(e,t="https://aifeatures.dev"){async function n(a,r={}){let o=`${t}${a}`,d=await fetch(o,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!d.ok){let c;try{c=await d.json()}catch{}throw new ht(tr(c?.error,d.status),d.status,c)}if(d.status!==204)return d.json()}async function s(a){let r=await fetch(`${t}${a}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let o;try{o=await r.json()}catch{}throw new ht(tr(o?.error,r.status),r.status,o)}return r.blob()}return{async getForms(){return(await n("/api/v1/forms")).forms},async getForm(a){return n(`/api/v1/forms/${a}`)},async createForm(a){return n("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,r){return n(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(a){await n(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,r={}){let o=new URLSearchParams;r.limit!==void 0&&o.set("limit",String(r.limit)),r.offset!==void 0&&o.set("offset",String(r.offset));let d=o.toString(),c=`/api/v1/forms/${a}/submissions${d?`?${d}`:""}`;return n(c)},async getSubmission(a){return n(`/api/v1/submissions/${a}`)},async exportSubmissionsCsv(a,r={}){let o=new URLSearchParams;return r.includeSpam&&o.set("include_spam","true"),s(ms(`/api/v1/forms/${encodeURIComponent(a)}/submissions/export`,o))},async deleteSubmission(a){await n(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,r){let o=typeof r=="string"?{name:r}:r,d=o.name,c=o.id??o.name,u=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(c)}`,i=await fetch(u,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){let l;try{l=await i.json()}catch{}throw new ht(tr(l?.error,i.status),i.status,l)}let g=await i.blob(),v=URL.createObjectURL(g),f=document.createElement("a");f.href=v,f.download=d,document.body.appendChild(f),f.click(),document.body.removeChild(f),URL.revokeObjectURL(v)},async getSite(a){return n(`/api/v1/sites/${encodeURIComponent(a)}`)},async updateSite(a,r){return n(`/api/v1/sites/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return n("/api/v1/payments/status")},getPromos(a){let r=new URLSearchParams({limit:"10"});return a&&r.set("cursor",a),n(`/api/v1/promos?${r}`)},getPromo(a){return n(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return n("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return n(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,r){return n(`/api/v1/promos/${encodeURIComponent(a)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(a={}){let r=new URLSearchParams;a.include&&r.set("include",a.include);let o=r.toString();return(await n(`/api/v1/products${o?`?${o}`:""}`)).products},async getProduct(a){return n(`/api/v1/products/${a}`)},async createProduct(a){return n("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,r){return n(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(a){await n(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,r){let o=new FormData;o.append("file",r);let d=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:o});if(!d.ok){let c;try{c=await d.json()}catch{}throw new ht(tr(c?.error,d.status),d.status,c)}return d.json()},async attachProductFileFromUrl(a,r){return n(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(a,r){return n(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(a,r){return n(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(a){await n(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,r){return n(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(a,r){return n(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(a){await n(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,r){return n(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(a,r){return n(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(a={}){let r=new URLSearchParams;a.email?r.set("email",a.email):a.q&&r.set("q",a.q),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/customers${o?`?${o}`:""}`)},async getCustomer(a){return n(`/api/v1/customers/${a}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(a={}){let r=Hi(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/orders${o?`?${o}`:""}`)},async exportOrdersCsv(a={}){return s(ms("/api/v1/orders/export",Hi(a)))},async getOrder(a){return n(`/api/v1/orders/${a}`)},async getInvoices(a={}){let r=new URLSearchParams;a.labels?.length&&r.set("label",a.labels.join(",")),a.customerEmail&&r.set("customer_email",a.customerEmail),a.customerId&&r.set("customer_id",a.customerId),a.q&&r.set("q",a.q),a.from&&r.set("from",a.from),a.to&&r.set("to",a.to),a.includeAggregates&&r.set("include","aggregates"),a.retainerId&&r.set("retainer_id",a.retainerId),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/invoices${o?`?${o}`:""}`)},async getInvoice(a){return n(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return n(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return n("/api/v1/invoice-settings")},async getRetainers(a={}){let r=zi(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/retainers${o?`?${o}`:""}`)},async exportRetainersCsv(a={}){return s(ms("/api/v1/retainers/export",zi(a)))},async getRetainer(a){return n(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await n(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return n(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,r){return n(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(a={}){let r=new URLSearchParams;a.status&&r.set("status",a.status),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/subscriptions${o?`?${o}`:""}`)},async exportSubscriptionsCsv(a={}){let r=new URLSearchParams;return a.status&&r.set("status",a.status),s(ms("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let a=new URLSearchParams,r=yn();r&&a.set("timezone",r);let o=a.toString();return n(`/api/v1/analytics/status${o?`?${o}`:""}`)},async getAnalyticsSummary(a,r){return n(`/api/v1/analytics/summary?${er(a,r)}`)},async getAnalyticsTimeseries(a,r){return n(`/api/v1/analytics/timeseries?${er(a,r)}`)},async getAnalyticsRealtime(){return n("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,r){return n(`/api/v1/analytics/channels?${er(a,r)}`)},async getAnalyticsConversions(a){return n((()=>{let r=new URLSearchParams({period:String(a)}),o=yn();return o&&r.set("timezone",o),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(a,r,o){let d=new URLSearchParams({goal:a,period:String(r)}),c=yn();return c&&d.set("timezone",c),o!==void 0&&d.set("limit",String(o)),n(`/api/v1/analytics/conversions/targets?${d.toString()}`)},async getAnalyticsBreakdown(a,r,o){let d=a.split("/").map(encodeURIComponent).join("/");return n(`/api/v1/analytics/${d}?${er(r,o)}`)},async getBusinessSummary(a){let r=new URLSearchParams;r.set("tz_offset_minutes",String(a.tzOffsetMinutes));let o=yn();return o&&r.set("timezone",o),n(`/api/v1/summary?${r.toString()}`)},async getPeople(a={}){let r=new URLSearchParams;a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/people${o?`?${o}`:""}`)},async exportPeopleCsv(a={}){let r=new URLSearchParams;return a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),s(ms("/api/v1/people/export",r))},async getPerson(a){return n(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await n("/api/v1/event-destinations")).destinations},async createEventDestination(a){return n("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,r){return n(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(a){await n(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return n(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await n(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,r){let o=r===void 0?"":`?limit=${r}`;return(await n(`/api/v1/event-destinations/${a}/deliveries${o}`)).deliveries},async retryEventDelivery(a,r){return n(`/api/v1/event-destinations/${a}/deliveries/${r}/retry`,{method:"POST"})}}}var hn=require("react/jsx-runtime"),qi=xn.createContext(null);function Yl(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 ji({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:n=!1,className:s,children:a}){let r=xn.useMemo(()=>Yl(e),[e]),o=xn.useMemo(()=>ar(e,t),[e,t]),d=xn.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return r?(0,hn.jsx)("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:(0,hn.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,hn.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,hn.jsx)("p",{className:"af-text-sm af-text-destructive",children:r})]})}):(0,hn.jsx)(qi.Provider,{value:d,children:(0,hn.jsx)("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:a})})}function ae(){let e=xn.useContext(qi);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var on=oe(require("react"),1),Yn=require("lucide-react");var nr=oe(require("react"),1),Aa=oe(require("@radix-ui/react-tabs"),1);var Gi=require("clsx"),Wi=require("tailwind-merge"),Xl=(0,Wi.extendTailwindMerge)({prefix:"af-"});function Q(...e){return Xl((0,Gi.clsx)(e))}var rr=require("react/jsx-runtime"),sr=Aa.Root,ps=nr.forwardRef(({className:e,...t},n)=>(0,rr.jsx)(Aa.List,{ref:n,className:Q("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}));ps.displayName=Aa.List.displayName;var Da=nr.forwardRef(({className:e,...t},n)=>(0,rr.jsx)(Aa.Trigger,{ref:n,className:Q("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}));Da.displayName=Aa.Trigger.displayName;var La=nr.forwardRef(({className:e,...t},n)=>(0,rr.jsx)(Aa.Content,{ref:n,className:Q("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}));La.displayName=Aa.Content.displayName;var Ki=oe(require("react"),1),Zi=require("@radix-ui/react-slot"),Ji=require("class-variance-authority");var Yi=require("react/jsx-runtime"),Ql=(0,Ji.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"}}),R=Ki.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...a},r)=>(0,Yi.jsx)(s?Zi.Slot:"button",{className:Q(Ql({variant:t,size:n,className:e})),ref:r,...a}));R.displayName="Button";var gs=require("lucide-react");var sn=oe(require("react"),1);var ja=require("react/jsx-runtime"),ze=sn.forwardRef(({className:e,...t},n)=>(0,ja.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,ja.jsx)("table",{ref:n,className:Q("af-w-full af-caption-bottom af-text-sm",e),...t})}));ze.displayName="Table";var qe=sn.forwardRef(({className:e,...t},n)=>(0,ja.jsx)("thead",{ref:n,className:Q("[&_tr]:af-border-b",e),...t}));qe.displayName="TableHeader";var je=sn.forwardRef(({className:e,...t},n)=>(0,ja.jsx)("tbody",{ref:n,className:Q("[&_tr:last-child]:af-border-0",e),...t}));je.displayName="TableBody";var ec=sn.forwardRef(({className:e,...t},n)=>(0,ja.jsx)("tfoot",{ref:n,className:Q("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));ec.displayName="TableFooter";var Ne=sn.forwardRef(({className:e,...t},n)=>(0,ja.jsx)("tr",{ref:n,className:Q("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Ne.displayName="TableRow";var G=sn.forwardRef(({className:e,...t},n)=>(0,ja.jsx)("th",{ref:n,className:Q("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}));G.displayName="TableHead";var W=sn.forwardRef(({className:e,...t},n)=>(0,ja.jsx)("td",{ref:n,className:Q("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));W.displayName="TableCell";var tc=sn.forwardRef(({className:e,...t},n)=>(0,ja.jsx)("caption",{ref:n,className:Q("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));tc.displayName="TableCaption";var Oa=oe(require("react"),1);function kn(){let{api:e}=ae(),[t,n]=Oa.useState([]),[s,a]=Oa.useState(!0),[r,o]=Oa.useState(null),d=Oa.useCallback(async()=>{try{a(!0),o(null);let g=await e.getForms();n(g)}catch(g){o(g instanceof Error?g:new Error("Failed to fetch forms"))}finally{a(!1)}},[e]);Oa.useEffect(()=>{d()},[d]);let c=Oa.useCallback(async g=>{let v=await e.createForm(g);return n(f=>[...f,v]),v},[e]),u=Oa.useCallback(async(g,v)=>{let f=await e.updateForm(g,v);return n(l=>l.map(m=>m.id===g?f:m)),f},[e]),i=Oa.useCallback(async g=>{await e.deleteForm(g),n(v=>v.filter(f=>f.id!==g))},[e]);return{forms:t,isLoading:s,error:r,refetch:d,createForm:c,updateForm:u,deleteForm:i}}var Qe=require("react/jsx-runtime");function vs({onSelectForm:e,className:t}){let{forms:n,isLoading:s,error:a}=kn();return s?(0,Qe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Qe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):a?(0,Qe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Qe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",a.message]})}):n.length===0?(0,Qe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,Qe.jsx)(gs.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Qe.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Qe.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Qe.jsx)("div",{className:t,children:(0,Qe.jsxs)(ze,{children:[(0,Qe.jsx)(qe,{children:(0,Qe.jsxs)(Ne,{children:[(0,Qe.jsx)(G,{children:"Name"}),(0,Qe.jsx)(G,{className:"af-text-right",children:"Actions"})]})}),(0,Qe.jsx)(je,{children:n.map(r=>(0,Qe.jsxs)(Ne,{children:[(0,Qe.jsx)(W,{className:"af-font-medium",children:r.name}),(0,Qe.jsx)(W,{className:"af-text-right",children:(0,Qe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Qe.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[(0,Qe.jsx)(gs.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Qe.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[(0,Qe.jsx)(gs.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}var eo=require("lucide-react");var Xi=require("class-variance-authority");var Qi=require("react/jsx-runtime"),ac=(0,Xi.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 ie({className:e,variant:t,...n}){return(0,Qi.jsx)("div",{className:Q(ac({variant:t}),e),...n})}var ia=require("react/jsx-runtime"),nc={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 ir(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 Jr(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function sc(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 bs({deliveries:e,label:t="Email needs attention"}){return Jr(e)?(0,ia.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,ia.jsx)(eo.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Ga({deliveries:e,problemsOnly:t=!1,className:n=""}){let s=(e??[]).filter(a=>!t||Jr([a]));return s.length?(0,ia.jsx)("div",{className:`af-space-y-3 ${n}`,"aria-label":"Email delivery",children:s.map(a=>{let r=ir(a),o=sc(a);return(0,ia.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,ia.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,ia.jsx)("span",{className:"af-font-medium",children:nc[a.kind]??"Email notification"}),(0,ia.jsx)(ie,{variant:r.variant,children:r.label})]}),(0,ia.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",a.recipients.join(", ")]}),a.recipients.length>1&&Jr([a])&&(0,ia.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."}),r.detail&&(0,ia.jsx)("p",{className:"af-mt-1",children:r.detail}),o&&(0,ia.jsx)("p",{className:"af-mt-1",children:o})]},a.id)})}):null}var Sn=oe(require("react"),1),wa=require("lucide-react");var wn=oe(require("react"),1),Ee=oe(require("@radix-ui/react-select"),1),En=require("lucide-react");var gt=require("react/jsx-runtime"),ya=Ee.Root;var ha=Ee.Value,oa=wn.forwardRef(({className:e,children:t,...n},s)=>(0,gt.jsxs)(Ee.Trigger,{ref:s,className:Q("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),...n,children:[t,(0,gt.jsx)(Ee.Icon,{asChild:!0,children:(0,gt.jsx)(En.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));oa.displayName=Ee.Trigger.displayName;var to=wn.forwardRef(({className:e,...t},n)=>(0,gt.jsx)(Ee.ScrollUpButton,{ref:n,className:Q("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,gt.jsx)(En.ChevronUp,{className:"af-h-4 af-w-4"})}));to.displayName=Ee.ScrollUpButton.displayName;var ao=wn.forwardRef(({className:e,...t},n)=>(0,gt.jsx)(Ee.ScrollDownButton,{ref:n,className:Q("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,gt.jsx)(En.ChevronDown,{className:"af-h-4 af-w-4"})}));ao.displayName=Ee.ScrollDownButton.displayName;var la=wn.forwardRef(({className:e,children:t,position:n="popper",...s},a)=>(0,gt.jsx)(Ee.Portal,{children:(0,gt.jsxs)(Ee.Content,{ref:a,className:Q("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",n==="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:n,...s,children:[(0,gt.jsx)(to,{}),(0,gt.jsx)(Ee.Viewport,{className:Q("af-p-1",n==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,gt.jsx)(ao,{})]})}));la.displayName=Ee.Content.displayName;var rc=wn.forwardRef(({className:e,...t},n)=>(0,gt.jsx)(Ee.Label,{ref:n,className:Q("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));rc.displayName=Ee.Label.displayName;var et=wn.forwardRef(({className:e,children:t,...n},s)=>(0,gt.jsxs)(Ee.Item,{ref:s,className:Q("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),...n,children:[(0,gt.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,gt.jsx)(Ee.ItemIndicator,{children:(0,gt.jsx)(En.Check,{className:"af-h-4 af-w-4"})})}),(0,gt.jsx)(Ee.ItemText,{children:t})]}));et.displayName=Ee.Item.displayName;var ic=wn.forwardRef(({className:e,...t},n)=>(0,gt.jsx)(Ee.Separator,{ref:n,className:Q("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));ic.displayName=Ee.Separator.displayName;var xa=oe(require("react"),1);function ys({formId:e,initialPageSize:t=25}){let{api:n}=ae(),[s,a]=xa.useState([]),[r,o]=xa.useState(0),[d,c]=xa.useState(!0),[u,i]=xa.useState(null),[g,v]=xa.useState(0),[f,l]=xa.useState(t),m=xa.useCallback(async()=>{if(e)try{c(!0),i(null);let S={limit:f,offset:g*f},_=await n.getSubmissions(e,S);a(_.submissions),o(_.total)}catch(S){i(S instanceof Error?S:new Error("Failed to fetch submissions"))}finally{c(!1)}},[n,e,g,f]);xa.useEffect(()=>{m()},[m]);let p=xa.useCallback(async S=>{await n.deleteSubmission(S),a(_=>_.filter(A=>A.id!==S)),o(_=>_-1)},[n]),b=Math.ceil(r/f);return{submissions:s,total:r,isLoading:d,error:u,page:g,pageSize:f,hasNextPage:g<b-1,hasPreviousPage:g>0,setPage:v,setPageSize:S=>{l(S),v(0)},refetch:m,deleteSubmission:p}}var so=oe(require("react"),1),$t=require("lucide-react");var _e=require("react/jsx-runtime");function no(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function oc(e){if(e===0)return"0 B";let t=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${n[s]}`}function hs({submission:e,onBack:t}){let{api:n}=ae(),[s,a]=so.useState(null),r=c=>c.id??c.name,o=async c=>{a(r(c));try{await n.downloadAttachment(e.id,c)}catch(u){console.error("Download failed:",u)}finally{a(null)}},d=Object.entries(e.data).filter(([c])=>!c.startsWith("_"));return(0,_e.jsxs)("div",{children:[(0,_e.jsxs)("div",{className:"af-mb-6",children:[(0,_e.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,_e.jsx)($t.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,_e.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,_e.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",no(e.metadata.submitted_at)]})]}),(0,_e.jsxs)("div",{className:"af-space-y-6",children:[(0,_e.jsx)(Ga,{deliveries:e.email_deliveries}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,_e.jsxs)("div",{className:"af-space-y-3",children:[d.map(([c,u])=>(0,_e.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,_e.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:c.replace(/_/g," ")}),(0,_e.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof u=="string"&&u.includes(`
3
- `)?(0,_e.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)})]},c)),d.length===0&&(0,_e.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,_e.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((c,u)=>(0,_e.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_e.jsx)($t.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,_e.jsx)("span",{className:"af-text-sm",children:c.name}),(0,_e.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",oc(c.size),")"]})]}),(0,_e.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>o(c),disabled:s===r(c),children:[s===r(c)?(0,_e.jsx)($t.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,_e.jsx)($t.Download,{className:"af-h-4 af-w-4 af-mr-1"}),s===r(c)?"Downloading...":"Download"]})]},u))})]}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,_e.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,_e.jsx)($t.Clock,{className:"af-h-4 af-w-4"}),(0,_e.jsx)("span",{children:no(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,_e.jsx)($t.Globe,{className:"af-h-4 af-w-4"}),(0,_e.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,_e.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,_e.jsx)($t.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,_e.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,_e.jsx)($t.Mail,{className:"af-h-4 af-w-4"}),(0,_e.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var io=require("lucide-react");var In=oe(require("react"),1);var lc=/^\+[1-9]\d{1,14}$/;function ro(e){let t=e==null?"":String(e),n=!lc.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),s=n?`'${t}`:t;return n||/[",;\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function or(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function lr(e,t){if(typeof document>"u")return;let n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n)}function xs({fetchCsv:e,filename:t}){let[n,s]=In.useState(!1),[a,r]=In.useState(null),o=In.useRef(!1);return{exportCsv:In.useCallback(async()=>{if(!o.current){o.current=!0,s(!0),r(null);try{let c=await e();lr(c,or(t))}catch(c){r(c instanceof Error?c:new Error("Export failed"))}finally{o.current=!1,s(!1)}}},[e,t]),exporting:n,error:a}}var Jn=require("react/jsx-runtime");function Bt({fetchCsv:e,filename:t,label:n="Export CSV",disabled:s,className:a}){let{exportCsv:r,exporting:o,error:d}=xs({fetchCsv:e,filename:t});return(0,Jn.jsxs)("span",{className:a,children:[(0,Jn.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||o,"aria-busy":o,children:[(0,Jn.jsx)(io.Download,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Exporting\u2026":n]}),d&&(0,Jn.jsx)("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}var fe=require("react/jsx-runtime");function cc(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function uc(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let n of t)if(typeof e[n]=="string")return e[n];return null}var dc=["message","comments","comment","inquiry","question","details","body","notes"];function fc(e){let t=Object.entries(e).filter(([r,o])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),n=new Map(t.map(([r,o])=>[r.toLowerCase(),o])),a=(dc.map(r=>n.get(r)).find(Boolean)??t.reduce((r,[,o])=>o.length>r.length?o:r,"")).trim().replace(/\s+/g," ");return a.length>80?a.slice(0,80)+"\u2026":a}function ws({formId:e,className:t,defaultSubmissionId:n,submissionId:s,onSelectSubmission:a}){let{api:r}=ae(),{submissions:o,total:d,isLoading:c,error:u,page:i,pageSize:g,hasNextPage:v,hasPreviousPage:f,setPage:l,setPageSize:m}=ys({formId:e}),p=Sn.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[b,S]=Sn.useState(n??null),_=a?s??null:b,A=a??S,y=M=>!!M&&M.id===_&&M.form_id===e,P=o.find(y),[T,L]=Sn.useState(null),N=y(T)?T:null,[k,I]=Sn.useState(null);if(Sn.useEffect(()=>{if(I(null),!_||P||N)return;let M=!1;return r.getSubmission(_).then(te=>{if(!M){if(te.form_id!==e){I("This submission could not be found.");return}L(te)}}).catch(()=>{M||I("This submission could not be found.")}),()=>{M=!0}},[r,e,_,P,N]),_){let M=P??N;return M?(0,fe.jsx)("div",{className:t,children:(0,fe.jsx)(hs,{submission:M,onBack:()=>A(null)})}):k?(0,fe.jsxs)("div",{className:t,children:[(0,fe.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>A(null),className:"af-mb-2 af--ml-2",children:[(0,fe.jsx)(wa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,fe.jsx)("p",{className:"af-text-sm af-text-destructive",children:k})]}):(0,fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,fe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(c)return(0,fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,fe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(u)return(0,fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,fe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",u.message]})});if(o.length===0&&i===0)return(0,fe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,fe.jsx)(wa.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,fe.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,fe.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let C=i*g+1,ee=Math.min((i+1)*g,d);return(0,fe.jsxs)("div",{className:t,children:[(0,fe.jsx)("div",{className:"af-mb-2 af-flex af-justify-end",children:(0,fe.jsx)(Bt,{fetchCsv:p,filename:"submissions"})}),(0,fe.jsxs)(ze,{children:[(0,fe.jsx)(qe,{children:(0,fe.jsxs)(Ne,{children:[(0,fe.jsx)(G,{children:"Email"}),(0,fe.jsx)(G,{children:"Preview"}),(0,fe.jsx)(G,{children:"Date"}),(0,fe.jsx)(G,{className:"af-text-right",children:"Actions"})]})}),(0,fe.jsx)(je,{children:o.map(M=>{let te=uc(M.data),ne=fc(M.data);return(0,fe.jsxs)(Ne,{children:[(0,fe.jsxs)(W,{className:"af-font-medium",children:[(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[te||(0,fe.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),M.attachments.length>0&&(0,fe.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${M.attachments.length} attachment(s)`,children:[(0,fe.jsx)(wa.Paperclip,{className:"af-h-3 af-w-3"}),(0,fe.jsx)("span",{className:"af-text-xs",children:M.attachments.length})]})]}),(0,fe.jsx)(bs,{deliveries:M.email_deliveries,label:"Notification email needs attention"})]}),(0,fe.jsx)(W,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:ne||(0,fe.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,fe.jsx)(W,{className:"af-text-muted-foreground",children:cc(M.metadata.submitted_at)}),(0,fe.jsx)(W,{className:"af-text-right",children:(0,fe.jsx)(R,{variant:"ghost",size:"icon",onClick:()=>A(M.id),title:"View details",children:(0,fe.jsx)(wa.Eye,{className:"af-h-4 af-w-4"})})})]},M.id)})})]}),(0,fe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,fe.jsxs)("span",{children:["Showing ",C,"-",ee," of ",d]}),(0,fe.jsxs)(ya,{value:String(g),onValueChange:M=>m(Number(M)),children:[(0,fe.jsx)(oa,{className:"af-w-[70px] af-h-8",children:(0,fe.jsx)(ha,{})}),(0,fe.jsxs)(la,{children:[(0,fe.jsx)(et,{value:"10",children:"10"}),(0,fe.jsx)(et,{value:"25",children:"25"}),(0,fe.jsx)(et,{value:"50",children:"50"}),(0,fe.jsx)(et,{value:"100",children:"100"})]})]}),(0,fe.jsx)("span",{children:"per page"})]}),(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,fe.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>l(i-1),disabled:!f,children:[(0,fe.jsx)(wa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,fe.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>l(i+1),disabled:!v,children:["Next",(0,fe.jsx)(wa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var ua=oe(require("react"),1),Nn=require("lucide-react");var oo=oe(require("react"),1);var lo=require("react/jsx-runtime"),pe=oo.forwardRef(({className:e,type:t,...n},s)=>(0,lo.jsx)("input",{type:t,className:Q("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...n}));pe.displayName="Input";var co=oe(require("react"),1),uo=require("class-variance-authority");var fo=require("react/jsx-runtime"),mc=(0,uo.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Ce=co.forwardRef(({className:e,...t},n)=>(0,fo.jsx)("label",{ref:n,className:Q(mc(),e),...t}));Ce.displayName="Label";var Sa=oe(require("react"),1),Vt=require("lucide-react");var Ss=oe(require("react"),1),_t=oe(require("@radix-ui/react-dialog"),1),mo=require("lucide-react");var Yt=require("react/jsx-runtime"),Wa=_t.Root;var pc=_t.Portal;var po=Ss.forwardRef(({className:e,...t},n)=>(0,Yt.jsx)(_t.Overlay,{ref:n,className:Q("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));po.displayName=_t.Overlay.displayName;var Ba=Ss.forwardRef(({className:e,children:t,...n},s)=>(0,Yt.jsx)(pc,{children:(0,Yt.jsxs)("div",{className:"aifeatures-admin",children:[(0,Yt.jsx)(po,{}),(0,Yt.jsxs)(_t.Content,{ref:s,className:Q("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),...n,children:[t,(0,Yt.jsxs)(_t.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,Yt.jsx)(mo.X,{className:"af-h-4 af-w-4"}),(0,Yt.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Ba.displayName=_t.Content.displayName;var Fa=({className:e,...t})=>(0,Yt.jsx)("div",{className:Q("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Fa.displayName="DialogHeader";var Ua=({className:e,...t})=>(0,Yt.jsx)("div",{className:Q("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ua.displayName="DialogFooter";var Ma=Ss.forwardRef(({className:e,...t},n)=>(0,Yt.jsx)(_t.Title,{ref:n,className:Q("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Ma.displayName=_t.Title.displayName;var $a=Ss.forwardRef(({className:e,...t},n)=>(0,Yt.jsx)(_t.Description,{ref:n,className:Q("af-text-sm af-text-muted-foreground",e),...t}));$a.displayName=_t.Description.displayName;var ca=oe(require("react"),1);function Ns(){let{api:e}=ae(),[t,n]=ca.useState([]),[s,a]=ca.useState(!0),[r,o]=ca.useState(null),d=ca.useCallback(async()=>{try{a(!0),o(null),n(await e.getEventDestinations())}catch(f){o(f instanceof Error?f:new Error("Failed to fetch webhooks"))}finally{a(!1)}},[e]);ca.useEffect(()=>{d()},[d]);let c=ca.useCallback(async f=>{let l=await e.createEventDestination(f);return n(m=>[l,...m]),l},[e]),u=ca.useCallback(async(f,l)=>{let m=await e.updateEventDestination(f,l);return n(p=>p.map(b=>b.id===f?m:b)),m},[e]),i=ca.useCallback(async f=>{await e.deleteEventDestination(f),n(l=>l.filter(m=>m.id!==f))},[e]),g=ca.useCallback(async f=>{let l=await e.rotateEventDestinationSecret(f);return n(m=>m.map(p=>p.id===f?l:p)),l},[e]),v=ca.useCallback(f=>e.getEventDestinationSecret(f),[e]);return{destinations:t,isLoading:s,error:r,refetch:d,createDestination:c,updateDestination:u,deleteDestination:i,rotateSecret:g,getSecret:v}}var rn=oe(require("react"),1),_s=require("lucide-react");var Rt=require("react/jsx-runtime");function Rs({destinationId:e,limit:t=25,className:n}){let{api:s}=ae(),[a,r]=rn.useState([]),[o,d]=rn.useState(!0),[c,u]=rn.useState(null),[i,g]=rn.useState(null),v=rn.useCallback(async()=>{try{d(!0),u(null),r(await s.getEventDeliveries(e,t))}catch(l){u(l instanceof Error?l.message:"Failed to load deliveries")}finally{d(!1)}},[s,e,t]);rn.useEffect(()=>{v()},[v]);let f=async l=>{try{g(l.id),u(null);let m=await s.retryEventDelivery(e,l.id);r(p=>p.map(b=>b.id===l.id?m:b))}catch(m){u(m instanceof Error?m.message:"Retry failed")}finally{g(null)}};return o?(0,Rt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,Rt.jsx)(_s.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):c?(0,Rt.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:c}):a.length===0?(0,Rt.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,Rt.jsx)("div",{className:n,children:(0,Rt.jsx)("div",{className:"af-divide-y af-border af-rounded",children:a.map(l=>{let m=l.delivered_at!==null;return(0,Rt.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,Rt.jsxs)("div",{className:"af-min-w-0",children:[(0,Rt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[m?(0,Rt.jsx)(ie,{variant:"secondary",children:l.last_status??200}):(0,Rt.jsx)(ie,{variant:"destructive",children:l.last_status??"failed"}),(0,Rt.jsx)("span",{className:"af-text-sm af-truncate",children:l.type})]}),(0,Rt.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[l.event_id," \xB7 ",l.created_at,l.attempts>0&&` \xB7 ${l.attempts} failed ${l.attempts===1?"attempt":"attempts"}`]}),!m&&l.last_error&&(0,Rt.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:l.last_error})]}),(0,Rt.jsx)(R,{variant:"ghost",size:"sm",title:"Send this event again",disabled:i===l.id,onClick:()=>f(l),children:i===l.id?(0,Rt.jsx)(_s.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Rt.jsx)(_s.RotateCw,{className:"af-h-4 af-w-4"})})]},l.id)})})})}var ge=require("react/jsx-runtime");function Ps({formId:e,topics:t,description:n,className:s}){let{destinations:a,isLoading:r,error:o,createDestination:d,updateDestination:c,deleteDestination:u,rotateSecret:i,getSecret:g}=Ns(),[v,f]=Sa.useState(""),[l,m]=Sa.useState(!1),[p,b]=Sa.useState(null),[S,_]=Sa.useState(null),[A,y]=Sa.useState(null),[P,T]=Sa.useState(!1),[L,N]=Sa.useState(null),[k,I]=Sa.useState(null),[C,ee]=Sa.useState(null),M=Sa.useMemo(()=>a.filter(j=>j.form_id===e),[a,e]),te=async()=>{let j=v.trim();if(j){if(!j.startsWith("https://")){b("Webhook URLs must start with https://");return}try{m(!0),b(null),await d({url:j,form_id:e,...t&&t.length>0?{topics:t}:{}}),f("")}catch(be){b(be instanceof Error?be.message:"Failed to add webhook")}finally{m(!1)}}},ne=async j=>{try{I(j.id),b(null),await i(j.id),T(!1),y(await g(j.id))}catch(be){b(be instanceof Error?be.message:"Failed to rotate secret")}finally{I(null)}},re=async j=>{try{I(j.id),b(null),await c(j.id,{status:"active"})}catch(be){b(be instanceof Error?be.message:"Failed to re-enable")}finally{I(null)}},se=async()=>{if(L)try{I(L.id),await u(L.id),N(null)}catch(j){b(j instanceof Error?j.message:"Failed to delete")}finally{I(null)}},q=async j=>{if(S===j.id){_(null),y(null);return}try{I(j.id),b(null),T(!1),_(j.id),y(await g(j.id))}catch(be){_(null),b(be instanceof Error?be.message:"Failed to read secret")}finally{I(null)}},V=async()=>{if(A)try{await navigator.clipboard.writeText(A),T(!0)}catch{}};return(0,ge.jsxs)("div",{className:s,children:[(0,ge.jsxs)("div",{className:"af-space-y-1",children:[(0,ge.jsx)(Ce,{children:"Webhooks"}),(0,ge.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:n??"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,ge.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,ge.jsx)(pe,{value:v,placeholder:"https://hooks.zapier.com/...",onChange:j=>f(j.target.value),onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),te())},disabled:l}),(0,ge.jsxs)(R,{onClick:te,disabled:l||!v.trim(),children:[l?(0,ge.jsx)(Vt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,ge.jsx)(Vt.Plus,{className:"af-h-4 af-w-4"}),(0,ge.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(p||o)&&(0,ge.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:p||o?.message}),(0,ge.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[r&&(0,ge.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ge.jsx)(Vt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&M.length===0&&(0,ge.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),M.map(j=>(0,ge.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,ge.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,ge.jsxs)("div",{className:"af-min-w-0",children:[(0,ge.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ge.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:j.url}),j.status==="disabled"?(0,ge.jsx)(ie,{variant:"destructive",children:"Disabled"}):(0,ge.jsx)(ie,{variant:"secondary",children:"Active"})]}),(0,ge.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:j.topics.includes("*")?"All events":j.topics.join(", ")})]}),(0,ge.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,ge.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>ee(C===j.id?null:j.id),children:C===j.id?"Hide log":"Deliveries"}),(0,ge.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>q(j),disabled:k===j.id,children:S===j.id?"Hide secret":"Show secret"}),(0,ge.jsx)(R,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:k===j.id,onClick:()=>N(j),children:(0,ge.jsx)(Vt.Trash2,{className:"af-h-4 af-w-4"})})]})]}),j.status==="disabled"&&(0,ge.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,ge.jsx)(Vt.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,ge.jsxs)("div",{className:"af-text-sm",children:[(0,ge.jsxs)("p",{children:["We stopped sending after repeated failures."," ",j.disabled_reason]}),(0,ge.jsx)(R,{variant:"outline",size:"sm",className:"af-mt-2",disabled:k===j.id,onClick:()=>re(j),children:"Re-enable"})]})]}),S===j.id&&A&&(0,ge.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,ge.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,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)(pe,{readOnly:!0,value:A,className:"af-font-mono"}),(0,ge.jsx)(R,{variant:"outline",title:"Copy signing secret",onClick:V,children:P?(0,ge.jsx)(Vt.Check,{className:"af-h-4 af-w-4"}):(0,ge.jsx)(Vt.Copy,{className:"af-h-4 af-w-4"})}),(0,ge.jsx)(R,{variant:"outline",title:"Rotate signing secret",disabled:k===j.id,onClick:()=>ne(j),children:k===j.id?(0,ge.jsx)(Vt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,ge.jsx)(Vt.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),C===j.id&&(0,ge.jsx)(Rs,{destinationId:j.id})]},j.id))]}),(0,ge.jsx)(Wa,{open:!!L,onOpenChange:j=>{!j&&!k&&N(null)},children:(0,ge.jsxs)(Ba,{children:[(0,ge.jsxs)(Fa,{children:[(0,ge.jsx)(Ma,{children:"Delete this webhook?"}),(0,ge.jsxs)($a,{children:["New submissions will stop being sent to ",L?.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,ge.jsxs)(Ua,{children:[(0,ge.jsx)(R,{variant:"outline",onClick:()=>N(null),disabled:!!k,children:"Cancel"}),(0,ge.jsx)(R,{variant:"destructive",onClick:se,disabled:!!k,children:k?"Deleting...":"Delete"})]})]})})]})}var Pe=require("react/jsx-runtime");function Cs({form:e,onSaved:t,className:n}){let{updateForm:s}=kn(),[a,r]=ua.useState(!1),[o,d]=ua.useState(null),[c,u]=ua.useState(null),[i,g]=ua.useState(e.name),[v,f]=ua.useState(e.redirect_url||""),[l,m]=ua.useState(e.email_recipients),[p,b]=ua.useState("");ua.useEffect(()=>{g(e.name),f(e.redirect_url||""),m(e.email_recipients),u(null)},[e]);let S=ua.useCallback(async T=>{try{r(!0),u(null);let L=await s(e.id,T);d(new Date),t?.(L)}catch(L){u(L instanceof Error?L.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);ua.useEffect(()=>{if(o){let T=setTimeout(()=>d(null),2e3);return()=>clearTimeout(T)}},[o]);let _=async()=>{let T=p.trim().toLowerCase();if(!T)return;if(!T.includes("@")){u("Please enter a valid email address");return}if(l.includes(T)){u("This email is already added");return}let L=[...l,T];m(L),b(""),u(null),await S({email_recipients:L})},A=async T=>{let L=l.filter(N=>N!==T);m(L),await S({email_recipients:L})},y=async()=>{i!==e.name&&await S({name:i})},P=async()=>{let T=v||null;T!==e.redirect_url&&await S({redirect_url:T})};return(0,Pe.jsxs)("div",{className:`af-space-y-6 af-relative ${n||""}`,children:[(a||o)&&(0,Pe.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:a?(0,Pe.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,Pe.jsx)(Nn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,Pe.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,Pe.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,Pe.jsx)(Nn.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,Pe.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,Pe.jsxs)("div",{className:"af-space-y-2",children:[(0,Pe.jsx)(Ce,{htmlFor:"form-name",children:"Form Name"}),(0,Pe.jsx)(pe,{id:"form-name",value:i,onChange:T=>g(T.target.value),onBlur:y,placeholder:"Contact Form"}),(0,Pe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,Pe.jsxs)("div",{className:"af-space-y-2",children:[(0,Pe.jsx)(Ce,{children:"Email Recipients"}),(0,Pe.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,Pe.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[l.map(T=>(0,Pe.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[T,(0,Pe.jsx)("button",{type:"button",onClick:()=>A(T),className:"af-ml-1 hover:af-text-destructive",disabled:a,children:(0,Pe.jsx)(Nn.X,{className:"af-h-3 af-w-3"})})]},T)),l.length===0&&(0,Pe.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,Pe.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Pe.jsx)(pe,{type:"email",value:p,onChange:T=>b(T.target.value),placeholder:"Add email address",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),_())},disabled:a}),(0,Pe.jsx)(R,{type:"button",variant:"outline",onClick:_,disabled:!p.trim()||a,children:(0,Pe.jsx)(Nn.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Pe.jsxs)("div",{className:"af-space-y-2",children:[(0,Pe.jsx)(Ce,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,Pe.jsx)(pe,{id:"redirect-url",value:v,onChange:T=>f(T.target.value),onBlur:P,placeholder:"/thank-you"}),(0,Pe.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,Pe.jsxs)("div",{className:"af-space-y-2",children:[(0,Pe.jsx)(Ce,{children:"Form Endpoint"}),(0,Pe.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Pe.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,Pe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,Pe.jsxs)("div",{className:"af-space-y-2",children:[(0,Pe.jsx)(Ce,{children:"Captcha Protection"}),(0,Pe.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Pe.jsx)(ie,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,Pe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,Pe.jsx)(Ps,{formId:e.id}),c&&(0,Pe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c})]})}var Ke=require("react/jsx-runtime");function Yr({className:e,location:t,onNavigate:n,submissionId:s}){let{api:a}=ae(),[r,o]=on.useState({submissionId:s});on.useEffect(()=>{s&&o({submissionId:s})},[s]);let d=n?t??{}:r,c=n??o,[u,i]=on.useState(null),g=`${d.formId??""}|${d.submissionId??""}`,[v,f]=on.useState(null),l=v?.key===g?v.message:null,m=d.formId??(u&&u.submissionId===d.submissionId?u.formId:void 0);on.useEffect(()=>{let T=d.submissionId;if(!T||d.formId)return;let L=!1;return a.getSubmission(T).then(N=>{L||(f(null),i({submissionId:T,formId:N.form_id}))}).catch(()=>{L||f({key:g,message:"This submission could not be found."})}),()=>{L=!0}},[a,d.submissionId,d.formId,g]);let[p,b]=on.useState(null);on.useEffect(()=>{if(!m||p?.id===m)return;let T=!1;return a.getForm(m).then(L=>{T||(f(null),b(L))}).catch(()=>{T||f({key:g,message:"This form could not be found."})}),()=>{T=!0}},[a,m,p?.id,g]);let S=(T,L)=>{b(T),c({formId:T.id,tab:L})},_=()=>c({});if(!d.formId&&!d.submissionId)return(0,Ke.jsxs)("div",{className:e,children:[(0,Ke.jsxs)("div",{className:"af-mb-6",children:[(0,Ke.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,Ke.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,Ke.jsx)(vs,{onSelectForm:S})]});let y=(0,Ke.jsxs)(R,{variant:"ghost",size:"sm",onClick:_,className:"af-mb-2 af--ml-2",children:[(0,Ke.jsx)(Yn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(l)return(0,Ke.jsxs)("div",{className:e,children:[y,(0,Ke.jsx)("p",{className:"af-text-sm af-text-destructive",children:l})]});if(!m||p?.id!==m)return(0,Ke.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,Ke.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let P=d.submissionId?"submissions":d.tab??"submissions";return(0,Ke.jsxs)("div",{className:e,children:[(0,Ke.jsxs)("div",{className:"af-mb-6",children:[y,(0,Ke.jsx)("h2",{className:"af-text-lg af-font-semibold",children:p.name})]}),(0,Ke.jsxs)(sr,{value:P,onValueChange:T=>c({formId:m,tab:T}),children:[(0,Ke.jsxs)(ps,{className:"af-mb-4",children:[(0,Ke.jsxs)(Da,{value:"submissions",className:"af-gap-2",children:[(0,Ke.jsx)(Yn.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,Ke.jsxs)(Da,{value:"settings",className:"af-gap-2",children:[(0,Ke.jsx)(Yn.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,Ke.jsx)(La,{value:"submissions",children:(0,Ke.jsx)(ws,{formId:m,submissionId:d.submissionId,onSelectSubmission:T=>c({formId:m,tab:"submissions",submissionId:T??void 0})})}),(0,Ke.jsx)(La,{value:"settings",children:(0,Ke.jsx)(Cs,{form:p,onSaved:b})})]})]})}var He=oe(require("react"),1);var Ka=oe(require("react"),1);function ln(){let{api:e}=ae(),[t,n]=Ka.useState(null),[s,a]=Ka.useState(!0),[r,o]=Ka.useState(null),d=Ka.useRef(0),c=Ka.useCallback(async()=>{let u=++d.current;try{a(!0),o(null);let i=await e.getPaymentsStatus();if(u!==d.current)return;n(i)}catch(i){if(u!==d.current)return;o(i instanceof Error?i:new Error("Failed to fetch payments status"))}finally{u===d.current&&a(!1)}},[e]);return Ka.useEffect(()=>{c()},[c]),{status:t,isLoading:s,error:r,refetch:c}}var gc=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function da(e){return gc.has(e.toLowerCase())}function Z(e,t,n){let s=da(t)?e:e/100;try{return new Intl.NumberFormat(n,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Za(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 It(e,t){let n=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(n)||n<0)return null;let s=da(t)?n:n*100;return Math.round(s)}function at(e,t){return da(t)?e:e/100}function cr(e){return e.amount_paid??Math.max(0,Za(e)-(e.credit_applied??0))}var ue=require("react/jsx-runtime");function Ts(e){return e instanceof ht&&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 go(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${Z(e.amount_off,e.currency)} off`:"Discount unavailable"}function An(){let{api:e,siteToken:t}=ae();return(0,ue.jsx)(vc,{api:e},t)}function vc({api:e}){let{status:t,error:n}=ln(),[s,a]=He.useState([]),[r,o]=He.useState(null),[d,c]=He.useState(null),[u,i]=He.useState(!1),[g,v]=He.useState(!1),[f,l]=He.useState(""),[m,p]=He.useState(null),[b,S]=He.useState(null),[_,A]=He.useState(!1),y=He.useRef(0),P=He.useCallback(async N=>{let k=++y.current;i(!0),l("");try{let I=await e.getPromos(N);if(k!==y.current)return;a(C=>N?[...C,...I.promos.filter(ee=>!C.some(M=>M.id===ee.id))]:I.promos),o(I.next_cursor),c(I.checkout_enabled)}catch(I){k===y.current&&l(Ts(I))}finally{k===y.current&&i(!1)}},[e]);He.useEffect(()=>(P(),()=>{y.current++}),[P]);async function T(N){let k=++y.current;i(!0),l(""),A(!1);try{let I=await e.getPromo(N);k===y.current&&p(I)}catch(I){k===y.current&&l(Ts(I))}finally{k===y.current&&i(!1)}}async function L(){if(m){v(!0),i(!0),l("");try{let N=await e.disablePromo(m.id);if(p(N),!["inactive","expired","exhausted"].includes(N.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");A(!1),await P()}catch(N){l(Ts(N))}finally{v(!1),i(!1)}}}return b?(0,ue.jsx)(bc,{currency:t?.currency??void 0,replaces:b.replaces,onCancel:()=>S(null),onSave:async N=>{let k=b.replaces?await e.replacePromo(b.replaces.id,N):await e.createPromo(N),I=await e.getPromo(k.id);if(I.status==="pending"||I.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(I),S(null),await P()}}):(0,ue.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,ue.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,ue.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,ue.jsx)(R,{disabled:u||!t?.currency,onClick:()=>{l(""),S({})},children:"Create promo code"})]}),(0,ue.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,ue.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,ue.jsx)("p",{className:"af-text-sm",children:n?Ts(n):"Connect Stripe and set the payment currency before creating codes."}),f&&(0,ue.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[f," ",(0,ue.jsx)(R,{variant:"outline",disabled:u,onClick:()=>m?void T(m.id):void P(),children:"Refresh"})]}),m?(0,ue.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,ue.jsx)(R,{variant:"ghost",disabled:g,onClick:()=>{p(null),A(!1),P()},children:"Back to codes"}),(0,ue.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[m.code," \xB7 ",m.name]}),(0,ue.jsxs)("p",{children:[go(m)," \xB7 ",m.status]}),(0,ue.jsxs)("p",{className:"af-text-sm",children:[m.times_redeemed==null?"Usage unavailable":`${m.times_redeemed} redemptions`,m.max_redemptions!=null?` / ${m.max_redemptions} maximum`:""]}),(0,ue.jsxs)("p",{className:"af-text-sm",children:[m.minimum_amount!=null&&m.currency?`Minimum order: ${Z(m.minimum_amount,m.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,ue.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",m.duration==="repeating"?`${m.duration_in_months} months`:m.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,ue.jsx)("p",{className:"af-text-sm",children:m.expires_at?`Expires ${new Date(m.expires_at).toLocaleString()}`:"No expiry"}),(0,ue.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ue.jsx)(R,{variant:"outline",disabled:u,onClick:()=>void T(m.id),children:"Refresh details"}),(0,ue.jsx)(R,{variant:"outline",disabled:u||m.status==="pending"||m.status==="unavailable"||!t?.currency,onClick:()=>S({replaces:m}),children:"Replace with new code"}),(0,ue.jsx)(R,{variant:"outline",disabled:u||!["active","pending","unavailable"].includes(m.status),onClick:()=>A(!0),children:m.status==="pending"?"Cancel pending offer":"Disable code"})]}),_&&(0,ue.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,ue.jsxs)("p",{className:"af-text-sm",children:[m.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${m.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,ue.jsx)(R,{disabled:u,onClick:()=>void L(),children:m.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,ue.jsx)(R,{variant:"ghost",disabled:u,onClick:()=>A(!1),children:"Cancel"})]})]}):(0,ue.jsxs)(ue.Fragment,{children:[s.map(N=>(0,ue.jsxs)("button",{type:"button",disabled:u,onClick:()=>void T(N.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,ue.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,ue.jsx)("span",{className:"af-font-semibold af-break-all",children:N.code}),(0,ue.jsx)("span",{className:"af-text-sm",children:N.status})]}),(0,ue.jsxs)("div",{className:"af-text-sm",children:[go(N)," \xB7"," ",N.times_redeemed==null?"Usage unavailable":`${N.times_redeemed} redemptions`]})]},N.id)),!u&&!f&&s.length===0&&(0,ue.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,ue.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),r&&(0,ue.jsx)(R,{variant:"outline",disabled:u,onClick:()=>void P(r),children:"Load more"})]})]})}function bc({currency:e,replaces:t,onCancel:n,onSave:s}){let[a,r]=He.useState(""),[o,d]=He.useState(t?.name??""),[c,u]=He.useState(t?.amount_off!=null?"fixed":"percent"),[i,g]=He.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(at(t.amount_off,e)):"")),[v,f]=He.useState(t?.minimum_amount!=null&&e?String(at(t.minimum_amount,e)):""),[l,m]=He.useState(()=>{if(!t?.expires_at)return"";let re=new Date(t.expires_at);return Number.isFinite(re.getTime())?new Date(re.getTime()-re.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,b]=He.useState(t?.max_redemptions?.toString()??""),[S,_]=He.useState(t?.duration??"once"),[A,y]=He.useState(t?.duration_in_months?.toString()??"3"),[P,T]=He.useState(null),[L,N]=He.useState(!1),[k,I]=He.useState(""),C=He.useRef(!1),ee=e&&da(e)?"1":"0.01";async function M(re){if(re.preventDefault(),C.current)return;I("");let se=P;if(!se){if(!e){I("Payment currency is not available.");return}if(t&&a.trim().toUpperCase()===t.code.toUpperCase()){I("Choose a different code for the replacement.");return}let q=It(i,e),V=v?It(v,e):null;if(c==="fixed"&&(!q||q>999999999999)||v&&(!V||V>999999999999)){I("Enter a positive amount within the supported range.");return}if(l&&new Date(l).getTime()<=Date.now()){I("Choose a future expiry.");return}se={request_id:crypto.randomUUID(),code:a.trim().toUpperCase(),name:o.trim(),duration:S,...c==="percent"?{percent_off:Number(i)}:{amount_off:q,currency:e},...v?{minimum_amount:V,currency:e}:{},...l?{expires_at:new Date(l).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...S==="repeating"?{duration_in_months:Number(A)}:{}},T(se)}C.current=!0,N(!0);try{await s(se)}catch(q){I(Ts(q)),q instanceof ht&&q.status>=400&&q.status<500&&q.details?.retryable!==!0&&T(null)}finally{C.current=!1,N(!1)}}let te=(re,se,q,V={})=>(0,ue.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[re,(0,ue.jsx)(pe,{"aria-label":re,value:se,onChange:j=>q(j.target.value),...V})]}),ne="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,ue.jsxs)("form",{onSubmit:M,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,ue.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,ue.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,ue.jsxs)("fieldset",{disabled:L||!!P,className:"af-grid af-gap-4",children:[te("Code",a,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),te("Name",o,d,{required:!0,maxLength:40}),(0,ue.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,ue.jsxs)("select",{"aria-label":"Discount type",className:ne,value:c,onChange:re=>u(re.target.value),children:[(0,ue.jsx)("option",{value:"percent",children:"Percentage"}),(0,ue.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),te("Discount",i,g,{type:"number",required:!0,min:c==="percent"?"0.01":ee,max:c==="percent"?"100":void 0,step:c==="percent"?"0.01":ee}),te("Minimum order amount",v,f,{type:"number",min:ee,step:ee,placeholder:e?.toUpperCase()}),(0,ue.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."]}),te("Expires at (local time)",l,m,{type:"datetime-local",step:1}),te("Maximum redemptions",p,b,{type:"number",min:1,max:1e6,step:1}),(0,ue.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,ue.jsxs)("select",{"aria-label":"Subscription duration",className:ne,value:S,onChange:re=>_(re.target.value),children:[(0,ue.jsx)("option",{value:"once",children:"First invoice only"}),(0,ue.jsx)("option",{value:"forever",children:"Every invoice"}),(0,ue.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),S==="repeating"&&te("Months",A,y,{type:"number",required:!0,min:1,max:36,step:1})]}),k&&(0,ue.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:k}),P&&!L&&(0,ue.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,ue.jsx)("span",{className:"af-break-all",children:P.request_id})]}),(0,ue.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ue.jsx)(R,{type:"submit",disabled:L,children:L?"Saving\u2026":P?"Retry same request":t?"Create replacement":"Create code"}),(0,ue.jsx)(R,{type:"button",variant:"ghost",disabled:L||!!P,onClick:n,children:"Cancel"})]})]})}var ns=oe(require("react"),1),Pa=require("lucide-react");var ur=oe(require("react"),1),cn=require("lucide-react");var xe=require("react/jsx-runtime");function yc(e){if(e.allow_custom_amount){let t=e.min_amount!==null?Z(e.min_amount,e.currency):"?",n=e.max_amount!==null?Z(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${n})`}return e.unit_amount===null?"Varies by variant":Z(e.unit_amount,e.currency)}function hc(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function ks({productsState:e,onSelectProduct:t,onCreateProduct:n,className:s}){let{products:a,isLoading:r,error:o,deleteProduct:d}=e,[c,u]=ur.useState(null),[i,g]=ur.useState(!1),[v,f]=ur.useState(null),l=async()=>{if(c)try{g(!0),f(null),await d(c.id),u(null)}catch(m){f(m instanceof Error?m.message:"Failed to delete product")}finally{g(!1)}};return r?(0,xe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,xe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,xe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,xe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):a.length===0?(0,xe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[(0,xe.jsx)(cn.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,xe.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,xe.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,xe.jsxs)(R,{variant:"outline",onClick:()=>n?.(),children:[(0,xe.jsx)(cn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,xe.jsxs)("div",{className:s,children:[(0,xe.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,xe.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>n?.(),children:[(0,xe.jsx)(cn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,xe.jsxs)(ze,{children:[(0,xe.jsx)(qe,{children:(0,xe.jsxs)(Ne,{children:[(0,xe.jsx)(G,{children:"Name"}),(0,xe.jsx)(G,{children:"Price"}),(0,xe.jsx)(G,{children:"Fulfillment"}),(0,xe.jsx)(G,{children:"Status"}),(0,xe.jsx)(G,{className:"af-text-right",children:"Actions"})]})}),(0,xe.jsx)(je,{children:a.map(m=>(0,xe.jsxs)(Ne,{children:[(0,xe.jsx)(W,{className:"af-font-medium",children:m.name}),(0,xe.jsx)(W,{children:yc(m)}),(0,xe.jsx)(W,{className:"af-text-muted-foreground",children:hc(m)}),(0,xe.jsx)(W,{children:(0,xe.jsx)(ie,{variant:m.active?"success":"secondary",children:m.active?"Active":"Inactive"})}),(0,xe.jsx)(W,{className:"af-text-right",children:(0,xe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,xe.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>t?.(m),children:[(0,xe.jsx)(cn.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,xe.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>{f(null),u(m)},children:[(0,xe.jsx)(cn.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},m.id))})]}),(0,xe.jsx)(Wa,{open:!!c,onOpenChange:m=>{!m&&!i&&u(null)},children:(0,xe.jsxs)(Ba,{children:[(0,xe.jsxs)(Fa,{children:[(0,xe.jsx)(Ma,{children:"Delete product?"}),(0,xe.jsxs)($a,{children:['"',c?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),v&&(0,xe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),(0,xe.jsxs)(Ua,{children:[(0,xe.jsx)(R,{variant:"outline",onClick:()=>u(null),disabled:i,children:"Cancel"}),(0,xe.jsx)(R,{variant:"destructive",onClick:l,disabled:i,children:i?"Deleting...":"Delete"})]})]})})]})}var nt=oe(require("react"),1),fa=require("lucide-react");var xt=oe(require("react"),1),Na=require("lucide-react");var O=require("react/jsx-runtime");function Xr(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Es({productId:e,currency:t,className:n}){let{api:s}=ae(),a=da(t)?"1":"0.01",[r,o]=xt.useState(null),[d,c]=xt.useState(!0),[u,i]=xt.useState(null),[g,v]=xt.useState(null),[f,l]=xt.useState(!1),m=xt.useRef(!0);xt.useEffect(()=>(m.current=!0,()=>{m.current=!1}),[]);let p=xt.useCallback(async()=>{try{let D=await s.getProduct(e);if(!m.current)return;o(D)}catch(D){if(!m.current)return;i(D instanceof Error?D.message:"Failed to load product")}finally{m.current&&c(!1)}},[s,e]);xt.useEffect(()=>{p()},[p]);let b=async D=>{v(null),l(!0);try{await D(),await p()}catch(U){m.current&&v(U instanceof Error?U.message:"Something went wrong")}finally{m.current&&l(!1)}},[S,_]=xt.useState(""),[A,y]=xt.useState(""),[P,T]=xt.useState({}),L=()=>b(async()=>{let D=S.trim(),U=A.split(",").map(F=>F.trim()).filter(Boolean);if(!D)throw new Error("Option name is required");if(U.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:D,values:U}),m.current&&(_(""),y(""))}),N=D=>b(async()=>{let U=(P[D.id]??"").trim();if(!U)throw new Error("Enter a value");await s.updateOption(D.id,{add_values:[U]}),m.current&&T(F=>({...F,[D.id]:""}))}),k=(D,U)=>b(()=>s.updateOption(D.id,{remove_values:[U]})),I=D=>b(()=>s.deleteOption(D.id)),[C,ee]=xt.useState(null),[M,te]=xt.useState(null),[ne,re]=xt.useState(!1),[se,q]=xt.useState(null),V=r?.options??[],j=r?.variants??[],be=()=>{te(null),ee({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(V.map(D=>[D.id,D.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Je=D=>{te(null);let U=D.inventory?.on_hand??0,F=U<0?"":String(U);ee({variant:D,title:D.title??"",sku:D.sku??"",unitAmount:D.unit_amount!=null?String(at(D.unit_amount,t)):"",compareAt:D.compare_at_amount!=null?String(at(D.compare_at_amount,t)):"",active:D.active,optionValues:{},tracked:D.inventory?.tracked??!1,onHand:F,initialOnHand:F,allowBackorder:D.inventory?.allow_backorder??!1})},yt=async()=>{if(!C)return;te(null);let D=C.variant?.allow_custom_amount??!1,U=null,F=null;if(!D){if(U=It(C.unitAmount,t),U===null||U<=0){te("Enter a valid price");return}if(C.compareAt.trim()&&(F=It(C.compareAt,t),F===null||F<=U)){te("Compare-at price must be greater than the price");return}}let ye=C.onHand.trim()!==C.initialOnHand.trim(),Se=parseInt(C.onHand,10);if(C.tracked&&ye&&(!Number.isFinite(Se)||Se<0)){te("On-hand quantity must be zero or more");return}try{if(re(!0),C.variant)await s.updateVariant(C.variant.id,{title:C.title.trim()||null,sku:C.sku.trim()||null,...D?{}:{unit_amount:U,compare_at_amount:F},active:C.active}),await s.setVariantInventory(C.variant.id,{tracked:C.tracked,on_hand:C.tracked&&ye?Se:void 0,allow_backorder:C.allowBackorder});else{let Te={};for(let Ue of V){let it=C.optionValues[Ue.id];if(!it){te(`Choose a ${Ue.title}`),re(!1);return}Te[Ue.title]=it}await s.createVariant(e,{title:C.title.trim()||null,sku:C.sku.trim()||null,unit_amount:U,compare_at_amount:F,active:C.active,option_values:V.length>0?Te:void 0,inventory:C.tracked?{tracked:!0,on_hand:Se,allow_backorder:C.allowBackorder}:{tracked:!1,allow_backorder:C.allowBackorder}})}await p(),m.current&&ee(null)}catch(Te){if(m.current&&te(Te instanceof Error?Te.message:"Failed to save variant"),C.variant)try{let Ue=await s.getProduct(e);m.current&&o(Ue)}catch{}}finally{m.current&&re(!1)}},Oe=()=>b(async()=>{se&&(await s.deleteVariant(se.id),m.current&&q(null))}),Ve=C?.variant?.allow_custom_amount??!1,Ye=C?.variant!=null&&C.variant.option_values.length===0&&V.length>0&&!C.variant.active,Ae=C?.variant?.inventory!=null&&C.variant.inventory.on_hand<0?-C.variant.inventory.on_hand:null;function Et(D){let U=D.inventory;if(!U||!U.tracked)return(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let F=U.available??U.on_hand;return F<0?(0,O.jsxs)("span",{children:[-F," backordered"]}):(0,O.jsxs)("span",{children:[F," in stock",U.allow_backorder&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return d?(0,O.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${n||""}`,children:(0,O.jsx)(Na.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):u?(0,O.jsx)("div",{className:n,children:(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})}):(0,O.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,O.jsxs)("div",{className:"af-space-y-3",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)(Ce,{children:"Options"}),(0,O.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."})]}),V.length>0&&(0,O.jsx)("div",{className:"af-space-y-3",children:V.map(D=>(0,O.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)("span",{className:"af-text-sm af-font-medium",children:D.title}),(0,O.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>I(D),disabled:f,children:(0,O.jsx)(Na.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,O.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:D.values.map(U=>(0,O.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[U.value,(0,O.jsx)("button",{type:"button",onClick:()=>k(D,U.value),className:"af-ml-1 hover:af-text-destructive",disabled:f,title:"Remove value",children:(0,O.jsx)(Na.X,{className:"af-h-3 af-w-3"})})]},U.id))}),(0,O.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,O.jsx)(pe,{value:P[D.id]??"",onChange:U=>T(F=>({...F,[D.id]:U.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),N(D))},disabled:f}),(0,O.jsx)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>N(D),disabled:f||!(P[D.id]??"").trim(),children:(0,O.jsx)(Na.Plus,{className:"af-h-4 af-w-4"})})]})]},D.id))}),(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Ce,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,O.jsx)(pe,{id:"new-option-title",value:S,onChange:D=>_(D.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:f})]}),(0,O.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,O.jsx)(Ce,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,O.jsx)(pe,{id:"new-option-values",value:A,onChange:D=>y(D.target.value),placeholder:"S, M, L",disabled:f})]}),(0,O.jsxs)(R,{type:"button",variant:"outline",onClick:L,disabled:f||!S.trim()||!A.trim(),children:[(0,O.jsx)(Na.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,O.jsxs)("div",{className:"af-space-y-3",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)(Ce,{children:"Variants"}),(0,O.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:be,disabled:f||V.length===0,children:[(0,O.jsx)(Na.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),V.length===0&&(0,O.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,O.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,O.jsxs)(ze,{children:[(0,O.jsx)(qe,{children:(0,O.jsxs)(Ne,{children:[(0,O.jsx)(G,{children:"Variant"}),(0,O.jsx)(G,{children:"SKU"}),(0,O.jsx)(G,{children:"Price"}),(0,O.jsx)(G,{children:"Stock"}),(0,O.jsx)(G,{children:"Status"}),(0,O.jsx)(G,{className:"af-text-right",children:"Actions"})]})}),(0,O.jsx)(je,{children:j.map(D=>(0,O.jsxs)(Ne,{children:[(0,O.jsx)(W,{className:"af-font-medium",children:Xr(D)}),(0,O.jsx)(W,{className:"af-text-muted-foreground",children:D.sku||"-"}),(0,O.jsx)(W,{children:D.unit_amount!=null?(0,O.jsxs)("span",{children:[D.compare_at_amount!=null&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:Z(D.compare_at_amount,D.currency)}),Z(D.unit_amount,D.currency)]}):D.allow_custom_amount?(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,O.jsx)(W,{children:Et(D)}),(0,O.jsx)(W,{children:(0,O.jsx)(ie,{variant:D.active?"success":"secondary",children:D.active?"Active":"Inactive"})}),(0,O.jsx)(W,{className:"af-text-right",children:(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,O.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>Je(D),disabled:f,children:"Edit"}),(0,O.jsx)(R,{variant:"ghost",size:"icon",onClick:()=>q(D),disabled:f,title:"Delete variant",children:(0,O.jsx)(Na.Trash2,{className:"af-h-4 af-w-4"})})]})})]},D.id))})]})]}),g&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g}),(0,O.jsx)(Wa,{open:C!==null,onOpenChange:D=>{!D&&!ne&&ee(null)},children:(0,O.jsxs)(Ba,{children:[(0,O.jsxs)(Fa,{children:[(0,O.jsx)(Ma,{children:C?.variant?"Edit variant":"Add variant"}),(0,O.jsx)($a,{children:"Price, markdown, and stock live on the variant."})]}),C&&(0,O.jsxs)("div",{className:"af-space-y-3",children:[C.variant?C.variant.option_values.length>0&&(0,O.jsxs)("div",{className:"af-text-sm",children:[(0,O.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Xr(C.variant)]}):V.map(D=>(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Ce,{className:"af-text-xs af-text-muted-foreground",children:D.title}),(0,O.jsxs)(ya,{value:C.optionValues[D.id]??"",onValueChange:U=>ee(F=>F&&{...F,optionValues:{...F.optionValues,[D.id]:U}}),children:[(0,O.jsx)(oa,{children:(0,O.jsx)(ha,{placeholder:`Choose ${D.title}`})}),(0,O.jsx)(la,{children:D.values.map(U=>(0,O.jsx)(et,{value:U.value,children:U.value},U.id))})]})]},D.id)),Ve?(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Ce,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,O.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,O.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsxs)(Ce,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,O.jsx)(pe,{id:"variant-price",type:"number",min:"0",step:a,value:C.unitAmount,onChange:D=>ee(U=>U&&{...U,unitAmount:D.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Ce,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,O.jsx)(pe,{id:"variant-compare",type:"number",min:"0",step:a,value:C.compareAt,onChange:D=>ee(U=>U&&{...U,compareAt:D.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Ce,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,O.jsx)(pe,{id:"variant-sku",value:C.sku,onChange:D=>ee(U=>U&&{...U,sku:D.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,O.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,O.jsx)("input",{type:"checkbox",checked:C.tracked,onChange:D=>ee(U=>U&&{...U,tracked:D.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),C.tracked&&(0,O.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,O.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Ce,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,O.jsx)(pe,{id:"variant-onhand",type:"number",min:"0",step:"1",value:C.onHand,onChange:D=>ee(U=>U&&{...U,onHand:D.target.value}),placeholder:Ae!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,O.jsx)("input",{type:"checkbox",checked:C.allowBackorder,onChange:D=>ee(U=>U&&{...U,allowBackorder:D.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Ae!=null&&(0,O.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Ae," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,O.jsx)("input",{type:"checkbox",checked:C.active,onChange:D=>ee(U=>U&&{...U,active:D.target.checked}),className:"af-h-4 af-w-4",disabled:Ye}),"Active (buyers can purchase this variant)"]}),Ye&&(0,O.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."})]}),M&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:M})]}),(0,O.jsxs)(Ua,{children:[(0,O.jsx)(R,{variant:"outline",onClick:()=>ee(null),disabled:ne,children:"Cancel"}),(0,O.jsxs)(R,{onClick:yt,disabled:ne,children:[ne?(0,O.jsx)(Na.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,C?.variant?"Save":"Add variant"]})]})]})}),(0,O.jsx)(Wa,{open:se!==null,onOpenChange:D=>{!D&&!f&&q(null)},children:(0,O.jsxs)(Ba,{children:[(0,O.jsxs)(Fa,{children:[(0,O.jsx)(Ma,{children:"Delete variant?"}),(0,O.jsx)($a,{children:se&&`"${Xr(se)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,O.jsxs)(Ua,{children:[(0,O.jsx)(R,{variant:"outline",onClick:()=>q(null),disabled:f,children:"Cancel"}),(0,O.jsx)(R,{variant:"destructive",onClick:Oe,disabled:f,children:"Delete"})]})]})})]})}var J=require("react/jsx-runtime");function xc(e){if(e===0)return"0 B";let t=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${n[s]}`}function Is({productsState:e,product:t,currency:n,onSaved:s,className:a}){let{createProduct:r,updateProduct:o,attachProductFile:d,attachProductFileFromUrl:c}=e,u=!!t,i=t?.currency??n,g=da(i)?"1":"0.01",v=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[f,l]=nt.useState(!1),[m,p]=nt.useState(null),b=nt.useRef(!0);nt.useEffect(()=>(b.current=!0,()=>{b.current=!1}),[]);let[S,_]=nt.useState(t?.name??""),[A,y]=nt.useState(t?.description??""),[P,T]=nt.useState(t?.allow_custom_amount?"custom":"fixed"),[L,N]=nt.useState(t?.unit_amount!=null?String(at(t.unit_amount,i)):""),[k,I]=nt.useState(t?.min_amount!=null?String(at(t.min_amount,i)):""),[C,ee]=nt.useState(t?.max_amount!=null?String(at(t.max_amount,i)):""),[M,te]=nt.useState(String(t?.max_quantity??10)),ne=nt.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(at(t.unit_amount,i)):"",minAmount:t?.min_amount!=null?String(at(t.min_amount,i)):"",maxAmount:t?.max_amount!=null?String(at(t.max_amount,i)):"",maxQuantity:String(t?.max_quantity??10)}).current,[re,se]=nt.useState(t?.collect_shipping_address??!1),[q,V]=nt.useState(t?.active??!0),[j,be]=nt.useState(t?.images??[]),[Je,yt]=nt.useState(""),[Oe,Ve]=nt.useState(t?.fulfillment??null),[Ye,Ae]=nt.useState(!1),[Et,D]=nt.useState(""),[U,F]=nt.useState(null),ye=nt.useRef(null),Se=f||Ye,Te=()=>{let me=Je.trim();if(me){if(j.includes(me)){p("This image URL is already added");return}be(ke=>[...ke,me]),yt(""),p(null)}},Ue=me=>{be(ke=>ke.filter(ot=>ot!==me))},it=async()=>{if(p(null),!S.trim()){p("Product name is required");return}let me=null,ke=null,ot=null,ra=!u||P!==ne.pricingMode||(P==="fixed"?L!==ne.unitAmount:k!==ne.minAmount||C!==ne.maxAmount),Ot=!u||M!==ne.maxQuantity,Kt=v||P==="fixed";if(!(v||!ra))if(P==="fixed"){if(me=It(L,i),me===null||me<=0){p("Enter a valid price");return}}else{if(ke=It(k,i),ot=It(C,i),ke===null||ot===null){p("Enter valid minimum and maximum amounts");return}if(ot<ke){p("Maximum amount must be at least the minimum amount");return}}let Mt=parseInt(M,10);if(Kt&&Ot&&(!Number.isFinite(Mt)||Mt<1)){p("Max quantity must be at least 1");return}try{l(!0);let We;if(u&&t){let lt={name:S.trim(),description:A.trim()||null,images:j,collect_shipping_address:re,active:q};!v&&ra&&(lt.allow_custom_amount=P==="custom",P==="fixed"?lt.unit_amount=me:(lt.min_amount=ke,lt.max_amount=ot)),Kt&&Ot&&(lt.max_quantity=Mt),We=await o(t.id,lt),ne.pricingMode=We.allow_custom_amount?"custom":"fixed",ne.unitAmount=We.unit_amount!=null?String(at(We.unit_amount,i)):"",ne.minAmount=We.min_amount!=null?String(at(We.min_amount,i)):"",ne.maxAmount=We.max_amount!=null?String(at(We.max_amount,i)):"",ne.maxQuantity=String(We.max_quantity)}else{let lt={name:S.trim(),allow_custom_amount:P==="custom",collect_shipping_address:re,active:q};A.trim()&&(lt.description=A.trim()),j.length>0&&(lt.images=j),P==="fixed"?(lt.unit_amount=me,lt.max_quantity=Mt):(lt.min_amount=ke,lt.max_amount=ot),We=await r(lt)}if(!b.current)return;Ve(We.fulfillment),s?.(We)}catch(We){if(!b.current)return;p(We instanceof Error?We.message:"Failed to save product")}finally{b.current&&l(!1)}},Me=async me=>{let ke=me.target.files?.[0];if(!(!ke||!t))try{Ae(!0),F(null);let ot=await d(t.id,ke);if(!b.current)return;Ve(ot.fulfillment),s?.(ot)}catch(ot){if(!b.current)return;F(ot instanceof Error?ot.message:"Failed to upload file")}finally{b.current&&(Ae(!1),ye.current&&(ye.current.value=""))}},pt=async()=>{let me=Et.trim();if(!(!me||!t))try{Ae(!0),F(null);let ke=await c(t.id,me);if(!b.current)return;Ve(ke.fulfillment),D(""),s?.(ke)}catch(ke){if(!b.current)return;F(ke instanceof Error?ke.message:"Failed to fetch file")}finally{b.current&&Ae(!1)}};return(0,J.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,J.jsxs)("div",{className:"af-space-y-2",children:[(0,J.jsx)(Ce,{htmlFor:"product-name",children:"Name"}),(0,J.jsx)(pe,{id:"product-name",value:S,onChange:me=>_(me.target.value),placeholder:"My product"})]}),(0,J.jsxs)("div",{className:"af-space-y-2",children:[(0,J.jsx)(Ce,{htmlFor:"product-description",children:"Description"}),(0,J.jsx)("textarea",{id:"product-description",value:A,onChange:me=>y(me.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,J.jsxs)("div",{className:"af-space-y-2",children:[(0,J.jsx)(Ce,{children:"Pricing"}),v?(0,J.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,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(ya,{value:P,onValueChange:me=>T(me),children:[(0,J.jsx)(oa,{className:"af-w-[260px]",children:(0,J.jsx)(ha,{})}),(0,J.jsxs)(la,{children:[(0,J.jsx)(et,{value:"fixed",children:"Fixed price"}),(0,J.jsx)(et,{value:"custom",children:"Buyer chooses the amount"})]})]}),P==="fixed"?(0,J.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,J.jsxs)("div",{className:"af-space-y-1",children:[(0,J.jsxs)(Ce,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",i.toUpperCase(),")"]}),(0,J.jsx)(pe,{id:"product-price",type:"number",min:"0",step:g,value:L,onChange:me=>N(me.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,J.jsxs)("div",{className:"af-space-y-1",children:[(0,J.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,J.jsxs)("div",{className:"af-space-y-1",children:[(0,J.jsxs)(Ce,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",i.toUpperCase(),")"]}),(0,J.jsx)(pe,{id:"product-min-amount",type:"number",min:"0",step:g,value:k,onChange:me=>I(me.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,J.jsxs)("div",{className:"af-space-y-1",children:[(0,J.jsxs)(Ce,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",i.toUpperCase(),")"]}),(0,J.jsx)(pe,{id:"product-max-amount",type:"number",min:"0",step:g,value:C,onChange:me=>ee(me.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,J.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,J.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",i.toUpperCase(),"), which follows the country of your payment account."]})]}),(v||P==="fixed")&&(0,J.jsxs)("div",{className:"af-space-y-1",children:[(0,J.jsx)(Ce,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,J.jsx)(pe,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:M,onChange:me=>te(me.target.value),className:"af-w-[140px]"})]})]}),(0,J.jsxs)("div",{className:"af-space-y-2",children:[(0,J.jsx)(Ce,{children:"Images"}),(0,J.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,J.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[j.map(me=>(0,J.jsxs)(ie,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,J.jsx)("span",{className:"af-truncate",children:me}),(0,J.jsx)("button",{type:"button",onClick:()=>Ue(me),className:"af-ml-1 hover:af-text-destructive",disabled:f,children:(0,J.jsx)(fa.X,{className:"af-h-3 af-w-3"})})]},me)),j.length===0&&(0,J.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,J.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,J.jsx)(pe,{type:"url",value:Je,onChange:me=>yt(me.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:me=>{me.key==="Enter"&&(me.preventDefault(),Te())},disabled:f}),(0,J.jsx)(R,{type:"button",variant:"outline",onClick:Te,disabled:!Je.trim()||f,children:(0,J.jsx)(fa.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,J.jsxs)("div",{className:"af-space-y-2",children:[(0,J.jsx)(Ce,{children:"Digital File"}),(0,J.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,J.jsxs)("div",{className:"af-space-y-3",children:[Oe?.type==="download"&&(0,J.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,J.jsx)(fa.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,J.jsx)("span",{className:"af-text-sm",children:Oe.filename}),Oe.size!=null&&(0,J.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",xc(Oe.size),")"]})]}),Oe?.type==="redirect"&&Oe.url&&(0,J.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,J.jsx)(fa.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,J.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Oe.url]})]}),(0,J.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,J.jsx)("input",{ref:ye,type:"file",onChange:Me,className:"af-hidden",disabled:Se}),(0,J.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>ye.current?.click(),disabled:Se,children:[Ye?(0,J.jsx)(fa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,J.jsx)(fa.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Oe?.type==="download"?"Replace file":"Upload file"]}),(0,J.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,J.jsx)(pe,{type:"url",value:Et,onChange:me=>D(me.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Ye}),(0,J.jsx)(R,{type:"button",variant:"outline",size:"sm",onClick:pt,disabled:!Et.trim()||Se,children:"Fetch from URL"})]}),U&&(0,J.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:U})]}):(0,J.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,J.jsxs)("div",{className:"af-space-y-2",children:[(0,J.jsx)(Ce,{children:"Settings"}),(0,J.jsxs)("div",{className:"af-space-y-2",children:[(0,J.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,J.jsx)("input",{type:"checkbox",checked:re,onChange:me=>se(me.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,J.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,J.jsx)("input",{type:"checkbox",checked:q,onChange:me=>V(me.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),u&&t&&(0,J.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,J.jsx)(Ce,{children:"Options & Variants"}),(0,J.jsx)(Es,{productId:t.id,currency:i})]}),m&&(0,J.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m}),(0,J.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,J.jsxs)(R,{type:"button",onClick:it,disabled:Se,children:[f?(0,J.jsx)(fa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,u?"Save changes":"Create product"]})})]})}var Pt=oe(require("react"),1),pa=require("lucide-react");var ct=oe(require("react"),1);var wc=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function As({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ae(),[s,a]=ct.useState([]),[r,o]=ct.useState(0),[d,c]=ct.useState(!0),[u,i]=ct.useState(null),[g,v]=ct.useState(0),[f,l]=ct.useState(e),[m,p]=ct.useState(void 0),[b,S]=ct.useState(""),[_,A]=ct.useState(""),[y,P]=ct.useState(""),[T,L]=ct.useState(!1),[N,k]=ct.useState(!1),[I,C]=ct.useState(void 0),ee=I?I.join(","):"",M=ct.useMemo(()=>{if(!ee)return;let q=new Set(ee.split(","));return wc.filter(V=>!q.has(V))},[ee]),te=ct.useMemo(()=>{let q={};return m?q.status=m:M?q.excludeStatus=M:T||(q.excludeStatus=["pending","expired"]),b.trim()&&(q.customerEmail=b.trim()),_.trim()&&(q.from=_.trim()),y.trim()&&(q.to=y.trim()),N&&(q.unfulfilledOnly=!0),q},[m,M,T,b,_,y,N]),ne=ct.useRef(0),re=ct.useCallback(async()=>{let q=++ne.current;try{c(!0),i(null);let V={...te,limit:f,offset:g*f},j=await n.getOrders(V);if(q!==ne.current)return;a(j.orders),o(j.total)}catch(V){if(q!==ne.current)return;i(V instanceof Error?V:new Error("Failed to fetch orders"))}finally{q===ne.current&&c(!1)}},[n,g,f,te,t]);ct.useEffect(()=>{re()},[re]);let se=Math.ceil(r/f);return{orders:s,total:r,isLoading:d,error:u,page:g,pageSize:f,hasNextPage:g<se-1,hasPreviousPage:g>0,setPage:v,setPageSize:q=>{l(q),v(0)},status:m,setStatus:q=>{p(q),v(0)},statusIn:I,setStatusIn:q=>{C(q&&q.length>0?q:void 0),v(0)},customerEmail:b,setCustomerEmail:q=>{S(q),v(0)},from:_,setFrom:q=>{A(q),v(0)},to:y,setTo:q=>{P(q),v(0)},showAbandoned:T,setShowAbandoned:q=>{L(q),v(0)},unfulfilledOnly:N,setUnfulfilledOnly:q=>{k(q),v(0)},clearFilters:()=>{p(void 0),C(void 0),L(!1),k(!1),S(""),A(""),P(""),v(0)},filters:te,refetch:re}}var vt=oe(require("react"),1),De=require("lucide-react");var vo=oe(require("react"),1),Ja=oe(require("@radix-ui/react-popover"),1);var dr=require("react/jsx-runtime"),fr=Ja.Root,mr=Ja.Trigger;var Ds=vo.forwardRef(({className:e,align:t="end",sideOffset:n=4,...s},a)=>(0,dr.jsx)(Ja.Portal,{children:(0,dr.jsx)("div",{className:"aifeatures-admin",children:(0,dr.jsx)(Ja.Content,{ref:a,align:t,sideOffset:n,className:Q("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...s})})}));Ds.displayName=Ja.Content.displayName;var Ls=require("react/jsx-runtime"),Sc={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Nc(e){return Sc[e]??e}function bo(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 Dn({status:e,className:t}){return(0,Ls.jsx)(ie,{variant:bo(e),className:t,children:Nc(e)})}function _n({status:e}){return(0,Ls.jsx)(Dn,{status:e})}function Xn({order:e,className:t}){return e.line_items.some(n=>n.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,Ls.jsx)(ie,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Ls.jsx)(ie,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function un(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var h=require("react/jsx-runtime"),wo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ln="af-text-xs af-text-muted-foreground";function Qr(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 _c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function So(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 pr=24,Rc=["paid","partially_refunded"],Pc=["paid","partially_refunded","disputed"],Cc=/^[A-Za-z0-9 _-]*$/,yo=100;function ai(e,t,n,s,a){let r=Rc.includes(s);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"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${n} of ${pr} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${n} of ${pr} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?n<pr&&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."}:n<pr&&e==="buyer"&&!a?{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 ${n} attempt${n===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${s==="refunded"?"because the order was refunded":s==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function ho({title:e,recipient:t,status:n,attempts:s,side:a,orderStatus:r,action:o,delivery:d}){if(d)return(0,h.jsxs)("div",{children:[(0,h.jsx)(Ga,{deliveries:[d]}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]});let c=ai(a,n,s,r,t);return(0,h.jsxs)("div",{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)("div",{className:"af-text-sm",children:e}),t&&(0,h.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,h.jsx)(ie,{variant:c.variant,className:"af-shrink-0",children:c.label})]}),c.detail&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:c.detail}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]})}function xo(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let n=_c(e.address)?e.address:null;if(n){for(let a of["line1","line2"]){let r=n[a];typeof r=="string"&&r&&t.push(r)}let s=["city","state","postal_code"].map(a=>n[a]).filter(a=>typeof a=="string"&&!!a).join(", ");s&&t.push(s),typeof n.country=="string"&&n.country&&t.push(n.country)}return t.length>0?t:Object.entries(e).map(([s,a])=>`${s}: ${So(a)}`)}function Tc(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function ni({value:e,label:t,children:n,className:s,size:a="icon"}){let[r,o]=vt.useState(!1);if(!Tc())return null;let d=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},c=r?(0,h.jsx)(De.Check,{className:"af-h-3 af-w-3"}):(0,h.jsx)(De.Copy,{className:"af-h-3 af-w-3"});return a==="icon"?(0,h.jsx)(R,{variant:"ghost",size:"icon",className:Q("af-h-6 af-w-6 af-shrink-0",s),onClick:d,title:t,"aria-label":t,children:c}):(0,h.jsxs)(R,{variant:"outline",size:"sm",className:s,onClick:d,"aria-label":t,children:[r?(0,h.jsx)(De.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,h.jsx)(De.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":n]})}function ei({label:e,value:t}){return(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:Ln,children:e}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,h.jsx)(ni,{value:t,label:`Copy ${e}`})]})]})}function kc({src:e}){let[t,n]=vt.useState(!1);return!e||t?(0,h.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,h.jsx)(De.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,h.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>n(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Ya({title:e,action:t,children:n,className:s}){return(0,h.jsxs)("section",{className:Q("af-rounded-lg af-border af-p-4",s),children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,h.jsx)("h4",{className:wo,children:e}),t]}),(0,h.jsx)("div",{className:"af-mt-3",children:n})]})}function Xt({label:e,emphasis:t,divider:n,children:s}){return(0,h.jsxs)("div",{className:Q("af-flex af-items-baseline af-justify-between af-gap-6",n&&"af-mt-2 af-border-t af-pt-2"),children:[(0,h.jsx)("span",{className:t?"af-text-base af-font-semibold":Ln,children:e}),(0,h.jsx)("span",{className:Q("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function ti({onSelect:e,disabled:t,icon:n,children:s}){return(0,h.jsxs)(R,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,h.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:n}),s]})}function Ec(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 ${Z(cr(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let n=e.email_deliveries?.find(a=>a.kind==="purchase_receipt"),s=n?ir(n):ai("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(a=>a.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let n=e.email_deliveries?.find(a=>a.kind==="merchant_sale"),s=n?ir(n):ai("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(a=>a.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${Z(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function Os({order:e,onBack:t,onRefund:n,onOrderUpdated:s,allowFulfillment:a=!1,onPrevOrder:r,onNextOrder:o,hasPrevOrder:d=!1,hasNextOrder:c=!1}){let{api:u}=ae(),[i,g]=vt.useState(e),[v,f]=vt.useState(null),[l,m]=vt.useState(null),[p,b]=vt.useState(!1),[S,_]=vt.useState(!1),[A,y]=vt.useState(!1),[P,T]=vt.useState(!1),[L,N]=vt.useState(""),[k,I]=vt.useState(!1),[C,ee]=vt.useState(null),[M,te]=vt.useState(!1),[ne,re]=vt.useState(""),[se,q]=vt.useState([]),[V,j]=vt.useState(!1),[be,Je]=vt.useState(!1),[yt,Oe]=vt.useState(null);vt.useEffect(()=>{g(e)},[e]);let Ve=B=>{let Fe=B.id===i.id&&B.email_deliveries===void 0?{...B,email_deliveries:i.email_deliveries}:B;g(Fe),s?.(Fe)},Ye=Object.entries(i.metadata??{}),Ae=Math.max(0,cr(i)-i.amount_refunded),Et=(i.status==="paid"||i.status==="partially_refunded")&&Ae>0,D=i.exclusive_tax_total!=null,U=B=>typeof B.amountNet=="number"?B.amountNet+(B.exclusiveTax??0):(typeof B.unitAmount=="number"?B.unitAmount:0)*(typeof B.quantity=="number"&&B.quantity>0?B.quantity:1),F=Math.max(0,(i.shipping_total??0)-(i.shipping_refunded??0)),ye=se.reduce((B,Fe)=>B+U(i.line_items[Fe]??{}),0)+(V?F:0),Se=i.tax_total??0,Te=Math.max(0,(i.exclusive_tax_total??0)-i.line_items.reduce((B,Fe)=>B+(Fe.exclusiveTax??0),0)),Ue=D?V&&F>0?Te:0:i.automatic_tax&&i.tax_behavior==="exclusive"&&Se>0&&i.amount_total+(i.shipping_total??0)>0?Math.min(Math.max(0,Se-(i.tax_refunded??0)),Math.round(Se*ye/(i.amount_total+(i.shipping_total??0)))):0,it=i.source==="subscription"&&(i.credit_applied??0)>0&&i.line_items.length===1?Math.min(ye+Ue,Ae):ye+Ue,Me=se.length>0||V,pt=Me?it:It(ne,i.currency),me=da(i.currency)?"1":"0.01",ke=async()=>{try{b(!0),f(null),m(null),await u.resendOrderReceipt(i.id);let B=await u.getOrder(i.id);Ve(B),m("Receipt email queued.")}catch(B){f(B instanceof Error?B.message:"Failed to resend receipt")}finally{b(!1)}},ot=async()=>{try{_(!0),f(null),m(null);let B=await u.resetOrderDownloads(i.id);Ve(B),y(!1),m("Download count reset.")}catch(B){f(B instanceof Error?B.message:"Failed to reset downloads")}finally{_(!1)}},ra=i.line_items.some(B=>B.collectShippingAddress===!0&&!B.refunded&&!B.unavailableReason),Ot=typeof i.merchant_fulfilled_at=="string",Kt=Pc.includes(i.status)||i.status==="refunded"&&i.line_items.some(B=>B.collectShippingAddress===!0&&B.amountNet===0&&!B.refunded&&!B.unavailableReason),Mt=L.trim(),We=Cc.test(Mt)&&Mt.length<=yo,lt=async B=>{try{I(!0),ee(null),m(null);let Fe=await u.setOrderFulfillment(i.id,{fulfilled:B,...B&&Mt?{trackingNumber:Mt}:{}});Ve(Fe),N(""),m(B?"Marked as shipped.":"Marked as not shipped.")}catch(Fe){Fe instanceof ht&&Fe.status===409?ee(`This order is ${i.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):ee(Fe instanceof Error?Fe.message:"Failed to update the order")}finally{I(!1)}},Ia=()=>{Oe(null),re(String(at(Ae,i.currency))),q([]),j(!1),te(!0)},Tn=B=>q(Fe=>Fe.includes(B)?Fe.filter(Jt=>Jt!==B):[...Fe,B]),Zt=async(B,Fe)=>{if(n)try{Je(!0),Oe(null),await n(i,B,Fe);let Jt=await u.getOrder(i.id);Ve(Jt),te(!1),m("Refund issued.")}catch(Jt){Oe(Jt instanceof Error?Jt.message:"Refund failed")}finally{Je(!1)}},zr=async()=>{if(Me){if(it<=0){Oe("The lines you picked were charged nothing");return}if(it>Ae){Oe(`That selection exceeds the refundable remainder (${Z(Ae,i.currency)})`);return}await Zt(it,{...se.length>0?{line_items:[...se].sort((Fe,Jt)=>Fe-Jt)}:{},...V?{shipping:!0}:{}});return}let B=It(ne,i.currency);if(B===null||B<=0){Oe("Enter a valid refund amount");return}if(B>Ae){Oe(`Amount exceeds the refundable remainder (${Z(Ae,i.currency)})`);return}await Zt(B,{amount:B})},K=()=>Zt(Ae,{full:!0}),Xe=!i.subscription_history_only&&i.fulfillment_type==="download",qa=!i.subscription_history_only&&a&&ra,qr=Ec(i),Y=i.shipping_address?xo(i.shipping_address).join(`
4
- `):"",qt=i.shipping_total!=null,jr=i.exclusive_tax_total??(i.automatic_tax&&i.tax_behavior==="exclusive"?i.tax_total??0:0),Oi=i.exclusive_tax_total!=null?Math.max(0,(i.tax_total??0)-jr):i.automatic_tax&&i.tax_behavior==="exclusive"?0:i.tax_total??0,Bi=jr>0,zl=Oi>0,Fi=i.amount_subtotal!=null||qt||Bi||(i.discount_total??0)>0,ds=[];return i.subscription_history_only||ds.push((0,h.jsx)(ti,{icon:p?(0,h.jsx)(De.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,h.jsx)(De.Mail,{className:"af-h-4 af-w-4"}),disabled:p||i.fulfillment_status!=="fulfilled",onSelect:()=>{T(!1),ke()},children:"Resend receipt"},"resend")),Xe&&ds.push((0,h.jsx)(ti,{icon:(0,h.jsx)(De.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:S,onSelect:()=>{T(!1),y(!0)},children:"Reset download count"},"reset")),Et&&ds.push((0,h.jsxs)("div",{children:[(0,h.jsx)(ti,{icon:(0,h.jsx)(De.Undo2,{className:"af-h-4 af-w-4"}),disabled:!n,onSelect:()=>{T(!1),Ia()},children:"Refund\u2026"}),!n&&(0,h.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,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-mb-6",children:[(0,h.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,h.jsx)(De.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(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:[(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("h3",{className:"af-text-xl af-font-semibold",children:un(i)}),(0,h.jsx)(Dn,{status:i.status}),a&&!i.subscription_history_only&&(0,h.jsx)(Xn,{order:i}),i.is_test&&(0,h.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,h.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Qr(i.created_at)]}),i.is_test&&(0,h.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,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||o)&&(0,h.jsxs)("div",{className:"af-flex af-items-center",children:[(0,h.jsx)(R,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!d,"aria-label":"Previous order",children:(0,h.jsx)(De.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,h.jsx)(R,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!c,"aria-label":"Next order",children:(0,h.jsx)(De.ChevronRight,{className:"af-h-4 af-w-4"})})]}),qa&&(Ot?(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",i.merchant_fulfilled_at?` \xB7 ${Qr(i.merchant_fulfilled_at)}`:""]}),Kt&&(0,h.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>lt(!1),disabled:k,children:[k?(0,h.jsx)(De.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(De.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Kt?(0,h.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,h.jsx)(pe,{value:L,onChange:B=>N(B.target.value),placeholder:"Tracking number (optional)",maxLength:yo,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:k}),(0,h.jsxs)(R,{variant:"default",className:"af-shrink-0",onClick:()=>lt(!0),disabled:k||!We,children:[k?(0,h.jsx)(De.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(De.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),ds.length>0&&(0,h.jsxs)(fr,{open:P,onOpenChange:T,children:[(0,h.jsx)(mr,{asChild:!0,children:(0,h.jsx)(R,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,h.jsx)(De.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,h.jsx)(Ds,{children:(0,h.jsx)("div",{className:"af-space-y-0.5",children:ds})})]})]})]}),qa&&!Ot&&!We&&(0,h.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."}),C&&(0,h.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:C}),l&&(0,h.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:l}),v&&(0,h.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:v})]}),(0,h.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,h.jsxs)("div",{className:"af-space-y-6",children:[i.line_items.length>0&&(0,h.jsx)(Ya,{title:"Items",children:(0,h.jsx)("ul",{className:"af-space-y-3",children:i.line_items.map((B,Fe)=>{let Jt=typeof B.name=="string"&&B.name?B.name:"Item",Ui=typeof B.quantity=="number"&&B.quantity>0?B.quantity:1,Mi=typeof B.unitAmount=="number";return(0,h.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,h.jsx)(kc,{src:typeof B.imageUrl=="string"&&B.imageUrl?B.imageUrl:void 0}),(0,h.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,h.jsxs)("div",{className:"af-text-sm af-font-medium",children:[Jt,typeof B.variantTitle=="string"&&B.variantTitle&&(0,h.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",B.variantTitle]})]}),(0,h.jsxs)("div",{className:Ln,children:[Ui," \xD7"," ",Mi?Z(B.unitAmount,i.currency):"\u2014"]}),B.unavailableReason==="oversold"&&!B.refunded&&(0,h.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:B.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),B.refunded===!0&&(0,h.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:B.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,h.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof B.amountNet=="number"||Mi?Z(B.amountNet??B.unitAmount*Ui,i.currency):"\u2014"})]},Fe)})})}),Ye.length>0&&(0,h.jsx)(Ya,{title:"Order details",children:(0,h.jsx)("dl",{className:"af-space-y-2",children:Ye.map(([B,Fe])=>(0,h.jsxs)("div",{children:[(0,h.jsx)("dt",{className:Q(Ln,"af-capitalize"),children:B.replace(/_/g," ")}),(0,h.jsx)("dd",{className:"af-text-sm af-break-words",children:So(Fe)})]},B))})}),(0,h.jsx)(Ya,{title:"Totals",children:(0,h.jsxs)("div",{className:"af-w-full",children:[Fi&&(0,h.jsx)(Xt,{label:"Subtotal",children:Z(i.amount_subtotal??i.amount_total+(i.discount_total??0),i.currency)}),(i.discount_total??0)>0&&(0,h.jsxs)(Xt,{label:"Discount",children:["\u2212",Z(i.discount_total,i.currency)]}),qt&&(0,h.jsx)(Xt,{label:"Shipping",children:i.shipping_total===0?"Free":Z(i.shipping_total??0,i.currency)}),Bi&&(0,h.jsx)(Xt,{label:"Tax",children:Z(jr,i.currency)}),(0,h.jsx)(Xt,{label:"Total",emphasis:!0,divider:Fi,children:Z(Za(i),i.currency)}),(i.credit_applied??0)>0&&(0,h.jsxs)(Xt,{label:"Credit applied",children:["\u2212",Z(i.credit_applied,i.currency)]}),i.amount_paid!=null&&(0,h.jsx)(Xt,{label:"Amount paid",children:Z(i.amount_paid,i.currency)}),zl&&(0,h.jsx)(Xt,{label:"incl. tax",children:Z(Oi,i.currency)}),i.base_currency!=null&&i.base_amount_total!=null&&(0,h.jsxs)(Xt,{label:"Your price",children:[Z(i.base_amount_total,i.base_currency),(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",i.currency.toUpperCase()]})]}),i.amount_refunded>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(Xt,{label:"Refunded",children:["\u2212",Z(i.amount_refunded,i.currency),(i.shipping_refunded??0)>0&&(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",Z(i.shipping_refunded??0,i.currency)," ","shipping"]})]}),(0,h.jsx)(Xt,{label:"Net",children:(0,h.jsx)("span",{className:"af-font-medium",children:Z(Math.max(0,cr(i)-i.amount_refunded),i.currency)})})]})]})}),i.application_fee_state&&(0,h.jsxs)(Ya,{title:"Platform fee",children:[i.application_fee_original!=null&&(0,h.jsx)(Xt,{label:"Collected",children:Z(i.application_fee_original,i.application_fee_currency??i.currency)}),i.application_fee_returned!=null&&(0,h.jsx)(Xt,{label:"Returned",children:Z(i.application_fee_returned,i.application_fee_currency??i.currency)}),i.application_fee_retained!=null&&(0,h.jsx)(Xt,{label:"Retained",children:Z(i.application_fee_retained,i.application_fee_currency??i.currency)}),i.application_fee_state!=="complete"&&(0,h.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:i.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,h.jsx)(Ya,{title:"Timeline",children:(0,h.jsx)("ol",{className:"af-space-y-3",children:qr.map(B=>(0,h.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,h.jsx)("span",{"aria-hidden":"true",className:Q("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",B.tone==="destructive"?"af-bg-destructive":B.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsx)("div",{className:"af-text-sm af-break-words",children:B.text}),B.at&&(0,h.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:Qr(B.at)})]})]},B.key))})})]}),(0,h.jsxs)("div",{className:"af-space-y-6",children:[(0,h.jsx)(Ya,{title:"Customer",children:(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:Ln,children:"Email"}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:i.customer_email||(0,h.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),i.customer_email&&(0,h.jsx)(ni,{value:i.customer_email,label:"Copy email"})]})]}),i.customer_name&&(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:Ln,children:"Name"}),(0,h.jsx)("div",{className:"af-text-sm",children:i.customer_name})]}),i.customer&&(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:Ln,children:"Customer record"}),(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("span",{className:"af-break-all af-text-sm",children:i.customer.name||i.customer.email}),(0,h.jsx)(ie,{variant:"secondary",children:"Linked"})]})]})]})}),i.shipping_address&&(0,h.jsx)(Ya,{title:"Ship to",action:(0,h.jsx)(ni,{value:Y,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,h.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:xo(i.shipping_address).map((B,Fe)=>(0,h.jsx)("div",{children:B},Fe))})}),i.subscription_history_only?(0,h.jsx)(Ya,{title:"Subscription history",children:(0,h.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,h.jsxs)(Ya,{title:"Emails",children:[(0,h.jsx)(Ga,{deliveries:i.email_deliveries?.filter(B=>!["purchase_receipt","merchant_sale"].includes(B.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,h.jsxs)("div",{className:"af-space-y-4",children:[(0,h.jsx)(ho,{side:"buyer",title:"Receipt to buyer",delivery:i.email_deliveries?.find(B=>B.kind==="purchase_receipt"),recipient:i.customer_email,status:i.buyer_email_status,attempts:i.buyer_email_attempts,orderStatus:i.status,action:(0,h.jsxs)(R,{variant:"outline",size:"sm",onClick:ke,disabled:p||i.fulfillment_status!=="fulfilled",children:[p?(0,h.jsx)(De.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(De.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,h.jsx)(ho,{side:"merchant",title:"Sale alert to you",delivery:i.email_deliveries?.find(B=>B.kind==="merchant_sale"),recipient:null,status:i.merchant_email_status,attempts:i.merchant_email_attempts,orderStatus:i.status})]})]}),Xe&&(0,h.jsx)(Ya,{title:"Download",children:(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,h.jsx)(De.Download,{className:"af-h-4 af-w-4"}),(0,h.jsxs)("span",{children:["Downloaded ",i.download_count," time",i.download_count===1?"":"s"]})]}),i.download_url&&(0,h.jsx)("a",{href:i.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,h.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,h.jsx)("summary",{className:Q(wo,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,h.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,h.jsx)(ei,{label:"Order ID",value:i.id}),i.stripe_checkout_session_id&&(0,h.jsx)(ei,{label:"Checkout session",value:i.stripe_checkout_session_id}),i.stripe_payment_intent_id&&(0,h.jsx)(ei,{label:"Payment",value:i.stripe_payment_intent_id})]})]})]})]}),(0,h.jsx)(Wa,{open:A,onOpenChange:B=>{!B&&!S&&y(!1)},children:(0,h.jsxs)(Ba,{children:[(0,h.jsxs)(Fa,{children:[(0,h.jsx)(Ma,{children:"Reset download count?"}),(0,h.jsx)($a,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,h.jsxs)(Ua,{children:[(0,h.jsx)(R,{variant:"outline",onClick:()=>y(!1),disabled:S,children:"Cancel"}),(0,h.jsx)(R,{onClick:ot,disabled:S,children:S?"Resetting...":"Reset"})]})]})}),(0,h.jsx)(Wa,{open:M,onOpenChange:B=>{!B&&!be&&te(!1)},children:(0,h.jsxs)(Ba,{children:[(0,h.jsxs)(Fa,{children:[(0,h.jsx)(Ma,{children:"Refund order"}),(0,h.jsxs)($a,{children:["Refund up to ",Z(Ae,i.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,h.jsxs)("div",{className:"af-space-y-4",children:[(i.line_items.length>0||F>0)&&(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsx)(Ce,{children:"Items"}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[i.line_items.map((B,Fe)=>{let Jt=B.refunded===!0;return(0,h.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,h.jsx)("input",{type:"checkbox",checked:se.includes(Fe),onChange:()=>Tn(Fe),disabled:be||Jt||!!B.unavailableReason||U(B)<=0,className:"af-h-4 af-w-4"}),(0,h.jsxs)("span",{className:Jt?"af-text-muted-foreground af-line-through":void 0,children:[typeof B.name=="string"&&B.name?B.name:"Item",typeof B.variantTitle=="string"&&B.variantTitle?` \u2014 ${B.variantTitle}`:"",typeof B.quantity=="number"&&B.quantity>1?` \xD7 ${B.quantity}`:""]}),(0,h.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Jt?"Refunded":Z(U(B),i.currency)})]},Fe)}),F>0&&(0,h.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,h.jsx)("input",{type:"checkbox",checked:V,onChange:B=>j(B.target.checked),disabled:be,className:"af-h-4 af-w-4"}),(0,h.jsx)("span",{children:"Shipping"}),(0,h.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Z(F,i.currency)})]})]})]}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)(Ce,{htmlFor:"refund-amount",children:["Amount (",i.currency.toUpperCase(),")"]}),(0,h.jsx)(pe,{id:"refund-amount",type:"number",min:"0",step:me,value:Me?String(at(it,i.currency)):ne,onChange:B=>re(B.target.value),disabled:be||Me}),Me&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),yt&&(0,h.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:yt}),(0,h.jsxs)(Ua,{children:[(0,h.jsx)(R,{variant:"outline",onClick:()=>te(!1),disabled:be,children:"Cancel"}),(0,h.jsx)(R,{variant:"outline",onClick:K,disabled:be,children:"Refund everything"}),(0,h.jsx)(R,{variant:"destructive",onClick:zr,disabled:be,children:be?"Refunding...":pt!==null&&pt>0?`Refund ${Z(pt,i.currency)}`:"Refund"})]})]})})]})}var gr=oe(require("react"),1),vr=require("lucide-react");var st=require("react/jsx-runtime");function wt({title:e,onBackToWebsite:t,hideBackButton:n=!1,children:s,className:a}){let r=gr.useRef(null);return gr.useEffect(()=>{r.current?.focus()},[]),(0,st.jsxs)("div",{className:Q("af-bg-background",a),children:[(0,st.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,st.jsx)("h2",{ref:r,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&&!n&&(0,st.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,st.jsx)(vr.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,st.jsx)("div",{className:"af-p-4",children:s})]})}function le({className:e}){return(0,st.jsx)("div",{"aria-hidden":"true",className:Q("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function ut({label:e,children:t,detail:n,valueClassName:s}){return(0,st.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,st.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,st.jsx)("div",{className:Q("af-mt-1 af-text-lg af-font-semibold",s),children:t}),n&&(0,st.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:n})]})}function ma({message:e,onRetry:t}){return(0,st.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,st.jsx)("span",{children:e}),(0,st.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,st.jsx)(vr.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Va({icon:e,children:t}){return(0,st.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,st.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function Qn({icon:e,heading:t,body:n,action:s,className:a,children:r}){return(0,st.jsxs)("div",{className:Q("af-px-6 af-py-10 af-text-center",a),children:[(0,st.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,st.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,st.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:n}),s&&(0,st.jsx)(R,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}var E=require("react/jsx-runtime"),Ic={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},No={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function _o(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 Ro(e){let t=Array.isArray(e.line_items)?e.line_items:[],n=t[0];if(!n)return"\u2014";let s=typeof n.name=="string"&&n.name?n.name:"Item",a=typeof n.quantity=="number"&&n.quantity>0?n.quantity:1,r=a>1?`${s} \xD7${a}`:s;return t.length>1?`${r} +${t.length-1} more`:r}function br(e){return e.customer?.name||e.customer_name||null}function Ac({onRefund:e,className:t,refreshKey:n,initialOrderId:s,showFulfillment:a=!1,emptyMessage:r,onDetailOpenChange:o,maxRows:d,onViewAll:c}){let u=typeof d=="number",{api:i}=ae(),g=As({refreshKey:n}),{orders:v,total:f,isLoading:l,error:m,page:p,pageSize:b,hasNextPage:S,hasPreviousPage:_,setPage:A,setPageSize:y,customerEmail:P,setCustomerEmail:T,setStatusIn:L,from:N,setFrom:k,to:I,setTo:C,showAbandoned:ee,setShowAbandoned:M,setUnfulfilledOnly:te,filters:ne,refetch:re}=g,se=Pt.useCallback(()=>i.exportOrdersCsv(ne),[i,ne]),[q,V]=Pt.useState("list"),[j,be]=Pt.useState(null),[Je,yt]=Pt.useState(""),[Oe,Ve]=Pt.useState(""),[Ye,Ae]=Pt.useState(!u&&a?"needs_shipping":"all"),[Et,D]=Pt.useState(!1),[U,F]=Pt.useState(!!s&&!u),[ye,Se]=Pt.useState(null);Pt.useEffect(()=>{if(!s||u)return;let Y=!1;return F(!0),Se(null),i.getOrder(s).then(qt=>{Y||(be(qt),V("detail"))}).catch(()=>{Y||Se("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{Y||F(!1)}),()=>{Y=!0}},[i,s,u]);let Te=Pt.useCallback(Y=>{Ae(Y);let qt=No[Y];L(qt.statusIn),te(qt.unfulfilledOnly)},[L,te]);Pt.useEffect(()=>{a&&!u&&te(!0)},[]);let Ue=Pt.useRef(!a);Pt.useEffect(()=>{Ue.current||l||(Ue.current=!0,v.length===0&&Te("all"))},[l,v.length,Te]);let it=q==="detail"&&!!j;Pt.useEffect(()=>{o?.(it)},[it,o]);let Me=(N?1:0)+(I?1:0)+(ee?1:0),pt=Me>0||!!P||!!Oe,me=!!N&&!!I&&N>I,ke=!u||!!c,ot=Y=>{if(u){c?.();return}be(Y),V("detail")},ra=()=>{V("list"),be(null),re()},Ot=Y=>{let qt=Y.trim();if(!qt){Ve(""),P&&T("");return}if(qt.startsWith("#")||/^\d+$/.test(qt)){Ve(qt),P&&T("");return}Ve(""),T(qt)},Kt=()=>{yt(""),Ve(""),T(""),k(""),C(""),M(!1),D(!1)},Mt=Oe.replace(/^#/,"").toLowerCase(),We=Mt?v.filter(Y=>String(Y.order_number??"")===Mt||Y.id.toLowerCase().startsWith(Mt)):v,lt=u?We.slice(0,d):We,Ia=j?v.findIndex(Y=>Y.id===j.id):-1,Tn=Ia>0,Zt=Ia>=0&&Ia<v.length-1;if(U)return(0,E.jsx)("div",{className:t,children:(0,E.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,E.jsx)(pa.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(q==="detail"&&j)return(0,E.jsx)("div",{className:t,children:(0,E.jsx)(Os,{order:j,onBack:ra,onRefund:e,onOrderUpdated:Y=>be(Y),allowFulfillment:a,onPrevOrder:Tn?()=>be(v[Ia-1]):void 0,onNextOrder:Zt?()=>be(v[Ia+1]):void 0,hasPrevOrder:Tn,hasNextOrder:Zt},j.id)});let K=(0,E.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[ye&&(0,E.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:ye}),(0,E.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,E.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:(a?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(Y=>(0,E.jsx)("button",{type:"button","aria-pressed":Ye===Y,onClick:()=>Te(Y),className:Q("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",Ye===Y?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ic[Y]},Y))}),(0,E.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,E.jsx)(pa.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,E.jsx)(pe,{type:"text",value:Je,onChange:Y=>yt(Y.target.value),onBlur:()=>Ot(Je),onKeyDown:Y=>{Y.key==="Enter"&&(Y.preventDefault(),Ot(Je))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,E.jsxs)(R,{type:"button",variant:Me>0?"secondary":"ghost",size:"sm",onClick:()=>D(Y=>!Y),"aria-expanded":Et,children:[(0,E.jsx)(pa.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Me>0&&(0,E.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:Me})]}),pt&&(0,E.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:Kt,children:"Clear filters"}),(0,E.jsx)(Bt,{fetchCsv:se,filename:"orders",disabled:!!Oe,className:"af-ml-auto"})]}),(Et||!!N||!!I)&&(0,E.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,E.jsx)(Ce,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,E.jsx)(pe,{id:"orders-from",type:"date",value:N,max:I||void 0,onChange:Y=>k(Y.target.value),className:"af-w-[170px]"}),(0,E.jsx)(Ce,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,E.jsx)(pe,{id:"orders-to",type:"date",value:I,min:N||void 0,onChange:Y=>C(Y.target.value),className:"af-w-[170px]"}),!No[Ye].statusIn&&(0,E.jsx)(R,{type:"button",variant:ee?"secondary":"ghost",size:"sm",onClick:()=>M(!ee),"aria-pressed":ee,children:ee?"Hide abandoned":"Show abandoned"})]}),me&&(0,E.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(l)return(0,E.jsxs)("div",{className:t,children:[u?null:K,(0,E.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(Y=>(0,E.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,E.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,E.jsx)(le,{className:"af-h-4 af-w-16"}),(0,E.jsx)(le,{className:"af-h-4 af-w-14"})]}),(0,E.jsx)(le,{className:"af-mt-2 af-h-3 af-w-40"}),(0,E.jsx)(le,{className:"af-mt-2 af-h-3 af-w-24"})]},Y))}),(0,E.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,E.jsxs)(ze,{children:[(0,E.jsx)(qe,{children:(0,E.jsxs)(Ne,{children:[(0,E.jsx)(G,{children:"Order"}),(0,E.jsx)(G,{children:"Date"}),(0,E.jsx)(G,{children:"Customer"}),(0,E.jsx)(G,{children:"Items"}),(0,E.jsx)(G,{className:"af-text-right",children:"Total"}),(0,E.jsx)(G,{children:"Status"}),(0,E.jsx)(G,{className:"af-w-8"})]})}),(0,E.jsx)(je,{"aria-hidden":"true",children:[0,1,2,3,4].map(Y=>(0,E.jsxs)(Ne,{children:[(0,E.jsx)(W,{children:(0,E.jsx)(le,{className:"af-h-4 af-w-14"})}),(0,E.jsx)(W,{children:(0,E.jsx)(le,{className:"af-h-4 af-w-24"})}),(0,E.jsx)(W,{children:(0,E.jsx)(le,{className:"af-h-4 af-w-40"})}),(0,E.jsx)(W,{children:(0,E.jsx)(le,{className:"af-h-4 af-w-32"})}),(0,E.jsx)(W,{children:(0,E.jsx)(le,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,E.jsx)(W,{children:(0,E.jsx)(le,{className:"af-h-5 af-w-16"})}),(0,E.jsx)(W,{})]},Y))})]})}),(0,E.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(m)return(0,E.jsxs)("div",{className:t,children:[u?null:K,(0,E.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,E.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,E.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>re(),children:"Try again"})]})]});let Xe=Ye!=="all";if(We.length===0&&p===0)return pt||Xe?(0,E.jsxs)("div",{className:t,children:[!u&&K,(0,E.jsx)(Va,{children:"No orders match these filters."})]}):(0,E.jsx)("div",{className:t,children:(0,E.jsx)(Qn,{icon:pa.Receipt,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!u&&(0,E.jsx)(R,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>M(!0),children:"Show abandoned checkouts"})})});let qa=p*b+1,qr=Math.min((p+1)*b,f);return(0,E.jsxs)("div",{className:t,children:[u?null:K,(0,E.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:lt.map(Y=>(0,E.jsxs)("button",{type:"button",onClick:()=>ot(Y),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,E.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,E.jsx)("span",{className:"af-font-medium",children:un(Y)}),(0,E.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:Z(Za(Y),Y.currency)})]}),(0,E.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,E.jsxs)("div",{className:"af-truncate af-text-sm",children:[Y.customer_email||(0,E.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),br(Y)&&(0,E.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",br(Y)]})]}),(0,E.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Ro(Y)}),Y.amount_refunded>0&&(0,E.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Z(Y.amount_refunded,Y.currency)," refunded"]})]}),(0,E.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,E.jsx)(Dn,{status:Y.status}),(0,E.jsx)(bs,{deliveries:Y.email_deliveries}),Y.is_test&&(0,E.jsx)(ie,{variant:"outline",children:"Test"}),a&&(0,E.jsx)(Xn,{order:Y}),(0,E.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:_o(Y.created_at)})]})]},Y.id))}),(0,E.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,E.jsxs)(ze,{children:[(0,E.jsx)(qe,{children:(0,E.jsxs)(Ne,{children:[(0,E.jsx)(G,{children:"Order"}),(0,E.jsx)(G,{children:"Date"}),(0,E.jsx)(G,{children:"Customer"}),(0,E.jsx)(G,{children:"Items"}),(0,E.jsx)(G,{className:"af-text-right",children:"Total"}),(0,E.jsx)(G,{children:"Status"}),(0,E.jsx)(G,{className:"af-w-8"})]})}),(0,E.jsx)(je,{children:lt.map(Y=>(0,E.jsxs)(Ne,{onClick:ke?()=>ot(Y):void 0,className:ke?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,E.jsxs)(W,{className:"af-whitespace-nowrap af-font-medium",children:[(0,E.jsx)("button",{type:"button",onClick:qt=>{qt.stopPropagation(),ot(Y)},disabled:!ke,"aria-label":`Open order ${un(Y)}`,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:un(Y)}),Y.is_test&&(0,E.jsx)(ie,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,E.jsx)(W,{className:"af-whitespace-nowrap af-text-muted-foreground",children:_o(Y.created_at)}),(0,E.jsxs)(W,{className:"af-max-w-[220px]",children:[(0,E.jsx)("div",{className:"af-truncate",children:Y.customer_email||(0,E.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),br(Y)&&(0,E.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:br(Y)})]}),(0,E.jsx)(W,{className:"af-max-w-[220px]",children:(0,E.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:Ro(Y)})}),(0,E.jsxs)(W,{className:"af-whitespace-nowrap af-text-right",children:[(0,E.jsx)("div",{className:"af-font-medium af-tabular-nums",children:Z(Za(Y),Y.currency)}),Y.amount_refunded>0&&(0,E.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Z(Y.amount_refunded,Y.currency)," ","refunded"]})]}),(0,E.jsx)(W,{children:(0,E.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,E.jsx)(Dn,{status:Y.status}),(0,E.jsx)(bs,{deliveries:Y.email_deliveries}),a&&(0,E.jsx)(Xn,{order:Y})]})}),(0,E.jsx)(W,{className:"af-w-8 af-text-right",children:(0,E.jsx)(pa.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},Y.id))})]})}),u?null:(0,E.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,E.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,E.jsx)("span",{children:Mt?`${We.length} matching this page`:`Showing ${qa}-${qr} of ${f}`}),(0,E.jsxs)(ya,{value:String(b),onValueChange:Y=>y(Number(Y)),children:[(0,E.jsx)(oa,{className:"af-w-[70px] af-h-8",children:(0,E.jsx)(ha,{})}),(0,E.jsxs)(la,{children:[(0,E.jsx)(et,{value:"10",children:"10"}),(0,E.jsx)(et,{value:"25",children:"25"}),(0,E.jsx)(et,{value:"50",children:"50"}),(0,E.jsx)(et,{value:"100",children:"100"})]})]}),(0,E.jsx)("span",{children:"per page"})]}),(0,E.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,E.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>A(p-1),disabled:!_,children:[(0,E.jsx)(pa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,E.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>A(p+1),disabled:!S,children:["Next",(0,E.jsx)(pa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function dn(e){return(0,E.jsx)(Ac,{...e},e.maxRows==null?"full":"compact")}var es=oe(require("react"),1),Xa=require("lucide-react");var Qt=oe(require("react"),1);function Bs({initialPageSize:e=25}={}){let{api:t}=ae(),[n,s]=Qt.useState([]),[a,r]=Qt.useState(0),[o,d]=Qt.useState(!0),[c,u]=Qt.useState(null),[i,g]=Qt.useState(0),[v,f]=Qt.useState(e),[l,m]=Qt.useState(""),p=Qt.useRef(0),b=Qt.useCallback(async()=>{let _=++p.current;try{d(!0),u(null);let A={limit:v,offset:i*v};l.trim()&&(A.email=l.trim());let y=await t.getCustomers(A);if(_!==p.current)return;s(y.customers),r(y.total)}catch(A){if(_!==p.current)return;u(A instanceof Error?A:new Error("Failed to fetch customers"))}finally{_===p.current&&d(!1)}},[t,i,v,l]);Qt.useEffect(()=>{b()},[b]);let S=Math.ceil(a/v);return{customers:n,total:a,isLoading:o,error:c,page:i,pageSize:v,hasNextPage:i<S-1,hasPreviousPage:i>0,setPage:g,setPageSize:_=>{f(_),g(0)},email:l,setEmail:_=>{m(_),g(0)},refetch:b}}var On=oe(require("react"),1),yr=require("lucide-react");var ve=require("react/jsx-runtime");function Po(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 Dc(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let n=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return n&&t.push(n),e.country&&t.push(e.country),t}function Fs({customer:e,onBack:t,className:n}){let{api:s}=ae(),[a,r]=On.useState(null),[o,d]=On.useState([]),[c,u]=On.useState(!0),[i,g]=On.useState(null);On.useEffect(()=>{let l=!1;return u(!0),g(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([m,p])=>{l||(r(m),d(p.orders))}).catch(m=>{l||g(m instanceof Error?m.message:"Failed to load customer")}).finally(()=>{l||u(!1)}),()=>{l=!0}},[s,e.id,e.email]);let v=a?.addresses??[],f=a?.order_count??o.length;return(0,ve.jsxs)("div",{className:n,children:[(0,ve.jsxs)("div",{className:"af-mb-6",children:[(0,ve.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,ve.jsx)(yr.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,ve.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,ve.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Po(e.created_at)]})]}),c?(0,ve.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ve.jsx)(yr.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):i?(0,ve.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i}):(0,ve.jsxs)("div",{className:"af-space-y-6",children:[(0,ve.jsx)(Ga,{deliveries:a?.email_deliveries}),(0,ve.jsxs)("div",{children:[(0,ve.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,ve.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,ve.jsx)("span",{children:e.email})]}),e.name&&(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,ve.jsx)("span",{children:e.name})]}),e.phone&&(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,ve.jsx)("span",{children:e.phone})]}),(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,ve.jsx)("span",{children:f})]})]})]}),v.length>0&&(0,ve.jsxs)("div",{children:[(0,ve.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,ve.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:v.map(l=>(0,ve.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[l.is_default&&(0,ve.jsx)(ie,{variant:"secondary",className:"af-mb-1",children:"Default"}),Dc(l).map((m,p)=>(0,ve.jsx)("div",{children:m},p))]},l.id))})]}),(0,ve.jsxs)("div",{children:[(0,ve.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,ve.jsxs)(ze,{children:[(0,ve.jsx)(qe,{children:(0,ve.jsxs)(Ne,{children:[(0,ve.jsx)(G,{children:"Date"}),(0,ve.jsx)(G,{children:"Amount"}),(0,ve.jsx)(G,{children:"Status"})]})}),(0,ve.jsx)(je,{children:o.map(l=>(0,ve.jsxs)(Ne,{children:[(0,ve.jsx)(W,{className:"af-text-muted-foreground",children:Po(l.created_at)}),(0,ve.jsx)(W,{children:Z(Za(l),l.currency)}),(0,ve.jsx)(W,{children:(0,ve.jsx)(_n,{status:l.status})})]},l.id))})]})]})]})]})}var de=require("react/jsx-runtime");function Lc(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 Us({className:e}){let{customers:t,total:n,isLoading:s,error:a,page:r,pageSize:o,hasNextPage:d,hasPreviousPage:c,setPage:u,setPageSize:i,email:g,setEmail:v,refetch:f}=Bs(),{api:l}=ae(),m=es.useCallback(()=>l.exportCustomersCsv(),[l]),[p,b]=es.useState("list"),[S,_]=es.useState(null),[A,y]=es.useState(""),P=I=>{_(I),b("detail")},T=()=>{b("list"),_(null),f()};if(p==="detail"&&S)return(0,de.jsx)("div",{className:e,children:(0,de.jsx)(Fs,{customer:S,onBack:T})});let L=(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,de.jsx)(pe,{type:"email",value:A,onChange:I=>y(I.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),v(A.trim()))}}),(0,de.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>v(A.trim()),children:[(0,de.jsx)(Xa.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),g&&(0,de.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>{y(""),v("")},children:"Clear"}),(0,de.jsx)(Bt,{fetchCsv:m,filename:"customers",className:"af-ml-auto"})]});if(s)return(0,de.jsxs)("div",{className:e,children:[L,(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(a)return(0,de.jsxs)("div",{className:e,children:[L,(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: ",a.message]})})]});if(t.length===0&&r===0)return(0,de.jsxs)("div",{className:e,children:[g&&L,(0,de.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,de.jsx)(Xa.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:g?"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 N=r*o+1,k=Math.min((r+1)*o,n);return(0,de.jsxs)("div",{className:e,children:[L,(0,de.jsxs)(ze,{children:[(0,de.jsx)(qe,{children:(0,de.jsxs)(Ne,{children:[(0,de.jsx)(G,{children:"Email"}),(0,de.jsx)(G,{children:"Name"}),(0,de.jsx)(G,{children:"Phone"}),(0,de.jsx)(G,{children:"Customer since"}),(0,de.jsx)(G,{className:"af-text-right",children:"Actions"})]})}),(0,de.jsx)(je,{children:t.map(I=>(0,de.jsxs)(Ne,{children:[(0,de.jsx)(W,{className:"af-font-medium",children:I.email}),(0,de.jsx)(W,{children:I.name||(0,de.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,de.jsx)(W,{children:I.phone||(0,de.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,de.jsx)(W,{className:"af-text-muted-foreground",children:Lc(I.created_at)}),(0,de.jsx)(W,{className:"af-text-right",children:(0,de.jsx)(R,{variant:"ghost",size:"icon",onClick:()=>P(I),title:"View customer",children:(0,de.jsx)(Xa.Eye,{className:"af-h-4 af-w-4"})})})]},I.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 ",N,"-",k," of ",n]}),(0,de.jsxs)(ya,{value:String(o),onValueChange:I=>i(Number(I)),children:[(0,de.jsx)(oa,{className:"af-w-[70px] af-h-8",children:(0,de.jsx)(ha,{})}),(0,de.jsxs)(la,{children:[(0,de.jsx)(et,{value:"10",children:"10"}),(0,de.jsx)(et,{value:"25",children:"25"}),(0,de.jsx)(et,{value:"50",children:"50"}),(0,de.jsx)(et,{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)(R,{variant:"outline",size:"sm",onClick:()=>u(r-1),disabled:!c,children:[(0,de.jsx)(Xa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,de.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>u(r+1),disabled:!d,children:["Next",(0,de.jsx)(Xa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ie=oe(require("react"),1),Nt=require("lucide-react");var St=oe(require("react"),1);function Bn({initialPageSize:e=25,refreshKey:t,includeAggregates:n=!1}={}){let{api:s}=ae(),[a,r]=St.useState([]),[o,d]=St.useState(0),[c,u]=St.useState(null),[i,g]=St.useState(!0),[v,f]=St.useState(null),[l,m]=St.useState(0),[p,b]=St.useState(e),[S,_]=St.useState(void 0),[A,y]=St.useState(""),[P,T]=St.useState(""),[L,N]=St.useState(""),[k,I]=St.useState(""),[C,ee]=St.useState(""),M=S?S.join(","):"",te=St.useRef(0),ne=St.useCallback(async()=>{let se=++te.current;g(!0),f(null);try{let q={labels:M?M.split(","):void 0,customerEmail:A||void 0,q:P||void 0,from:L||void 0,to:k||void 0,retainerId:C||void 0,includeAggregates:n,limit:p,offset:l*p},V=await s.getInvoices(q);if(se!==te.current)return;if(l>0&&l*p>=V.total){m(Math.max(0,Math.ceil(V.total/p)-1));return}r(V.invoices),d(V.total),n&&u(V.aggregates??null)}catch(q){if(se!==te.current)return;f(q instanceof Error?q:new Error("Failed to fetch invoices"))}finally{se===te.current&&g(!1)}},[s,M,A,P,L,k,C,l,p,n]);St.useEffect(()=>{ne()},[ne,t]);let re=se=>q=>{m(0),se(q)};return{invoices:a,total:o,aggregates:c,isLoading:i,error:v,page:l,pageSize:p,hasNextPage:(l+1)*p<o,hasPreviousPage:l>0,setPage:m,setPageSize:re(b),labels:S,setLabels:re(_),customerEmail:A,setCustomerEmail:re(y),q:P,setQ:re(T),from:L,setFrom:re(N),to:k,setTo:re(I),retainerId:C,setRetainerId:re(ee),clearFilters:()=>{m(0),_(void 0),y(""),T(""),N(""),I(""),ee("")},refetch:ne}}var x=require("react/jsx-runtime"),Oc={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 oi(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Oc[e.label]??e.label}function Bc(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 ii={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Fc={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function as({invoice:e,className:t}){return(0,x.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,x.jsx)(ie,{variant:Bc(e.label),className:t,children:oi(e)}),e.collection_method==="charge_automatically"&&(0,x.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"})]})}function wr({delivery:e,className:t}){if(!e)return null;let n=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,x.jsx)(ie,{variant:n,className:t,children:ii[e.state]??e.state})}function ts(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function Ra(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,n=new Date(t);return Number.isNaN(n.getTime())?e:n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Co={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},hr={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},si=100,ri=5e3;async function Uc(e,t){let n=[],s=0;for(let a=0;a<ri;a+=si){let r=await e.getInvoices({...t,limit:si,offset:a});if(s=r.total,n.push(...r.invoices),r.invoices.length<si||n.length>=s)break}return{invoices:n.slice(0,ri),total:s,truncated:s>n.length||s>ri}}function ko(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"],n=e.map(s=>[s.id,ts(s),oi(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),Z(s.amount_subtotal,s.currency),Z(s.tax_total,s.currency),Z(s.amount_total,s.currency),s.amount_due===null?"":Z(s.amount_due,s.currency),s.amount_paid===null?"":Z(s.amount_paid,s.currency),Z(s.amount_refunded,s.currency),s.payment_method??"",s.pay_url??"",s.retainer_id??"",s.replaces_order_id??"",s.replaced_by_order_id??"",s.tax_behavior??"",s.discount_total===void 0?"":Z(s.discount_total,s.currency),s.collection_method??""]);return[t,...n].map(s=>s.map(ro).join(",")).join(`
5
- `)}function Mc(e){lr(new Blob([ko(e)],{type:"text/csv;charset=utf-8"}),or("invoices"))}function $c({className:e,refreshKey:t,initialInvoiceId:n,onDetailOpenChange:s,onConnectStripe:a,onUpgradePlan:r,needsPaidPlan:o=!1,retainerFilter:d=null,onClearRetainerFilter:c,maxRows:u,onViewAll:i}){let g=typeof u=="number",{api:v}=ae(),{invoices:f,total:l,isLoading:m,error:p,page:b,pageSize:S,hasNextPage:_,hasPreviousPage:A,setPage:y,labels:P,setLabels:T,customerEmail:L,setCustomerEmail:N,q:k,setQ:I,from:C,setFrom:ee,to:M,setTo:te,retainerId:ne,setRetainerId:re,refetch:se}=Bn({refreshKey:t}),[q,V]=Ie.useState(typeof u=="number"?"all":"open"),[j,be]=Ie.useState(""),[Je,yt]=Ie.useState(null),Oe=Ie.useRef(0),Ve=!g||!!i,Ye=Ie.useCallback(K=>{if(g){i?.();return}Oe.current++,Et(!1),yt(K)},[g,i]),[Ae,Et]=Ie.useState(!1),[D,U]=Ie.useState(0),[F,ye]=Ie.useState(null),[Se,Te]=Ie.useState(!1),[Ue,it]=Ie.useState(0);Ie.useEffect(()=>{yt(K=>{if(!K)return K;let Xe=f.find(qa=>qa.id===K.id);return Xe&&Xe!==K?Xe:K})},[f]);let[Me,pt]=Ie.useState(!1),[me,ke]=Ie.useState(null),ot=async()=>{if(!Me){pt(!0),ke(null);try{let{invoices:K,total:Xe,truncated:qa}=await Uc(v,{labels:P,customerEmail:L,q:k,from:C,to:M,retainerId:ne});Mc(K),ke(qa?`Exported the first ${K.length.toLocaleString()} of ${Xe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{ke("Couldn't export \u2014 try again.")}finally{pt(!1)}}},ra=!L&&!k&&!C&&!M&&!ne,[Ot,Kt]=Ie.useState(null);Ie.useEffect(()=>{if(m||l>0||!ra||q!=="open")return;let K=!1;return v.getInvoices({limit:1}).then(Xe=>{K||Kt(Xe.total>0)}).catch(()=>{K||Kt(!0)}),()=>{K=!0}},[v,m,l,ra,q,t]),Ie.useEffect(()=>{T(g?hr.all:hr.open)},[]),Ie.useEffect(()=>{let K=d?.id??"";K!==ne&&(re(K),K&&(V("all"),T(hr.all),N(""),I(""),be(""),ee(""),te("")))},[d?.id]),Ie.useEffect(()=>{let K=!1;return Te(!1),v.getInvoiceSettings().then(Xe=>{K||ye({payments_active:Xe.payments_active,blocked:Xe.blocked})}).catch(()=>{K||Te(!0)}),()=>{K=!0}},[v,t,Ue]),Ie.useEffect(()=>{if(!n||g)return;let K=!1,Xe=Oe.current;return Et(!1),v.getInvoice(n).then(qa=>{!K&&Xe===Oe.current&&yt(qa)}).catch(()=>{!K&&Xe===Oe.current&&Et(!0)}),()=>{K=!0}},[v,n,D,g]),Ie.useEffect(()=>{s?.(Je!==null)},[Je,s]);let Mt=K=>{V(K),T(hr[K])},We=K=>{let Xe=K.trim();if(!Xe){k&&I(""),L&&N("");return}if(Xe.includes("@")){k&&I(""),N(Xe);return}L&&N(""),I(Xe.replace(/^#/,""))},lt=f,Ia=g?lt.slice(0,u):lt,Tn=Ae&&(0,x.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,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>U(K=>K+1),children:"Retry opening invoice"})]});if(Je)return(0,x.jsxs)("div",{className:e,children:[Tn,(0,x.jsx)(Sr,{invoice:Je,refreshKey:t,onBack:()=>{Ye(null),se()}},Je.id)]});let Zt=(0,x.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[Se&&(0,x.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>it(K=>K+1),children:"Retry setup check"})]}),Tn,F?.blocked&&(0,x.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",F.blocked.reason?`: ${F.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),d&&(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,x.jsxs)(ie,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",d.label]}),c&&(0,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:c,children:"Clear schedule filter"})]}),(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,x.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(Co).map(K=>(0,x.jsx)("button",{type:"button","aria-pressed":q===K,onClick:()=>Mt(K),className:Q("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",q===K?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Co[K]},K))}),(0,x.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,x.jsx)(Nt.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,x.jsx)(pe,{type:"text",value:j,onChange:K=>be(K.target.value),onBlur:()=>We(j),onKeyDown:K=>{K.key==="Enter"&&(K.preventDefault(),We(j))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,x.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,x.jsx)(Ce,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,x.jsx)(pe,{id:"invoices-from",type:"date",value:C,max:M||void 0,onChange:K=>ee(K.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,x.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,x.jsx)(Ce,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,x.jsx)(pe,{id:"invoices-to",type:"date",value:M,min:C||void 0,onChange:K=>te(K.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,x.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>void ot(),disabled:Me||m||!!p||l===0,"aria-busy":Me,children:[(0,x.jsx)(Nt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),Me?"Exporting\u2026":"Export CSV (all matching)"]})]}),me&&(0,x.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:me})]});return m?(0,x.jsxs)("div",{className:e,children:[g?null:Zt,(0,x.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(K=>(0,x.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,x.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,x.jsx)(le,{className:"af-h-4 af-w-20"}),(0,x.jsx)(le,{className:"af-h-4 af-w-16"})]}),(0,x.jsx)(le,{className:"af-mt-2 af-h-3 af-w-40"})]},K))})]}):p?(0,x.jsxs)("div",{className:e,children:[g?null:Zt,(0,x.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>void se(),children:"Retry"})]})]}):l===0&&ra&&(q==="all"||Ot===!1)&&(q==="open"||q==="all")?F?.blocked?(0,x.jsxs)("div",{className:e,children:[g?null:Zt,(0,x.jsx)(xr,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,x.jsxs)("div",{className:e,children:[g?null:Zt,(0,x.jsx)(xr,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):F&&!F.payments_active?(0,x.jsxs)("div",{className:e,children:[g?null:Zt,(0,x.jsx)(xr,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:a?{label:"Payment setup",onClick:a}:void 0})]}):(0,x.jsxs)("div",{className:e,children:[g?null:Zt,(0,x.jsx)(xr,{heading:"No invoices yet",body:!F||Se?"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,x.jsxs)("div",{className:e,children:[g?null:Zt,Ia.length===0?(0,x.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,x.jsxs)(x.Fragment,{children:[(0,x.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Ia.map(K=>(0,x.jsxs)("button",{type:"button",onClick:()=>Ye(K),disabled:!Ve,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ve?" hover:af-bg-muted/50":""}`,children:[(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,x.jsx)("span",{className:"af-font-medium",children:ts(K)}),(0,x.jsx)(as,{invoice:K})]}),(0,x.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:K.customer_name??K.customer_email??"\u2014"}),K.delivery&&(0,x.jsx)("div",{className:"af-mt-1",children:(0,x.jsx)(wr,{delivery:K.delivery})}),(0,x.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,x.jsx)("span",{children:K.collection_method==="charge_automatically"?"Automatic collection":K.due_at?`Due ${Ra(K.due_at)}`:"Due on receipt"}),(0,x.jsx)("span",{className:"af-font-medium af-tabular-nums",children:Z(K.amount_due??K.amount_total,K.currency)})]})]},K.id))}),(0,x.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,x.jsxs)(ze,{children:[(0,x.jsx)(qe,{children:(0,x.jsxs)(Ne,{children:[(0,x.jsx)(G,{children:"Invoice"}),(0,x.jsx)(G,{children:"Created"}),(0,x.jsx)(G,{children:"Customer"}),(0,x.jsx)(G,{children:"Due"}),(0,x.jsx)(G,{className:"af-text-right",children:"Amount"}),(0,x.jsx)(G,{children:"Status"}),(0,x.jsx)(G,{children:"Delivery"}),(0,x.jsx)(G,{className:"af-w-8"})]})}),(0,x.jsx)(je,{children:Ia.map(K=>(0,x.jsxs)(Ne,{className:Ve?"af-cursor-pointer":void 0,onClick:Ve?()=>Ye(K):void 0,children:[(0,x.jsx)(W,{className:"af-font-medium",children:(0,x.jsx)("button",{type:"button",disabled:!Ve,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ve?" hover:af-underline":""}`,onClick:Xe=>{Xe.stopPropagation(),Ye(K)},"aria-label":`Open invoice ${ts(K)}`,children:ts(K)})}),(0,x.jsx)(W,{children:Ra(K.created_at)}),(0,x.jsxs)(W,{children:[(0,x.jsx)("div",{children:K.customer_name??"\u2014"}),(0,x.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:K.customer_email})]}),(0,x.jsx)(W,{children:K.collection_method==="charge_automatically"?"Automatic":K.due_at?Ra(K.due_at):"On receipt"}),(0,x.jsx)(W,{className:"af-text-right af-tabular-nums",children:Z(K.amount_due??K.amount_total,K.currency)}),(0,x.jsx)(W,{children:(0,x.jsx)(as,{invoice:K})}),(0,x.jsx)(W,{children:(0,x.jsx)(wr,{delivery:K.delivery})}),(0,x.jsx)(W,{children:(0,x.jsx)(Nt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},K.id))})]})}),g?null:(0,x.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,x.jsxs)("span",{children:[l," invoice",l===1?"":"s"]}),(0,x.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,x.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b-1),disabled:!A,"aria-label":"Previous page",children:(0,x.jsx)(Nt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,x.jsxs)("span",{className:"af-tabular-nums",children:[b*S+1,"\u2013",Math.min((b+1)*S,l)]}),(0,x.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b+1),disabled:!_,"aria-label":"Next page",children:(0,x.jsx)(Nt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function xr({heading:e,body:t,action:n}){return(0,x.jsx)(Qn,{icon:Nt.FileText,heading:e,body:t,action:n})}function mn(e){return(0,x.jsx)($c,{...e},e.maxRows==null?"full":"compact")}var fn="af-text-xs af-text-muted-foreground";function To(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Sr({invoice:e,onBack:t,refreshKey:n,className:s}){let{api:a}=ae(),r=Ie.useRef(null);Ie.useEffect(()=>{r.current?.focus()},[e.id]);let[o,d]=Ie.useState(!1),[c,u]=Ie.useState(null),[i,g]=Ie.useState(!1),[v,f]=Ie.useState(!1),l=Ie.useRef(0),[m,p]=Ie.useState(null),[b,S]=Ie.useState(!1),[_,A]=Ie.useState(0);Ie.useEffect(()=>{let C=!1;return S(!1),a.getInvoice(e.id).then(ee=>{C||p({source:e,value:ee})}).catch(()=>{C||S(!0)}),()=>{C=!0}},[a,e,n,_]);let y=m?.source===e?m.value:e,P=y.collection_method==="charge_automatically";Ie.useEffect(()=>(l.current++,u(null),g(!1),f(!1),d(!1),()=>{l.current++}),[a,y,n]);let T=C=>C==null?"\u2014":Z(C,y.currency),L=async()=>{if(!(!y.pay_url||!To()))try{await navigator.clipboard.writeText(y.pay_url),d(!0),setTimeout(()=>d(!1),1500)}catch{}},N=async()=>{if(c){u(null);return}let C=++l.current;f(!1),g(!0);try{let ee=await a.getInvoicePreview(y.id);C===l.current&&u(ee)}catch{C===l.current&&f(!0)}finally{C===l.current&&g(!1)}},k=y.bill_to,I=k?[k.company,k.name,k.address?.line1,k.address?.line2,[k.address?.city,k.address?.state,k.address?.postal_code].filter(Boolean).join(", "),k.address?.country,k.tax_id?`${k.tax_id.value}`:null,k.po_number?`PO ${k.po_number}`:null,k.service_period?`Service period: ${k.service_period}`:null].filter(C=>!!C&&C.length>0):[];return(0,x.jsxs)("div",{className:s,children:[(0,x.jsxs)("div",{className:"af-mb-4",children:[(0,x.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,x.jsx)(Nt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,x.jsxs)("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",ts(y)]}),(0,x.jsx)(as,{invoice:y}),(0,x.jsx)(wr,{delivery:y.delivery})]}),(0,x.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[y.customer_name??y.customer_email,y.customer_name&&y.customer_email?` \xB7 ${y.customer_email}`:""]})]}),b&&(0,x.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,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>A(C=>C+1),children:"Retry details"})]}),y.label==="failed"&&(0,x.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."}),y.label==="creating"&&(0,x.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,x.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,x.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,x.jsxs)(ze,{children:[(0,x.jsx)(qe,{children:(0,x.jsxs)(Ne,{children:[(0,x.jsx)(G,{children:"Description"}),(0,x.jsx)(G,{className:"af-text-right",children:"Qty"}),(0,x.jsx)(G,{className:"af-text-right",children:"Amount"})]})}),(0,x.jsx)(je,{children:y.line_items.map((C,ee)=>(0,x.jsxs)(Ne,{children:[(0,x.jsx)(W,{style:{overflowWrap:"anywhere"},children:C.description}),(0,x.jsx)(W,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:C.quantity}),(0,x.jsx)(W,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:T(C.amount)})]},ee))})]}),(0,x.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,x.jsx)(Rn,{label:"Subtotal",value:T(y.amount_subtotal)}),(y.discount_total??0)>0&&(0,x.jsx)(Rn,{label:"Discount",value:`-${T(y.discount_total)}`}),y.tax_total>0&&(0,x.jsx)(Rn,{label:y.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:T(y.tax_total)}),(0,x.jsx)(Rn,{label:"Total",value:T(y.amount_total),strong:!0}),y.credit_applied>0&&(0,x.jsx)(Rn,{label:"Credit applied",value:`-${T(y.credit_applied)}`}),y.amount_due!==null&&y.amount_due!==y.amount_total&&(0,x.jsx)(Rn,{label:"Amount due",value:T(y.amount_due),strong:!0}),y.amount_paid!==null&&y.amount_paid>0&&(0,x.jsx)(Rn,{label:"Amount paid",value:T(y.amount_paid)}),y.amount_refunded>0&&(0,x.jsx)(Rn,{label:"Refunded",value:T(y.amount_refunded)})]}),y.credit_notes?.length>0&&(0,x.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,x.jsx)("div",{className:fn,children:"Credit notes"}),y.credit_notes.map(C=>(0,x.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,x.jsxs)("span",{className:"af-text-muted-foreground",children:[Ra(C.created_at)," \xB7 ",C.origin==="dashboard"?"issued in Stripe":"refund",C.stripe_credit_note_id?"":" \xB7 being created"]}),(0,x.jsxs)("span",{className:"af-tabular-nums",children:["-",Z(C.amount,C.currency)]})]},C.id))]})]}),(y.note||y.footer)&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[y.note&&(0,x.jsxs)("div",{children:[(0,x.jsx)("div",{className:fn,children:"Note"}),(0,x.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:y.note})]}),y.footer&&(0,x.jsxs)("div",{children:[(0,x.jsx)("div",{className:fn,children:"Footer"}),(0,x.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:y.footer})]})]}),c&&!P&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,x.jsxs)("div",{className:Q(fn,"af-break-words"),children:["Email preview \u2014 ",c.subject]}),(0,x.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,x.jsx)("iframe",{title:"Invoice email preview",srcDoc:c.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,x.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,x.jsx)(_a,{label:"Created",value:Ra(y.created_at)}),(0,x.jsx)(_a,{label:"Due",value:y.collection_method==="charge_automatically"?"Managed in Stripe":y.due_at?Ra(y.due_at):"On receipt"}),y.paid_at&&(0,x.jsx)(_a,{label:"Paid",value:Ra(y.paid_at)}),y.payment_method&&(0,x.jsx)(_a,{label:"Paid by",value:y.paid_out_of_band?`${y.payment_method} (recorded outside Stripe)`:y.payment_method}),y.payment_state!=="none"&&(0,x.jsx)(_a,{label:"Payment",value:y.payment_state==="processing"?"Processing":y.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),y.delivery&&(0,x.jsx)(_a,{label:"Delivery",value:`${ii[y.delivery.state]} \xB7 ${y.delivery.recipient}`}),y.marked_uncollectible_at&&(0,x.jsx)(_a,{label:"Written off",value:Ra(y.marked_uncollectible_at)}),y.correction_reason&&(0,x.jsx)(_a,{label:"Correction",value:y.correction_reason}),y.replaced_by_order_id&&(0,x.jsx)(_a,{label:"Replaced by",value:y.replaced_by_order_id}),y.collection_method==="charge_automatically"?(0,x.jsx)(_a,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):y.retainer_id&&(0,x.jsx)(_a,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),y.replaces_order_id&&(0,x.jsx)(_a,{label:"Replaces",value:y.replaces_order_id})]}),(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,x.jsx)("div",{className:fn,children:"Reminders"}),P?(0,x.jsx)("div",{children:"View automatic payment reminders in Stripe."}):y.reminders.disabled?(0,x.jsx)("div",{children:"Off for this invoice."}):y.reminders.paused_until?(0,x.jsxs)("div",{children:["Paused until ",Ra(y.reminders.paused_until),"."]}):y.reminders.next_at?(0,x.jsxs)("div",{children:["Next on ",Ra(y.reminders.next_at),"."]}):y.reminders.final_sent_at?(0,x.jsxs)("div",{children:["Final reminder sent ",Ra(y.reminders.final_sent_at),"."]}):(0,x.jsx)("div",{children:"None scheduled."}),!P&&(0,x.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",y.reminders.schedule.length===0?"none":y.reminders.schedule.map(C=>C<0?`${-C}d before`:C===0?"due day":`${C}d after`).join(", ")]})]}),y.communications&&y.communications.length>0&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,x.jsx)("div",{className:fn,children:"Email delivery history"}),y.communications.map(C=>(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,x.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[Fc[C.kind]??C.kind,C.kind==="reminder"&&C.slot!==null?` #${C.slot}`:"",(0,x.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",C.recipient]})]}),(0,x.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[ii[C.state]??C.state," \xB7 ",Ra(C.state_at??C.created_at)]})]},C.id))]}),I.length>0&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,x.jsx)("div",{className:fn,children:"Bill to"}),I.map((C,ee)=>(0,x.jsx)("div",{className:"af-break-words",children:C},ee))]}),(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[y.pay_url&&(0,x.jsxs)(R,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void L(),disabled:!To(),children:[(0,x.jsx)(Nt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":P?"Copy invoice link":"Copy pay link"]}),y.pdf_url&&(0,x.jsx)(R,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,x.jsxs)("a",{href:y.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,x.jsx)(Nt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!P&&(0,x.jsxs)(R,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void N(),disabled:i,children:[i?(0,x.jsx)(Nt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,x.jsx)(Nt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),c?"Hide email preview":v?"Retry email preview":"Show email preview"]}),v&&!P&&(0,x.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),y.pay_url&&(0,x.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:y.pay_url}),(0,x.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:P?"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 _a({label:e,value:t}){return(0,x.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,x.jsx)("span",{className:Q(fn,"af-shrink-0"),children:e}),(0,x.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function Rn({label:e,value:t,strong:n}){return(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,x.jsx)("dt",{className:Q(fn,n&&"af-font-medium af-text-foreground"),children:e}),(0,x.jsx)("dd",{className:Q("af-tabular-nums",n&&"af-font-semibold"),children:t})]})}var Io=require("lucide-react");var Le=require("react/jsx-runtime"),Vc={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Eo={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Hc(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 Ao(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>Eo[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>Eo[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Vc[e.status]}function Do(e){let t=e.interval==="year"?"every year":"every month";return`${Z(e.amount,e.currency)} ${t}`}function zc(e){return e.status==="canceled"?`Ended ${Nr(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Nr(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 ${Nr(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Nr(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Nr(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),n=new Date(t);return Number.isNaN(n.getTime())?e.slice(0,10):n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function _r({retainer:e,className:t}){return(0,Le.jsx)(ie,{variant:Hc(e.status),className:Q("af-max-w-full af-whitespace-normal af-break-words",t),children:Ao(e)})}function Fn({retainers:e,isLoading:t,error:n,onRetry:s,onShowCycles:a,activeRetainerId:r,total:o,endedTotal:d=0,isLoadingMore:c=!1,onLoadMore:u,includeEnded:i=!1,onIncludeEndedChange:g,exportCsv:v,className:f}){let l=!!g;if(!t&&!n&&e.length===0&&!(l&&(i||d>0)))return null;let m=o!==void 0?Math.max(0,o-e.length):0;return(0,Le.jsxs)("section",{className:Q("af-mb-6",f),"aria-label":"Recurring invoices",children:[(0,Le.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Le.jsx)(Io.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,Le.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,Le.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."}),l&&(0,Le.jsx)(R,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":i,onClick:()=>g?.(!i),children:i?"Hide ended recurring invoices":d>0&&e.length===0?`Show ended recurring invoices (${d})`:"Show ended recurring invoices"}),v&&(0,Le.jsx)(Bt,{fetchCsv:v,filename:"retainers",className:l?void 0:"af-ml-auto"})]}),n?(0,Le.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,Le.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?(0,Le.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(p=>(0,Le.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,Le.jsx)(le,{className:"af-h-4 af-w-48"}),(0,Le.jsx)(le,{className:"af-mt-2 af-h-3 af-w-32"})]},p))}):e.length===0?(0,Le.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:i?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,Le.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(p=>{let b=r===p.id;return(0,Le.jsxs)("li",{className:Q("af-rounded-md af-border af-p-3",b&&"af-border-primary af-bg-muted/40"),children:[(0,Le.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,Le.jsxs)("div",{className:"af-min-w-0",children:[(0,Le.jsx)("div",{className:"af-truncate af-font-medium",children:p.customer_name??p.customer_email??"\u2014"}),(0,Le.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:p.description})]}),(0,Le.jsx)(_r,{retainer:p})]}),p.collection_method==="charge_automatically"?(0,Le.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,Le.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"}),(0,Le.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,Le.jsx)("div",{className:"af-mt-2 af-text-sm",children:Do(p)}),(0,Le.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,Le.jsxs)("span",{children:[zc(p)," \xB7 ",p.cycles.count===0?"no invoices yet":`${p.cycles.paid} paid${p.cycles.open>0?`, ${p.cycles.open} open`:""}`]}),p.cycles.count>0&&(0,Le.jsx)(R,{type:"button",variant:b?"secondary":"ghost",size:"sm",onClick:()=>a(p),"aria-pressed":b,children:b?"Showing invoices":"View invoices"})]}),p.status==="failed"&&p.operation?.last_error&&(0,Le.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",p.operation.last_error,". Ask in the chat to try again."]})]},p.id)})}),!t&&!n&&m>0&&u&&(0,Le.jsx)("div",{className:"af-mt-2",children:(0,Le.jsx)(R,{type:"button",variant:"outline",size:"sm",onClick:u,disabled:c,children:c?"Loading\u2026":`Load more (${m} more)`})})]})}var Lo=oe(require("react"),1),ga=require("lucide-react");var Re=require("react/jsx-runtime");function Un({onConnectStripe:e,onUpgradePlan:t,whenActive:n,className:s}){let{status:a,isLoading:r,error:o,refetch:d}=ln(),[c,u]=Lo.useState(!1),i=async()=>{u(!0);try{await d()}finally{u(!1)}};return r&&!a?(0,Re.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Re.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):o||!a?(0,Re.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Re.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o?.message||"Failed to load payment status"]})}):a.status==="active"?n!==void 0?(0,Re.jsx)("div",{className:s,children:n}):(0,Re.jsx)("div",{className:s,children:(0,Re.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,Re.jsx)(ga.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Re.jsxs)("div",{children:[(0,Re.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Re.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,Re.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[a.reason==="needs_stripe"&&(0,Re.jsxs)("div",{className:"af-space-y-3",children:[(0,Re.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Re.jsx)(ga.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Re.jsxs)("div",{children:[(0,Re.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Re.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,Re.jsxs)(R,{onClick:e,children:[(0,Re.jsx)(ga.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Re.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,Re.jsxs)("div",{className:"af-space-y-3",children:[(0,Re.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Re.jsx)(ga.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Re.jsxs)("div",{children:[(0,Re.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Re.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,Re.jsx)(R,{onClick:t,children:"Upgrade plan"}):(0,Re.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,Re.jsxs)("div",{className:"af-space-y-3",children:[(0,Re.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,Re.jsx)(ga.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Re.jsxs)("div",{children:[(0,Re.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?(0,Re.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,Re.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,Re.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&(0,Re.jsxs)(R,{onClick:e,children:[(0,Re.jsx)(ga.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Re.jsxs)(R,{variant:"outline",onClick:i,disabled:c,children:[c?(0,Re.jsx)(ga.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Re.jsx)(ga.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var jt=oe(require("react"),1);function li(e,t,n){return e.map(s=>s.id===t?{...s,...n}:s)}function Mn({includeStats:e=!1,refreshKey:t}={}){let{api:n}=ae(),[s,a]=jt.useState([]),[r,o]=jt.useState(!0),[d,c]=jt.useState(null),u=jt.useRef(0),i=jt.useCallback(async()=>{let p=++u.current;try{o(!0),c(null);let b=await n.getProducts(e?{include:"stats"}:{});if(p!==u.current)return;a(b)}catch(b){if(p!==u.current)return;c(b instanceof Error?b:new Error("Failed to fetch products"))}finally{p===u.current&&o(!1)}},[n,e,t]);jt.useEffect(()=>{i()},[i]);let g=jt.useCallback(async p=>{let b=await n.createProduct(p);return a(S=>[b,...S]),b},[n]),v=jt.useCallback(async(p,b)=>{let S=await n.updateProduct(p,b);return a(_=>li(_,p,S)),S},[n]),f=jt.useCallback(async p=>{await n.deleteProduct(p),a(b=>b.filter(S=>S.id!==p))},[n]),l=jt.useCallback(async(p,b)=>{let S=await n.attachProductFile(p,b);return a(_=>li(_,p,S)),S},[n]),m=jt.useCallback(async(p,b)=>{let S=await n.attachProductFileFromUrl(p,b);return a(_=>li(_,p,S)),S},[n]);return{products:s,isLoading:r,error:d,refetch:i,createProduct:g,updateProduct:v,deleteProduct:f,attachProductFile:l,attachProductFileFromUrl:m}}var Gt=oe(require("react"),1);var ci=["creating","active","paused","canceling"],qc=["canceled","failed"],jc={statuses:ci},Gc={};function $n({refreshKey:e,includeEnded:t=!1,limit:n=50}={}){let{api:s}=ae(),[a,r]=Gt.useState([]),[o,d]=Gt.useState(0),[c,u]=Gt.useState(0),[i,g]=Gt.useState(!0),[v,f]=Gt.useState(!1),[l,m]=Gt.useState(null),[p,b]=Gt.useState(t),S=Gt.useRef(0),_=Gt.useCallback(async()=>{let y=++S.current;g(!0),f(!1),m(null);try{let P=await s.getRetainers({statuses:p?void 0:ci,limit:n,offset:0});if(y!==S.current)return;if(r(P.retainers),d(P.total),!p&&P.total===0){let T=await s.getRetainers({statuses:qc,limit:1,offset:0});if(y!==S.current)return;u(T.total)}else u(0)}catch(P){if(y!==S.current)return;m(P instanceof Error?P:new Error("Failed to fetch retainers"))}finally{y===S.current&&g(!1)}},[s,p,n]);Gt.useEffect(()=>{_()},[_,e]);let A=Gt.useCallback(async()=>{if(i||v||a.length>=o)return;let y=S.current;f(!0);try{let P=await s.getRetainers({statuses:p?void 0:ci,limit:n,offset:a.length});if(y!==S.current)return;r(T=>{let L=new Set(T.map(N=>N.id));return[...T,...P.retainers.filter(N=>!L.has(N.id))]}),d(P.total)}catch(P){if(y!==S.current)return;m(P instanceof Error?P:new Error("Failed to fetch retainers"))}finally{y===S.current&&f(!1)}},[s,p,n,i,v,a.length,o]);return{retainers:a,total:o,endedTotal:c,hasMore:a.length<o,isLoading:i,isLoadingMore:v,error:l,includeEnded:p,setIncludeEnded:b,loadMore:A,refetch:_,filters:p?Gc:jc}}var we=require("react/jsx-runtime");function ui({className:e,defaultTab:t="products",onConnectStripe:n,onRefund:s,onUpgradePlan:a}){let[r,o]=ns.useState(t),[d,c]=ns.useState("list"),[u,i]=ns.useState(null),g=Mn(),{status:v,error:f}=ln(),l=v?.currency,m=_=>{i(_),c("edit")},p=()=>{i(null),c("create")},b=()=>{c("list"),i(null)},S=_=>{i(_),c("edit")};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:"Payments"}),(0,we.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,we.jsxs)(sr,{value:r,onValueChange:_=>o(_),children:[(0,we.jsxs)(ps,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,we.jsxs)(Da,{value:"products",className:"af-gap-2",children:[(0,we.jsx)(Pa.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,we.jsxs)(Da,{value:"orders",className:"af-gap-2",children:[(0,we.jsx)(Pa.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,we.jsxs)(Da,{value:"invoices",className:"af-gap-2",children:[(0,we.jsx)(Pa.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,we.jsxs)(Da,{value:"customers",className:"af-gap-2",children:[(0,we.jsx)(Pa.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,we.jsx)(Da,{value:"promos",children:"Promo codes"}),(0,we.jsxs)(Da,{value:"setup",className:"af-gap-2",children:[(0,we.jsx)(Pa.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,we.jsx)(La,{value:"products",children:d==="list"?(0,we.jsx)(ks,{productsState:g,onSelectProduct:m,onCreateProduct:p}):(0,we.jsxs)("div",{children:[(0,we.jsxs)("div",{className:"af-mb-6",children:[(0,we.jsxs)(R,{variant:"ghost",size:"sm",onClick:b,className:"af-mb-2 af--ml-2",children:[(0,we.jsx)(Pa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,we.jsx)("h3",{className:"af-text-lg af-font-semibold",children:d==="create"?"New Product":u?.name})]}),d==="create"&&!l?(0,we.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:f?(0,we.jsxs)("div",{className:"af-text-destructive",children:["Error: ",f.message]}):(0,we.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,we.jsx)(Is,{productsState:g,product:d==="edit"?u:null,currency:l??"usd",onSaved:S},d==="edit"?u?.id??"edit":"new")]})}),(0,we.jsx)(La,{value:"orders",children:(0,we.jsx)(dn,{onRefund:s})}),(0,we.jsx)(La,{value:"invoices",children:(0,we.jsx)(Wc,{onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:v?.reason==="needs_paid_plan"})}),(0,we.jsx)(La,{value:"customers",children:(0,we.jsx)(Us,{})}),(0,we.jsx)(La,{value:"promos",children:(0,we.jsx)(An,{})}),(0,we.jsx)(La,{value:"setup",children:(0,we.jsx)(Un,{onConnectStripe:n,onUpgradePlan:a})})]})]})}function Wc({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:n}){let s=$n(),[a,r]=ns.useState(null),[o,d]=ns.useState(!1);return(0,we.jsxs)(we.Fragment,{children:[!o&&(0,we.jsx)(Fn,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:a?.id??null,onShowCycles:c=>r(u=>u?.id===c.id?null:c),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),(0,we.jsx)(mn,{onDetailOpenChange:d,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:n,retainerFilter:a?{id:a.id,label:`${a.customer_name??a.customer_email??"Recurring invoices"} \u2014 ${a.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}var Bo=oe(require("react"),1);var Qa=oe(require("react"),1);function Vn({refreshKey:e}={}){let{api:t}=ae(),[n,s]=Qa.useState(null),[a,r]=Qa.useState(!0),[o,d]=Qa.useState(null),c=Qa.useRef(0),u=Qa.useCallback(async()=>{let i=++c.current;try{r(!0),d(null);let g=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(i!==c.current)return;s(g)}catch(g){if(i!==c.current)return;d(g instanceof Error?g:new Error("Failed to fetch summary"))}finally{i===c.current&&r(!1)}},[t,e]);return Qa.useEffect(()=>{u()},[u]),{summary:n,isLoading:a,error:o,refetch:u}}var Ge=require("react/jsx-runtime");function Oo(e,t){if(e.settled.complete)return{headline:Z(e.settled.gross,e.settled.currency),extra:[]};let n=e.totals[0];return n?{headline:Z(n.gross,n.currency),extra:e.totals.slice(1).map(s=>`+ ${Z(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:Z(0,t),extra:[]}}function di({refreshKey:e,initialOrderId:t,isOwner:n=!1,onRefund:s,onBackToWebsite:a,className:r}){let{summary:o,isLoading:d,error:c,refetch:u}=Vn({refreshKey:e}),[i,g]=Bo.useState(!1),v=(0,Ge.jsx)("div",{className:"af-mb-6",children:c&&!o?(0,Ge.jsx)(ma,{message:"Couldn't load your revenue summary.",onRetry:()=>u()}):(0,Ge.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:d||!o?(0,Ge.jsxs)(Ge.Fragment,{children:[(0,Ge.jsx)(ut,{label:"This week",children:(0,Ge.jsx)(le,{className:"af-h-6 af-w-24"})}),(0,Ge.jsx)(ut,{label:"Today",children:(0,Ge.jsx)(le,{className:"af-h-6 af-w-24"})}),(0,Ge.jsx)(ut,{label:"Needs attention",children:(0,Ge.jsx)(le,{className:"af-h-6 af-w-10"})})]}):(0,Ge.jsx)(Ge.Fragment,{children:(()=>{let f=Oo(o.revenue.d7,o.currency),l=Oo(o.revenue.today,o.currency);return(0,Ge.jsxs)(Ge.Fragment,{children:[(0,Ge.jsx)(ut,{label:"This week",detail:f.extra.length>0?(0,Ge.jsx)("div",{children:f.extra.map(m=>(0,Ge.jsx)("div",{children:m},m))}):void 0,children:f.headline}),(0,Ge.jsx)(ut,{label:"Today",detail:l.extra.length>0?(0,Ge.jsx)("div",{children:l.extra.map(m=>(0,Ge.jsx)("div",{children:m},m))}):void 0,children:l.headline}),(0,Ge.jsx)(ut,{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,Ge.jsxs)(wt,{title:"Orders",onBackToWebsite:a,hideBackButton:i,className:r,children:[v,(0,Ge.jsx)(dn,{refreshKey:e,initialOrderId:t,onDetailOpenChange:g,showFulfillment:!0,onRefund:n?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Ca=oe(require("react"),1),ss=require("lucide-react");var en=oe(require("react"),1),Er=require("lucide-react");var At=require("react/jsx-runtime"),Fo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Pn="af-text-xs af-text-muted-foreground",Rr="af-text-sm af-font-medium af-tabular-nums",Kc=3;function Zc(e){let t=e.pricing,n=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let c=e.min_amount??t?.min_amount??null,u=e.max_amount??t?.max_amount??null;return c!==null&&u!==null?{text:`Buyer chooses (${Z(c,n)} \u2013 ${Z(u,n)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let a=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(a===null||r===null)return{text:"Varies by variant",compareAt:null};let o=a===r?Z(a,n):`${Z(a,n)} \u2013 ${Z(r,n)}`,d=t?.compare_at_amount??null;return{text:o,compareAt:d!==null&&d>r?Z(d,n):null}}function Pr({product:e,className:t}){let n=Zc(e);return(0,At.jsxs)("div",{className:t,children:[(0,At.jsx)("span",{className:Rr,children:n.text}),n.compareAt&&(0,At.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:n.compareAt})]})}function Cr({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,At.jsx)(ie,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,At.jsxs)(ie,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,At.jsx)(ie,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,At.jsxs)(ie,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,At.jsx)(ie,{variant:"warning",children:"Low stock"}):null}function Tr(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function kr(e){return e.map(t=>Z(t.amount,t.currency)).join(" + ")}function Uo(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${Z(e.min_amount,e.currency)} \u2013 ${Z(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":Z(e.unit_amount,e.currency)}function Mo({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,At.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let n=t.available??0;return t.allow_backorder?(0,At.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,At.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,n)}),(0,At.jsx)(ie,{variant:"secondary",children:n<0?`${Math.abs(n)} on backorder`:"Backorder"})]}):n<=0?(0,At.jsx)(ie,{variant:"destructive",children:"Out of stock"}):(0,At.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,At.jsx)("span",{className:"af-tabular-nums",children:n}),n<=Kc&&(0,At.jsx)(ie,{variant:"warning",children:"Low"})]})}var X=require("react/jsx-runtime");function Ms({title:e,children:t,className:n}){return(0,X.jsxs)("section",{className:Q("af-rounded-lg af-border af-p-4",n),children:[(0,X.jsx)("h4",{className:Fo,children:e}),(0,X.jsx)("div",{className:"af-mt-3",children:t})]})}function $o({src:e,className:t}){let[n,s]=en.useState(!1);return en.useEffect(()=>s(!1),[e]),!e||n?(0,X.jsx)("div",{"aria-hidden":"true",className:Q("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,X.jsx)(Er.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,X.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:Q("af-object-cover",t)})}function Vo({product:e,showStats:t=!1,onBack:n}){let{api:s}=ae(),[a,r]=en.useState(null),[o,d]=en.useState(!0),[c,u]=en.useState(null),[i,g]=en.useState(0),[v,f]=en.useState(0);en.useEffect(()=>{let y=!1;return d(!0),u(null),s.getProduct(e.id).then(P=>{y||r(P)}).catch(P=>{y||u(P instanceof Error?P:new Error("Failed to load product"))}).finally(()=>{y||d(!1)}),()=>{y=!0}},[s,e.id,i]);let l=a?{...e,...a}:e,m=l.images.length>0?l.images:e.images,p=m[v]??m[0],b=Tr(l),S=t?l.stats:void 0,_=a?.variants??[],A=_.length>1;return(0,X.jsxs)("div",{children:[(0,X.jsxs)("div",{className:"af-mb-6",children:[(0,X.jsxs)(R,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[(0,X.jsx)(Er.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,X.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,X.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:l.name}),(0,X.jsx)(ie,{variant:l.active?"success":"secondary",children:l.active?"Active":"Draft"}),(0,X.jsx)(Cr,{product:l})]}),(0,X.jsx)(Pr,{product:l,className:"af-mt-1"}),!l.active&&(0,X.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,X.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)($o,{src:p,className:"af-h-48 af-w-full af-rounded-md af-border"}),m.length>1&&(0,X.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:m.map((y,P)=>(0,X.jsx)("button",{type:"button",onClick:()=>f(P),"aria-label":`Show photo ${P+1} of ${m.length}`,"aria-pressed":P===v,className:Q("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",P===v?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,X.jsx)($o,{src:y,className:"af-h-12 af-w-12 af-rounded-md"})},`${y}-${P}`))})]}),(0,X.jsxs)("div",{className:"af-space-y-6",children:[l.description&&(0,X.jsx)(Ms,{title:"Description",children:(0,X.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:l.description})}),o?(0,X.jsxs)(Ms,{title:"Variants",children:[(0,X.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(y=>(0,X.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,X.jsx)(le,{className:"af-h-4 af-w-28"}),(0,X.jsx)(le,{className:"af-h-4 af-w-20"}),(0,X.jsx)(le,{className:"af-h-4 af-w-16"})]},y))}),(0,X.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):c?(0,X.jsx)(ma,{message:"Couldn't load this product's variants.",onRetry:()=>g(y=>y+1)}):A?(0,X.jsx)(Ms,{title:`Variants \xB7 ${_.length}`,children:(0,X.jsx)("div",{className:"af-overflow-x-auto",children:(0,X.jsxs)(ze,{children:[(0,X.jsx)(qe,{children:(0,X.jsxs)(Ne,{children:[(0,X.jsx)(G,{children:"Variant"}),(0,X.jsx)(G,{children:"SKU"}),(0,X.jsx)(G,{className:"af-text-right",children:"Price"}),(0,X.jsx)(G,{children:"Stock"})]})}),(0,X.jsx)(je,{children:_.map(y=>(0,X.jsxs)(Ne,{children:[(0,X.jsxs)(W,{className:"af-font-medium",children:[y.title||y.option_values.map(P=>P.value).join(" / ")||"\u2014",!y.active&&(0,X.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,X.jsx)(W,{className:"af-text-muted-foreground",children:y.sku?(0,X.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:y.sku}):"\u2014"}),(0,X.jsxs)(W,{className:"af-whitespace-nowrap af-text-right",children:[(0,X.jsx)("div",{className:Rr,children:Uo(y)}),y.compare_at_amount!==null&&y.unit_amount!==null&&y.compare_at_amount>y.unit_amount&&(0,X.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:Z(y.compare_at_amount,y.currency)})]}),(0,X.jsx)(W,{className:"af-text-sm",children:(0,X.jsx)(Mo,{variant:y})})]},y.id))})]})})}):null,(0,X.jsx)(Ms,{title:"Details",children:(0,X.jsxs)("dl",{className:"af-space-y-2",children:[(0,X.jsxs)("div",{children:[(0,X.jsx)("dt",{className:Pn,children:"Delivery"}),(0,X.jsx)("dd",{className:"af-text-sm",children:b==="Digital download"?l.fulfillment.filename??"Digital download":b??"Nothing to deliver"})]}),l.fulfillment.type==="redirect"&&l.fulfillment.url&&(0,X.jsxs)("div",{children:[(0,X.jsx)("dt",{className:Pn,children:"Sends buyers to"}),(0,X.jsx)("dd",{className:"af-break-all af-text-sm",children:l.fulfillment.url})]}),(0,X.jsxs)("div",{children:[(0,X.jsx)("dt",{className:Pn,children:"Shipping address"}),(0,X.jsx)("dd",{className:"af-text-sm",children:l.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,X.jsxs)("div",{children:[(0,X.jsx)("dt",{className:Pn,children:"Most one buyer can order"}),(0,X.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:l.max_quantity})]})]})}),S&&(0,X.jsx)(Ms,{title:"Last 30 days",children:(0,X.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,X.jsxs)("div",{children:[(0,X.jsx)("dt",{className:Pn,children:"Units sold"}),(0,X.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.units_sold})]}),(0,X.jsxs)("div",{children:[(0,X.jsx)("dt",{className:Pn,children:"Orders"}),(0,X.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.orders})]}),(0,X.jsxs)("div",{children:[(0,X.jsx)("dt",{className:Pn,children:"Gross"}),(0,X.jsx)("dd",{className:Rr,children:S.gross.length>0?kr(S.gross):"\u2014"})]})]})}),(0,X.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var z=require("react/jsx-runtime"),Jc={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Yc=["all","active","draft","low_stock","out_of_stock"];function Ho(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,n=new Date(t).getTime();return Number.isNaN(n)?0:n}function zo(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Xc(e){return e.inventory?.out_of_stock??!1}function Qc(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return zo(e);case"out_of_stock":return Xc(e);default:return!0}}function eu({product:e,showStats:t,onOpen:n}){let s=e.images[0],a=t?e.stats:void 0,r=Tr(e),o=e.variant_count??0;return(0,z.jsxs)("button",{type:"button",onClick:n,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?(0,z.jsx)("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,z.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,z.jsx)(ss.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,z.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,z.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,z.jsxs)("div",{className:"af-min-w-0",children:[(0,z.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,z.jsx)(Pr,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,z.jsx)(ie,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,z.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,z.jsx)(Cr,{product:e}),o>1&&(0,z.jsxs)(ie,{variant:"outline",children:[o," variants"]}),r&&(0,z.jsx)(ie,{variant:"outline",children:r})]}),a&&(0,z.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[a.units_sold," sold",a.gross.length>0?` \xB7 ${kr(a.gross)}`:""," ",(0,z.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function tu(){return(0,z.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,z.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,z.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,z.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,z.jsx)(le,{className:"af-w-32"}),(0,z.jsx)(le,{className:"af-w-16"}),(0,z.jsx)(le,{className:"af-h-5 af-w-24"})]})]},e))})}function fi({refreshKey:e,showStats:t=!1,onBackToWebsite:n,className:s}){let{products:a,isLoading:r,error:o,refetch:d}=Mn({includeStats:t,refreshKey:e}),[c,u]=Ca.useState(!1),[i,g]=Ca.useState(null),[v,f]=Ca.useState("all"),{api:l}=ae(),m=Ca.useCallback(()=>l.exportProductsCsv(),[l]),[p,b]=Ca.useState(""),[S,_]=Ca.useState("newest"),A=Ca.useMemo(()=>{if(!t)return null;let M=null;for(let te of a)!te.stats||te.stats.units_sold===0||(!M||te.stats.units_sold>(M.stats?.units_sold??0))&&(M=te);return M},[a,t]),y=Ca.useMemo(()=>a.filter(zo).length,[a]),P=p.trim().toLowerCase(),T=Ca.useMemo(()=>{let te=[...a.filter(ne=>Qc(ne,v)&&(!P||ne.name.toLowerCase().includes(P)))];return S==="name"?te.sort((ne,re)=>ne.name.localeCompare(re.name)):S==="best_selling"?te.sort((ne,re)=>(re.stats?.units_sold??0)-(ne.stats?.units_sold??0)):te.sort((ne,re)=>Ho(re.created_at)-Ho(ne.created_at)),te},[a,v,P,S]),L=v!=="all"||!!P,N=()=>{f("all"),b("")},k=r||o!==null&&a.length===0,I=(0,z.jsx)("div",{className:"af-mb-6",children:(0,z.jsx)("div",{className:Q("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:k?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(ut,{label:"Products",children:(0,z.jsx)(le,{className:"af-h-6 af-w-10"})}),t?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(ut,{label:"Best seller",children:(0,z.jsx)(le,{className:"af-h-6 af-w-28"})}),(0,z.jsx)(ut,{label:"Low stock",children:(0,z.jsx)(le,{className:"af-h-6 af-w-10"})})]}):(0,z.jsx)(ut,{label:"Active",children:(0,z.jsx)(le,{className:"af-h-6 af-w-10"})})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(ut,{label:"Products",children:a.length}),t?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(ut,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:A?`${A.stats?.units_sold??0} sold, last 30 days`:void 0,children:A?(0,z.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:A.name}):(0,z.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,z.jsx)(ut,{label:"Low stock",children:y})]}):(0,z.jsx)(ut,{label:"Active",children:a.filter(M=>M.active).length})]})})}),C=(0,z.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,z.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,z.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:Yc.map(M=>(0,z.jsx)("button",{type:"button","aria-pressed":v===M,onClick:()=>f(M),className:Q("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",v===M?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Jc[M]},M))}),(0,z.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,z.jsx)(ss.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,z.jsx)(pe,{type:"text",value:p,onChange:M=>b(M.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,z.jsxs)(ya,{value:S,onValueChange:M=>_(M),children:[(0,z.jsx)(oa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,z.jsx)(ha,{})}),(0,z.jsxs)(la,{children:[(0,z.jsx)(et,{value:"newest",children:"Newest"}),(0,z.jsx)(et,{value:"name",children:"Name A\u2013Z"}),t&&(0,z.jsx)(et,{value:"best_selling",children:"Best selling"})]})]}),L&&(0,z.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:N,children:"Clear filters"}),(0,z.jsx)(Bt,{fetchCsv:m,filename:"products",label:L?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&a.length===0?(0,z.jsx)(le,{className:"af-h-4 af-w-28"}):(0,z.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:L?`${T.length} of ${a.length} products`:`${a.length} ${a.length===1?"product":"products"}${y>0?` \xB7 ${y} low stock`:""}`})]}),ee;return i?ee=(0,z.jsx)(Vo,{product:i,showStats:t,onBack:()=>{g(null),d()}},i.id):r&&a.length===0?ee=(0,z.jsxs)(z.Fragment,{children:[C,(0,z.jsx)(tu,{}),(0,z.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&a.length===0?ee=(0,z.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,z.jsx)(ma,{message:"Couldn't load your products.",onRetry:()=>d()})}):a.length===0?ee=(0,z.jsxs)(Va,{icon:(0,z.jsx)(ss.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,z.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):ee=(0,z.jsxs)(z.Fragment,{children:[C,o&&(0,z.jsx)("div",{className:"af-mb-4",children:(0,z.jsx)(ma,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>d()})}),T.length===0?(0,z.jsxs)(Va,{children:["No products match these filters.",(0,z.jsx)("br",{}),(0,z.jsx)(R,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:N,children:"Show all products"})]}):(0,z.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:T.map(M=>(0,z.jsx)(eu,{product:M,showStats:t,onOpen:()=>g(M)},M.id))})]}),(0,z.jsx)(wt,{title:"Products",onBackToWebsite:n,hideBackButton:!!i,className:s,children:c?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(R,{variant:"ghost",onClick:()=>u(!1),children:"Back to products"}),(0,z.jsx)(An,{})]}):(0,z.jsxs)(z.Fragment,{children:[!i&&(0,z.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,z.jsx)(R,{variant:"outline",onClick:()=>u(!0),children:"Promo codes"})}),!i&&I,ee]})})}var Ta=oe(require("react"),1),bt=require("lucide-react");var ea=oe(require("react"),1);function $s({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ae(),[s,a]=ea.useState([]),[r,o]=ea.useState(!0),[d,c]=ea.useState(null),[u,i]=ea.useState(0),[g]=ea.useState(e),[v,f]=ea.useState(""),[l,m]=ea.useState(void 0),p=ea.useRef(0),b=ea.useCallback(async()=>{let S=++p.current;try{o(!0),c(null);let _={limit:g,offset:u*g};v.trim()&&(_.q=v.trim()),l&&(_.source=l);let A=await n.getPeople(_);if(S!==p.current)return;a(A.people)}catch(_){if(S!==p.current)return;c(_ instanceof Error?_:new Error("Failed to fetch people"))}finally{S===p.current&&o(!1)}},[n,u,g,v,l,t]);return ea.useEffect(()=>{b()},[b]),{people:s,isLoading:r,error:d,page:u,pageSize:g,hasNextPage:s.length===g,hasPreviousPage:u>0,setPage:i,q:v,setQ:S=>{f(S),i(0)},source:l,setSource:S=>{m(S),i(0)},refetch:b}}var tn=oe(require("react"),1);function Vs(e,{refreshKey:t}={}){let{api:n}=ae(),[s,a]=tn.useState(null),[r,o]=tn.useState(e!==null),[d,c]=tn.useState(null),u=tn.useRef(0),i=tn.useCallback(async()=>{if(e===null){a(null),o(!1),c(null);return}let g=++u.current;try{o(!0),c(null);let v=await n.getPerson(e);if(g!==u.current)return;a(v)}catch(v){if(g!==u.current)return;c(v instanceof Error?v:new Error("Failed to fetch person"))}finally{g===u.current&&o(!1)}},[n,e,t]);return tn.useEffect(()=>{i()},[i]),{person:s,isLoading:r,error:d,refetch:i}}var w=require("react/jsx-runtime"),mi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",au="af-text-xs af-text-muted-foreground";function rs(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 pi(e,t){let n=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(n)}`}function nu(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function su({value:e,label:t}){let[n,s]=Ta.useState(!1);return nu()?(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[n?(0,w.jsx)(bt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,w.jsx)(bt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),n?"Copied":"Copy email"]}):null}function qo(e){return(0,w.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,w.jsxs)(ie,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,w.jsx)(ie,{variant:"secondary",children:"Contact form"})]})}function jo(e){return e.name?e.name:e.email?e.email:(0,w.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var ru=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,iu=40;function ou(e){let t=Object.entries(e).filter(([a])=>!a.startsWith("_")),s=t.find(([a,r])=>ru.test(a)&&typeof r=="string"&&r.trim())??t.filter(([,a])=>typeof a=="string"&&a.trim().length>=iu).sort((a,r)=>String(r[1]).trim().length-String(a[1]).trim().length)[0];return s?{message:String(s[1]),rest:t.filter(([a])=>a!==s[0])}:{message:null,rest:t}}function lu(e){return e.replace(/_/g," ")}function cu(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function uu({data:e}){let{message:t,rest:n}=ou(e);return t===null&&n.length===0?(0,w.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,w.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,w.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),n.length>0&&(0,w.jsx)("dl",{className:"af-space-y-1",children:n.map(([s,a])=>(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,w.jsx)("dt",{className:Q(au,"af-w-28 af-shrink-0 af-capitalize"),children:lu(s)}),(0,w.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:cu(a)})]},s))})]})}function Wo({formName:e,createdAt:t,data:n}){return(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,w.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)(ie,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,w.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,w.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:rs(t)})]}),(0,w.jsx)(uu,{data:n})]})}function du(e){return e.charged_total??e.amount_total}function fu({email:e,refreshKey:t,onBack:n}){let{person:s,isLoading:a,error:r,refetch:o}=Vs(e,{refreshKey:t}),d=pi(e,s?.submissions[0]?.form_name);return(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"af-mb-6",children:[(0,w.jsxs)(R,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[(0,w.jsx)(bt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,w.jsxs)("div",{className:"af-min-w-0",children:[a?(0,w.jsx)(le,{className:"af-h-7 af-w-48"}):(0,w.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:s?.name||e}),(0,w.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,w.jsx)(su,{value:e,label:"Copy email address"})]})]}),(0,w.jsx)(R,{asChild:!0,children:(0,w.jsxs)("a",{href:d,children:[(0,w.jsx)(bt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),a?(0,w.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(c=>(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,w.jsx)(le,{className:"af-w-40"}),(0,w.jsx)(le,{className:"af-mt-2 af-w-64"})]},c)),(0,w.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):r||!s?(0,w.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,w.jsx)(ma,{message:"Couldn't load this person.",onRetry:()=>o()})}):(0,w.jsxs)("div",{className:"af-space-y-6",children:[s.customer&&(0,w.jsxs)("div",{children:[(0,w.jsx)("h4",{className:Q(mi,"af-mb-3"),children:"Customer"}),(0,w.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[s.customer.name&&(0,w.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,w.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,w.jsx)("dd",{children:s.customer.name})]}),s.customer.phone&&(0,w.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,w.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,w.jsx)("dd",{children:s.customer.phone})]}),(0,w.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,w.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,w.jsx)("dd",{children:rs(s.customer.created_at)})]})]})]}),s.orders.length>0&&(0,w.jsxs)("div",{children:[(0,w.jsx)("h4",{className:Q(mi,"af-mb-3"),children:"Purchases"}),(0,w.jsx)("div",{className:"af-overflow-x-auto",children:(0,w.jsxs)(ze,{children:[(0,w.jsx)(qe,{children:(0,w.jsxs)(Ne,{children:[(0,w.jsx)(G,{children:"Order"}),(0,w.jsx)(G,{children:"Date"}),(0,w.jsx)(G,{className:"af-text-right",children:"Total"}),(0,w.jsx)(G,{children:"Status"})]})}),(0,w.jsx)(je,{children:s.orders.map(c=>(0,w.jsxs)(Ne,{children:[(0,w.jsx)(W,{className:"af-whitespace-nowrap af-font-medium",children:un(c)}),(0,w.jsx)(W,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rs(c.created_at)}),(0,w.jsx)(W,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:Z(du(c),c.currency)}),(0,w.jsx)(W,{children:(0,w.jsx)(_n,{status:c.status})})]},c.id))})]})}),(0,w.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."})]}),s.submissions.length>0&&(0,w.jsxs)("div",{children:[(0,w.jsx)("h4",{className:Q(mi,"af-mb-3"),children:"Messages"}),(0,w.jsx)("div",{className:"af-space-y-3",children:s.submissions.map(c=>(0,w.jsx)(Wo,{formName:c.form_name,createdAt:c.created_at,data:c.data},c.id))})]})]})]})}function mu({submissionId:e,onBack:t}){let{api:n}=ae(),[s,a]=Ta.useState(null),[r,o]=Ta.useState(!0),[d,c]=Ta.useState(null),[u,i]=Ta.useState(0);return Ta.useEffect(()=>{let g=!1;return o(!0),c(null),n.getSubmission(e).then(v=>{g||a(v)}).catch(v=>{g||c(v instanceof Error?v:new Error("Failed to load submission"))}).finally(()=>{g||o(!1)}),()=>{g=!0}},[n,e,u]),(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"af-mb-6",children:[(0,w.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,w.jsx)(bt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,w.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),r?(0,w.jsx)(le,{className:"af-mt-1 af-h-4 af-w-32"}):s&&(0,w.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:rs(s.metadata.submitted_at)})]}),r?(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,w.jsx)(le,{className:"af-w-40"}),(0,w.jsx)(le,{className:"af-mt-2 af-w-64"}),(0,w.jsx)(le,{className:"af-mt-2 af-w-52"}),(0,w.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):d||!s?(0,w.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,w.jsx)(ma,{message:"Couldn't load this submission.",onRetry:()=>i(g=>g+1)})}):(0,w.jsxs)("div",{className:"af-space-y-3",children:[(0,w.jsx)(Wo,{formName:null,createdAt:s.metadata.submitted_at,data:s.data}),(0,w.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 pu={all:"All",customers:"Customers",leads:"Leads"},gu=["all","customers","leads"],Go={all:void 0,customers:"customer",leads:"lead"};function vu({refreshKey:e,onBackToWebsite:t,className:n,maxRows:s,onViewAll:a}){let r=typeof s=="number",{people:o,isLoading:d,error:c,page:u,pageSize:i,hasNextPage:g,hasPreviousPage:v,setPage:f,q:l,setQ:m,source:p,setSource:b,refetch:S}=$s({refreshKey:e}),[_,A]=Ta.useState({kind:"list"}),[y,P]=Ta.useState(""),T=p==="customer"?"customers":p==="lead"?"leads":"all",L=re=>{Go[re]!==p&&b(Go[re])},{api:N}=ae(),k=Ta.useCallback(()=>N.exportPeopleCsv({...l?{q:l}:{},...p?{source:p}:{}}),[N,l,p]),I=!r||!!a,C=re=>{if(r){a?.();return}re.email?A({kind:"person",email:re.email}):re.submission_id&&A({kind:"submission",submissionId:re.submission_id})},ee=()=>{A({kind:"list"}),S()},M=re=>{let se=re.trim();se!==l&&m(se)},te=r?o.slice(0,s):o,ne;if(_.kind==="person")ne=(0,w.jsx)(fu,{email:_.email,refreshKey:e,onBack:ee});else if(_.kind==="submission")ne=(0,w.jsx)(mu,{submissionId:_.submissionId,onBack:ee});else{let re=(0,w.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.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:gu.map(se=>(0,w.jsx)("button",{type:"button","aria-pressed":T===se,onClick:()=>L(se),className:Q("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",T===se?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:pu[se]},se))}),(0,w.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,w.jsx)(bt.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,w.jsx)(pe,{type:"text",value:y,onChange:se=>P(se.target.value),onBlur:()=>M(y),onKeyDown:se=>{se.key==="Enter"&&(se.preventDefault(),M(y))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),l&&(0,w.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>{P(""),m("")},children:"Clear search"}),(0,w.jsx)(Bt,{fetchCsv:k,filename:"people",className:"af-ml-auto"})]});if(d)ne=(0,w.jsxs)("div",{children:[r?null:re,(0,w.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(se=>(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,w.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,w.jsx)(le,{className:"af-h-4 af-w-32"}),(0,w.jsx)(le,{className:"af-h-4 af-w-16"})]}),(0,w.jsx)(le,{className:"af-mt-2 af-h-5 af-w-28"}),(0,w.jsx)(le,{className:"af-mt-2 af-h-3 af-w-56"})]},se))}),(0,w.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,w.jsxs)(ze,{children:[(0,w.jsx)(qe,{children:(0,w.jsxs)(Ne,{children:[(0,w.jsx)(G,{children:"Person"}),(0,w.jsx)(G,{children:"Came from"}),(0,w.jsx)(G,{children:"Latest message"}),(0,w.jsx)(G,{children:"Last activity"}),(0,w.jsx)(G,{className:"af-w-8"}),(0,w.jsx)(G,{className:"af-w-8"})]})}),(0,w.jsx)(je,{"aria-hidden":"true",children:[0,1,2,3,4].map(se=>(0,w.jsxs)(Ne,{children:[(0,w.jsx)(W,{children:(0,w.jsx)(le,{className:"af-h-4 af-w-40"})}),(0,w.jsx)(W,{children:(0,w.jsx)(le,{className:"af-h-5 af-w-24"})}),(0,w.jsx)(W,{children:(0,w.jsx)(le,{className:"af-h-4 af-w-56"})}),(0,w.jsx)(W,{children:(0,w.jsx)(le,{className:"af-h-4 af-w-24"})}),(0,w.jsx)(W,{}),(0,w.jsx)(W,{})]},se))})]})}),(0,w.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(c)ne=(0,w.jsxs)("div",{children:[r?null:re,(0,w.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,w.jsx)(ma,{message:"Couldn't load your leads.",onRetry:()=>S()})})]});else if(te.length===0&&u===0){let se=!!l||T!=="all";ne=(0,w.jsxs)("div",{children:[se&&re,se?(0,w.jsx)(Va,{children:l?"Nobody matches that search.":T==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,w.jsx)(Qn,{icon:bt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)ne=(0,w.jsxs)("div",{children:[r?null:re,(0,w.jsx)(Va,{children:"No more results."}),(0,w.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>f(u-1),children:[(0,w.jsx)(bt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let se=u*i+1,q=u*i+o.length;ne=(0,w.jsxs)("div",{children:[r?null:re,(0,w.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:te.map((V,j)=>(0,w.jsxs)("div",{onClick:I?()=>C(V):void 0,className:`af-rounded-md af-border af-p-3${I?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,w.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,w.jsxs)("div",{className:"af-min-w-0",children:[(0,w.jsx)("button",{type:"button",onClick:be=>{be.stopPropagation(),C(V)},disabled:!I,"aria-label":`Open ${V.name||V.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${I?" hover:af-underline":""}`,children:jo(V)}),V.name&&V.email&&(0,w.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:V.email})]}),(0,w.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,w.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:rs(V.last_activity_at)}),V.email&&(0,w.jsx)(R,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,w.jsx)("a",{href:pi(V.email),onClick:be=>be.stopPropagation(),"aria-label":`Email ${V.email}`,children:(0,w.jsx)(bt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,w.jsx)("div",{className:"af-mt-2",children:qo(V)}),V.latest_message_excerpt&&(0,w.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:V.latest_message_excerpt})]},V.email??V.submission_id??j))}),(0,w.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,w.jsxs)(ze,{children:[(0,w.jsx)(qe,{children:(0,w.jsxs)(Ne,{children:[(0,w.jsx)(G,{children:"Person"}),(0,w.jsx)(G,{children:"Came from"}),(0,w.jsx)(G,{children:"Latest message"}),(0,w.jsx)(G,{children:"Last activity"}),(0,w.jsx)(G,{className:"af-w-8",children:(0,w.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,w.jsx)(G,{className:"af-w-8"})]})}),(0,w.jsx)(je,{children:te.map((V,j)=>(0,w.jsxs)(Ne,{onClick:I?()=>C(V):void 0,className:I?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,w.jsxs)(W,{className:"af-max-w-[260px] af-font-medium",children:[(0,w.jsx)("button",{type:"button",onClick:be=>{be.stopPropagation(),C(V)},disabled:!I,"aria-label":`Open ${V.name||V.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${I?" hover:af-underline":""}`,children:jo(V)}),V.name&&V.email&&(0,w.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:V.email})]}),(0,w.jsx)(W,{children:qo(V)}),(0,w.jsx)(W,{className:"af-max-w-[320px]",children:V.latest_message_excerpt?(0,w.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:V.latest_message_excerpt}):(0,w.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,w.jsx)(W,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rs(V.last_activity_at)}),(0,w.jsx)(W,{className:"af-w-8",children:V.email&&(0,w.jsx)(R,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,w.jsx)("a",{href:pi(V.email),onClick:be=>be.stopPropagation(),"aria-label":`Email ${V.email}`,children:(0,w.jsx)(bt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,w.jsx)(W,{className:"af-w-8 af-text-right",children:(0,w.jsx)(bt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},V.email??V.submission_id??j))})]})}),!r&&(0,w.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,w.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${se}-${q}`}),(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>f(u-1),disabled:!v,children:[(0,w.jsx)(bt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>f(u+1),disabled:!g,children:["Next",(0,w.jsx)(bt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?(0,w.jsx)("div",{className:n,children:ne}):(0,w.jsx)(wt,{title:"Leads",onBackToWebsite:t,hideBackButton:_.kind!=="list",className:n,children:ne})}function Hs(e){return(0,w.jsx)(vu,{...e},e.maxRows==null?"full":"compact")}var Xo=oe(require("react"),1),Hn=require("lucide-react");var ta=oe(require("react"),1);function zs({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ae(),[s,a]=ta.useState([]),[r,o]=ta.useState(0),[d,c]=ta.useState(!0),[u,i]=ta.useState(null),[g,v]=ta.useState(0),[f,l]=ta.useState(e),[m,p]=ta.useState(void 0),b=ta.useRef(0),S=ta.useCallback(async()=>{let A=++b.current;try{c(!0),i(null);let y={limit:f,offset:g*f};m&&(y.status=m);let P=await n.getSubscriptions(y);if(A!==b.current)return;a(P.subscriptions),o(P.total)}catch(y){if(A!==b.current)return;i(y instanceof Error?y:new Error("Failed to fetch subscriptions"))}finally{A===b.current&&c(!1)}},[n,g,f,m,t]);ta.useEffect(()=>{S()},[S]);let _=Math.ceil(r/f);return{subscriptions:s,total:r,isLoading:d,error:u,page:g,pageSize:f,hasNextPage:g<_-1,hasPreviousPage:g>0,setPage:v,setPageSize:A=>{l(A),v(0)},status:m,setStatus:A=>{p(A),v(0)},refetch:S}}var $=require("react/jsx-runtime");function Ko(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 Zo({sub:e}){return e.status==="canceled"?(0,$.jsx)(ie,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,$.jsx)(ie,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,$.jsx)(ie,{variant:"warning",children:"Scheduled to cancel"}):(0,$.jsx)(ie,{variant:"success",children:"Active"}):(0,$.jsx)(ie,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function bu(e,t){let n=Z(t,e.currency);return e.plan_interval_count===1?`${n} / ${e.plan_interval}`:`${n} every ${e.plan_interval_count} ${e.plan_interval}s`}function Jo({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:bu(e,e.current_amount)}),t&&(0,$.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",Z(e.plan_amount,e.currency)]})]})}function Yo(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Ko(e.current_period_end)}`:"Ends at period end":e.current_period_end?Ko(e.current_period_end):"\u2014"}function gi({refreshKey:e,onBackToWebsite:t,className:n}){let{subscriptions:s,total:a,isLoading:r,error:o,page:d,pageSize:c,hasNextPage:u,hasPreviousPage:i,setPage:g,status:v,refetch:f}=zs({refreshKey:e}),{api:l}=ae(),m=Xo.useCallback(()=>l.exportSubscriptionsCsv(v?{status:v}:{}),[l,v]),p;if(r)p=(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(b=>(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)(le,{className:"af-h-4 af-w-40"}),(0,$.jsx)(le,{className:"af-h-4 af-w-20"})]}),(0,$.jsx)(le,{className:"af-mt-2 af-h-3 af-w-32"}),(0,$.jsx)(le,{className:"af-mt-2 af-h-5 af-w-24"})]},b))}),(0,$.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,$.jsxs)(ze,{children:[(0,$.jsx)(qe,{children:(0,$.jsxs)(Ne,{children:[(0,$.jsx)(G,{children:"Subscriber"}),(0,$.jsx)(G,{children:"Plan"}),(0,$.jsx)(G,{className:"af-text-right",children:"Amount"}),(0,$.jsx)(G,{children:"Renews"}),(0,$.jsx)(G,{children:"Status"})]})}),(0,$.jsx)(je,{"aria-hidden":"true",children:[0,1,2,3,4].map(b=>(0,$.jsxs)(Ne,{children:[(0,$.jsx)(W,{children:(0,$.jsx)(le,{className:"af-h-4 af-w-44"})}),(0,$.jsx)(W,{children:(0,$.jsx)(le,{className:"af-h-4 af-w-32"})}),(0,$.jsx)(W,{className:"af-text-right",children:(0,$.jsx)(le,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,$.jsx)(W,{children:(0,$.jsx)(le,{className:"af-h-4 af-w-24"})}),(0,$.jsx)(W,{children:(0,$.jsx)(le,{className:"af-h-5 af-w-20"})})]},b))})]})}),(0,$.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=(0,$.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,$.jsx)(ma,{message:"Couldn't load your subscriptions.",onRetry:()=>f()})});else if(s.length===0&&d===0)p=(0,$.jsx)(Va,{icon:(0,$.jsx)(Hn.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(s.length===0)p=(0,$.jsxs)("div",{children:[(0,$.jsx)(Va,{children:"No more results."}),(0,$.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,$.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>g(d-1),children:[(0,$.jsx)(Hn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let b=d*c+1,S=d*c+s.length;p=(0,$.jsxs)("div",{children:[(0,$.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,$.jsx)(Bt,{fetchCsv:m,filename:"subscriptions"})}),(0,$.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(_=>(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:_.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:_.plan_title||"Untitled plan"})]}),(0,$.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,$.jsx)(Jo,{sub:_})})]}),(0,$.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,$.jsx)(Zo,{sub:_}),_.is_test&&(0,$.jsx)(ie,{variant:"outline",children:"Test"}),(0,$.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Yo(_)})]}),(0,$.jsx)(Ga,{deliveries:_.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},_.id))}),(0,$.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,$.jsxs)(ze,{children:[(0,$.jsx)(qe,{children:(0,$.jsxs)(Ne,{children:[(0,$.jsx)(G,{children:"Subscriber"}),(0,$.jsx)(G,{children:"Plan"}),(0,$.jsx)(G,{className:"af-text-right",children:"Amount"}),(0,$.jsx)(G,{children:"Renews"}),(0,$.jsx)(G,{children:"Status"})]})}),(0,$.jsx)(je,{children:s.map(_=>(0,$.jsxs)(Ne,{children:[(0,$.jsx)(W,{className:"af-max-w-[240px]",children:(0,$.jsx)("div",{className:"af-truncate af-font-medium",children:_.customer_email||(0,$.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,$.jsx)(W,{className:"af-max-w-[220px]",children:(0,$.jsx)("div",{className:"af-truncate",children:_.plan_title||(0,$.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,$.jsx)(W,{className:"af-whitespace-nowrap af-text-right",children:(0,$.jsx)(Jo,{sub:_})}),(0,$.jsx)(W,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Yo(_)}),(0,$.jsxs)(W,{children:[(0,$.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,$.jsx)(Zo,{sub:_}),_.is_test&&(0,$.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,$.jsx)(Ga,{deliveries:_.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},_.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 ${b}-${S} of ${a}`}),(0,$.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,$.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>g(d-1),disabled:!i,children:[(0,$.jsx)(Hn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,$.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>g(d+1),disabled:!u,children:["Next",(0,$.jsx)(Hn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,$.jsx)(wt,{title:"Subscriptions",onBackToWebsite:t,className:n,children:p})}var nn=oe(require("react"),1),ml=require("lucide-react");var Ht=oe(require("react"),1);var Ir=oe(require("react"),1),zn=typeof window>"u"?Ir.useEffect:Ir.useLayoutEffect;var Ar=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},yu=(e,t)=>e instanceof Error?e:new Error(t);function hu(e){let t={};return e.due_days!==void 0&&(t.invoice_due_days=e.due_days),e.reminder_schedule!==void 0&&(t.invoice_reminder_schedule=e.reminder_schedule),e.footer!==void 0&&(t.invoice_footer=e.footer),t}function Qo(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function pn({siteId:e,refreshKey:t,onSaveInvoiceSettings:n}){let{api:s}=ae(),[a,r]=Ht.useState(null),[o,d]=Ht.useState(!0),[c,u]=Ht.useState(null),i=Ht.useRef(null),[g,v]=Ht.useState(()=>Qo(s,e)),f=g.api!==s||g.siteId!==e,l=g;f&&(l=Qo(s,e),v(l),r(null),d(!0),u(null));let m=Ht.useRef(l);zn(()=>{m.current!==l&&(m.current=l,i.current=null)},[l]);let p=(N,k)=>m.current===N&&k>N.applied,b=(N,k,I)=>p(N,k)?(N.applied=k,i.current=I,r(I),d(!1),!0):!1,S=async N=>{for(;N.writing;)await N.idle;let k=++N.seq;try{let I=await N.api.getSite(N.siteId);return b(N,k,I)&&u(null),{seq:k,error:null}}catch(I){return{seq:k,error:yu(I,"Failed to load store settings")}}},_=(N,k)=>{let I=async()=>{if(m.current!==N)throw new Error("Not saved: the store switched to another site first.");N.writing=!0,N.idle=new Promise(ee=>{N.markIdle=ee});try{return await k(++N.seq)}finally{N.writing=!1,N.markIdle()}},C=N.queue.then(I,I);return N.queue=C.catch(()=>{}),C},A=Ht.useCallback(async()=>{let N=await S(l);N.error&&p(l,N.seq)&&(u(N.error),d(!1))},[l]);Ht.useEffect(()=>{A()},[A,t]);let y=Ht.useCallback(N=>_(l,async k=>{let I=await l.api.updateSite(l.siteId,N),{currency_restatement:C,...ee}=I;return b(l,k,ee)&&u(M=>M instanceof Ar?M:null),I}),[l]),P=Ht.useRef(n);zn(()=>{P.current=n});let T=Ht.useCallback(async(N,k)=>{await _(l,()=>N());let I=await S(l);return I.error&&p(l,I.seq)&&i.current&&(b(l,I.seq,{...i.current,...k}),u(new Ar(`Saved, but couldn't refresh settings: ${I.error.message}`))),m.current===l?i.current:null},[l]),L=Ht.useCallback(N=>{let k=P.current;return T(()=>k(N),hu(N))},[T]);return{site:f?null:a,isLoading:f||o,error:f?null:c,refetch:A,updateSite:y,saveInvoiceSettings:n?L:null}}var Ct=oe(require("react"),1),yi=require("lucide-react");var rt=require("react/jsx-runtime");function Dr(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var Ha="af-grid af-gap-1 af-text-sm",el="af-h-9 af-rounded-md af-border af-border-input af-bg-background af-px-3 af-text-sm disabled:af-cursor-not-allowed disabled:af-opacity-50",tl="af-min-h-[72px] 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 disabled:af-cursor-not-allowed disabled:af-opacity-50";function aa({children:e}){return(0,rt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function qs({children:e}){return(0,rt.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var an=Ct.forwardRef(function({id:t,title:n,description:s,children:a},r){let o=`af-store-${t}-title`;return(0,rt.jsxs)("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":o,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[(0,rt.jsxs)("div",{className:"af-space-y-1",children:[(0,rt.jsx)("h3",{id:o,className:"af-text-sm af-font-semibold",children:n}),s&&(0,rt.jsx)(aa,{children:s})]}),a]})});function hi({label:e,description:t,checked:n,onSave:s,disabled:a=!1,disabledReason:r}){let[o,d]=Ct.useState(null),[c,u]=Ct.useState(null),i=o??n,g=async v=>{d(v),u(null);try{await s(v)}catch(f){u(Dr(f))}finally{d(null)}};return(0,rt.jsxs)("div",{className:"af-space-y-1",children:[(0,rt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,rt.jsx)("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":i,checked:i,disabled:a||o!==null,onChange:v=>void g(v.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),(0,rt.jsxs)("span",{className:"af-space-y-0.5",children:[(0,rt.jsxs)("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,o!==null&&(0,rt.jsx)(yi.Loader2,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&(0,rt.jsx)(aa,{children:t})]})]}),(a&&r||c)&&(0,rt.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[a&&r&&(0,rt.jsx)(aa,{children:r}),c&&(0,rt.jsx)(qs,{children:c})]})]})}var bi=(e,t)=>JSON.stringify(e)===JSON.stringify(t),vi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function xu(e,t,n,s=[]){if(!vi(e)||!vi(t)||!vi(n))return{draft:bi(e,t)?n:e,dropped:[]};let a=[],r={...n};for(let o of Object.keys(n))bi(e[o],t[o])||(s.includes(o)?a.push(o):r[o]=e[o]);return{draft:r,dropped:a}}function is(e,t){let n=JSON.stringify(e),[s,a]=Ct.useState(e),[r,o]=Ct.useState([]),d=Ct.useRef(e),c=Ct.useRef(e),u=Ct.useRef(s);zn(()=>{c.current=e,u.current=s});let i=Ct.useRef(t?.when);Ct.useEffect(()=>{let v=Object.is(i.current,t?.when)?[]:t?.fields??[];if(i.current=t?.when,bi(d.current,c.current)&&v.length===0)return;let f=xu(u.current,d.current,c.current,v);d.current=c.current,a(f.draft),f.dropped.length&&o(f.dropped)},[n,t?.when]);let g=Ct.useCallback(v=>{a(v??c.current),o([])},[]);return{draft:s,setDraft:a,dirty:JSON.stringify(s)!==n,reset:g,dropped:r}}function os({dirty:e,saving:t,error:n,onSave:s,onDiscard:a}){return e?(0,rt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,rt.jsxs)(R,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&(0,rt.jsx)(yi.Loader2,{className:"af-animate-spin"}),"Save"]}),(0,rt.jsx)(R,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:a,children:"Discard"}),n&&(0,rt.jsx)("p",{role:"alert",className:Q("af-text-sm af-text-destructive"),children:n})]}):null}function ls(){let[e,t]=Ct.useState(!1),[n,s]=Ct.useState(null),a=Ct.useCallback(async r=>{t(!0),s(null);try{await r()}catch(o){s(Dr(o))}finally{t(!1)}},[]);return{saving:e,error:n,setError:s,run:a}}function al({what:e}){return(0,rt.jsxs)(aa,{children:["Only the site owner can change ",e,"."]})}var ka=oe(require("react"),1),qn=require("lucide-react");var H=require("react/jsx-runtime"),wi=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function il({site:e,updateSite:t}){return(0,H.jsx)("div",{className:"af-space-y-4",children:(0,H.jsx)(hi,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:n=>t({collect_phone_at_checkout:n})})})}function nl(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(at(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(at(e.free_shipping_over,e.currency))}}function ol({site:e,updateSite:t,refetch:n,providerSlot:s,currencyChanging:a=!1}){let{draft:r,setDraft:o,dirty:d,reset:c,dropped:u}=is(nl(e),{when:e.currency,fields:["rates","threshold"]}),{saving:i,error:g,setError:v,run:f}=ls(),l=e.currency.toUpperCase(),m=()=>f(async()=>{let b={},S=[...new Set(r.countries.split(/[\s,]+/).map(N=>N.trim().toUpperCase()).filter(Boolean))],_=S.find(N=>!/^[A-Z]{2}$/.test(N));if(_)throw new Error(`"${_}" isn't a two-letter country code (e.g. US, CA).`);let A=S.length?S:null;wi(A,e.shipping_countries)||(b.shipping_countries=A);let y=[];for(let N of r.rates){let k=N.label.trim(),I=It(N.amount,e.currency);if(!k)throw new Error("Every rate needs a name.");if(N.amount.trim()===""||I===null)throw new Error(`Enter a price for "${k}" (0 for free).`);y.push({label:k,amount:I})}let P=y.length?y:null;wi(P,e.shipping_rates)||(b.shipping_rates=P);let T=null;if(r.threshold.trim()!==""&&(T=It(r.threshold,e.currency),T===null||T===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(T!==e.free_shipping_over&&(b.free_shipping_over=T),Object.keys(b).length===0){c();return}("shipping_rates"in b||"free_shipping_over"in b)&&(b.expected_currency=e.currency);let L;try{L=await t(b)}catch(N){throw N instanceof ht&&N.details?.code==="currency_changed"&&await n?.(),N}c(nl(L))}),p=(b,S)=>o({...r,rates:r.rates.map((_,A)=>A===b?{..._,...S}:_)});return(0,H.jsxs)("fieldset",{disabled:i||a,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:Ha,children:["Countries you ship to",(0,H.jsx)(pe,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:b=>o({...r,countries:b.target.value})}),(0,H.jsx)(aa,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),(0,H.jsxs)("div",{className:"af-space-y-2",children:[(0,H.jsxs)("p",{className:"af-text-sm",children:["Flat shipping rates (",l,")"]}),r.rates.length===0&&(0,H.jsx)(aa,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((b,S)=>(0,H.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,H.jsx)(pe,{"aria-label":`Rate ${S+1} name`,value:b.label,placeholder:"Standard",onChange:_=>p(S,{label:_.target.value})}),(0,H.jsx)(pe,{"aria-label":`Rate ${S+1} price`,type:"number",min:"0",step:"any",value:b.amount,placeholder:"0",className:"af-w-32",onChange:_=>p(S,{amount:_.target.value})}),(0,H.jsx)(R,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${S+1}`,onClick:()=>o({...r,rates:r.rates.filter((_,A)=>A!==S)}),children:(0,H.jsx)(qn.X,{})})]},S)),(0,H.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>o({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[(0,H.jsx)(qn.Plus,{})," Add rate"]}),(0,H.jsx)(aa,{children:"Buyers pick one at checkout. The first is preselected."})]}),(0,H.jsxs)("label",{className:Ha,children:["Free shipping over (",l,")",(0,H.jsx)(pe,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:b=>o({...r,threshold:b.target.value})}),(0,H.jsx)(aa,{children:"Orders at or above this get the cheapest rate free."})]}),u.length>0&&(0,H.jsxs)("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",l,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),(0,H.jsx)(os,{dirty:d,saving:i,error:g,onSave:()=>void m(),onDiscard:()=>{v(null),c()}}),s]})}var xi="exclusive",wu=[{href:"https://docs.stripe.com/tax/set-up",label:"Set up Stripe Tax"},{href:"https://docs.stripe.com/tax/registering",label:"Add tax registrations"},{href:"https://docs.stripe.com/tax/zero-tax",label:"Why tax can be zero"},{href:"https://stripe.com/tax/pricing",label:"Stripe Tax pricing"}];function Su({href:e,children:t}){return(0,H.jsxs)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"af-inline-flex af-items-center af-gap-1 af-font-medium af-underline af-underline-offset-2 hover:af-text-foreground",children:[t,(0,H.jsx)(qn.ExternalLink,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function ll({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=is(e.tax_behavior??xi),{saving:o,error:d,setError:c,run:u}=ls(),[i,g]=ka.useState(!1),v=e.stripe_tax_enabled,f=v||i,l=()=>u(async()=>{let b=n;if(b===e.tax_behavior){r();return}let S={tax_behavior:b};b!=="inclusive"&&e.tax_rate_bps!=null&&(S.tax_rate_bps=null);let _=await t(S);r(_.tax_behavior??xi)}),m=()=>u(async()=>{let b={stripe_tax_enabled:!0,tax_behavior:n};n!=="inclusive"&&e.tax_rate_bps!=null&&(b.tax_rate_bps=null);let S=await t(b);r(S.tax_behavior??xi),g(!1)}),p=(a||i)&&n!=="inclusive"&&e.tax_rate_bps!=null;return(0,H.jsxs)("div",{className:"af-space-y-5",children:[(0,H.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[(0,H.jsx)("p",{children:"Tax at checkout is calculated by Stripe Tax, which you set up in your Stripe Dashboard (Settings \u2192 Tax): your business address, a default product tax code, and the places you're registered to collect tax."}),(0,H.jsx)("p",{children:"Stripe only collects tax where you've added a registration; anywhere else the tax comes out as zero. Stripe Tax has its own fees, and what it covers (such as filing) depends on your Stripe Tax plan."}),(0,H.jsx)("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:wu.map(b=>(0,H.jsx)("li",{children:(0,H.jsx)(Su,{href:b.href,children:b.label})},b.href))})]}),(0,H.jsx)(hi,{label:"Stripe automatic tax",description:v?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:f,onSave:async b=>{if(i){g(!1),c(null),r();return}if(b&&!e.tax_behavior){g(!0);return}return t({stripe_tax_enabled:b})}}),f&&(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4 af-pl-6",children:[(0,H.jsxs)("label",{className:Ha,children:["Do your prices already include tax?",(0,H.jsxs)("select",{"aria-label":"Your prices",className:el,value:n,onChange:b=>s(b.target.value),children:[(0,H.jsx)("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),(0,H.jsx)("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),(0,H.jsx)(aa,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),p&&(0,H.jsxs)(aa,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),i?(0,H.jsxs)("div",{className:"af-space-y-2",children:[(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(R,{type:"button",size:"sm",disabled:o,onClick:()=>void m(),children:"Turn on"}),(0,H.jsx)(R,{type:"button",size:"sm",variant:"outline",disabled:o,onClick:()=>{g(!1),c(null),r()},children:"Cancel"})]}),d&&(0,H.jsx)(qs,{children:d})]}):(0,H.jsx)(os,{dirty:a,saving:o,error:d,onSave:()=>void l(),onDiscard:()=>{c(null),r()}})]})]})}function sl(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function cl({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=is(sl(e)),{saving:o,error:d,setError:c,run:u}=ls(),i=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),g=()=>u(async()=>{let v={},f=null;if(i&&n.rate.trim()!==""){let b=Number(n.rate);if(!Number.isFinite(b)||b<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");f=Math.round(b*100)}i&&f!==e.tax_rate_bps&&(v.tax_rate_bps=f),f!=null&&e.tax_behavior!=="inclusive"&&(v.tax_behavior="inclusive");let l=n.taxId.trim()||null;l!==e.tax_id&&(v.tax_id=l);let m=n.label.trim()||null;if(m!==e.tax_label&&(v.tax_label=m),Object.keys(v).length===0){r();return}let p=await t(v);r(sl(p))});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:Ha,children:["Tax rate (%)",(0,H.jsx)(pe,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!i,value:i?n.rate:"",onChange:v=>s({...n,rate:v.target.value})}),(0,H.jsx)(aa,{children:i?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),(0,H.jsxs)("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[(0,H.jsxs)("label",{className:Ha,children:["Tax ID",(0,H.jsx)(pe,{"aria-label":"Tax ID",value:n.taxId,maxLength:64,placeholder:"DE123456789",onChange:v=>s({...n,taxId:v.target.value})})]}),(0,H.jsxs)("label",{className:Ha,children:["Tax label",(0,H.jsx)(pe,{"aria-label":"Tax label",value:n.label,maxLength:24,placeholder:"Tax",onChange:v=>s({...n,label:v.target.value})})]})]}),(0,H.jsx)(os,{dirty:a,saving:o,error:d,onSave:()=>void g(),onDiscard:()=>{c(null),r()}})]})}function ul({site:e,updateSite:t,onChangeStart:n}){let[s,a]=ka.useState(e.currency.toUpperCase()),[r,o]=ka.useState(!1),[d,c]=ka.useState(!1),[u,i]=ka.useState(null),g=e.currency.toUpperCase(),v=ka.useRef(g);ka.useEffect(()=>{v.current!==g&&(a(b=>b===v.current?g:b),v.current=g)},[g]);let f=s.trim().toUpperCase(),l=f!==g,m=/^[A-Z]{3}$/.test(f),p=async()=>{c(!0);let b=n?.(),S=!1;i(null);try{let _=await t({currency:f.toLowerCase()});S=!0;let A=_.currency_restatement;A&&!A.applied?i(A.reason?`Not changed: ${A.reason}.`:"The currency was not changed."):(a(_.currency.toUpperCase()),v.current=_.currency.toUpperCase()),o(!1)}catch(_){i(Dr(_))}finally{c(!1),b?.(S)}};return(0,H.jsxs)("div",{className:"af-space-y-3",children:[(0,H.jsxs)("div",{className:"af-flex af-items-end af-gap-2",children:[(0,H.jsxs)("label",{className:Ha,children:["Store currency",(0,H.jsx)(pe,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:d||r,onChange:b=>{a(b.target.value),i(null)}})]}),l&&!r&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(R,{type:"button",size:"sm",disabled:!m,onClick:()=>o(!0),children:"Change currency"}),(0,H.jsx)(R,{type:"button",size:"sm",variant:"ghost",onClick:()=>{a(g),i(null)},children:"Discard"})]})]}),(0,H.jsx)(aa,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&(0,H.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,H.jsxs)("p",{className:"af-text-sm",children:["Change the store currency from ",g," to ",f,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",f,":"," ",Z(2e3,g)," becomes ",Z(2e3,f),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(R,{type:"button",size:"sm",disabled:d,onClick:()=>void p(),children:"Confirm change"}),(0,H.jsx)(R,{type:"button",size:"sm",variant:"ghost",disabled:d,onClick:()=>o(!1),children:"Cancel"})]})]}),u&&(0,H.jsx)(qs,{children:u})]})}function rl(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function Nu(e){return e.length===0?"Off":e.map(t=>t===0?"on the due date":t<0?`${-t} day${t===-1?"":"s"} before`:`${t} day${t===1?"":"s"} after`).join(", ")}function dl({site:e,save:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=is(rl(e)),{saving:o,error:d,setError:c,run:u}=ls();if(!t)return(0,H.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,H.jsxs)("p",{children:["Due ",e.invoice_due_days," days after sending"]}),(0,H.jsxs)("p",{children:["Reminders: ",Nu(e.invoice_reminder_schedule)]}),(0,H.jsxs)("p",{children:["Footer: ",e.invoice_footer||"None"]}),(0,H.jsx)(al,{what:"invoice defaults"})]});let i=()=>u(async()=>{let g={},v=Number(n.dueDays);if(n.dueDays.trim()===""||!Number.isInteger(v)||v<0||v>90)throw new Error("Due days must be a whole number from 0 to 90.");v!==e.invoice_due_days&&(g.due_days=v);let l=n.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(l.some(S=>!Number.isInteger(S)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let m=[...new Set(l)].sort((S,_)=>S-_);wi(m,e.invoice_reminder_schedule)||(g.reminder_schedule=m);let p=n.footer.trim()||null;if(p!==e.invoice_footer&&(g.footer=p),Object.keys(g).length===0){r();return}let b=await t(g);r(b?rl(b):void 0)});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:Ha,children:["Days until due",(0,H.jsx)(pe,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:n.dueDays,onChange:g=>s({...n,dueDays:g.target.value})})]}),(0,H.jsxs)("label",{className:Ha,children:["Reminder schedule",(0,H.jsx)(pe,{"aria-label":"Reminder schedule",value:n.reminders,placeholder:"Off",onChange:g=>s({...n,reminders:g.target.value})}),(0,H.jsx)(aa,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),(0,H.jsxs)("label",{className:Ha,children:["Invoice footer",(0,H.jsx)("textarea",{"aria-label":"Invoice footer",className:tl,maxLength:300,value:n.footer,onChange:g=>s({...n,footer:g.target.value})})]}),(0,H.jsx)(os,{dirty:a,saving:o,error:d,onSave:()=>void i(),onDiscard:()=>{c(null),r()}})]})}function fl({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=is(e.default_email_recipients),{saving:o,error:d,setError:c,run:u}=ls(),[i,g]=ka.useState(""),[v,f]=ka.useState(null),l=()=>{let p=i.trim().toLowerCase();if(p){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p)){f("Enter a valid email address.");return}if(n.some(b=>b.toLowerCase()===p)){f("Already added.");return}s([...n,p]),g(""),f(null)}},m=()=>u(async()=>{let p=await t({default_email_recipients:n});r(p.default_email_recipients)});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-3",children:[(0,H.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[n.map(p=>(0,H.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[p,(0,H.jsx)("button",{type:"button","aria-label":`Remove ${p}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(n.filter(b=>b!==p)),children:(0,H.jsx)(qn.X,{className:"af-h-3 af-w-3"})})]},p)),n.length===0&&(0,H.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(pe,{"aria-label":"Add notification email",type:"email",value:i,placeholder:"Add email address",onChange:p=>{g(p.target.value),f(null)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),l())}}),(0,H.jsx)(R,{type:"button",variant:"outline",disabled:!i.trim(),onClick:l,children:"Add"})]}),v&&(0,H.jsx)(qs,{children:v}),(0,H.jsx)(os,{dirty:a,saving:o,error:d,onSave:()=>void m(),onDiscard:()=>{c(null),r()}})]})}var Ft=require("react/jsx-runtime");function Si({siteId:e,refreshKey:t,section:n,shippingProviderSlot:s,onConnectStripe:a,onUpgradePlan:r,className:o}){let{site:d,isLoading:c,error:u,refetch:i,updateSite:g}=pn({siteId:e,refreshKey:t}),v=nn.useRef(i),f=nn.useRef(e);zn(()=>{v.current=i,f.current=e});let l=nn.useRef({}),[m,p]=nn.useState([]),b=m.some(P=>P.siteId===e),S=nn.useCallback(()=>{let P={siteId:e},T=v.current;return p(L=>[...L,P]),L=>{let N=()=>p(I=>I.filter(C=>C!==P));!(f.current===P.siteId)||L&&v.current===T?N():v.current().finally(N)}},[e]),_=P=>T=>{l.current[P]=T},A=d!==null&&d.payments_active;if(nn.useEffect(()=>{if(!A||!n)return;let P=l.current[n];P&&(P.scrollIntoView?.({behavior:"smooth",block:"start"}),P.focus({preventScroll:!0}))},[A,n]),c)return(0,Ft.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Ft.jsx)(ml.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!d)return(0,Ft.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u?.message??"Could not load store settings."});if(!d.payments_active)return(0,Ft.jsx)(Un,{className:o,onConnectStripe:a,onUpgradePlan:r,whenActive:(0,Ft.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let y={site:d,updateSite:g,refetch:i};return(0,Ft.jsxs)("div",{className:`af-space-y-6 ${o??""}`,children:[u&&(0,Ft.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u.message}),(0,Ft.jsx)(an,{ref:_("checkout"),id:"checkout",title:"Checkout",children:(0,Ft.jsx)(il,{...y})}),(0,Ft.jsx)(an,{ref:_("shipping"),id:"shipping",title:"Shipping",children:(0,Ft.jsx)(ol,{...y,providerSlot:s,currencyChanging:b})}),(0,Ft.jsx)(an,{ref:_("tax"),id:"tax",title:"Tax",children:(0,Ft.jsx)(ll,{...y})}),(0,Ft.jsx)(an,{ref:_("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:(0,Ft.jsx)(ul,{...y,onChangeStart:S})})]},e)}var pl=require("lucide-react");var za=require("react/jsx-runtime");function js({siteId:e,refreshKey:t,onSaveInvoiceSettings:n,className:s}){let{site:a,isLoading:r,error:o,updateSite:d,refetch:c,saveInvoiceSettings:u}=pn({siteId:e,refreshKey:t,onSaveInvoiceSettings:n});return r?(0,za.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,za.jsx)(pl.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):a?(0,za.jsxs)("div",{className:`af-space-y-6 ${s??""}`,children:[o&&(0,za.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o.message}),(0,za.jsx)(an,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:(0,za.jsx)(dl,{site:a,save:u})}),(0,za.jsx)(an,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:(0,za.jsx)(cl,{site:a,updateSite:d,refetch:c})})]},e):(0,za.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o?.message??"Could not load invoice settings."})}var gl=require("lucide-react");var gn=require("react/jsx-runtime");function Ni({siteId:e,refreshKey:t,className:n}){let{site:s,isLoading:a,error:r,updateSite:o,refetch:d}=pn({siteId:e,refreshKey:t});return a?(0,gn.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,gn.jsx)(gl.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?(0,gn.jsxs)("div",{className:`af-space-y-3 ${n??""}`,children:[r&&(0,gn.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r.message}),(0,gn.jsx)(an,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:(0,gn.jsx)(fl,{site:s,updateSite:o,refetch:d})})]},e):(0,gn.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r?.message??"Could not load notification settings."})}var cs=oe(require("react"),1);var Ze=require("react/jsx-runtime");function _i({refreshKey:e,initialInvoiceId:t,onBackToWebsite:n,onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:r,siteId:o,onSaveInvoiceSettings:d,className:c}){let{aggregates:u,isLoading:i,error:g,refetch:v}=Bn({refreshKey:e,initialPageSize:1,includeAggregates:!0}),f=$n({refreshKey:e}),{api:l}=ae(),m=f.filters,p=cs.useCallback(()=>l.exportRetainersCsv(m),[l,m]),[b,S]=cs.useState(!1),[_,A]=cs.useState(null),[y,P]=cs.useState(!1),T=(0,Ze.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:g||!i&&!u?(0,Ze.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,Ze.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>void v(),children:"Retry totals"})]}):i||!u?(0,Ze.jsxs)(Ze.Fragment,{children:[(0,Ze.jsx)(ut,{label:"Outstanding",children:(0,Ze.jsx)(le,{className:"af-h-6 af-w-24"})}),(0,Ze.jsx)(ut,{label:"Overdue",children:(0,Ze.jsx)(le,{className:"af-h-6 af-w-24"})}),(0,Ze.jsx)(ut,{label:"Paid this month",children:(0,Ze.jsx)(le,{className:"af-h-6 af-w-24"})})]}):(0,Ze.jsxs)(Ze.Fragment,{children:[(0,Ze.jsx)(ut,{label:"Outstanding",detail:`${u.outstanding.count} open`,children:Z(u.outstanding.amount,u.currency)}),(0,Ze.jsx)(ut,{label:"Overdue",detail:u.overdue.count===0?"Nothing overdue":`${u.overdue.count} overdue`,valueClassName:u.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:Z(u.overdue.amount,u.currency)}),(0,Ze.jsx)(ut,{label:"Paid this month",detail:`${u.paid_this_month.count} paid`,children:Z(u.paid_this_month.amount,u.currency)})]})});return(0,Ze.jsxs)(wt,{title:"Invoices",onBackToWebsite:n,hideBackButton:b,className:c,children:[T,o&&!b&&(0,Ze.jsxs)("div",{className:"af-mb-6",children:[(0,Ze.jsx)(R,{type:"button",variant:"outline",size:"sm","aria-expanded":y,"aria-controls":"af-invoice-settings",onClick:()=>P(L=>!L),children:"Invoice settings"}),y&&(0,Ze.jsx)("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:(0,Ze.jsx)(js,{siteId:o,refreshKey:e,onSaveInvoiceSettings:d})})]}),!b&&(0,Ze.jsx)(Fn,{retainers:f.retainers,isLoading:f.isLoading,error:f.error,onRetry:()=>void f.refetch(),activeRetainerId:_?.id??null,onShowCycles:L=>A(N=>N?.id===L.id?null:L),total:f.total,endedTotal:f.endedTotal,isLoadingMore:f.isLoadingMore,onLoadMore:()=>void f.loadMore(),includeEnded:f.includeEnded,onIncludeEndedChange:f.setIncludeEnded,exportCsv:p}),(0,Ze.jsx)(mn,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:S,onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:r,retainerFilter:_?{id:_.id,label:`${_.customer_name??_.customer_email??"Recurring invoices"} \u2014 ${_.description}`}:null,onClearRetainerFilter:()=>A(null)})]})}var Tt=oe(require("react"),1);var _u=2e3,Ut=()=>({data:null,error:null,isLoading:!0});function jn(e,{refreshKey:t,breakdowns:n=[],filters:s=[]}={}){let{api:a}=ae(),[r,o]=Tt.useState(Ut),[d,c]=Tt.useState(Ut),[u,i]=Tt.useState(Ut),[g,v]=Tt.useState(Ut),[f,l]=Tt.useState(Ut),m=q=>Object.fromEntries(q.map(V=>[V,Ut()])),[p,b]=Tt.useState(()=>m(n)),S=Tt.useRef(0),_=Tt.useRef(0),A=Tt.useRef("idle"),y=n.join(","),P=yn()??"",T=JSON.stringify(s),L=`${e}:${y}:${T}:${P}`,[N,k]=Tt.useState({api:a,fetchIdentity:L});(N.api!==a||N.fetchIdentity!==L)&&(k({api:a,fetchIdentity:L}),S.current+=1,o(Ut),c(Ut),i(Ut),v(Ut),b(m(y?y.split(","):[])));let I=`${e}:${String(t??"")}:${P}`,[C,ee]=Tt.useState({api:a,conversionsIdentity:I});(C.api!==a||C.conversionsIdentity!==I)&&(ee({api:a,conversionsIdentity:I}),_.current+=1,A.current="idle",l(Ut));let M=Tt.useCallback(async q=>{let V=++S.current,j=y?y.split(","):[];o(Ut),c(Ut),i(Ut),v(Ut),b(Object.fromEntries(j.map(D=>[D,Ut()])));let be=A.current!=="pending"&&(q?.force===!0||A.current==="idle"),Je=(D,U)=>U.then(F=>{V===S.current&&D({data:F,error:null,isLoading:!1})},F=>{V===S.current&&D({data:null,error:F instanceof Error?F:new Error("Failed to fetch report"),isLoading:!1})}),yt=a.getAnalyticsStatus(),Oe=Je(o,yt),Ve=Symbol("status-timeout"),Ye,Ae=await Promise.race([yt.then(D=>D,()=>null),new Promise(D=>{Ye=setTimeout(()=>D(Ve),_u)})]);if(clearTimeout(Ye),V!==S.current)return;if(Ae===Ve&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Ae!==null&&Ae!==Ve&&(Ae.collecting!==!0||Ae.first_seen===null&&!Ae.first_seen_unavailable||Ae.first_seen!==null&&Ae.first_seen_in_reports===!1)){let D={data:null,error:null,isLoading:!1};c(D),i(D),v(D),b(Object.fromEntries(j.map(U=>[U,{...D}]))),be&&(l(D),A.current="done"),await Oe;return}await Promise.all([Ae===Ve?Promise.resolve():Oe,Je(c,a.getAnalyticsSummary(e,s)),Je(i,a.getAnalyticsTimeseries(e,s)),Je(v,a.getAnalyticsChannels(e,s)),be?(()=>{A.current="pending";let D=++_.current;return l(Ut),a.getAnalyticsConversions(e).then(U=>{D===_.current&&(l({data:U,error:null,isLoading:!1}),A.current="done")},U=>{D===_.current&&(l({data:null,error:U instanceof Error?U:new Error("Failed to fetch report"),isLoading:!1}),A.current="done")})})():Promise.resolve(),...j.map(D=>a.getAnalyticsBreakdown(D,e,s).then(U=>{V===S.current&&b(F=>({...F,[D]:{data:U,error:null,isLoading:!1}}))},U=>{V===S.current&&b(F=>({...F,[D]:{data:null,error:U instanceof Error?U:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[a,e,y,T,I,P]),te=Tt.useCallback(async()=>{let q=S.current;try{let V=await a.getAnalyticsStatus();if(q!==S.current)return;o({data:V,error:null,isLoading:!1})}catch(V){if(q!==S.current)return;o(j=>({data:j.data,error:V instanceof Error?V:new Error("Failed to fetch status"),isLoading:!1}))}},[a]),ne=Tt.useCallback(()=>M({force:!0}),[M]);Tt.useEffect(()=>{M()},[M,t]);let re=r.isLoading||d.isLoading||u.isLoading||g.isLoading||f.isLoading||Object.values(p).some(q=>q.isLoading),se=[u,d,g,f,...Object.values(p)].map(q=>q.data?.status==="ok"?q.data.timezone:void 0).find(q=>q!==void 0);return{status:r,summary:d,timeseries:u,channels:g,conversions:f,breakdowns:p,reportedZone:se,isLoading:re,refetch:ne,refetchStatus:te}}var kt=oe(require("react"),1);var Lr=3e4,Or=3;function Gs(e={}){let t="collecting"in e,{collecting:n,statusFailed:s=!1,identity:a}=e,{api:r}=ae(),[o,d]=kt.useState(null),[c,u]=kt.useState(null),[i,g]=kt.useState(!1),[v,f]=kt.useState(null),[l,m]=kt.useState(!1),[p,b]=kt.useState(!0),[S,_]=kt.useState(0),A=kt.useRef(0),y=kt.useRef(0),P=kt.useRef(void 0);n!==void 0&&(P.current=n);let T=t?P.current===!0||P.current===void 0&&s:!0,[L,N]=kt.useState({api:r,identity:a}),k=a!==void 0&&a!==L.identity;(L.api!==r||k)&&(P.current=void 0,N({api:r,identity:a}),y.current+=1,A.current=0,d(null),u(null),g(!1),f(null),m(!1),b(!0),_(0));let I=kt.useRef(()=>{}),C=kt.useRef(null),ee=kt.useCallback(async()=>{if(C.current!==null&&C.current===y.current)return;let M=++y.current;C.current=M;try{let te=await r.getAnalyticsRealtime();if(M!==y.current)return;if(te.status==="unreachable"){m(!0),g(!0),b(!1),_(ne=>ne+1);return}A.current=0,m(!1),d(te.data.current_visitors),u(te.as_of),g(!1),f(null),b(!1),_(ne=>ne+1)}catch(te){if(M!==y.current)return;A.current+=1,b(!1),_(ne=>ne+1),g(!0),A.current>=Or&&f(te instanceof Error?te:new Error("Realtime unavailable"))}finally{C.current===M&&(C.current=null)}},[r]);return I.current=()=>void ee(),kt.useEffect(()=>{let M,te=()=>{M===void 0&&(M=setInterval(()=>I.current(),Lr))},ne=()=>{M!==void 0&&(clearInterval(M),M=void 0)},re=()=>{typeof document<"u"&&document.hidden?ne():(I.current(),te())};return T?((typeof document>"u"||!document.hidden)&&(I.current(),te()),document?.addEventListener("visibilitychange",re),()=>{ne(),document?.removeEventListener("visibilitychange",re),y.current+=1}):()=>{document?.removeEventListener("visibilitychange",re)}},[L.api,L.identity,T]),{currentVisitors:o,asOf:c,isStale:i,error:v,isUnreachable:l,isInitialLoad:p,polls:S}}var ft=oe(require("react"),1);var vl=oe(require("react"),1);var Gn=require("react/jsx-runtime");function Ru(){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 Ri({value:e,chosen:t,onChange:n}){let s=fs(),a=t===null&&s!==null&&e===s,r=vl.useMemo(()=>{let o=Ru();return o.includes(e)?o:[e,...o]},[e]);return(0,Gn.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,Gn.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,Gn.jsxs)("select",{value:a?"":e,onChange:o=>n(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,Gn.jsx)("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(o=>(0,Gn.jsx)("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var Br=(e,{published:t}={})=>{let n=t===!1,s=e!=null&&(!e.collecting||n&&e.first_seen===null&&!e.first_seen_unavailable),a=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=a||r;return{notCollecting:s,awaitingFirstVisit:a,firstVisitTooRecent:r,holdingForFirstData:o,nothingToReport:s||o}};var Ws=oe(require("react"),1),Pu=3e4;function Fr({status:e,holdingForFirstData:t,refetchStatus:n,refetch:s}){Ws.useEffect(()=>{if(!t)return;let r,o=()=>{r===void 0&&(r=setInterval(()=>void n(),Pu))},d=()=>{r!==void 0&&(clearInterval(r),r=void 0)},c=()=>{typeof document<"u"&&document.hidden?d():(n(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",c),()=>{d(),document?.removeEventListener("visibilitychange",c)}},[t,n]);let a=Ws.useRef(void 0);Ws.useEffect(()=>{if(!e){a.current=void 0;return}let r=a.current;a.current=t,r===!0&&!t&&s()},[e,t,s])}var Wn=oe(require("react"),1);var Cu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Wt(e){let t=Math.abs(e);if(t<1e3)return String(e);let n=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[s,a]of n)if(t>=s){let r=e/s,o=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(o)>=1e3&&s!==1e9?Wt(o*s):`${o}${a}`}return String(e)}function us(e){return`${(e*100).toFixed(1)}%`}function Ks(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`}function yl(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`:Ks(t)}function hl(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function xl(e,t){if(!(!Number.isFinite(e)||e<=0))for(let n of t){let s=Math.ceil(e/n);if(s<=5)return Array.from({length:s+1},(a,r)=>Number((r*n).toPrecision(12)))}}function Zs(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function wl(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 Pi(e){let t=Number(e.slice(5,7)),n=Number(e.slice(8,10));return`${Cu[t-1]} ${n}`}function bl(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Tu(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Sl(e,t,n="UTC"){let s=new Map(t.map(o=>[o.date,o])),a=[],r=bl(e.to,n);for(let o=bl(e.from,n);o<r;o=Tu(o))a.push(s.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return a}function Nl(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=new Date(`${e}T00:00:00Z`);if(Number.isNaN(s.getTime()))return e;let a=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${a} ${n[s.getUTCMonth()]}`}var va=require("react/jsx-runtime");function _l({what:e="This report",onRetry:t,collecting:n}){return(0,va.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,va.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,va.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:n===!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,va.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 Ur({what:e="No data"}){return(0,va.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 vn({sourced:e,error:t,isLoading:n,what:s,onRetry:a,collecting:r,children:o}){return n?(0,va.jsx)("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,va.jsx)(_l,{what:s,onRetry:a,collecting:r}):!e||e.status==="unreachable"?(0,va.jsx)(_l,{what:s,onRetry:a,collecting:r}):(0,va.jsx)(va.Fragment,{children:o(e.data)})}var tt=require("react/jsx-runtime");function Ci({rows:e,dimension:t,metric:n,metricLabel:s,secondary:a,emptyCopy:r="No data for this period",onFilter:o,canFilter:d,maxRows:c=9}){let[u,i]=Wn.useState(!1);if(e.length===0)return(0,tt.jsx)(Ur,{what:r});let g=e.reduce((l,m)=>Math.max(l,Number(m[n]??0)),0)||1,v=Math.max(0,e.length-c),f=u?e:e.slice(0,c);return(0,tt.jsxs)(tt.Fragment,{children:[(0,tt.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,tt.jsx)("thead",{children:(0,tt.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,tt.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,tt.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),(0,tt.jsx)("tbody",{children:f.map((l,m)=>{let p=Number(l[n]??0),b=l[t]??null,S=Zs(b),_=a?l[a]:null,A=b!==null&&(d?d(b,_):!0);return(0,tt.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,tt.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,tt.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,p/g*100)}%`}}),b!==null&&o&&A?(0,tt.jsx)("button",{type:"button",onClick:()=>o(b,_),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,tt.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:S}),_?(0,tt.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:_}):null]}),(0,tt.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Wt(p)})]},`${S}-${_??""}-${m}`)})})]}),v>0?(0,tt.jsx)("button",{type:"button",onClick:()=>i(l=>!l),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 Js({title:e,tabs:t,defaultTabId:n,headerRight:s}){let[a,r]=Wn.useState(n),o=t.find(f=>f.id===a)??t[0],d=Wn.useId(),c=f=>`${d}-tab-${f}`,u=f=>`${d}-panel-${f}`,i=Wn.useRef(null),g=(f,l)=>{f.preventDefault();let m=(l+t.length)%t.length;r(t[m].id),i.current?.querySelectorAll('[role="tab"]')?.[m]?.focus()};return(0,tt.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,tt.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,tt.jsx)("div",{ref:i,role:"tablist","aria-label":e,onKeyDown:f=>{let l=t.findIndex(m=>m.id===a);f.key==="ArrowRight"&&g(f,l+1),f.key==="ArrowLeft"&&g(f,l-1),f.key==="Home"&&g(f,0),f.key==="End"&&g(f,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(f=>(0,tt.jsx)("button",{id:c(f.id),role:"tab",type:"button","aria-selected":f.id===a,"aria-controls":u(f.id),tabIndex:f.id===a?0:-1,onClick:()=>r(f.id),className:f.id===a?"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:f.label},f.id))}),s]}),o?(0,tt.jsx)("div",{id:u(o.id),role:"tabpanel","aria-labelledby":c(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var na=oe(require("react"),1),Cn=oe(require("@radix-ui/react-popover"),1);var Kn=3,Zn=100;var Be=require("react/jsx-runtime"),Ys={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"},ku=Object.keys(Ys);function Rl(e){let t=Ys[e.dimension],n=e.operator==="is_not"?"is not":"is",s=e.values.map(a=>Zs(a)).join(" or ");return`${t} ${n} ${s}`}function Ti(e,t){let n=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));if(n>=0){let s=[...new Set([...e[n].values,...t.values])];return s.length>100||s.length===e[n].values.length?e:e.map((a,r)=>r===n?{...a,values:s}:a)}return t.values.length>100||e.length>=3?e:[...e,t]}function Eu(e,t){let n={};for(let[s,a]of Object.entries(t)){let r=e.get(s)??new Set;for(let o of a)r.add(o);e.set(s,r),n[s]=[...r]}return n}function Pl(e,t){let n=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));return n>=0?e.map((s,a)=>a===n?t:s):t.values.length>100||e.length>=3?e:[...e,t]}function Iu(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Cl(e,t,n,s={}){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 a=Eu(e.byDimension,n);for(let[r,o]of Object.entries(s)){let d=e.foldsByLabel.get(r)??new Set;for(let c of o)d.add(c);e.foldsByLabel.set(r,d)}return{suggestions:a,folds:new Map([...e.foldsByLabel].map(([r,o])=>[r,[...o]]))}}function Tl(e){let{filters:t,onChange:n}=e,s=t.length>=3;return na.useEffect(()=>{if(t.length===0)return;let a=r=>{let o=r.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||r.key==="Escape"&&n([])};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[t.length,n]),(0,Be.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((a,r)=>(0,Be.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,Be.jsx)("span",{className:"af-text-foreground",children:Rl(a)}),(0,Be.jsx)("button",{type:"button","aria-label":`Remove filter ${Rl(a)}`,onClick:()=>n(t.filter((o,d)=>d!==r)),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"})]},`${a.dimension}-${a.operator??"is"}`)),(0,Be.jsx)(Au,{...e,disabled:s}),t.length>0?(0,Be.jsx)("button",{type:"button",onClick:()=>n([]),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 Au({filters:e,onChange:t,suggestions:n,resetKey:s,disabled:a,expandValues:r}){let[o,d]=na.useState(!1),c=na.useRef(null),[u,i]=na.useState(null);na.useEffect(()=>{i(c.current?.closest(".aifeatures-admin")??null)},[]);let[g,v]=na.useState(null),[f,l]=na.useState("is"),[m,p]=na.useState(""),[b,S]=na.useState([]);na.useEffect(()=>{o||(v(null),l("is"),p(""),S([]))},[o]);let _=na.useRef(s);_.current!==s&&(_.current=s,o&&d(!1),g!==null&&v(null),b.length>0&&S([]),m!==""&&p(""),f!=="is"&&l("is"));let A=k=>{let I=Iu(k);v(I.dimension),S(I.picked),p(I.search),l(I.operator)},P=(g?n[g]??[]:[]).filter(k=>k.toLowerCase().includes(m.trim().toLowerCase())),T=g===null||b.length===0?null:Ti(e,{dimension:g,operator:f,values:r?r(g,b):b}),L=T!==null&&T!==e,N=()=>{let k=T;!k||k===e||(t(k),d(!1))};return(0,Be.jsxs)(Cn.Root,{open:o,onOpenChange:d,children:[(0,Be.jsx)(Cn.Trigger,{asChild:!0,children:(0,Be.jsx)("button",{ref:c,type:"button",disabled:!1,title:a?`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,Be.jsx)(Cn.Portal,{container:u,children:(0,Be.jsx)(Cn.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:g===null?(0,Be.jsxs)("div",{children:[(0,Be.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Be.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:ku.filter(k=>n[k]!==void 0).map(k=>{let I=n[k]?.length??0,C=!e.some(ee=>ee.dimension===k)&&e.length>=3;return(0,Be.jsxs)("button",{type:"button",onClick:()=>A(k),disabled:I===0||C,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,Be.jsx)("span",{children:Ys[k]}),(0,Be.jsx)("span",{className:"af-text-muted-foreground",children:I===0?"no data":C?"no room":I})]},k)})})]}):(0,Be.jsxs)("div",{children:[(0,Be.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Be.jsx)("button",{type:"button",onClick:()=>A(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Be.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Ys[g]}),(0,Be.jsxs)("select",{"aria-label":"Operator",value:f,onChange:k=>l(k.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,Be.jsx)("option",{value:"is",children:"is"}),(0,Be.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Be.jsx)("input",{type:"text",value:m,onChange:k=>p(k.target.value),placeholder:"Search\u2026","aria-label":`Search ${Ys[g]}`,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,Be.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:P.length===0?(0,Be.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",m,"\u201D."]}):P.map(k=>(0,Be.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,Be.jsx)("input",{type:"checkbox",checked:b.includes(k),disabled:!b.includes(k)&&b.length>=100,onChange:I=>S(C=>I.target.checked?[...C,k]:C.filter(ee=>ee!==k))}),(0,Be.jsx)("span",{className:"af-break-all",children:Zs(k)})]},k))}),(0,Be.jsx)("button",{type:"button",onClick:N,disabled:!L,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:b.length<=1?"Apply filter":b.length>=100?`Apply filter (${b.length} values \u2014 the maximum)`:`Apply filter (${b.length} values)`})]})})})]})}var dt=require("react/jsx-runtime"),Du=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Wt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Wt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Wt,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:us,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Ks,chart:"visit_duration_seconds"}];function Lu({current:e,previous:t,downIsGood:n}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let a=s>0,r=n?!a:a,o=`${a?"+":""}${(s*100).toFixed(1)}%`;return(0,dt.jsx)("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:o})}function kl({summary:e,selected:t,onSelect:n}){return(0,dt.jsx)("div",{className:"af-@container",children:(0,dt.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Du.map(s=>{let a=s.chart===t,r=n!==void 0,o=(0,dt.jsxs)(dt.Fragment,{children:[(0,dt.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),(0,dt.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,dt.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?(0,dt.jsx)(Lu,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?(0,dt.jsx)("button",{type:"button","aria-pressed":a,onClick:()=>n(s.chart),className:a?"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},s.key):(0,dt.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},s.key)})})})}function ki({currentVisitors:e,asOf:t,isStale:n,isUnreachable:s,isInitialLoad:a=!1,scopeIsSiteWide:r=!1}){if(a&&!s)return(0,dt.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,dt.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,dt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return(0,dt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?wl(t):"freshness unknown",d=r?" across the whole site, not the current filter,":"",c=n?`${e} current visitors${d} ${o} (not updating)`:`${e} current visitors${d} ${o}`;return(0,dt.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:c,children:[(0,dt.jsx)("span",{"aria-hidden":"true",className:n?"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,dt.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,dt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),(0,dt.jsx)("span",{className:"af-sr-only",children:c})]})}var El=oe(require("react"),1),Il=require("lucide-react");var $e=require("react/jsx-runtime");function Mr(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function $r({rows:e,denominator:t,windowPrecedesCollection:n=!1,coverageUnknown:s=!1,emptyCopy:a="No conversions in this period",maxRows:r=9,primaryConversion:o}){let[d,c]=El.useState(!1),u=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||Mr(p,o)),i=n?(0,$e.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."}):s?(0,$e.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,$e.jsxs)($e.Fragment,{children:[(0,$e.jsx)(Ur,{what:a}),i]});let g=u.slice(0,r),v=o?u.find(p=>Mr(p,o)):void 0,f=v&&!g.includes(v)?u.filter(p=>g.includes(p)||p===v).slice(0,Math.max(0,r-1)).concat(v):g,l=d?e:f,m=Math.max(0,e.length-f.length);return(0,$e.jsxs)($e.Fragment,{children:[(0,$e.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,$e.jsx)("thead",{children:(0,$e.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,$e.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,$e.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,$e.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,$e.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,$e.jsx)("tbody",{children:l.map((p,b)=>(0,$e.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":Mr(p,o)?"true":void 0,children:[(0,$e.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Mr(p,o)?(0,$e.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,$e.jsx)(Il.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,$e.jsx)("span",{className:"af-font-medium af-text-foreground",children:p.goal}),(0,$e.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):p.goal}),(0,$e.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Wt(p.visitors)}),(0,$e.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Wt(p.events)}),(0,$e.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:p.conversion_rate===null?(0,$e.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):us(p.conversion_rate)})]},`${p.goal}-${b}`))})]}),m>0?(0,$e.jsx)("button",{type:"button",onClick:()=>c(p=>!p),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,$e.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Wt(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),i]})}var sa=require("recharts");var mt=require("react/jsx-runtime"),Vr={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Ii={visitors:Wt,visits:Wt,pageviews:Wt,views_per_visit:e=>e.toFixed(2),bounce_rate:us,visit_duration_seconds:Ks},Ou=31,Bu=new Set(["visitors","visits","pageviews"]),Fu={...Ii,bounce_rate:hl,visit_duration_seconds:yl},Ei=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Uu=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Mu=[.01,.02,.05,.1,.2,.25,.5,1],$u=[.25,.5,1,2,5,10,25,50],Vu={visitors:Ei,visits:Ei,pageviews:Ei,views_per_visit:$u,bounce_rate:Mu,visit_duration_seconds:Uu};function Hu({active:e,payload:t,label:n,metric:s}){if(!e||!t||t.length===0)return null;let a=t[0].payload;return(0,mt.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,mt.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Vr[s]}),(0,mt.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,mt.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,mt.jsx)("span",{className:"af-text-muted-foreground",children:Nl(String(n))}),(0,mt.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Ii[s](Number(a[s]??0))})]})]})}function Hr({rows:e,window:t,metric:n,timeZone:s="UTC",height:a=260}){let r=Sl(t,e,s),o=Ii[n],d=Fu[n],c=xl(r.reduce((i,g)=>Math.max(i,Number(g[n]??0)),0),Vu[n]),u=`${Vr[n]} by day: ${r.map(i=>`${Pi(i.date)}: ${o(Number(i[n]??0))}`).join("; ")}.`;return(0,mt.jsxs)("figure",{"aria-label":`${Vr[n]} over time`,className:"af-m-0",children:[(0,mt.jsx)(sa.ResponsiveContainer,{width:"100%",height:a,children:(0,mt.jsxs)(sa.AreaChart,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,mt.jsx)("defs",{children:(0,mt.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,mt.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,mt.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,mt.jsx)(sa.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,mt.jsx)(sa.XAxis,{dataKey:"date",tickFormatter:Pi,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,mt.jsx)(sa.YAxis,{allowDecimals:!Bu.has(n),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...c?{ticks:c,domain:[0,c[c.length-1]]}:{},tickFormatter:i=>d(i),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,mt.jsx)(sa.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,mt.jsx)(Hu,{metric:n})}),(0,mt.jsx)(sa.Area,{type:"linear",dataKey:n,name:Vr[n],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=Ou?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,mt.jsx)("figcaption",{className:"af-sr-only",children:u})]})}var ce=require("react/jsx-runtime"),zu="2026-08-13",qu=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],ju=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Al({filters:e,onFiltersChange:t,refreshKey:n,onBackToWebsite:s,primaryConversion:a,className:r,published:o,lastPublishedAt:d}){let[c,u]=ft.useState(30),[i,g]=ft.useState(()=>Kr()),v=e!==void 0&&t!==void 0,[f,l]=ft.useState(e??[]),{api:m}=ae(),[p,b]=ft.useState(m);p!==m&&(b(m),!v&&f.length>0&&l([]));let S=v?e:f,_=ft.useCallback(F=>{t&&t(F),v||l(F)},[t,v]),A=ft.useCallback((F,ye,Se)=>{let Te=Array.isArray(ye)?ye:[ye];if(Te.length===0)return null;let Ue=Ti(S,{dimension:F,operator:"is",values:Te});if(Se&&(!Se.value||(Ue=Pl(Ue,{dimension:Se.dimension,operator:"is",values:[Se.value]}),!Ue.find(pt=>pt.dimension===Se.dimension&&pt.operator!=="is_not")?.values.includes(Se.value))))return null;let it=Ue.find(Me=>Me.dimension===F&&Me.operator!=="is_not");return Te.every(Me=>it?.values.includes(Me))?JSON.stringify(Ue)===JSON.stringify(S)?null:Ue:null},[S]),y=ft.useCallback((F,ye,Se)=>A(F,ye,Se)!==null,[A]),P=ft.useCallback((F,ye,Se)=>{let Te=A(F,ye,Se);Te&&_(Te)},[A,_]),[T,L]=ft.useState("visitors"),N=jn(c,{refreshKey:n,breakdowns:ju,filters:S}),k=N.status.data,I=N.reportedZone??k?.timezone,C=I??i??fs()??"UTC",{notCollecting:ee,awaitingFirstVisit:M,firstVisitTooRecent:te,holdingForFirstData:ne}=Br(k,{published:o}),re=o===!1,se=Gs({collecting:M||ee?!1:k?.collecting,statusFailed:N.status.error!=null,identity:k?.analytics_id}),q=ft.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),V=ft.useMemo(()=>{let F=N.breakdowns.sources?.data,ye={};if(!F||F.status!=="ok")return ye;for(let Se of F.data){let Te=Se.source,Ue=Se.sources;typeof Te=="string"&&Array.isArray(Ue)&&Ue.length>0&&(ye[Te]=Ue)}return ye},[N.breakdowns.sources?.data]),j=ft.useMemo(()=>{let F=(Te,Ue)=>{let it=N.breakdowns[Te]?.data;return!it||it.status!=="ok"?[]:[...new Set(it.data.map(Me=>Me[Ue]).filter(Me=>typeof Me=="string"&&Me!==""))]};return{channel:N.channels.data?.status==="ok"?[...new Set(N.channels.data.data.map(Te=>Te.channel))]:[],source:F("sources","source"),campaign:F("utm/campaign","campaign"),page:F("pages","pathname"),entry_page:F("entry-pages","pathname"),exit_page:F("exit-pages","pathname"),country:F("countries","country"),browser:F("browsers","browser"),os:F("operating-systems","os"),device:F("devices","device")}},[N.breakdowns,N.channels.data]),[be,Je]=ft.useState({}),yt=JSON.stringify(j),[Oe,Ve]=ft.useState(new Map),Ye=JSON.stringify(V);ft.useEffect(()=>{let{suggestions:F,folds:ye}=Cl(q.current,{api:m,period:c},JSON.parse(yt),JSON.parse(Ye));Je(F),Ve(ye)},[yt,Ye,m,c]);let Ae=ft.useCallback((F,ye)=>F!=="source"?ye:[...new Set(ye.flatMap(Se=>{let Te=[...Oe.get(Se)??[],...V[Se]??[]];return Te.length>0?Te:[Se]}))],[Oe,V]),Et=ft.useMemo(()=>{let F=N.conversions.error;return F instanceof ht&&F.details?.code==="goals_exceed_report_budget"?F.message:null},[N.conversions.error]),D=ft.useMemo(()=>{let F=[N.summary,N.timeseries,N.channels,...Object.values(N.breakdowns)];for(let ye of F){let Se=ye?.error;if(Se instanceof ht&&Se.details?.code==="filter_unsupported")return Se.message}return null},[N.summary,N.timeseries,N.channels,N.breakdowns]),U=(F,ye,Se,Te,Ue,it,Me,pt,me)=>()=>{let ke=N.breakdowns[F];return(0,ce.jsx)(vn,{sourced:ke?.data??null,error:ke?.error,isLoading:ke?.isLoading,what:ye,collecting:k?.collecting,onRetry:N.refetch,children:ot=>{let ra=Ot=>pt?Ae(pt,[Ot]):Ot;return(0,ce.jsx)(Ci,{rows:ot,dimension:Se,metric:Te,metricLabel:Ue,secondary:it,emptyCopy:S.length>0?"No data for this filter":Me,canFilter:pt?(Ot,Kt)=>y(pt,ra(Ot),me?{dimension:me,value:Kt}:void 0):()=>!1,onFilter:pt?(Ot,Kt)=>P(pt,ra(Ot),me?{dimension:me,value:Kt}:void 0):void 0})}})};if(Fr({status:k,holdingForFirstData:ne,refetchStatus:N.refetchStatus,refetch:N.refetch}),ee){let F=!!d&&String(d).slice(0,10)<zu;return(0,ce.jsx)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,ce.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ce.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,ce.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:re?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":F?"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 M?(0,ce.jsx)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,ce.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ce.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,ce.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."})]})}):te?(0,ce.jsxs)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:[(0,ce.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,ce.jsx)(Ri,{value:C,chosen:i,onChange:F=>{Zr(F),g(F)}})}),(0,ce.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ce.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,ce.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",k?.timezone?` ${k.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,ce.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,ce.jsx)(ki,{currentVisitors:se.currentVisitors,asOf:se.asOf,isStale:se.isStale,isUnreachable:se.isUnreachable||se.error!==null,isInitialLoad:se.isInitialLoad})})]})]}):(0,ce.jsx)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,ce.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,ce.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,ce.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:qu.map(F=>(0,ce.jsx)("button",{type:"button","aria-pressed":F.value===c,onClick:()=>u(F.value),className:F.value===c?"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:F.label},F.value))}),(0,ce.jsx)(Ri,{value:C,chosen:i,onChange:F=>{Zr(F),g(F)}}),(0,ce.jsx)(ki,{currentVisitors:se.currentVisitors,asOf:se.asOf,isStale:se.isStale,isUnreachable:se.isUnreachable||se.error!==null,isInitialLoad:se.isInitialLoad,scopeIsSiteWide:S.length>0})]}),(0,ce.jsx)(Tl,{filters:S,onChange:_,suggestions:be,expandValues:Ae,resetKey:m}),D?(0,ce.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ce.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,ce.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:D}),(0,ce.jsx)("button",{type:"button",onClick:()=>_([]),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,!D&&k?.timezone_defaulted?(0,ce.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,D?null:(0,ce.jsxs)(ce.Fragment,{children:[(0,ce.jsx)(vn,{sourced:N.summary.data,error:N.summary.error,isLoading:N.summary.isLoading,what:"The traffic summary",collecting:k?.collecting,onRetry:N.refetch,children:F=>(0,ce.jsxs)(ce.Fragment,{children:[(0,ce.jsx)(kl,{summary:F,selected:T,onSelect:L}),F.previous_unavailable?(0,ce.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[F.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,ce.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,ce.jsx)(vn,{sourced:N.timeseries.data,error:N.timeseries.error,isLoading:N.timeseries.isLoading,what:"The visitors chart",collecting:k?.collecting,onRetry:N.refetch,children:F=>{let ye=N.timeseries.data?.status==="ok"?N.timeseries.data.window:{from:"",to:""};return(0,ce.jsx)(Hr,{rows:F,window:ye,metric:T,timeZone:I??"UTC"})}})}),(0,ce.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,ce.jsx)(Js,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,ce.jsx)(vn,{sourced:N.channels.data,error:N.channels.error,isLoading:N.channels.isLoading,what:"Channels",collecting:k?.collecting,onRetry:N.refetch,children:F=>(0,ce.jsx)(Ci,{rows:F,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:S.length>0?"No data for this filter":"No data for this period",canFilter:ye=>y("channel",ye),onFilter:ye=>P("channel",ye)})})},{id:"sources",label:"Sources",render:U("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:U("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,ce.jsx)(Js,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:U("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:U("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:U("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,ce.jsx)(Js,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:U("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:U("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:U("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,ce.jsx)(Js,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:U("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:U("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:U("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,ce.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,ce.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,ce.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,ce.jsxs)("div",{className:"af-px-3 af-py-2",children:[S.length>0?(0,ce.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,ce.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,ce.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,ce.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,ce.jsx)(vn,{sourced:N.conversions.data,error:N.conversions.error,isLoading:N.conversions.isLoading,what:"Conversions",collecting:k?.collecting,onRetry:N.refetch,children:F=>{let ye=N.conversions.data?.status==="ok"?N.conversions.data:null;return(0,ce.jsx)(ce.Fragment,{children:(0,ce.jsx)($r,{rows:F,primaryConversion:a,denominator:ye?.denominator??0,windowPrecedesCollection:ye?.window_precedes_collection??!1,coverageUnknown:ye?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var Ul=oe(require("react"),1),Dt=require("lucide-react");var Ea=oe(require("react"),1),bn=require("lucide-react");var he=require("react/jsx-runtime"),Dl=90,Ll=100;function Gu(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Ol(e){return!!e.label&&e.label!==e.target}function Wu(e,t,n){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:s,with_a_value:a}=t;return s===0?e===0?"Nothing specific has converted here yet.":null:a===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":a<s?n?`These cover ${a.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${a.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function Xs(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Bl({current:e,onChange:t,onClose:n}){let{api:s}=ae(),[a,r]=Ea.useState(null),[o,d]=Ea.useState(!1),[c,u]=Ea.useState({at:"goals"}),[i,g]=Ea.useState(null),[v,f]=Ea.useState(null),[l,m]=Ea.useState(!1),[p,b]=Ea.useState(null),S=Ea.useRef(0);Ea.useEffect(()=>{let P=!0;return r(null),d(!1),u({at:"goals"}),g(null),f(null),m(!1),b(null),S.current+=1,s.getAnalyticsConversions(Dl).then(T=>{if(P){if(T.status!=="ok"){d(!0);return}r(T.data)}}).catch(()=>{P&&d(!0)}),()=>{P=!1}},[s]);let _=P=>{u({at:"targets",row:P}),g(null),f(null),m(!1),b(null);let T=++S.current;s.getAnalyticsGoalTargets(P.goal,Dl,Ll).then(L=>{if(T===S.current){if(L.status!=="ok"){f("failed");return}g(L.data),m(L.truncated===!0),b(L.coverage??null)}}).catch(L=>{if(T!==S.current)return;let N=L instanceof ht?L.details?.code:void 0;f(N==="goal_has_no_targets"?"no-values":"failed")})},A=P=>{t(P),n()};if(o)return(0,he.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(!a)return(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,he.jsx)(bn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,he.jsx)("span",{children:"Loading your conversions\u2026"})]});if(c.at==="targets"){let P=c.row,T=new Map;for(let L of i??[])T.set(L.label,(T.get(L.label)??0)+1);return(0,he.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,he.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,he.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({at:"goals"}),children:[(0,he.jsx)(bn.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,he.jsx)("span",{children:"All conversions"})]})}),(0,he.jsxs)("button",{type:"button","aria-current":e&&Xs(P,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:()=>A({goal:P.goal,implicit:P.implicit}),children:[e&&Xs(P,e)&&!e.target&&(0,he.jsx)(bn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,he.jsxs)("span",{children:["Any ",P.goal.toLowerCase()]})]}),v==="no-values"&&(0,he.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."}),v==="failed"&&(0,he.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,he.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,he.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>_(P),children:"Try again"})]}),!i&&v===null&&(0,he.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,he.jsx)(bn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,he.jsx)("span",{children:"Loading\u2026"})]}),i&&(0,he.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Wu(i.length,p,l)}),l&&(0,he.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Ll,". If what you want isn\u2019t here, pick the conversion itself instead."]}),i?.some(Ol)&&(0,he.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."}),i?.map(L=>{let N=!!(e&&Xs(P,e)&&e.target===L.target),k=T.get(L.label)>1;return Ol(L)?(0,he.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,he.jsxs)("span",{className:"af-min-w-0",children:[(0,he.jsx)("span",{className:"af-block af-truncate",children:L.label}),k&&(0,he.jsx)("span",{className:"af-block af-truncate af-text-xs",children:L.target})]}),(0,he.jsx)("span",{className:"af-shrink-0 af-text-xs",children:L.visitors.toLocaleString()})]},L.target):(0,he.jsxs)("button",{type:"button","aria-current":N?"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:()=>A({goal:P.goal,implicit:P.implicit,target:L.target,...L.label&&L.label!==L.target?{label:L.label}:{}}),children:[(0,he.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[N&&(0,he.jsx)(bn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,he.jsxs)("span",{className:"af-min-w-0",children:[(0,he.jsx)("span",{className:"af-block af-truncate",children:L.label}),k&&(0,he.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:L.target})]})]}),(0,he.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:L.visitors.toLocaleString()})]},L.target)})]})}let y=e?.goal&&!a.some(P=>Xs(P,e));return(0,he.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:[y&&(0,he.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."]}),a.length===0&&(0,he.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."}),a.map(P=>{let T=e?Xs(P,e):!1;return(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,he.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:()=>A({goal:P.goal,implicit:P.implicit}),children:[(0,he.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[T&&(0,he.jsx)(bn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,he.jsx)("span",{className:"af-truncate",children:P.goal})]}),(0,he.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:P.visitors.toLocaleString()})]}),Gu(P)&&(0,he.jsx)(R,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${P.goal}`,onClick:()=>_(P),children:"Narrow"})]},P.goal)}),e?.goal&&(0,he.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:()=>A(null),children:"No main conversion"})]})}var ba=require("react/jsx-runtime");function Ku(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let n of t)try{let{hostname:s}=new URL(n);if(s)return s.toLowerCase().replace(/^www\./,"")}catch{}return null}function Zu(e){if(Ai(e,"whatsapp"))return!0;let t=Ku(e);return t===null?!1:["wa.me","whatsapp.com"].some(n=>t===n||t.endsWith(`.${n}`))}function Ai(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var Fl=[{goal:"Contact",target:e=>Ai(e,"tel"),icon:Dt.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Ai(e,"mailto"),icon:Dt.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:Dt.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Zu(e),icon:Dt.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:Dt.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Dt.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Dt.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:Dt.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:Dt.Download,line:"This site is set up to get your file downloaded."}];function Ml(e){let{goal:t,target:n}=e;return e.implicit!==!0?null:(n?Fl.find(a=>a.goal===t&&a.target?.(n)):void 0)??Fl.find(a=>a.goal===t&&!a.target)??null}function Ju(e){return Ml(e)?.icon??Dt.Target}function $l({primaryConversion:e,onChange:t}){let[n,s]=Ul.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?Ml(e):null,o=e?.label?.trim(),d=e?Ju(e):Dt.Target,c=e?.goal?o?`Your main conversion is ${o}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",u=(0,ba.jsxs)(ba.Fragment,{children:[(0,ba.jsx)(d,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ba.jsx)("span",{children:c})]});return t?(0,ba.jsxs)(fr,{open:n,onOpenChange:s,children:[(0,ba.jsx)(mr,{asChild:!0,children:(0,ba.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,ba.jsx)(Ds,{align:"start",className:"af-w-80 af-p-1",children:n&&(0,ba.jsx)(Bl,{current:e,onChange:t,onClose:()=>s(!1)})})]}):(0,ba.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:u})}var zt=require("react/jsx-runtime");function Vl({refreshKey:e,onViewAll:t,primaryConversion:n}){let s=jn(7,{refreshKey:e,breakdowns:[]}),a=s.status.data??void 0,{nothingToReport:r,notCollecting:o,holdingForFirstData:d}=Br(a);return Fr({status:a,holdingForFirstData:d,refetchStatus:s.refetchStatus,refetch:s.refetch}),(0,zt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,zt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,zt.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,zt.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?(0,zt.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,zt.jsxs)(zt.Fragment,{children:[(0,zt.jsx)(vn,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:a?.collecting,onRetry:s.refetch,children:c=>{let u=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return(0,zt.jsx)(Hr,{rows:c,window:u?.window??{from:"",to:""},metric:"visitors",timeZone:u?.timezone,height:140})}}),(0,zt.jsxs)("div",{className:"af-mt-3",children:[(0,zt.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,zt.jsx)(vn,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:a?.collecting,onRetry:s.refetch,children:c=>{let u=s.conversions.data?.status==="ok"?s.conversions.data:null;return(0,zt.jsx)($r,{rows:c,primaryConversion:n,denominator:u?.denominator??0,windowPrecedesCollection:u?.window_precedes_collection??!1,coverageUnknown:u?.first_seen_unavailable??!1})}})]})]})]})}var Lt=require("react/jsx-runtime"),Di=5;function Li({title:e,viewAllLabel:t,onViewAll:n}){return(0,Lt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Lt.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),n&&(0,Lt.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:n,children:t})]})}function Hl({refreshKey:e,onBackToWebsite:t,primaryConversion:n,onChangePrimaryConversion:s,onOpenSurface:a,needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:d}){let c=Vn({refreshKey:e}),u=(c.summary?.products.count??0)>0||(c.summary?.commerce?.storefront_orders??!1),i=u||(c.summary?.commerce?.invoicing??!1);return(0,Lt.jsx)(wt,{title:"Dashboard",onBackToWebsite:t,children:(0,Lt.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,Lt.jsx)($l,{primaryConversion:n,onChange:s}),(0,Lt.jsx)(Vl,{refreshKey:e,onViewAll:a&&(()=>a("analytics")),primaryConversion:n}),(0,Lt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Lt.jsx)(Li,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:a&&(()=>a("leads"))}),(0,Lt.jsx)(Hs,{refreshKey:e,maxRows:Di,onViewAll:a&&(()=>a("leads"))})]}),u&&(0,Lt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Lt.jsx)(Li,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:a&&(()=>a("orders"))}),(0,Lt.jsx)(dn,{refreshKey:e,maxRows:Di,onViewAll:a&&(()=>a("orders"))})]}),i&&(0,Lt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Lt.jsx)(Li,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:a&&(()=>a("invoices"))}),(0,Lt.jsx)(mn,{refreshKey:e,maxRows:Di,onViewAll:a&&(()=>a("invoices")),needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:d})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,DashboardView,ExportCsvButton,FormSettings,FormSubmissions,FormsDashboard,FormsList,InvoiceDetail,InvoiceLabelBadge,InvoiceSettingsPanel,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,NotificationRecipientsSettings,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,PromosPanel,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,StoreSettings,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,chargedTotal,createApiClient,formatPrice,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useBusinessSummary,useCsvExport,useCustomers,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSiteSettings,useSubmissions,useSubscriptions});
2
+ "use strict";var Kl=Object.create;var tr=Object.defineProperty;var Zl=Object.getOwnPropertyDescriptor;var Jl=Object.getOwnPropertyNames;var Yl=Object.getPrototypeOf,Xl=Object.prototype.hasOwnProperty;var Ql=(e,t)=>{for(var n in t)tr(e,n,{get:t[n],enumerable:!0})},zi=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Jl(t))!Xl.call(e,a)&&a!==n&&tr(e,a,{get:()=>t[a],enumerable:!(s=Zl(t,a))||s.enumerable});return e};var re=(e,t,n)=>(n=e!=null?Kl(Yl(e)):{},zi(t||!e||!e.__esModule?tr(n,"default",{value:e,enumerable:!0}):n,e)),ec=e=>zi(tr({},"__esModule",{value:!0}),e);var td={};Ql(td,{AifeaturesApiError:()=>ht,AifeaturesProvider:()=>Ki,AnalyticsView:()=>Bl,CustomerDetail:()=>Ms,CustomersList:()=>$s,DashboardView:()=>Gl,ExportCsvButton:()=>Bt,FormSettings:()=>ks,FormSubmissions:()=>Rs,FormsDashboard:()=>ei,FormsList:()=>ys,InvoiceDetail:()=>_r,InvoiceLabelBadge:()=>ss,InvoiceSettingsPanel:()=>Ws,InvoicesList:()=>pn,InvoicesView:()=>Ci,LeadsView:()=>qs,MAX_ANALYTICS_FILTERS:()=>Zn,MAX_ANALYTICS_FILTER_VALUES:()=>Jn,NotificationRecipientsSettings:()=>Pi,OrderDetail:()=>Fs,OrderStatusBadge:()=>_n,OrdersList:()=>fn,OrdersView:()=>pi,PaymentsDashboard:()=>mi,PaymentsSetup:()=>Mn,ProductSettings:()=>Ds,ProductsList:()=>Is,ProductsView:()=>gi,PromosPanel:()=>Dn,REALTIME_FAILURES_BEFORE_ERROR:()=>Ur,REALTIME_POLL_MS:()=>Fr,RetainerStatusBadge:()=>Cr,RetainersPanel:()=>Un,StoreSettings:()=>_i,SubmissionDetail:()=>Ss,SubscriptionsView:()=>yi,VariantsEditor:()=>As,ViewShell:()=>wt,WebhookDeliveries:()=>Cs,WebhookSettings:()=>Ts,chargedTotal:()=>Ja,createApiClient:()=>sr,formatPrice:()=>K,isZeroDecimalCurrency:()=>ha,toMajorUnits:()=>nt,toMinorUnits:()=>It,useAifeatures:()=>ae,useAifeaturesContext:()=>ae,useAnalytics:()=>Gn,useBusinessSummary:()=>Hn,useCsvExport:()=>Ns,useCustomers:()=>Us,useEventDestinations:()=>_s,useForms:()=>En,useInvoices:()=>Fn,useOrders:()=>Ls,usePaymentsStatus:()=>cn,usePeople:()=>Hs,usePerson:()=>zs,useProducts:()=>$n,useRealtimeVisitors:()=>Ks,useRetainers:()=>Vn,useSiteSettings:()=>gn,useSubmissions:()=>xs,useSubscriptions:()=>js});module.exports=ec(td);var wn=re(require("react"),1);var Zr="aifeatures:analytics:timezone",Jr;function ps(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function qi(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function hn(){return Yr()??ps()}function Yr(){if(Jr!==void 0)return Jr;try{let e=window.localStorage.getItem(Zr);return qi(e)?e:null}catch{return null}}function Xr(e){if(!(e!==null&&!qi(e))){Jr=e;try{e===null?window.localStorage.removeItem(Zr):window.localStorage.setItem(Zr,e)}catch{}}}function ar(e,t){let n=new URLSearchParams({period:String(e)}),s=hn();return s&&n.set("timezone",s),t&&t.length>0&&n.set("filters",JSON.stringify(t)),n.toString()}var ht=class extends Error{constructor(n,s,a){super(n);this.status=s;this.details=a;this.name="AifeaturesApiError"}};function nr(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 gs(e,t){let n=t.toString();return n?`${e}?${n}`:e}function ji(e){let t=new URLSearchParams;return e.status&&t.set("status",e.status),e.source&&t.set("source",e.source),e.excludeStatus?.length&&t.set("exclude_status",e.excludeStatus.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),e.from&&t.set("from",e.from),e.to&&t.set("to",e.to),e.unfulfilledOnly&&t.set("unfulfilled_only","true"),t}function Gi(e){let t=new URLSearchParams;return e.statuses?.length&&t.set("status",e.statuses.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),t}function sr(e,t="https://aifeatures.dev"){async function n(a,r={}){let o=`${t}${a}`,u=await fetch(o,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!u.ok){let g;try{g=await u.json()}catch{}throw new ht(nr(g?.error,u.status),u.status,g)}if(u.status!==204)return u.json()}async function s(a){let r=await fetch(`${t}${a}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let o;try{o=await r.json()}catch{}throw new ht(nr(o?.error,r.status),r.status,o)}return r.blob()}return{async getForms(){return(await n("/api/v1/forms")).forms},async getForm(a){return n(`/api/v1/forms/${a}`)},async createForm(a){return n("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,r){return n(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(a){await n(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,r={}){let o=new URLSearchParams;r.limit!==void 0&&o.set("limit",String(r.limit)),r.offset!==void 0&&o.set("offset",String(r.offset));let u=o.toString(),g=`/api/v1/forms/${a}/submissions${u?`?${u}`:""}`;return n(g)},async getSubmission(a){return n(`/api/v1/submissions/${a}`)},async exportSubmissionsCsv(a,r={}){let o=new URLSearchParams;return r.includeSpam&&o.set("include_spam","true"),s(gs(`/api/v1/forms/${encodeURIComponent(a)}/submissions/export`,o))},async deleteSubmission(a){await n(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,r){let o=typeof r=="string"?{name:r}:r,u=o.name,g=o.id??o.name,l=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(g)}`,i=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){let c;try{c=await i.json()}catch{}throw new ht(nr(c?.error,i.status),i.status,c)}let d=await i.blob(),b=URL.createObjectURL(d),f=document.createElement("a");f.href=b,f.download=u,document.body.appendChild(f),f.click(),document.body.removeChild(f),URL.revokeObjectURL(b)},async getSite(a){return n(`/api/v1/sites/${encodeURIComponent(a)}`)},async updateSite(a,r){return n(`/api/v1/sites/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return n("/api/v1/payments/status")},getPromos(a){let r=new URLSearchParams({limit:"10"});return a&&r.set("cursor",a),n(`/api/v1/promos?${r}`)},getPromo(a){return n(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return n("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return n(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,r){return n(`/api/v1/promos/${encodeURIComponent(a)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(a={}){let r=new URLSearchParams;a.include&&r.set("include",a.include);let o=r.toString();return(await n(`/api/v1/products${o?`?${o}`:""}`)).products},async getProduct(a){return n(`/api/v1/products/${a}`)},async createProduct(a){return n("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,r){return n(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(a){await n(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,r){let o=new FormData;o.append("file",r);let u=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:o});if(!u.ok){let g;try{g=await u.json()}catch{}throw new ht(nr(g?.error,u.status),u.status,g)}return u.json()},async attachProductFileFromUrl(a,r){return n(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(a,r){return n(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(a,r){return n(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(a){await n(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,r){return n(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(a,r){return n(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(a){await n(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,r){return n(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(a,r){return n(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(a={}){let r=new URLSearchParams;a.email?r.set("email",a.email):a.q&&r.set("q",a.q),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/customers${o?`?${o}`:""}`)},async getCustomer(a){return n(`/api/v1/customers/${a}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(a={}){let r=ji(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/orders${o?`?${o}`:""}`)},async exportOrdersCsv(a={}){return s(gs("/api/v1/orders/export",ji(a)))},async getOrder(a){return n(`/api/v1/orders/${a}`)},async getInvoices(a={}){let r=new URLSearchParams;a.labels?.length&&r.set("label",a.labels.join(",")),a.customerEmail&&r.set("customer_email",a.customerEmail),a.customerId&&r.set("customer_id",a.customerId),a.q&&r.set("q",a.q),a.from&&r.set("from",a.from),a.to&&r.set("to",a.to),a.includeAggregates&&r.set("include","aggregates"),a.retainerId&&r.set("retainer_id",a.retainerId),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/invoices${o?`?${o}`:""}`)},async getInvoice(a){return n(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return n(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return n("/api/v1/invoice-settings")},async getRetainers(a={}){let r=Gi(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/retainers${o?`?${o}`:""}`)},async exportRetainersCsv(a={}){return s(gs("/api/v1/retainers/export",Gi(a)))},async getRetainer(a){return n(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await n(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return n(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,r){return n(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(a={}){let r=new URLSearchParams;a.status&&r.set("status",a.status),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/subscriptions${o?`?${o}`:""}`)},async exportSubscriptionsCsv(a={}){let r=new URLSearchParams;return a.status&&r.set("status",a.status),s(gs("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let a=new URLSearchParams,r=hn();r&&a.set("timezone",r);let o=a.toString();return n(`/api/v1/analytics/status${o?`?${o}`:""}`)},async getAnalyticsSummary(a,r){return n(`/api/v1/analytics/summary?${ar(a,r)}`)},async getAnalyticsTimeseries(a,r){return n(`/api/v1/analytics/timeseries?${ar(a,r)}`)},async getAnalyticsRealtime(){return n("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,r){return n(`/api/v1/analytics/channels?${ar(a,r)}`)},async getAnalyticsConversions(a){return n((()=>{let r=new URLSearchParams({period:String(a)}),o=hn();return o&&r.set("timezone",o),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(a,r,o){let u=new URLSearchParams({goal:a,period:String(r)}),g=hn();return g&&u.set("timezone",g),o!==void 0&&u.set("limit",String(o)),n(`/api/v1/analytics/conversions/targets?${u.toString()}`)},async getAnalyticsBreakdown(a,r,o){let u=a.split("/").map(encodeURIComponent).join("/");return n(`/api/v1/analytics/${u}?${ar(r,o)}`)},async getBusinessSummary(a){let r=new URLSearchParams;r.set("tz_offset_minutes",String(a.tzOffsetMinutes));let o=hn();return o&&r.set("timezone",o),n(`/api/v1/summary?${r.toString()}`)},async getPeople(a={}){let r=new URLSearchParams;a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/people${o?`?${o}`:""}`)},async exportPeopleCsv(a={}){let r=new URLSearchParams;return a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),s(gs("/api/v1/people/export",r))},async getPerson(a){return n(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await n("/api/v1/event-destinations")).destinations},async createEventDestination(a){return n("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,r){return n(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(a){await n(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return n(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await n(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,r){let o=r===void 0?"":`?limit=${r}`;return(await n(`/api/v1/event-destinations/${a}/deliveries${o}`)).deliveries},async retryEventDelivery(a,r){return n(`/api/v1/event-destinations/${a}/deliveries/${r}/retry`,{method:"POST"})}}}var xn=require("react/jsx-runtime"),Wi=wn.createContext(null);function tc(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 Ki({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:n=!1,className:s,children:a}){let r=wn.useMemo(()=>tc(e),[e]),o=wn.useMemo(()=>sr(e,t),[e,t]),u=wn.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return r?(0,xn.jsx)("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:(0,xn.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,xn.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,xn.jsx)("p",{className:"af-text-sm af-text-destructive",children:r})]})}):(0,xn.jsx)(Wi.Provider,{value:u,children:(0,xn.jsx)("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:a})})}function ae(){let e=wn.useContext(Wi);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var ln=re(require("react"),1),Qn=require("lucide-react");var rr=re(require("react"),1),Ma=re(require("@radix-ui/react-tabs"),1);var Zi=require("clsx"),Ji=require("tailwind-merge"),ac=(0,Ji.extendTailwindMerge)({prefix:"af-"});function ee(...e){return ac((0,Zi.clsx)(e))}var or=require("react/jsx-runtime"),ir=Ma.Root,vs=rr.forwardRef(({className:e,...t},n)=>(0,or.jsx)(Ma.List,{ref:n,className:ee("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=Ma.List.displayName;var $a=rr.forwardRef(({className:e,...t},n)=>(0,or.jsx)(Ma.Trigger,{ref:n,className:ee("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}));$a.displayName=Ma.Trigger.displayName;var Va=rr.forwardRef(({className:e,...t},n)=>(0,or.jsx)(Ma.Content,{ref:n,className:ee("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}));Va.displayName=Ma.Content.displayName;var Yi=re(require("react"),1),Xi=require("@radix-ui/react-slot"),Qi=require("class-variance-authority");var eo=require("react/jsx-runtime"),nc=(0,Qi.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"}}),R=Yi.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...a},r)=>(0,eo.jsx)(s?Xi.Slot:"button",{className:ee(nc({variant:t,size:n,className:e})),ref:r,...a}));R.displayName="Button";var bs=require("lucide-react");var rn=re(require("react"),1);var Wa=require("react/jsx-runtime"),qe=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,Wa.jsx)("table",{ref:n,className:ee("af-w-full af-caption-bottom af-text-sm",e),...t})}));qe.displayName="Table";var je=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("thead",{ref:n,className:ee("[&_tr]:af-border-b",e),...t}));je.displayName="TableHeader";var Ge=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("tbody",{ref:n,className:ee("[&_tr:last-child]:af-border-0",e),...t}));Ge.displayName="TableBody";var sc=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("tfoot",{ref:n,className:ee("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));sc.displayName="TableFooter";var Re=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("tr",{ref:n,className:ee("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Re.displayName="TableRow";var j=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("th",{ref:n,className:ee("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}));j.displayName="TableHead";var G=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("td",{ref:n,className:ee("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));G.displayName="TableCell";var rc=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("caption",{ref:n,className:ee("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));rc.displayName="TableCaption";var Ha=re(require("react"),1);function En(){let{api:e}=ae(),[t,n]=Ha.useState([]),[s,a]=Ha.useState(!0),[r,o]=Ha.useState(null),u=Ha.useCallback(async()=>{try{a(!0),o(null);let d=await e.getForms();n(d)}catch(d){o(d instanceof Error?d:new Error("Failed to fetch forms"))}finally{a(!1)}},[e]);Ha.useEffect(()=>{u()},[u]);let g=Ha.useCallback(async d=>{let b=await e.createForm(d);return n(f=>[...f,b]),b},[e]),l=Ha.useCallback(async(d,b)=>{let f=await e.updateForm(d,b);return n(c=>c.map(m=>m.id===d?f:m)),f},[e]),i=Ha.useCallback(async d=>{await e.deleteForm(d),n(b=>b.filter(f=>f.id!==d))},[e]);return{forms:t,isLoading:s,error:r,refetch:u,createForm:g,updateForm:l,deleteForm:i}}var Qe=require("react/jsx-runtime");function ys({onSelectForm:e,className:t}){let{forms:n,isLoading:s,error:a}=En();return s?(0,Qe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Qe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):a?(0,Qe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Qe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",a.message]})}):n.length===0?(0,Qe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,Qe.jsx)(bs.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Qe.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Qe.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Qe.jsx)("div",{className:t,children:(0,Qe.jsxs)(qe,{children:[(0,Qe.jsx)(je,{children:(0,Qe.jsxs)(Re,{children:[(0,Qe.jsx)(j,{children:"Name"}),(0,Qe.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,Qe.jsx)(Ge,{children:n.map(r=>(0,Qe.jsxs)(Re,{children:[(0,Qe.jsx)(G,{className:"af-font-medium",children:r.name}),(0,Qe.jsx)(G,{className:"af-text-right",children:(0,Qe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Qe.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[(0,Qe.jsx)(bs.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Qe.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[(0,Qe.jsx)(bs.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}var no=require("lucide-react");var to=require("class-variance-authority");var ao=require("react/jsx-runtime"),ic=(0,to.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 ne({className:e,variant:t,...n}){return(0,ao.jsx)("div",{className:ee(ic({variant:t}),e),...n})}var ca=require("react/jsx-runtime"),oc={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 lr(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 Qr(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function lc(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 hs({deliveries:e,label:t="Email needs attention"}){return Qr(e)?(0,ca.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,ca.jsx)(no.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Ka({deliveries:e,problemsOnly:t=!1,className:n=""}){let s=(e??[]).filter(a=>!t||Qr([a]));return s.length?(0,ca.jsx)("div",{className:`af-space-y-3 ${n}`,"aria-label":"Email delivery",children:s.map(a=>{let r=lr(a),o=lc(a);return(0,ca.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,ca.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,ca.jsx)("span",{className:"af-font-medium",children:oc[a.kind]??"Email notification"}),(0,ca.jsx)(ne,{variant:r.variant,children:r.label})]}),(0,ca.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",a.recipients.join(", ")]}),a.recipients.length>1&&Qr([a])&&(0,ca.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."}),r.detail&&(0,ca.jsx)("p",{className:"af-mt-1",children:r.detail}),o&&(0,ca.jsx)("p",{className:"af-mt-1",children:o})]},a.id)})}):null}var Nn=re(require("react"),1),ka=require("lucide-react");var Sn=re(require("react"),1),Ae=re(require("@radix-ui/react-select"),1),In=require("lucide-react");var vt=require("react/jsx-runtime"),Pa=Ae.Root;var Ca=Ae.Value,ua=Sn.forwardRef(({className:e,children:t,...n},s)=>(0,vt.jsxs)(Ae.Trigger,{ref:s,className:ee("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),...n,children:[t,(0,vt.jsx)(Ae.Icon,{asChild:!0,children:(0,vt.jsx)(In.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));ua.displayName=Ae.Trigger.displayName;var so=Sn.forwardRef(({className:e,...t},n)=>(0,vt.jsx)(Ae.ScrollUpButton,{ref:n,className:ee("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,vt.jsx)(In.ChevronUp,{className:"af-h-4 af-w-4"})}));so.displayName=Ae.ScrollUpButton.displayName;var ro=Sn.forwardRef(({className:e,...t},n)=>(0,vt.jsx)(Ae.ScrollDownButton,{ref:n,className:ee("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,vt.jsx)(In.ChevronDown,{className:"af-h-4 af-w-4"})}));ro.displayName=Ae.ScrollDownButton.displayName;var da=Sn.forwardRef(({className:e,children:t,position:n="popper",...s},a)=>(0,vt.jsx)(Ae.Portal,{children:(0,vt.jsxs)(Ae.Content,{ref:a,className:ee("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",n==="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:n,...s,children:[(0,vt.jsx)(so,{}),(0,vt.jsx)(Ae.Viewport,{className:ee("af-p-1",n==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,vt.jsx)(ro,{})]})}));da.displayName=Ae.Content.displayName;var cc=Sn.forwardRef(({className:e,...t},n)=>(0,vt.jsx)(Ae.Label,{ref:n,className:ee("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));cc.displayName=Ae.Label.displayName;var et=Sn.forwardRef(({className:e,children:t,...n},s)=>(0,vt.jsxs)(Ae.Item,{ref:s,className:ee("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),...n,children:[(0,vt.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,vt.jsx)(Ae.ItemIndicator,{children:(0,vt.jsx)(In.Check,{className:"af-h-4 af-w-4"})})}),(0,vt.jsx)(Ae.ItemText,{children:t})]}));et.displayName=Ae.Item.displayName;var uc=Sn.forwardRef(({className:e,...t},n)=>(0,vt.jsx)(Ae.Separator,{ref:n,className:ee("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));uc.displayName=Ae.Separator.displayName;var Gt=re(require("react"),1);function xs({formId:e,initialPageSize:t=25}){let{api:n}=ae(),[s,a]=Gt.useState([]),[r,o]=Gt.useState(0),[u,g]=Gt.useState(!0),[l,i]=Gt.useState(null),[d,b]=Gt.useState(0),[f,c]=Gt.useState(t),m=Gt.useRef(0),p=Gt.useCallback(async()=>{if(!e)return;let E=++m.current;try{g(!0),i(null);let v={limit:f,offset:d*f},_=await n.getSubmissions(e,v);if(E!==m.current)return;if(_.submissions.length===0&&d>0){b(Math.max(0,Math.ceil(_.total/f)-1));return}a(_.submissions),o(_.total)}catch(v){if(E!==m.current)return;i(v instanceof Error?v:new Error("Failed to fetch submissions"))}finally{E===m.current&&g(!1)}},[n,e,d,f]);Gt.useEffect(()=>{p()},[p]);let y=Gt.useRef(p);y.current=p;let S=Gt.useCallback(async E=>{await n.deleteSubmission(E),y.current()},[n]),C=Math.ceil(r/f);return{submissions:s,total:r,isLoading:u,error:l,page:d,pageSize:f,hasNextPage:d<C-1,hasPreviousPage:d>0,setPage:b,setPageSize:E=>{c(E),b(0)},refetch:p,deleteSubmission:S}}var cr=re(require("react"),1),lo=require("lucide-react");var ws=re(require("react"),1),Rt=re(require("@radix-ui/react-dialog"),1),io=require("lucide-react");var Qt=require("react/jsx-runtime"),Ta=Rt.Root;var dc=Rt.Portal;var oo=ws.forwardRef(({className:e,...t},n)=>(0,Qt.jsx)(Rt.Overlay,{ref:n,className:ee("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));oo.displayName=Rt.Overlay.displayName;var fa=ws.forwardRef(({className:e,children:t,...n},s)=>(0,Qt.jsx)(dc,{children:(0,Qt.jsxs)("div",{className:"aifeatures-admin",children:[(0,Qt.jsx)(oo,{}),(0,Qt.jsxs)(Rt.Content,{ref:s,className:ee("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),...n,children:[t,(0,Qt.jsxs)(Rt.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)(io.X,{className:"af-h-4 af-w-4"}),(0,Qt.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));fa.displayName=Rt.Content.displayName;var ma=({className:e,...t})=>(0,Qt.jsx)("div",{className:ee("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});ma.displayName="DialogHeader";var pa=({className:e,...t})=>(0,Qt.jsx)("div",{className:ee("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});pa.displayName="DialogFooter";var ga=ws.forwardRef(({className:e,...t},n)=>(0,Qt.jsx)(Rt.Title,{ref:n,className:ee("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));ga.displayName=Rt.Title.displayName;var va=ws.forwardRef(({className:e,...t},n)=>(0,Qt.jsx)(Rt.Description,{ref:n,className:ee("af-text-sm af-text-muted-foreground",e),...t}));va.displayName=Rt.Description.displayName;var $t=require("react/jsx-runtime");function Yn({onDelete:e,iconOnly:t}){let[n,s]=cr.useState(!1),[a,r]=cr.useState(!1),[o,u]=cr.useState(null);return(0,$t.jsxs)($t.Fragment,{children:[(0,$t.jsxs)(R,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{u(null),s(!0)},children:[(0,$t.jsx)(lo.Trash2,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),(0,$t.jsx)(Ta,{open:n,onOpenChange:l=>{!l&&!a&&s(!1)},children:(0,$t.jsxs)(fa,{children:[(0,$t.jsxs)(ma,{children:[(0,$t.jsx)(ga,{children:"Delete this submission?"}),(0,$t.jsx)(va,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),o&&(0,$t.jsx)("p",{className:"af-text-sm af-text-destructive",children:o}),(0,$t.jsxs)(pa,{children:[(0,$t.jsx)(R,{variant:"outline",onClick:()=>s(!1),disabled:a,children:"Cancel"}),(0,$t.jsx)(R,{variant:"destructive",onClick:async()=>{r(!0),u(null);try{await e(),s(!1)}catch(l){u(l instanceof Error?l.message:"Failed to delete submission")}finally{r(!1)}},disabled:a,children:a?"Deleting...":"Delete"})]})]})})]})}var uo=re(require("react"),1),Vt=require("lucide-react");var he=require("react/jsx-runtime");function co(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function fc(e){if(e===0)return"0 B";let t=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${n[s]}`}function Ss({submission:e,onBack:t,onDelete:n}){let{api:s}=ae(),[a,r]=uo.useState(null),o=l=>l.id??l.name,u=async l=>{r(o(l));try{await s.downloadAttachment(e.id,l)}catch(i){console.error("Download failed:",i)}finally{r(null)}},g=Object.entries(e.data).filter(([l])=>!l.startsWith("_"));return(0,he.jsxs)("div",{children:[(0,he.jsxs)("div",{className:"af-mb-6",children:[(0,he.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,he.jsx)(Vt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,he.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,he.jsxs)("div",{children:[(0,he.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,he.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",co(e.metadata.submitted_at)]})]}),n&&(0,he.jsx)(Yn,{onDelete:n})]})]}),(0,he.jsxs)("div",{className:"af-space-y-6",children:[(0,he.jsx)(Ka,{deliveries:e.email_deliveries}),(0,he.jsxs)("div",{children:[(0,he.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,he.jsxs)("div",{className:"af-space-y-3",children:[g.map(([l,i])=>(0,he.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,he.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:l.replace(/_/g," ")}),(0,he.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof i=="string"&&i.includes(`
3
+ `)?(0,he.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:i}):String(i)})]},l)),g.length===0&&(0,he.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,he.jsxs)("div",{children:[(0,he.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,he.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((l,i)=>(0,he.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,he.jsx)(Vt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,he.jsx)("span",{className:"af-text-sm",children:l.name}),(0,he.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",fc(l.size),")"]})]}),(0,he.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>u(l),disabled:a===o(l),children:[a===o(l)?(0,he.jsx)(Vt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,he.jsx)(Vt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),a===o(l)?"Downloading...":"Download"]})]},i))})]}),(0,he.jsxs)("div",{children:[(0,he.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,he.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,he.jsx)(Vt.Clock,{className:"af-h-4 af-w-4"}),(0,he.jsx)("span",{children:co(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,he.jsx)(Vt.Globe,{className:"af-h-4 af-w-4"}),(0,he.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,he.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,he.jsx)(Vt.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,he.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,he.jsx)(Vt.Mail,{className:"af-h-4 af-w-4"}),(0,he.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var mo=require("lucide-react");var An=re(require("react"),1);var mc=/^\+[1-9]\d{1,14}$/;function fo(e){let t=e==null?"":String(e),n=!mc.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),s=n?`'${t}`:t;return n||/[",;\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function ur(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function dr(e,t){if(typeof document>"u")return;let n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n)}function Ns({fetchCsv:e,filename:t}){let[n,s]=An.useState(!1),[a,r]=An.useState(null),o=An.useRef(!1);return{exportCsv:An.useCallback(async()=>{if(!o.current){o.current=!0,s(!0),r(null);try{let g=await e();dr(g,ur(t))}catch(g){r(g instanceof Error?g:new Error("Export failed"))}finally{o.current=!1,s(!1)}}},[e,t]),exporting:n,error:a}}var Xn=require("react/jsx-runtime");function Bt({fetchCsv:e,filename:t,label:n="Export CSV",disabled:s,className:a}){let{exportCsv:r,exporting:o,error:u}=Ns({fetchCsv:e,filename:t});return(0,Xn.jsxs)("span",{className:a,children:[(0,Xn.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||o,"aria-busy":o,children:[(0,Xn.jsx)(mo.Download,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Exporting\u2026":n]}),u&&(0,Xn.jsx)("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}var de=require("react/jsx-runtime");function pc(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function gc(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let n of t)if(typeof e[n]=="string")return e[n];return null}var vc=["message","comments","comment","inquiry","question","details","body","notes"];function bc(e){let t=Object.entries(e).filter(([r,o])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),n=new Map(t.map(([r,o])=>[r.toLowerCase(),o])),a=(vc.map(r=>n.get(r)).find(Boolean)??t.reduce((r,[,o])=>o.length>r.length?o:r,"")).trim().replace(/\s+/g," ");return a.length>80?a.slice(0,80)+"\u2026":a}function Rs({formId:e,className:t,defaultSubmissionId:n,submissionId:s,onSelectSubmission:a}){let{api:r}=ae(),{submissions:o,total:u,isLoading:g,error:l,page:i,pageSize:d,hasNextPage:b,hasPreviousPage:f,setPage:c,setPageSize:m,deleteSubmission:p}=xs({formId:e}),y=Nn.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[S,C]=Nn.useState(n??null),E=a?s??null:S,v=a??C,_=q=>!!q&&q.id===E&&q.form_id===e,T=o.find(_),[A,N]=Nn.useState(null),k=_(A)?A:null,[L,P]=Nn.useState(null);if(Nn.useEffect(()=>{if(P(null),!E||T||k)return;let q=!1;return r.getSubmission(E).then(se=>{if(!q){if(se.form_id!==e){P("This submission could not be found.");return}N(se)}}).catch(()=>{q||P("This submission could not be found.")}),()=>{q=!0}},[r,e,E,T,k]),E){let q=T??k;return q?(0,de.jsx)("div",{className:t,children:(0,de.jsx)(Ss,{submission:q,onBack:()=>v(null),onDelete:async()=>{await p(q.id),v(null)}})}):L?(0,de.jsxs)("div",{className:t,children:[(0,de.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>v(null),className:"af-mb-2 af--ml-2",children:[(0,de.jsx)(ka.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,de.jsx)("p",{className:"af-text-sm af-text-destructive",children:L})]}):(0,de.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,de.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(g)return(0,de.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,de.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(l)return(0,de.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,de.jsxs)("div",{className:"af-text-destructive",children:["Error: ",l.message]})});if(o.length===0&&i===0)return(0,de.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,de.jsx)(ka.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,de.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,de.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let Y=i*d+1,J=Math.min((i+1)*d,u);return(0,de.jsxs)("div",{className:t,children:[(0,de.jsx)("div",{className:"af-mb-2 af-flex af-justify-end",children:(0,de.jsx)(Bt,{fetchCsv:y,filename:"submissions"})}),(0,de.jsxs)(qe,{children:[(0,de.jsx)(je,{children:(0,de.jsxs)(Re,{children:[(0,de.jsx)(j,{children:"Email"}),(0,de.jsx)(j,{children:"Preview"}),(0,de.jsx)(j,{children:"Date"}),(0,de.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,de.jsx)(Ge,{children:o.map(q=>{let se=gc(q.data),ce=bc(q.data);return(0,de.jsxs)(Re,{children:[(0,de.jsxs)(G,{className:"af-font-medium",children:[(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[se||(0,de.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),q.attachments.length>0&&(0,de.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${q.attachments.length} attachment(s)`,children:[(0,de.jsx)(ka.Paperclip,{className:"af-h-3 af-w-3"}),(0,de.jsx)("span",{className:"af-text-xs",children:q.attachments.length})]})]}),(0,de.jsx)(hs,{deliveries:q.email_deliveries,label:"Notification email needs attention"})]}),(0,de.jsx)(G,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:ce||(0,de.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,de.jsx)(G,{className:"af-text-muted-foreground",children:pc(q.metadata.submitted_at)}),(0,de.jsxs)(G,{className:"af-text-right",children:[(0,de.jsx)(R,{variant:"ghost",size:"icon",onClick:()=>v(q.id),title:"View details",children:(0,de.jsx)(ka.Eye,{className:"af-h-4 af-w-4"})}),(0,de.jsx)(Yn,{iconOnly:!0,onDelete:()=>p(q.id)})]})]},q.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 ",Y,"-",J," of ",u]}),(0,de.jsxs)(Pa,{value:String(d),onValueChange:q=>m(Number(q)),children:[(0,de.jsx)(ua,{className:"af-w-[70px] af-h-8",children:(0,de.jsx)(Ca,{})}),(0,de.jsxs)(da,{children:[(0,de.jsx)(et,{value:"10",children:"10"}),(0,de.jsx)(et,{value:"25",children:"25"}),(0,de.jsx)(et,{value:"50",children:"50"}),(0,de.jsx)(et,{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)(R,{variant:"outline",size:"sm",onClick:()=>c(i-1),disabled:!f,children:[(0,de.jsx)(ka.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,de.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>c(i+1),disabled:!b,children:["Next",(0,de.jsx)(ka.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var ya=re(require("react"),1),Rn=require("lucide-react");var po=re(require("react"),1);var go=require("react/jsx-runtime"),pe=po.forwardRef(({className:e,type:t,...n},s)=>(0,go.jsx)("input",{type:t,className:ee("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...n}));pe.displayName="Input";var vo=re(require("react"),1),bo=require("class-variance-authority");var yo=require("react/jsx-runtime"),yc=(0,bo.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),ke=vo.forwardRef(({className:e,...t},n)=>(0,yo.jsx)("label",{ref:n,className:ee(yc(),e),...t}));ke.displayName="Label";var Ea=re(require("react"),1),Ht=require("lucide-react");var ba=re(require("react"),1);function _s(){let{api:e}=ae(),[t,n]=ba.useState([]),[s,a]=ba.useState(!0),[r,o]=ba.useState(null),u=ba.useCallback(async()=>{try{a(!0),o(null),n(await e.getEventDestinations())}catch(f){o(f instanceof Error?f:new Error("Failed to fetch webhooks"))}finally{a(!1)}},[e]);ba.useEffect(()=>{u()},[u]);let g=ba.useCallback(async f=>{let c=await e.createEventDestination(f);return n(m=>[c,...m]),c},[e]),l=ba.useCallback(async(f,c)=>{let m=await e.updateEventDestination(f,c);return n(p=>p.map(y=>y.id===f?m:y)),m},[e]),i=ba.useCallback(async f=>{await e.deleteEventDestination(f),n(c=>c.filter(m=>m.id!==f))},[e]),d=ba.useCallback(async f=>{let c=await e.rotateEventDestinationSecret(f);return n(m=>m.map(p=>p.id===f?c:p)),c},[e]),b=ba.useCallback(f=>e.getEventDestinationSecret(f),[e]);return{destinations:t,isLoading:s,error:r,refetch:u,createDestination:g,updateDestination:l,deleteDestination:i,rotateSecret:d,getSecret:b}}var on=re(require("react"),1),Ps=require("lucide-react");var _t=require("react/jsx-runtime");function Cs({destinationId:e,limit:t=25,className:n}){let{api:s}=ae(),[a,r]=on.useState([]),[o,u]=on.useState(!0),[g,l]=on.useState(null),[i,d]=on.useState(null),b=on.useCallback(async()=>{try{u(!0),l(null),r(await s.getEventDeliveries(e,t))}catch(c){l(c instanceof Error?c.message:"Failed to load deliveries")}finally{u(!1)}},[s,e,t]);on.useEffect(()=>{b()},[b]);let f=async c=>{try{d(c.id),l(null);let m=await s.retryEventDelivery(e,c.id);r(p=>p.map(y=>y.id===c.id?m:y))}catch(m){l(m instanceof Error?m.message:"Retry failed")}finally{d(null)}};return o?(0,_t.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,_t.jsx)(Ps.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):g?(0,_t.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:g}):a.length===0?(0,_t.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,_t.jsx)("div",{className:n,children:(0,_t.jsx)("div",{className:"af-divide-y af-border af-rounded",children:a.map(c=>{let m=c.delivered_at!==null;return(0,_t.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,_t.jsxs)("div",{className:"af-min-w-0",children:[(0,_t.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[m?(0,_t.jsx)(ne,{variant:"secondary",children:c.last_status??200}):(0,_t.jsx)(ne,{variant:"destructive",children:c.last_status??"failed"}),(0,_t.jsx)("span",{className:"af-text-sm af-truncate",children:c.type})]}),(0,_t.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"}`]}),!m&&c.last_error&&(0,_t.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:c.last_error})]}),(0,_t.jsx)(R,{variant:"ghost",size:"sm",title:"Send this event again",disabled:i===c.id,onClick:()=>f(c),children:i===c.id?(0,_t.jsx)(Ps.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,_t.jsx)(Ps.RotateCw,{className:"af-h-4 af-w-4"})})]},c.id)})})})}var ve=require("react/jsx-runtime");function Ts({formId:e,topics:t,description:n,className:s}){let{destinations:a,isLoading:r,error:o,createDestination:u,updateDestination:g,deleteDestination:l,rotateSecret:i,getSecret:d}=_s(),[b,f]=Ea.useState(""),[c,m]=Ea.useState(!1),[p,y]=Ea.useState(null),[S,C]=Ea.useState(null),[E,v]=Ea.useState(null),[_,T]=Ea.useState(!1),[A,N]=Ea.useState(null),[k,L]=Ea.useState(null),[P,Y]=Ea.useState(null),J=Ea.useMemo(()=>a.filter(U=>U.form_id===e),[a,e]),q=async()=>{let U=b.trim();if(U){if(!U.startsWith("https://")){y("Webhook URLs must start with https://");return}try{m(!0),y(null),await u({url:U,form_id:e,...t&&t.length>0?{topics:t}:{}}),f("")}catch(Pe){y(Pe instanceof Error?Pe.message:"Failed to add webhook")}finally{m(!1)}}},se=async U=>{try{L(U.id),y(null),await i(U.id),T(!1),v(await d(U.id))}catch(Pe){y(Pe instanceof Error?Pe.message:"Failed to rotate secret")}finally{L(null)}},ce=async U=>{try{L(U.id),y(null),await g(U.id,{status:"active"})}catch(Pe){y(Pe instanceof Error?Pe.message:"Failed to re-enable")}finally{L(null)}},ge=async()=>{if(A)try{L(A.id),await l(A.id),N(null)}catch(U){y(U instanceof Error?U.message:"Failed to delete")}finally{L(null)}},$=async U=>{if(S===U.id){C(null),v(null);return}try{L(U.id),y(null),T(!1),C(U.id),v(await d(U.id))}catch(Pe){C(null),y(Pe instanceof Error?Pe.message:"Failed to read secret")}finally{L(null)}},te=async()=>{if(E)try{await navigator.clipboard.writeText(E),T(!0)}catch{}};return(0,ve.jsxs)("div",{className:s,children:[(0,ve.jsxs)("div",{className:"af-space-y-1",children:[(0,ve.jsx)(ke,{children:"Webhooks"}),(0,ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:n??"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,ve.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,ve.jsx)(pe,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:U=>f(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),q())},disabled:c}),(0,ve.jsxs)(R,{onClick:q,disabled:c||!b.trim(),children:[c?(0,ve.jsx)(Ht.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,ve.jsx)(Ht.Plus,{className:"af-h-4 af-w-4"}),(0,ve.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(p||o)&&(0,ve.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:p||o?.message}),(0,ve.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[r&&(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ve.jsx)(Ht.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&J.length===0&&(0,ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),J.map(U=>(0,ve.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,ve.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,ve.jsxs)("div",{className:"af-min-w-0",children:[(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ve.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:U.url}),U.status==="disabled"?(0,ve.jsx)(ne,{variant:"destructive",children:"Disabled"}):(0,ve.jsx)(ne,{variant:"secondary",children:"Active"})]}),(0,ve.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:U.topics.includes("*")?"All events":U.topics.join(", ")})]}),(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,ve.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>Y(P===U.id?null:U.id),children:P===U.id?"Hide log":"Deliveries"}),(0,ve.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>$(U),disabled:k===U.id,children:S===U.id?"Hide secret":"Show secret"}),(0,ve.jsx)(R,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:k===U.id,onClick:()=>N(U),children:(0,ve.jsx)(Ht.Trash2,{className:"af-h-4 af-w-4"})})]})]}),U.status==="disabled"&&(0,ve.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,ve.jsx)(Ht.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,ve.jsxs)("div",{className:"af-text-sm",children:[(0,ve.jsxs)("p",{children:["We stopped sending after repeated failures."," ",U.disabled_reason]}),(0,ve.jsx)(R,{variant:"outline",size:"sm",className:"af-mt-2",disabled:k===U.id,onClick:()=>ce(U),children:"Re-enable"})]})]}),S===U.id&&E&&(0,ve.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,ve.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,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)(pe,{readOnly:!0,value:E,className:"af-font-mono"}),(0,ve.jsx)(R,{variant:"outline",title:"Copy signing secret",onClick:te,children:_?(0,ve.jsx)(Ht.Check,{className:"af-h-4 af-w-4"}):(0,ve.jsx)(Ht.Copy,{className:"af-h-4 af-w-4"})}),(0,ve.jsx)(R,{variant:"outline",title:"Rotate signing secret",disabled:k===U.id,onClick:()=>se(U),children:k===U.id?(0,ve.jsx)(Ht.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,ve.jsx)(Ht.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),P===U.id&&(0,ve.jsx)(Cs,{destinationId:U.id})]},U.id))]}),(0,ve.jsx)(Ta,{open:!!A,onOpenChange:U=>{!U&&!k&&N(null)},children:(0,ve.jsxs)(fa,{children:[(0,ve.jsxs)(ma,{children:[(0,ve.jsx)(ga,{children:"Delete this webhook?"}),(0,ve.jsxs)(va,{children:["New submissions will stop being sent to ",A?.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,ve.jsxs)(pa,{children:[(0,ve.jsx)(R,{variant:"outline",onClick:()=>N(null),disabled:!!k,children:"Cancel"}),(0,ve.jsx)(R,{variant:"destructive",onClick:ge,disabled:!!k,children:k?"Deleting...":"Delete"})]})]})})]})}var Ce=require("react/jsx-runtime");function ks({form:e,onSaved:t,className:n}){let{updateForm:s}=En(),[a,r]=ya.useState(!1),[o,u]=ya.useState(null),[g,l]=ya.useState(null),[i,d]=ya.useState(e.name),[b,f]=ya.useState(e.redirect_url||""),[c,m]=ya.useState(e.email_recipients),[p,y]=ya.useState("");ya.useEffect(()=>{d(e.name),f(e.redirect_url||""),m(e.email_recipients),l(null)},[e]);let S=ya.useCallback(async T=>{try{r(!0),l(null);let A=await s(e.id,T);u(new Date),t?.(A)}catch(A){l(A instanceof Error?A.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);ya.useEffect(()=>{if(o){let T=setTimeout(()=>u(null),2e3);return()=>clearTimeout(T)}},[o]);let C=async()=>{let T=p.trim().toLowerCase();if(!T)return;if(!T.includes("@")){l("Please enter a valid email address");return}if(c.includes(T)){l("This email is already added");return}let A=[...c,T];m(A),y(""),l(null),await S({email_recipients:A})},E=async T=>{let A=c.filter(N=>N!==T);m(A),await S({email_recipients:A})},v=async()=>{i!==e.name&&await S({name:i})},_=async()=>{let T=b||null;T!==e.redirect_url&&await S({redirect_url:T})};return(0,Ce.jsxs)("div",{className:`af-space-y-6 af-relative ${n||""}`,children:[(a||o)&&(0,Ce.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:a?(0,Ce.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,Ce.jsx)(Rn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,Ce.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,Ce.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,Ce.jsx)(Rn.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,Ce.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{htmlFor:"form-name",children:"Form Name"}),(0,Ce.jsx)(pe,{id:"form-name",value:i,onChange:T=>d(T.target.value),onBlur:v,placeholder:"Contact Form"}),(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{children:"Email Recipients"}),(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,Ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[c.map(T=>(0,Ce.jsxs)(ne,{variant:"secondary",className:"af-gap-1",children:[T,(0,Ce.jsx)("button",{type:"button",onClick:()=>E(T),className:"af-ml-1 hover:af-text-destructive",disabled:a,children:(0,Ce.jsx)(Rn.X,{className:"af-h-3 af-w-3"})})]},T)),c.length===0&&(0,Ce.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,Ce.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ce.jsx)(pe,{type:"email",value:p,onChange:T=>y(T.target.value),placeholder:"Add email address",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),C())},disabled:a}),(0,Ce.jsx)(R,{type:"button",variant:"outline",onClick:C,disabled:!p.trim()||a,children:(0,Ce.jsx)(Rn.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,Ce.jsx)(pe,{id:"redirect-url",value:b,onChange:T=>f(T.target.value),onBlur:_,placeholder:"/thank-you"}),(0,Ce.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,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{children:"Form Endpoint"}),(0,Ce.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Ce.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,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{children:"Captcha Protection"}),(0,Ce.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Ce.jsx)(ne,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,Ce.jsx)(Ts,{formId:e.id}),g&&(0,Ce.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g})]})}var Ze=require("react/jsx-runtime");function ei({className:e,location:t,onNavigate:n,submissionId:s}){let{api:a}=ae(),[r,o]=ln.useState({submissionId:s});ln.useEffect(()=>{s&&o({submissionId:s})},[s]);let u=n?t??{}:r,g=n??o,[l,i]=ln.useState(null),d=`${u.formId??""}|${u.submissionId??""}`,[b,f]=ln.useState(null),c=b?.key===d?b.message:null,m=u.formId??(l&&l.submissionId===u.submissionId?l.formId:void 0);ln.useEffect(()=>{let T=u.submissionId;if(!T||u.formId)return;let A=!1;return a.getSubmission(T).then(N=>{A||(f(null),i({submissionId:T,formId:N.form_id}))}).catch(()=>{A||f({key:d,message:"This submission could not be found."})}),()=>{A=!0}},[a,u.submissionId,u.formId,d]);let[p,y]=ln.useState(null);ln.useEffect(()=>{if(!m||p?.id===m)return;let T=!1;return a.getForm(m).then(A=>{T||(f(null),y(A))}).catch(()=>{T||f({key:d,message:"This form could not be found."})}),()=>{T=!0}},[a,m,p?.id,d]);let S=(T,A)=>{y(T),g({formId:T.id,tab:A})},C=()=>g({});if(!u.formId&&!u.submissionId)return(0,Ze.jsxs)("div",{className:e,children:[(0,Ze.jsxs)("div",{className:"af-mb-6",children:[(0,Ze.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,Ze.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,Ze.jsx)(ys,{onSelectForm:S})]});let v=(0,Ze.jsxs)(R,{variant:"ghost",size:"sm",onClick:C,className:"af-mb-2 af--ml-2",children:[(0,Ze.jsx)(Qn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(c)return(0,Ze.jsxs)("div",{className:e,children:[v,(0,Ze.jsx)("p",{className:"af-text-sm af-text-destructive",children:c})]});if(!m||p?.id!==m)return(0,Ze.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,Ze.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let _=u.submissionId?"submissions":u.tab??"submissions";return(0,Ze.jsxs)("div",{className:e,children:[(0,Ze.jsxs)("div",{className:"af-mb-6",children:[v,(0,Ze.jsx)("h2",{className:"af-text-lg af-font-semibold",children:p.name})]}),(0,Ze.jsxs)(ir,{value:_,onValueChange:T=>g({formId:m,tab:T}),children:[(0,Ze.jsxs)(vs,{className:"af-mb-4",children:[(0,Ze.jsxs)($a,{value:"submissions",className:"af-gap-2",children:[(0,Ze.jsx)(Qn.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,Ze.jsxs)($a,{value:"settings",className:"af-gap-2",children:[(0,Ze.jsx)(Qn.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,Ze.jsx)(Va,{value:"submissions",children:(0,Ze.jsx)(Rs,{formId:m,submissionId:u.submissionId,onSelectSubmission:T=>g({formId:m,tab:"submissions",submissionId:T??void 0})})}),(0,Ze.jsx)(Va,{value:"settings",children:(0,Ze.jsx)(ks,{form:p,onSaved:y})})]})]})}var ze=re(require("react"),1);var Za=re(require("react"),1);function cn(){let{api:e}=ae(),[t,n]=Za.useState(null),[s,a]=Za.useState(!0),[r,o]=Za.useState(null),u=Za.useRef(0),g=Za.useCallback(async()=>{let l=++u.current;try{a(!0),o(null);let i=await e.getPaymentsStatus();if(l!==u.current)return;n(i)}catch(i){if(l!==u.current)return;o(i instanceof Error?i:new Error("Failed to fetch payments status"))}finally{l===u.current&&a(!1)}},[e]);return Za.useEffect(()=>{g()},[g]),{status:t,isLoading:s,error:r,refetch:g}}var hc=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function ha(e){return hc.has(e.toLowerCase())}function K(e,t,n){let s=ha(t)?e:e/100;try{return new Intl.NumberFormat(n,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Ja(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 It(e,t){let n=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(n)||n<0)return null;let s=ha(t)?n:n*100;return Math.round(s)}function nt(e,t){return ha(t)?e:e/100}function fr(e){return e.amount_paid??Math.max(0,Ja(e)-(e.credit_applied??0))}var le=require("react/jsx-runtime");function Es(e){return e instanceof ht&&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 ho(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${K(e.amount_off,e.currency)} off`:"Discount unavailable"}function Dn(){let{api:e,siteToken:t}=ae();return(0,le.jsx)(xc,{api:e},t)}function xc({api:e}){let{status:t,error:n}=cn(),[s,a]=ze.useState([]),[r,o]=ze.useState(null),[u,g]=ze.useState(null),[l,i]=ze.useState(!1),[d,b]=ze.useState(!1),[f,c]=ze.useState(""),[m,p]=ze.useState(null),[y,S]=ze.useState(null),[C,E]=ze.useState(!1),v=ze.useRef(0),_=ze.useCallback(async N=>{let k=++v.current;i(!0),c("");try{let L=await e.getPromos(N);if(k!==v.current)return;a(P=>N?[...P,...L.promos.filter(Y=>!P.some(J=>J.id===Y.id))]:L.promos),o(L.next_cursor),g(L.checkout_enabled)}catch(L){k===v.current&&c(Es(L))}finally{k===v.current&&i(!1)}},[e]);ze.useEffect(()=>(_(),()=>{v.current++}),[_]);async function T(N){let k=++v.current;i(!0),c(""),E(!1);try{let L=await e.getPromo(N);k===v.current&&p(L)}catch(L){k===v.current&&c(Es(L))}finally{k===v.current&&i(!1)}}async function A(){if(m){b(!0),i(!0),c("");try{let N=await e.disablePromo(m.id);if(p(N),!["inactive","expired","exhausted"].includes(N.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");E(!1),await _()}catch(N){c(Es(N))}finally{b(!1),i(!1)}}}return y?(0,le.jsx)(wc,{currency:t?.currency??void 0,replaces:y.replaces,onCancel:()=>S(null),onSave:async N=>{let k=y.replaces?await e.replacePromo(y.replaces.id,N):await e.createPromo(N),L=await e.getPromo(k.id);if(L.status==="pending"||L.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(L),S(null),await _()}}):(0,le.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,le.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,le.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,le.jsx)(R,{disabled:l||!t?.currency,onClick:()=>{c(""),S({})},children:"Create promo code"})]}),(0,le.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."}),u===!1&&(0,le.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,le.jsx)("p",{className:"af-text-sm",children:n?Es(n):"Connect Stripe and set the payment currency before creating codes."}),f&&(0,le.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[f," ",(0,le.jsx)(R,{variant:"outline",disabled:l,onClick:()=>m?void T(m.id):void _(),children:"Refresh"})]}),m?(0,le.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,le.jsx)(R,{variant:"ghost",disabled:d,onClick:()=>{p(null),E(!1),_()},children:"Back to codes"}),(0,le.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[m.code," \xB7 ",m.name]}),(0,le.jsxs)("p",{children:[ho(m)," \xB7 ",m.status]}),(0,le.jsxs)("p",{className:"af-text-sm",children:[m.times_redeemed==null?"Usage unavailable":`${m.times_redeemed} redemptions`,m.max_redemptions!=null?` / ${m.max_redemptions} maximum`:""]}),(0,le.jsxs)("p",{className:"af-text-sm",children:[m.minimum_amount!=null&&m.currency?`Minimum order: ${K(m.minimum_amount,m.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,le.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",m.duration==="repeating"?`${m.duration_in_months} months`:m.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,le.jsx)("p",{className:"af-text-sm",children:m.expires_at?`Expires ${new Date(m.expires_at).toLocaleString()}`:"No expiry"}),(0,le.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,le.jsx)(R,{variant:"outline",disabled:l,onClick:()=>void T(m.id),children:"Refresh details"}),(0,le.jsx)(R,{variant:"outline",disabled:l||m.status==="pending"||m.status==="unavailable"||!t?.currency,onClick:()=>S({replaces:m}),children:"Replace with new code"}),(0,le.jsx)(R,{variant:"outline",disabled:l||!["active","pending","unavailable"].includes(m.status),onClick:()=>E(!0),children:m.status==="pending"?"Cancel pending offer":"Disable code"})]}),C&&(0,le.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,le.jsxs)("p",{className:"af-text-sm",children:[m.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${m.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,le.jsx)(R,{disabled:l,onClick:()=>void A(),children:m.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,le.jsx)(R,{variant:"ghost",disabled:l,onClick:()=>E(!1),children:"Cancel"})]})]}):(0,le.jsxs)(le.Fragment,{children:[s.map(N=>(0,le.jsxs)("button",{type:"button",disabled:l,onClick:()=>void T(N.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,le.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,le.jsx)("span",{className:"af-font-semibold af-break-all",children:N.code}),(0,le.jsx)("span",{className:"af-text-sm",children:N.status})]}),(0,le.jsxs)("div",{className:"af-text-sm",children:[ho(N)," \xB7"," ",N.times_redeemed==null?"Usage unavailable":`${N.times_redeemed} redemptions`]})]},N.id)),!l&&!f&&s.length===0&&(0,le.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."}),l&&(0,le.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),r&&(0,le.jsx)(R,{variant:"outline",disabled:l,onClick:()=>void _(r),children:"Load more"})]})]})}function wc({currency:e,replaces:t,onCancel:n,onSave:s}){let[a,r]=ze.useState(""),[o,u]=ze.useState(t?.name??""),[g,l]=ze.useState(t?.amount_off!=null?"fixed":"percent"),[i,d]=ze.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(nt(t.amount_off,e)):"")),[b,f]=ze.useState(t?.minimum_amount!=null&&e?String(nt(t.minimum_amount,e)):""),[c,m]=ze.useState(()=>{if(!t?.expires_at)return"";let ce=new Date(t.expires_at);return Number.isFinite(ce.getTime())?new Date(ce.getTime()-ce.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,y]=ze.useState(t?.max_redemptions?.toString()??""),[S,C]=ze.useState(t?.duration??"once"),[E,v]=ze.useState(t?.duration_in_months?.toString()??"3"),[_,T]=ze.useState(null),[A,N]=ze.useState(!1),[k,L]=ze.useState(""),P=ze.useRef(!1),Y=e&&ha(e)?"1":"0.01";async function J(ce){if(ce.preventDefault(),P.current)return;L("");let ge=_;if(!ge){if(!e){L("Payment currency is not available.");return}if(t&&a.trim().toUpperCase()===t.code.toUpperCase()){L("Choose a different code for the replacement.");return}let $=It(i,e),te=b?It(b,e):null;if(g==="fixed"&&(!$||$>999999999999)||b&&(!te||te>999999999999)){L("Enter a positive amount within the supported range.");return}if(c&&new Date(c).getTime()<=Date.now()){L("Choose a future expiry.");return}ge={request_id:crypto.randomUUID(),code:a.trim().toUpperCase(),name:o.trim(),duration:S,...g==="percent"?{percent_off:Number(i)}:{amount_off:$,currency:e},...b?{minimum_amount:te,currency:e}:{},...c?{expires_at:new Date(c).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...S==="repeating"?{duration_in_months:Number(E)}:{}},T(ge)}P.current=!0,N(!0);try{await s(ge)}catch($){L(Es($)),$ instanceof ht&&$.status>=400&&$.status<500&&$.details?.retryable!==!0&&T(null)}finally{P.current=!1,N(!1)}}let q=(ce,ge,$,te={})=>(0,le.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[ce,(0,le.jsx)(pe,{"aria-label":ce,value:ge,onChange:U=>$(U.target.value),...te})]}),se="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,le.jsxs)("form",{onSubmit:J,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,le.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,le.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,le.jsxs)("fieldset",{disabled:A||!!_,className:"af-grid af-gap-4",children:[q("Code",a,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),q("Name",o,u,{required:!0,maxLength:40}),(0,le.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,le.jsxs)("select",{"aria-label":"Discount type",className:se,value:g,onChange:ce=>l(ce.target.value),children:[(0,le.jsx)("option",{value:"percent",children:"Percentage"}),(0,le.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),q("Discount",i,d,{type:"number",required:!0,min:g==="percent"?"0.01":Y,max:g==="percent"?"100":void 0,step:g==="percent"?"0.01":Y}),q("Minimum order amount",b,f,{type:"number",min:Y,step:Y,placeholder:e?.toUpperCase()}),(0,le.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,m,{type:"datetime-local",step:1}),q("Maximum redemptions",p,y,{type:"number",min:1,max:1e6,step:1}),(0,le.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,le.jsxs)("select",{"aria-label":"Subscription duration",className:se,value:S,onChange:ce=>C(ce.target.value),children:[(0,le.jsx)("option",{value:"once",children:"First invoice only"}),(0,le.jsx)("option",{value:"forever",children:"Every invoice"}),(0,le.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),S==="repeating"&&q("Months",E,v,{type:"number",required:!0,min:1,max:36,step:1})]}),k&&(0,le.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:k}),_&&!A&&(0,le.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,le.jsx)("span",{className:"af-break-all",children:_.request_id})]}),(0,le.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,le.jsx)(R,{type:"submit",disabled:A,children:A?"Saving\u2026":_?"Retry same request":t?"Create replacement":"Create code"}),(0,le.jsx)(R,{type:"button",variant:"ghost",disabled:A||!!_,onClick:n,children:"Cancel"})]})]})}var rs=re(require("react"),1),La=require("lucide-react");var mr=re(require("react"),1),un=require("lucide-react");var we=require("react/jsx-runtime");function Sc(e){if(e.allow_custom_amount){let t=e.min_amount!==null?K(e.min_amount,e.currency):"?",n=e.max_amount!==null?K(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${n})`}return e.unit_amount===null?"Varies by variant":K(e.unit_amount,e.currency)}function Nc(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Is({productsState:e,onSelectProduct:t,onCreateProduct:n,className:s}){let{products:a,isLoading:r,error:o,deleteProduct:u}=e,[g,l]=mr.useState(null),[i,d]=mr.useState(!1),[b,f]=mr.useState(null),c=async()=>{if(g)try{d(!0),f(null),await u(g.id),l(null)}catch(m){f(m instanceof Error?m.message:"Failed to delete product")}finally{d(!1)}};return r?(0,we.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,we.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,we.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,we.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):a.length===0?(0,we.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[(0,we.jsx)(un.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,we.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,we.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,we.jsxs)(R,{variant:"outline",onClick:()=>n?.(),children:[(0,we.jsx)(un.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,we.jsxs)("div",{className:s,children:[(0,we.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,we.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>n?.(),children:[(0,we.jsx)(un.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,we.jsxs)(qe,{children:[(0,we.jsx)(je,{children:(0,we.jsxs)(Re,{children:[(0,we.jsx)(j,{children:"Name"}),(0,we.jsx)(j,{children:"Price"}),(0,we.jsx)(j,{children:"Fulfillment"}),(0,we.jsx)(j,{children:"Status"}),(0,we.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,we.jsx)(Ge,{children:a.map(m=>(0,we.jsxs)(Re,{children:[(0,we.jsx)(G,{className:"af-font-medium",children:m.name}),(0,we.jsx)(G,{children:Sc(m)}),(0,we.jsx)(G,{className:"af-text-muted-foreground",children:Nc(m)}),(0,we.jsx)(G,{children:(0,we.jsx)(ne,{variant:m.active?"success":"secondary",children:m.active?"Active":"Inactive"})}),(0,we.jsx)(G,{className:"af-text-right",children:(0,we.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,we.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>t?.(m),children:[(0,we.jsx)(un.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,we.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>{f(null),l(m)},children:[(0,we.jsx)(un.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},m.id))})]}),(0,we.jsx)(Ta,{open:!!g,onOpenChange:m=>{!m&&!i&&l(null)},children:(0,we.jsxs)(fa,{children:[(0,we.jsxs)(ma,{children:[(0,we.jsx)(ga,{children:"Delete product?"}),(0,we.jsxs)(va,{children:['"',g?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&(0,we.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),(0,we.jsxs)(pa,{children:[(0,we.jsx)(R,{variant:"outline",onClick:()=>l(null),disabled:i,children:"Cancel"}),(0,we.jsx)(R,{variant:"destructive",onClick:c,disabled:i,children:i?"Deleting...":"Delete"})]})]})})]})}var st=re(require("react"),1),xa=require("lucide-react");var xt=re(require("react"),1),Ia=require("lucide-react");var O=require("react/jsx-runtime");function ti(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function As({productId:e,currency:t,className:n}){let{api:s}=ae(),a=ha(t)?"1":"0.01",[r,o]=xt.useState(null),[u,g]=xt.useState(!0),[l,i]=xt.useState(null),[d,b]=xt.useState(null),[f,c]=xt.useState(!1),m=xt.useRef(!0);xt.useEffect(()=>(m.current=!0,()=>{m.current=!1}),[]);let p=xt.useCallback(async()=>{try{let D=await s.getProduct(e);if(!m.current)return;o(D)}catch(D){if(!m.current)return;i(D instanceof Error?D.message:"Failed to load product")}finally{m.current&&g(!1)}},[s,e]);xt.useEffect(()=>{p()},[p]);let y=async D=>{b(null),c(!0);try{await D(),await p()}catch(M){m.current&&b(M instanceof Error?M.message:"Something went wrong")}finally{m.current&&c(!1)}},[S,C]=xt.useState(""),[E,v]=xt.useState(""),[_,T]=xt.useState({}),A=()=>y(async()=>{let D=S.trim(),M=E.split(",").map(F=>F.trim()).filter(Boolean);if(!D)throw new Error("Option name is required");if(M.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:D,values:M}),m.current&&(C(""),v(""))}),N=D=>y(async()=>{let M=(_[D.id]??"").trim();if(!M)throw new Error("Enter a value");await s.updateOption(D.id,{add_values:[M]}),m.current&&T(F=>({...F,[D.id]:""}))}),k=(D,M)=>y(()=>s.updateOption(D.id,{remove_values:[M]})),L=D=>y(()=>s.deleteOption(D.id)),[P,Y]=xt.useState(null),[J,q]=xt.useState(null),[se,ce]=xt.useState(!1),[ge,$]=xt.useState(null),te=r?.options??[],U=r?.variants??[],Pe=()=>{q(null),Y({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(te.map(D=>[D.id,D.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},ue=D=>{q(null);let M=D.inventory?.on_hand??0,F=M<0?"":String(M);Y({variant:D,title:D.title??"",sku:D.sku??"",unitAmount:D.unit_amount!=null?String(nt(D.unit_amount,t)):"",compareAt:D.compare_at_amount!=null?String(nt(D.compare_at_amount,t)):"",active:D.active,optionValues:{},tracked:D.inventory?.tracked??!1,onHand:F,initialOnHand:F,allowBackorder:D.inventory?.allow_backorder??!1})},at=async()=>{if(!P)return;q(null);let D=P.variant?.allow_custom_amount??!1,M=null,F=null;if(!D){if(M=It(P.unitAmount,t),M===null||M<=0){q("Enter a valid price");return}if(P.compareAt.trim()&&(F=It(P.compareAt,t),F===null||F<=M)){q("Compare-at price must be greater than the price");return}}let ye=P.onHand.trim()!==P.initialOnHand.trim(),Ne=parseInt(P.onHand,10);if(P.tracked&&ye&&(!Number.isFinite(Ne)||Ne<0)){q("On-hand quantity must be zero or more");return}try{if(ce(!0),P.variant)await s.updateVariant(P.variant.id,{title:P.title.trim()||null,sku:P.sku.trim()||null,...D?{}:{unit_amount:M,compare_at_amount:F},active:P.active}),await s.setVariantInventory(P.variant.id,{tracked:P.tracked,on_hand:P.tracked&&ye?Ne:void 0,allow_backorder:P.allowBackorder});else{let Ee={};for(let Me of te){let ot=P.optionValues[Me.id];if(!ot){q(`Choose a ${Me.title}`),ce(!1);return}Ee[Me.title]=ot}await s.createVariant(e,{title:P.title.trim()||null,sku:P.sku.trim()||null,unit_amount:M,compare_at_amount:F,active:P.active,option_values:te.length>0?Ee:void 0,inventory:P.tracked?{tracked:!0,on_hand:Ne,allow_backorder:P.allowBackorder}:{tracked:!1,allow_backorder:P.allowBackorder}})}await p(),m.current&&Y(null)}catch(Ee){if(m.current&&q(Ee instanceof Error?Ee.message:"Failed to save variant"),P.variant)try{let Me=await s.getProduct(e);m.current&&o(Me)}catch{}}finally{m.current&&ce(!1)}},Te=()=>y(async()=>{ge&&(await s.deleteVariant(ge.id),m.current&&$(null))}),He=P?.variant?.allow_custom_amount??!1,Ye=P?.variant!=null&&P.variant.option_values.length===0&&te.length>0&&!P.variant.active,Le=P?.variant?.inventory!=null&&P.variant.inventory.on_hand<0?-P.variant.inventory.on_hand:null;function Et(D){let M=D.inventory;if(!M||!M.tracked)return(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let F=M.available??M.on_hand;return F<0?(0,O.jsxs)("span",{children:[-F," backordered"]}):(0,O.jsxs)("span",{children:[F," in stock",M.allow_backorder&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return u?(0,O.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${n||""}`,children:(0,O.jsx)(Ia.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):l?(0,O.jsx)("div",{className:n,children:(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l})}):(0,O.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,O.jsxs)("div",{className:"af-space-y-3",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)(ke,{children:"Options"}),(0,O.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."})]}),te.length>0&&(0,O.jsx)("div",{className:"af-space-y-3",children:te.map(D=>(0,O.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)("span",{className:"af-text-sm af-font-medium",children:D.title}),(0,O.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>L(D),disabled:f,children:(0,O.jsx)(Ia.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,O.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:D.values.map(M=>(0,O.jsxs)(ne,{variant:"secondary",className:"af-gap-1",children:[M.value,(0,O.jsx)("button",{type:"button",onClick:()=>k(D,M.value),className:"af-ml-1 hover:af-text-destructive",disabled:f,title:"Remove value",children:(0,O.jsx)(Ia.X,{className:"af-h-3 af-w-3"})})]},M.id))}),(0,O.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,O.jsx)(pe,{value:_[D.id]??"",onChange:M=>T(F=>({...F,[D.id]:M.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),N(D))},disabled:f}),(0,O.jsx)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>N(D),disabled:f||!(_[D.id]??"").trim(),children:(0,O.jsx)(Ia.Plus,{className:"af-h-4 af-w-4"})})]})]},D.id))}),(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,O.jsx)(pe,{id:"new-option-title",value:S,onChange:D=>C(D.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:f})]}),(0,O.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,O.jsx)(ke,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,O.jsx)(pe,{id:"new-option-values",value:E,onChange:D=>v(D.target.value),placeholder:"S, M, L",disabled:f})]}),(0,O.jsxs)(R,{type:"button",variant:"outline",onClick:A,disabled:f||!S.trim()||!E.trim(),children:[(0,O.jsx)(Ia.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,O.jsxs)("div",{className:"af-space-y-3",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)(ke,{children:"Variants"}),(0,O.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:Pe,disabled:f||te.length===0,children:[(0,O.jsx)(Ia.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),te.length===0&&(0,O.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),U.length===0?(0,O.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,O.jsxs)(qe,{children:[(0,O.jsx)(je,{children:(0,O.jsxs)(Re,{children:[(0,O.jsx)(j,{children:"Variant"}),(0,O.jsx)(j,{children:"SKU"}),(0,O.jsx)(j,{children:"Price"}),(0,O.jsx)(j,{children:"Stock"}),(0,O.jsx)(j,{children:"Status"}),(0,O.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,O.jsx)(Ge,{children:U.map(D=>(0,O.jsxs)(Re,{children:[(0,O.jsx)(G,{className:"af-font-medium",children:ti(D)}),(0,O.jsx)(G,{className:"af-text-muted-foreground",children:D.sku||"-"}),(0,O.jsx)(G,{children:D.unit_amount!=null?(0,O.jsxs)("span",{children:[D.compare_at_amount!=null&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:K(D.compare_at_amount,D.currency)}),K(D.unit_amount,D.currency)]}):D.allow_custom_amount?(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,O.jsx)(G,{children:Et(D)}),(0,O.jsx)(G,{children:(0,O.jsx)(ne,{variant:D.active?"success":"secondary",children:D.active?"Active":"Inactive"})}),(0,O.jsx)(G,{className:"af-text-right",children:(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,O.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>ue(D),disabled:f,children:"Edit"}),(0,O.jsx)(R,{variant:"ghost",size:"icon",onClick:()=>$(D),disabled:f,title:"Delete variant",children:(0,O.jsx)(Ia.Trash2,{className:"af-h-4 af-w-4"})})]})})]},D.id))})]})]}),d&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d}),(0,O.jsx)(Ta,{open:P!==null,onOpenChange:D=>{!D&&!se&&Y(null)},children:(0,O.jsxs)(fa,{children:[(0,O.jsxs)(ma,{children:[(0,O.jsx)(ga,{children:P?.variant?"Edit variant":"Add variant"}),(0,O.jsx)(va,{children:"Price, markdown, and stock live on the variant."})]}),P&&(0,O.jsxs)("div",{className:"af-space-y-3",children:[P.variant?P.variant.option_values.length>0&&(0,O.jsxs)("div",{className:"af-text-sm",children:[(0,O.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),ti(P.variant)]}):te.map(D=>(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{className:"af-text-xs af-text-muted-foreground",children:D.title}),(0,O.jsxs)(Pa,{value:P.optionValues[D.id]??"",onValueChange:M=>Y(F=>F&&{...F,optionValues:{...F.optionValues,[D.id]:M}}),children:[(0,O.jsx)(ua,{children:(0,O.jsx)(Ca,{placeholder:`Choose ${D.title}`})}),(0,O.jsx)(da,{children:D.values.map(M=>(0,O.jsx)(et,{value:M.value,children:M.value},M.id))})]})]},D.id)),He?(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,O.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,O.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsxs)(ke,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,O.jsx)(pe,{id:"variant-price",type:"number",min:"0",step:a,value:P.unitAmount,onChange:D=>Y(M=>M&&{...M,unitAmount:D.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,O.jsx)(pe,{id:"variant-compare",type:"number",min:"0",step:a,value:P.compareAt,onChange:D=>Y(M=>M&&{...M,compareAt:D.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,O.jsx)(pe,{id:"variant-sku",value:P.sku,onChange:D=>Y(M=>M&&{...M,sku:D.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,O.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,O.jsx)("input",{type:"checkbox",checked:P.tracked,onChange:D=>Y(M=>M&&{...M,tracked:D.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),P.tracked&&(0,O.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,O.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,O.jsx)(pe,{id:"variant-onhand",type:"number",min:"0",step:"1",value:P.onHand,onChange:D=>Y(M=>M&&{...M,onHand:D.target.value}),placeholder:Le!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,O.jsx)("input",{type:"checkbox",checked:P.allowBackorder,onChange:D=>Y(M=>M&&{...M,allowBackorder:D.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Le!=null&&(0,O.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Le," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,O.jsx)("input",{type:"checkbox",checked:P.active,onChange:D=>Y(M=>M&&{...M,active:D.target.checked}),className:"af-h-4 af-w-4",disabled:Ye}),"Active (buyers can purchase this variant)"]}),Ye&&(0,O.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."})]}),J&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:J})]}),(0,O.jsxs)(pa,{children:[(0,O.jsx)(R,{variant:"outline",onClick:()=>Y(null),disabled:se,children:"Cancel"}),(0,O.jsxs)(R,{onClick:at,disabled:se,children:[se?(0,O.jsx)(Ia.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,P?.variant?"Save":"Add variant"]})]})]})}),(0,O.jsx)(Ta,{open:ge!==null,onOpenChange:D=>{!D&&!f&&$(null)},children:(0,O.jsxs)(fa,{children:[(0,O.jsxs)(ma,{children:[(0,O.jsx)(ga,{children:"Delete variant?"}),(0,O.jsx)(va,{children:ge&&`"${ti(ge)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,O.jsxs)(pa,{children:[(0,O.jsx)(R,{variant:"outline",onClick:()=>$(null),disabled:f,children:"Cancel"}),(0,O.jsx)(R,{variant:"destructive",onClick:Te,disabled:f,children:"Delete"})]})]})})]})}var Z=require("react/jsx-runtime");function Rc(e){if(e===0)return"0 B";let t=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${n[s]}`}function Ds({productsState:e,product:t,currency:n,onSaved:s,className:a}){let{createProduct:r,updateProduct:o,attachProductFile:u,attachProductFileFromUrl:g}=e,l=!!t,i=t?.currency??n,d=ha(i)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[f,c]=st.useState(!1),[m,p]=st.useState(null),y=st.useRef(!0);st.useEffect(()=>(y.current=!0,()=>{y.current=!1}),[]);let[S,C]=st.useState(t?.name??""),[E,v]=st.useState(t?.description??""),[_,T]=st.useState(t?.allow_custom_amount?"custom":"fixed"),[A,N]=st.useState(t?.unit_amount!=null?String(nt(t.unit_amount,i)):""),[k,L]=st.useState(t?.min_amount!=null?String(nt(t.min_amount,i)):""),[P,Y]=st.useState(t?.max_amount!=null?String(nt(t.max_amount,i)):""),[J,q]=st.useState(String(t?.max_quantity??10)),se=st.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(nt(t.unit_amount,i)):"",minAmount:t?.min_amount!=null?String(nt(t.min_amount,i)):"",maxAmount:t?.max_amount!=null?String(nt(t.max_amount,i)):"",maxQuantity:String(t?.max_quantity??10)}).current,[ce,ge]=st.useState(t?.collect_shipping_address??!1),[$,te]=st.useState(t?.active??!0),[U,Pe]=st.useState(t?.images??[]),[ue,at]=st.useState(""),[Te,He]=st.useState(t?.fulfillment??null),[Ye,Le]=st.useState(!1),[Et,D]=st.useState(""),[M,F]=st.useState(null),ye=st.useRef(null),Ne=f||Ye,Ee=()=>{let me=ue.trim();if(me){if(U.includes(me)){p("This image URL is already added");return}Pe(Ie=>[...Ie,me]),at(""),p(null)}},Me=me=>{Pe(Ie=>Ie.filter(lt=>lt!==me))},ot=async()=>{if(p(null),!S.trim()){p("Product name is required");return}let me=null,Ie=null,lt=null,la=!l||_!==se.pricingMode||(_==="fixed"?A!==se.unitAmount:k!==se.minAmount||P!==se.maxAmount),Ot=!l||J!==se.maxQuantity,Jt=b||_==="fixed";if(!(b||!la))if(_==="fixed"){if(me=It(A,i),me===null||me<=0){p("Enter a valid price");return}}else{if(Ie=It(k,i),lt=It(P,i),Ie===null||lt===null){p("Enter valid minimum and maximum amounts");return}if(lt<Ie){p("Maximum amount must be at least the minimum amount");return}}let Mt=parseInt(J,10);if(Jt&&Ot&&(!Number.isFinite(Mt)||Mt<1)){p("Max quantity must be at least 1");return}try{c(!0);let Ke;if(l&&t){let ct={name:S.trim(),description:E.trim()||null,images:U,collect_shipping_address:ce,active:$};!b&&la&&(ct.allow_custom_amount=_==="custom",_==="fixed"?ct.unit_amount=me:(ct.min_amount=Ie,ct.max_amount=lt)),Jt&&Ot&&(ct.max_quantity=Mt),Ke=await o(t.id,ct),se.pricingMode=Ke.allow_custom_amount?"custom":"fixed",se.unitAmount=Ke.unit_amount!=null?String(nt(Ke.unit_amount,i)):"",se.minAmount=Ke.min_amount!=null?String(nt(Ke.min_amount,i)):"",se.maxAmount=Ke.max_amount!=null?String(nt(Ke.max_amount,i)):"",se.maxQuantity=String(Ke.max_quantity)}else{let ct={name:S.trim(),allow_custom_amount:_==="custom",collect_shipping_address:ce,active:$};E.trim()&&(ct.description=E.trim()),U.length>0&&(ct.images=U),_==="fixed"?(ct.unit_amount=me,ct.max_quantity=Mt):(ct.min_amount=Ie,ct.max_amount=lt),Ke=await r(ct)}if(!y.current)return;He(Ke.fulfillment),s?.(Ke)}catch(Ke){if(!y.current)return;p(Ke instanceof Error?Ke.message:"Failed to save product")}finally{y.current&&c(!1)}},$e=async me=>{let Ie=me.target.files?.[0];if(!(!Ie||!t))try{Le(!0),F(null);let lt=await u(t.id,Ie);if(!y.current)return;He(lt.fulfillment),s?.(lt)}catch(lt){if(!y.current)return;F(lt instanceof Error?lt.message:"Failed to upload file")}finally{y.current&&(Le(!1),ye.current&&(ye.current.value=""))}},gt=async()=>{let me=Et.trim();if(!(!me||!t))try{Le(!0),F(null);let Ie=await g(t.id,me);if(!y.current)return;He(Ie.fulfillment),D(""),s?.(Ie)}catch(Ie){if(!y.current)return;F(Ie instanceof Error?Ie.message:"Failed to fetch file")}finally{y.current&&Le(!1)}};return(0,Z.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{htmlFor:"product-name",children:"Name"}),(0,Z.jsx)(pe,{id:"product-name",value:S,onChange:me=>C(me.target.value),placeholder:"My product"})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{htmlFor:"product-description",children:"Description"}),(0,Z.jsx)("textarea",{id:"product-description",value:E,onChange:me=>v(me.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,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{children:"Pricing"}),b?(0,Z.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(Pa,{value:_,onValueChange:me=>T(me),children:[(0,Z.jsx)(ua,{className:"af-w-[260px]",children:(0,Z.jsx)(Ca,{})}),(0,Z.jsxs)(da,{children:[(0,Z.jsx)(et,{value:"fixed",children:"Fixed price"}),(0,Z.jsx)(et,{value:"custom",children:"Buyer chooses the amount"})]})]}),_==="fixed"?(0,Z.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsxs)(ke,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",i.toUpperCase(),")"]}),(0,Z.jsx)(pe,{id:"product-price",type:"number",min:"0",step:d,value:A,onChange:me=>N(me.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsxs)(ke,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",i.toUpperCase(),")"]}),(0,Z.jsx)(pe,{id:"product-min-amount",type:"number",min:"0",step:d,value:k,onChange:me=>L(me.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsxs)(ke,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",i.toUpperCase(),")"]}),(0,Z.jsx)(pe,{id:"product-max-amount",type:"number",min:"0",step:d,value:P,onChange:me=>Y(me.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,Z.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,Z.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",i.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||_==="fixed")&&(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsx)(ke,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,Z.jsx)(pe,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:J,onChange:me=>q(me.target.value),className:"af-w-[140px]"})]})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{children:"Images"}),(0,Z.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,Z.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[U.map(me=>(0,Z.jsxs)(ne,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,Z.jsx)("span",{className:"af-truncate",children:me}),(0,Z.jsx)("button",{type:"button",onClick:()=>Me(me),className:"af-ml-1 hover:af-text-destructive",disabled:f,children:(0,Z.jsx)(xa.X,{className:"af-h-3 af-w-3"})})]},me)),U.length===0&&(0,Z.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,Z.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Z.jsx)(pe,{type:"url",value:ue,onChange:me=>at(me.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:me=>{me.key==="Enter"&&(me.preventDefault(),Ee())},disabled:f}),(0,Z.jsx)(R,{type:"button",variant:"outline",onClick:Ee,disabled:!ue.trim()||f,children:(0,Z.jsx)(xa.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{children:"Digital File"}),(0,Z.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, Word, Excel, PowerPoint, CSV, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),l?(0,Z.jsxs)("div",{className:"af-space-y-3",children:[Te?.type==="download"&&(0,Z.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,Z.jsx)(xa.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,Z.jsx)("span",{className:"af-text-sm",children:Te.filename}),Te.size!=null&&(0,Z.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Rc(Te.size),")"]})]}),Te?.type==="redirect"&&Te.url&&(0,Z.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,Z.jsx)(xa.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,Z.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Te.url]})]}),(0,Z.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Z.jsx)("input",{ref:ye,type:"file",onChange:$e,className:"af-hidden",disabled:Ne}),(0,Z.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>ye.current?.click(),disabled:Ne,children:[Ye?(0,Z.jsx)(xa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Z.jsx)(xa.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Te?.type==="download"?"Replace file":"Upload file"]}),(0,Z.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,Z.jsx)(pe,{type:"url",value:Et,onChange:me=>D(me.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Ye}),(0,Z.jsx)(R,{type:"button",variant:"outline",size:"sm",onClick:gt,disabled:!Et.trim()||Ne,children:"Fetch from URL"})]}),M&&(0,Z.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:M})]}):(0,Z.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{children:"Settings"}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,Z.jsx)("input",{type:"checkbox",checked:ce,onChange:me=>ge(me.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,Z.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,Z.jsx)("input",{type:"checkbox",checked:$,onChange:me=>te(me.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),l&&t&&(0,Z.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,Z.jsx)(ke,{children:"Options & Variants"}),(0,Z.jsx)(As,{productId:t.id,currency:i})]}),m&&(0,Z.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m}),(0,Z.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Z.jsxs)(R,{type:"button",onClick:ot,disabled:Ne,children:[f?(0,Z.jsx)(xa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,l?"Save changes":"Create product"]})})]})}var Pt=re(require("react"),1),Sa=require("lucide-react");var ut=re(require("react"),1);var _c=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Ls({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ae(),[s,a]=ut.useState([]),[r,o]=ut.useState(0),[u,g]=ut.useState(!0),[l,i]=ut.useState(null),[d,b]=ut.useState(0),[f,c]=ut.useState(e),[m,p]=ut.useState(void 0),[y,S]=ut.useState(""),[C,E]=ut.useState(""),[v,_]=ut.useState(""),[T,A]=ut.useState(!1),[N,k]=ut.useState(!1),[L,P]=ut.useState(void 0),Y=L?L.join(","):"",J=ut.useMemo(()=>{if(!Y)return;let $=new Set(Y.split(","));return _c.filter(te=>!$.has(te))},[Y]),q=ut.useMemo(()=>{let $={};return m?$.status=m:J?$.excludeStatus=J:T||($.excludeStatus=["pending","expired"]),y.trim()&&($.customerEmail=y.trim()),C.trim()&&($.from=C.trim()),v.trim()&&($.to=v.trim()),N&&($.unfulfilledOnly=!0),$},[m,J,T,y,C,v,N]),se=ut.useRef(0),ce=ut.useCallback(async()=>{let $=++se.current;try{g(!0),i(null);let te={...q,limit:f,offset:d*f},U=await n.getOrders(te);if($!==se.current)return;a(U.orders),o(U.total)}catch(te){if($!==se.current)return;i(te instanceof Error?te:new Error("Failed to fetch orders"))}finally{$===se.current&&g(!1)}},[n,d,f,q,t]);ut.useEffect(()=>{ce()},[ce]);let ge=Math.ceil(r/f);return{orders:s,total:r,isLoading:u,error:l,page:d,pageSize:f,hasNextPage:d<ge-1,hasPreviousPage:d>0,setPage:b,setPageSize:$=>{c($),b(0)},status:m,setStatus:$=>{p($),b(0)},statusIn:L,setStatusIn:$=>{P($&&$.length>0?$:void 0),b(0)},customerEmail:y,setCustomerEmail:$=>{S($),b(0)},from:C,setFrom:$=>{E($),b(0)},to:v,setTo:$=>{_($),b(0)},showAbandoned:T,setShowAbandoned:$=>{A($),b(0)},unfulfilledOnly:N,setUnfulfilledOnly:$=>{k($),b(0)},clearFilters:()=>{p(void 0),P(void 0),A(!1),k(!1),S(""),E(""),_(""),b(0)},filters:q,refetch:ce}}var bt=re(require("react"),1),Oe=require("lucide-react");var xo=re(require("react"),1),Ya=re(require("@radix-ui/react-popover"),1);var pr=require("react/jsx-runtime"),gr=Ya.Root,vr=Ya.Trigger;var Os=xo.forwardRef(({className:e,align:t="end",sideOffset:n=4,...s},a)=>(0,pr.jsx)(Ya.Portal,{children:(0,pr.jsx)("div",{className:"aifeatures-admin",children:(0,pr.jsx)(Ya.Content,{ref:a,align:t,sideOffset:n,className:ee("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...s})})}));Os.displayName=Ya.Content.displayName;var Bs=require("react/jsx-runtime"),Pc={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Cc(e){return Pc[e]??e}function wo(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 Ln({status:e,className:t}){return(0,Bs.jsx)(ne,{variant:wo(e),className:t,children:Cc(e)})}function _n({status:e}){return(0,Bs.jsx)(Ln,{status:e})}function es({order:e,className:t}){return e.line_items.some(n=>n.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,Bs.jsx)(ne,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Bs.jsx)(ne,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function dn(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var h=require("react/jsx-runtime"),_o="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",On="af-text-xs af-text-muted-foreground";function ai(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 Tc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Po(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 br=24,kc=["paid","partially_refunded"],Ec=["paid","partially_refunded","disputed"],Ic=/^[A-Za-z0-9 _-]*$/,So=100;function ri(e,t,n,s,a){let r=kc.includes(s);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"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${n} of ${br} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${n} of ${br} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?n<br&&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."}:n<br&&e==="buyer"&&!a?{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 ${n} attempt${n===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${s==="refunded"?"because the order was refunded":s==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function No({title:e,recipient:t,status:n,attempts:s,side:a,orderStatus:r,action:o,delivery:u}){if(u)return(0,h.jsxs)("div",{children:[(0,h.jsx)(Ka,{deliveries:[u]}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]});let g=ri(a,n,s,r,t);return(0,h.jsxs)("div",{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)("div",{className:"af-text-sm",children:e}),t&&(0,h.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,h.jsx)(ne,{variant:g.variant,className:"af-shrink-0",children:g.label})]}),g.detail&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:g.detail}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]})}function Ro(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let n=Tc(e.address)?e.address:null;if(n){for(let a of["line1","line2"]){let r=n[a];typeof r=="string"&&r&&t.push(r)}let s=["city","state","postal_code"].map(a=>n[a]).filter(a=>typeof a=="string"&&!!a).join(", ");s&&t.push(s),typeof n.country=="string"&&n.country&&t.push(n.country)}return t.length>0?t:Object.entries(e).map(([s,a])=>`${s}: ${Po(a)}`)}function Ac(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function ii({value:e,label:t,children:n,className:s,size:a="icon"}){let[r,o]=bt.useState(!1);if(!Ac())return null;let u=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},g=r?(0,h.jsx)(Oe.Check,{className:"af-h-3 af-w-3"}):(0,h.jsx)(Oe.Copy,{className:"af-h-3 af-w-3"});return a==="icon"?(0,h.jsx)(R,{variant:"ghost",size:"icon",className:ee("af-h-6 af-w-6 af-shrink-0",s),onClick:u,title:t,"aria-label":t,children:g}):(0,h.jsxs)(R,{variant:"outline",size:"sm",className:s,onClick:u,"aria-label":t,children:[r?(0,h.jsx)(Oe.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,h.jsx)(Oe.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":n]})}function ni({label:e,value:t}){return(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:On,children:e}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,h.jsx)(ii,{value:t,label:`Copy ${e}`})]})]})}function Dc({src:e}){let[t,n]=bt.useState(!1);return!e||t?(0,h.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,h.jsx)(Oe.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,h.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>n(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Xa({title:e,action:t,children:n,className:s}){return(0,h.jsxs)("section",{className:ee("af-rounded-lg af-border af-p-4",s),children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,h.jsx)("h4",{className:_o,children:e}),t]}),(0,h.jsx)("div",{className:"af-mt-3",children:n})]})}function ea({label:e,emphasis:t,divider:n,children:s}){return(0,h.jsxs)("div",{className:ee("af-flex af-items-baseline af-justify-between af-gap-6",n&&"af-mt-2 af-border-t af-pt-2"),children:[(0,h.jsx)("span",{className:t?"af-text-base af-font-semibold":On,children:e}),(0,h.jsx)("span",{className:ee("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function si({onSelect:e,disabled:t,icon:n,children:s}){return(0,h.jsxs)(R,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,h.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:n}),s]})}function Lc(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 ${K(fr(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let n=e.email_deliveries?.find(a=>a.kind==="purchase_receipt"),s=n?lr(n):ri("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(a=>a.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let n=e.email_deliveries?.find(a=>a.kind==="merchant_sale"),s=n?lr(n):ri("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(a=>a.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${K(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 Fs({order:e,onBack:t,onRefund:n,onOrderUpdated:s,allowFulfillment:a=!1,onPrevOrder:r,onNextOrder:o,hasPrevOrder:u=!1,hasNextOrder:g=!1}){let{api:l}=ae(),[i,d]=bt.useState(e),[b,f]=bt.useState(null),[c,m]=bt.useState(null),[p,y]=bt.useState(!1),[S,C]=bt.useState(!1),[E,v]=bt.useState(!1),[_,T]=bt.useState(!1),[A,N]=bt.useState(""),[k,L]=bt.useState(!1),[P,Y]=bt.useState(null),[J,q]=bt.useState(!1),[se,ce]=bt.useState(""),[ge,$]=bt.useState([]),[te,U]=bt.useState(!1),[Pe,ue]=bt.useState(!1),[at,Te]=bt.useState(null);bt.useEffect(()=>{d(e)},[e]);let He=B=>{let Ue=B.id===i.id&&B.email_deliveries===void 0?{...B,email_deliveries:i.email_deliveries}:B;d(Ue),s?.(Ue)},Ye=Object.entries(i.metadata??{}),Le=Math.max(0,fr(i)-i.amount_refunded),Et=(i.status==="paid"||i.status==="partially_refunded")&&Le>0,D=i.exclusive_tax_total!=null,M=B=>typeof B.amountNet=="number"?B.amountNet+(B.exclusiveTax??0):(typeof B.unitAmount=="number"?B.unitAmount:0)*(typeof B.quantity=="number"&&B.quantity>0?B.quantity:1),F=Math.max(0,(i.shipping_total??0)-(i.shipping_refunded??0)),ye=ge.reduce((B,Ue)=>B+M(i.line_items[Ue]??{}),0)+(te?F:0),Ne=i.tax_total??0,Ee=Math.max(0,(i.exclusive_tax_total??0)-i.line_items.reduce((B,Ue)=>B+(Ue.exclusiveTax??0),0)),Me=D?te&&F>0?Ee:0:i.automatic_tax&&i.tax_behavior==="exclusive"&&Ne>0&&i.amount_total+(i.shipping_total??0)>0?Math.min(Math.max(0,Ne-(i.tax_refunded??0)),Math.round(Ne*ye/(i.amount_total+(i.shipping_total??0)))):0,ot=i.source==="subscription"&&(i.credit_applied??0)>0&&i.line_items.length===1?Math.min(ye+Me,Le):ye+Me,$e=ge.length>0||te,gt=$e?ot:It(se,i.currency),me=ha(i.currency)?"1":"0.01",Ie=async()=>{try{y(!0),f(null),m(null),await l.resendOrderReceipt(i.id);let B=await l.getOrder(i.id);He(B),m("Receipt email queued.")}catch(B){f(B instanceof Error?B.message:"Failed to resend receipt")}finally{y(!1)}},lt=async()=>{try{C(!0),f(null),m(null);let B=await l.resetOrderDownloads(i.id);He(B),v(!1),m("Download count reset.")}catch(B){f(B instanceof Error?B.message:"Failed to reset downloads")}finally{C(!1)}},la=i.line_items.some(B=>B.collectShippingAddress===!0&&!B.refunded&&!B.unavailableReason),Ot=typeof i.merchant_fulfilled_at=="string",Jt=Ec.includes(i.status)||i.status==="refunded"&&i.line_items.some(B=>B.collectShippingAddress===!0&&B.amountNet===0&&!B.refunded&&!B.unavailableReason),Mt=A.trim(),Ke=Ic.test(Mt)&&Mt.length<=So,ct=async B=>{try{L(!0),Y(null),m(null);let Ue=await l.setOrderFulfillment(i.id,{fulfilled:B,...B&&Mt?{trackingNumber:Mt}:{}});He(Ue),N(""),m(B?"Marked as shipped.":"Marked as not shipped.")}catch(Ue){Ue instanceof ht&&Ue.status===409?Y(`This order is ${i.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Y(Ue instanceof Error?Ue.message:"Failed to update the order")}finally{L(!1)}},Ua=()=>{Te(null),ce(String(nt(Le,i.currency))),$([]),U(!1),q(!0)},kn=B=>$(Ue=>Ue.includes(B)?Ue.filter(Xt=>Xt!==B):[...Ue,B]),Yt=async(B,Ue)=>{if(n)try{ue(!0),Te(null),await n(i,B,Ue);let Xt=await l.getOrder(i.id);He(Xt),q(!1),m("Refund issued.")}catch(Xt){Te(Xt instanceof Error?Xt.message:"Refund failed")}finally{ue(!1)}},Gr=async()=>{if($e){if(ot<=0){Te("The lines you picked were charged nothing");return}if(ot>Le){Te(`That selection exceeds the refundable remainder (${K(Le,i.currency)})`);return}await Yt(ot,{...ge.length>0?{line_items:[...ge].sort((Ue,Xt)=>Ue-Xt)}:{},...te?{shipping:!0}:{}});return}let B=It(se,i.currency);if(B===null||B<=0){Te("Enter a valid refund amount");return}if(B>Le){Te(`Amount exceeds the refundable remainder (${K(Le,i.currency)})`);return}await Yt(B,{amount:B})},W=()=>Yt(Le,{full:!0}),Xe=!i.subscription_history_only&&i.fulfillment_type==="download",Ga=!i.subscription_history_only&&a&&la,Wr=Lc(i),X=i.shipping_address?Ro(i.shipping_address).join(`
4
+ `):"",jt=i.shipping_total!=null,Kr=i.exclusive_tax_total??(i.automatic_tax&&i.tax_behavior==="exclusive"?i.tax_total??0:0),Ui=i.exclusive_tax_total!=null?Math.max(0,(i.tax_total??0)-Kr):i.automatic_tax&&i.tax_behavior==="exclusive"?0:i.tax_total??0,Mi=Kr>0,Wl=Ui>0,$i=i.amount_subtotal!=null||jt||Mi||(i.discount_total??0)>0,ms=[];return i.subscription_history_only||ms.push((0,h.jsx)(si,{icon:p?(0,h.jsx)(Oe.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,h.jsx)(Oe.Mail,{className:"af-h-4 af-w-4"}),disabled:p||i.fulfillment_status!=="fulfilled",onSelect:()=>{T(!1),Ie()},children:"Resend receipt"},"resend")),Xe&&ms.push((0,h.jsx)(si,{icon:(0,h.jsx)(Oe.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:S,onSelect:()=>{T(!1),v(!0)},children:"Reset download count"},"reset")),Et&&ms.push((0,h.jsxs)("div",{children:[(0,h.jsx)(si,{icon:(0,h.jsx)(Oe.Undo2,{className:"af-h-4 af-w-4"}),disabled:!n,onSelect:()=>{T(!1),Ua()},children:"Refund\u2026"}),!n&&(0,h.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,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-mb-6",children:[(0,h.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,h.jsx)(Oe.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(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:[(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("h3",{className:"af-text-xl af-font-semibold",children:dn(i)}),(0,h.jsx)(Ln,{status:i.status}),a&&!i.subscription_history_only&&(0,h.jsx)(es,{order:i}),i.is_test&&(0,h.jsx)(ne,{variant:"outline",children:"Test"})]}),(0,h.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",ai(i.created_at)]}),i.is_test&&(0,h.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,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||o)&&(0,h.jsxs)("div",{className:"af-flex af-items-center",children:[(0,h.jsx)(R,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!u,"aria-label":"Previous order",children:(0,h.jsx)(Oe.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,h.jsx)(R,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!g,"aria-label":"Next order",children:(0,h.jsx)(Oe.ChevronRight,{className:"af-h-4 af-w-4"})})]}),Ga&&(Ot?(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",i.merchant_fulfilled_at?` \xB7 ${ai(i.merchant_fulfilled_at)}`:""]}),Jt&&(0,h.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>ct(!1),disabled:k,children:[k?(0,h.jsx)(Oe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(Oe.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Jt?(0,h.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,h.jsx)(pe,{value:A,onChange:B=>N(B.target.value),placeholder:"Tracking number (optional)",maxLength:So,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:k}),(0,h.jsxs)(R,{variant:"default",className:"af-shrink-0",onClick:()=>ct(!0),disabled:k||!Ke,children:[k?(0,h.jsx)(Oe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(Oe.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),ms.length>0&&(0,h.jsxs)(gr,{open:_,onOpenChange:T,children:[(0,h.jsx)(vr,{asChild:!0,children:(0,h.jsx)(R,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,h.jsx)(Oe.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,h.jsx)(Os,{children:(0,h.jsx)("div",{className:"af-space-y-0.5",children:ms})})]})]})]}),Ga&&!Ot&&!Ke&&(0,h.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."}),P&&(0,h.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:P}),c&&(0,h.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}),b&&(0,h.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:b})]}),(0,h.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,h.jsxs)("div",{className:"af-space-y-6",children:[i.line_items.length>0&&(0,h.jsx)(Xa,{title:"Items",children:(0,h.jsx)("ul",{className:"af-space-y-3",children:i.line_items.map((B,Ue)=>{let Xt=typeof B.name=="string"&&B.name?B.name:"Item",Vi=typeof B.quantity=="number"&&B.quantity>0?B.quantity:1,Hi=typeof B.unitAmount=="number";return(0,h.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,h.jsx)(Dc,{src:typeof B.imageUrl=="string"&&B.imageUrl?B.imageUrl:void 0}),(0,h.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,h.jsxs)("div",{className:"af-text-sm af-font-medium",children:[Xt,typeof B.variantTitle=="string"&&B.variantTitle&&(0,h.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",B.variantTitle]})]}),(0,h.jsxs)("div",{className:On,children:[Vi," \xD7"," ",Hi?K(B.unitAmount,i.currency):"\u2014"]}),B.unavailableReason==="oversold"&&!B.refunded&&(0,h.jsx)(ne,{variant:"secondary",className:"af-mt-1",children:B.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),B.refunded===!0&&(0,h.jsx)(ne,{variant:"secondary",className:"af-mt-1",children:B.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,h.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof B.amountNet=="number"||Hi?K(B.amountNet??B.unitAmount*Vi,i.currency):"\u2014"})]},Ue)})})}),Ye.length>0&&(0,h.jsx)(Xa,{title:"Order details",children:(0,h.jsx)("dl",{className:"af-space-y-2",children:Ye.map(([B,Ue])=>(0,h.jsxs)("div",{children:[(0,h.jsx)("dt",{className:ee(On,"af-capitalize"),children:B.replace(/_/g," ")}),(0,h.jsx)("dd",{className:"af-text-sm af-break-words",children:Po(Ue)})]},B))})}),(0,h.jsx)(Xa,{title:"Totals",children:(0,h.jsxs)("div",{className:"af-w-full",children:[$i&&(0,h.jsx)(ea,{label:"Subtotal",children:K(i.amount_subtotal??i.amount_total+(i.discount_total??0),i.currency)}),(i.discount_total??0)>0&&(0,h.jsxs)(ea,{label:"Discount",children:["\u2212",K(i.discount_total,i.currency)]}),jt&&(0,h.jsx)(ea,{label:"Shipping",children:i.shipping_total===0?"Free":K(i.shipping_total??0,i.currency)}),Mi&&(0,h.jsx)(ea,{label:"Tax",children:K(Kr,i.currency)}),(0,h.jsx)(ea,{label:"Total",emphasis:!0,divider:$i,children:K(Ja(i),i.currency)}),(i.credit_applied??0)>0&&(0,h.jsxs)(ea,{label:"Credit applied",children:["\u2212",K(i.credit_applied,i.currency)]}),i.amount_paid!=null&&(0,h.jsx)(ea,{label:"Amount paid",children:K(i.amount_paid,i.currency)}),Wl&&(0,h.jsx)(ea,{label:"incl. tax",children:K(Ui,i.currency)}),i.base_currency!=null&&i.base_amount_total!=null&&(0,h.jsxs)(ea,{label:"Your price",children:[K(i.base_amount_total,i.base_currency),(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",i.currency.toUpperCase()]})]}),i.amount_refunded>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(ea,{label:"Refunded",children:["\u2212",K(i.amount_refunded,i.currency),(i.shipping_refunded??0)>0&&(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",K(i.shipping_refunded??0,i.currency)," ","shipping"]})]}),(0,h.jsx)(ea,{label:"Net",children:(0,h.jsx)("span",{className:"af-font-medium",children:K(Math.max(0,fr(i)-i.amount_refunded),i.currency)})})]})]})}),i.application_fee_state&&(0,h.jsxs)(Xa,{title:"Platform fee",children:[i.application_fee_original!=null&&(0,h.jsx)(ea,{label:"Collected",children:K(i.application_fee_original,i.application_fee_currency??i.currency)}),i.application_fee_returned!=null&&(0,h.jsx)(ea,{label:"Returned",children:K(i.application_fee_returned,i.application_fee_currency??i.currency)}),i.application_fee_retained!=null&&(0,h.jsx)(ea,{label:"Retained",children:K(i.application_fee_retained,i.application_fee_currency??i.currency)}),i.application_fee_state!=="complete"&&(0,h.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:i.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,h.jsx)(Xa,{title:"Timeline",children:(0,h.jsx)("ol",{className:"af-space-y-3",children:Wr.map(B=>(0,h.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,h.jsx)("span",{"aria-hidden":"true",className:ee("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",B.tone==="destructive"?"af-bg-destructive":B.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsx)("div",{className:"af-text-sm af-break-words",children:B.text}),B.at&&(0,h.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:ai(B.at)})]})]},B.key))})})]}),(0,h.jsxs)("div",{className:"af-space-y-6",children:[(0,h.jsx)(Xa,{title:"Customer",children:(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:On,children:"Email"}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:i.customer_email||(0,h.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),i.customer_email&&(0,h.jsx)(ii,{value:i.customer_email,label:"Copy email"})]})]}),i.customer_name&&(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:On,children:"Name"}),(0,h.jsx)("div",{className:"af-text-sm",children:i.customer_name})]}),i.customer&&(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:On,children:"Customer record"}),(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("span",{className:"af-break-all af-text-sm",children:i.customer.name||i.customer.email}),(0,h.jsx)(ne,{variant:"secondary",children:"Linked"})]})]})]})}),i.shipping_address&&(0,h.jsx)(Xa,{title:"Ship to",action:(0,h.jsx)(ii,{value:X,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,h.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Ro(i.shipping_address).map((B,Ue)=>(0,h.jsx)("div",{children:B},Ue))})}),i.subscription_history_only?(0,h.jsx)(Xa,{title:"Subscription history",children:(0,h.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,h.jsxs)(Xa,{title:"Emails",children:[(0,h.jsx)(Ka,{deliveries:i.email_deliveries?.filter(B=>!["purchase_receipt","merchant_sale"].includes(B.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,h.jsxs)("div",{className:"af-space-y-4",children:[(0,h.jsx)(No,{side:"buyer",title:"Receipt to buyer",delivery:i.email_deliveries?.find(B=>B.kind==="purchase_receipt"),recipient:i.customer_email,status:i.buyer_email_status,attempts:i.buyer_email_attempts,orderStatus:i.status,action:(0,h.jsxs)(R,{variant:"outline",size:"sm",onClick:Ie,disabled:p||i.fulfillment_status!=="fulfilled",children:[p?(0,h.jsx)(Oe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(Oe.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,h.jsx)(No,{side:"merchant",title:"Sale alert to you",delivery:i.email_deliveries?.find(B=>B.kind==="merchant_sale"),recipient:null,status:i.merchant_email_status,attempts:i.merchant_email_attempts,orderStatus:i.status})]})]}),Xe&&(0,h.jsx)(Xa,{title:"Download",children:(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,h.jsx)(Oe.Download,{className:"af-h-4 af-w-4"}),(0,h.jsxs)("span",{children:["Downloaded ",i.download_count," time",i.download_count===1?"":"s"]})]}),i.download_url&&(0,h.jsx)("a",{href:i.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,h.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,h.jsx)("summary",{className:ee(_o,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,h.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,h.jsx)(ni,{label:"Order ID",value:i.id}),i.stripe_checkout_session_id&&(0,h.jsx)(ni,{label:"Checkout session",value:i.stripe_checkout_session_id}),i.stripe_payment_intent_id&&(0,h.jsx)(ni,{label:"Payment",value:i.stripe_payment_intent_id})]})]})]})]}),(0,h.jsx)(Ta,{open:E,onOpenChange:B=>{!B&&!S&&v(!1)},children:(0,h.jsxs)(fa,{children:[(0,h.jsxs)(ma,{children:[(0,h.jsx)(ga,{children:"Reset download count?"}),(0,h.jsx)(va,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,h.jsxs)(pa,{children:[(0,h.jsx)(R,{variant:"outline",onClick:()=>v(!1),disabled:S,children:"Cancel"}),(0,h.jsx)(R,{onClick:lt,disabled:S,children:S?"Resetting...":"Reset"})]})]})}),(0,h.jsx)(Ta,{open:J,onOpenChange:B=>{!B&&!Pe&&q(!1)},children:(0,h.jsxs)(fa,{children:[(0,h.jsxs)(ma,{children:[(0,h.jsx)(ga,{children:"Refund order"}),(0,h.jsxs)(va,{children:["Refund up to ",K(Le,i.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,h.jsxs)("div",{className:"af-space-y-4",children:[(i.line_items.length>0||F>0)&&(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsx)(ke,{children:"Items"}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[i.line_items.map((B,Ue)=>{let Xt=B.refunded===!0;return(0,h.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,h.jsx)("input",{type:"checkbox",checked:ge.includes(Ue),onChange:()=>kn(Ue),disabled:Pe||Xt||!!B.unavailableReason||M(B)<=0,className:"af-h-4 af-w-4"}),(0,h.jsxs)("span",{className:Xt?"af-text-muted-foreground af-line-through":void 0,children:[typeof B.name=="string"&&B.name?B.name:"Item",typeof B.variantTitle=="string"&&B.variantTitle?` \u2014 ${B.variantTitle}`:"",typeof B.quantity=="number"&&B.quantity>1?` \xD7 ${B.quantity}`:""]}),(0,h.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Xt?"Refunded":K(M(B),i.currency)})]},Ue)}),F>0&&(0,h.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,h.jsx)("input",{type:"checkbox",checked:te,onChange:B=>U(B.target.checked),disabled:Pe,className:"af-h-4 af-w-4"}),(0,h.jsx)("span",{children:"Shipping"}),(0,h.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:K(F,i.currency)})]})]})]}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)(ke,{htmlFor:"refund-amount",children:["Amount (",i.currency.toUpperCase(),")"]}),(0,h.jsx)(pe,{id:"refund-amount",type:"number",min:"0",step:me,value:$e?String(nt(ot,i.currency)):se,onChange:B=>ce(B.target.value),disabled:Pe||$e}),$e&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),at&&(0,h.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:at}),(0,h.jsxs)(pa,{children:[(0,h.jsx)(R,{variant:"outline",onClick:()=>q(!1),disabled:Pe,children:"Cancel"}),(0,h.jsx)(R,{variant:"outline",onClick:W,disabled:Pe,children:"Refund everything"}),(0,h.jsx)(R,{variant:"destructive",onClick:Gr,disabled:Pe,children:Pe?"Refunding...":gt!==null&&gt>0?`Refund ${K(gt,i.currency)}`:"Refund"})]})]})})]})}var yr=re(require("react"),1),hr=require("lucide-react");var rt=require("react/jsx-runtime");function wt({title:e,onBackToWebsite:t,hideBackButton:n=!1,children:s,className:a}){let r=yr.useRef(null);return yr.useEffect(()=>{r.current?.focus()},[]),(0,rt.jsxs)("div",{className:ee("af-bg-background",a),children:[(0,rt.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,rt.jsx)("h2",{ref:r,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&&!n&&(0,rt.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,rt.jsx)(hr.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,rt.jsx)("div",{className:"af-p-4",children:s})]})}function ie({className:e}){return(0,rt.jsx)("div",{"aria-hidden":"true",className:ee("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function dt({label:e,children:t,detail:n,valueClassName:s}){return(0,rt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,rt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,rt.jsx)("div",{className:ee("af-mt-1 af-text-lg af-font-semibold",s),children:t}),n&&(0,rt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:n})]})}function wa({message:e,onRetry:t}){return(0,rt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,rt.jsx)("span",{children:e}),(0,rt.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,rt.jsx)(hr.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function za({icon:e,children:t}){return(0,rt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,rt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function ts({icon:e,heading:t,body:n,action:s,className:a,children:r}){return(0,rt.jsxs)("div",{className:ee("af-px-6 af-py-10 af-text-center",a),children:[(0,rt.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,rt.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,rt.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:n}),s&&(0,rt.jsx)(R,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}var I=require("react/jsx-runtime"),Oc={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Co={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function To(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 ko(e){let t=Array.isArray(e.line_items)?e.line_items:[],n=t[0];if(!n)return"\u2014";let s=typeof n.name=="string"&&n.name?n.name:"Item",a=typeof n.quantity=="number"&&n.quantity>0?n.quantity:1,r=a>1?`${s} \xD7${a}`:s;return t.length>1?`${r} +${t.length-1} more`:r}function xr(e){return e.customer?.name||e.customer_name||null}function Bc({onRefund:e,className:t,refreshKey:n,initialOrderId:s,showFulfillment:a=!1,emptyMessage:r,onDetailOpenChange:o,maxRows:u,onViewAll:g}){let l=typeof u=="number",{api:i}=ae(),d=Ls({refreshKey:n}),{orders:b,total:f,isLoading:c,error:m,page:p,pageSize:y,hasNextPage:S,hasPreviousPage:C,setPage:E,setPageSize:v,customerEmail:_,setCustomerEmail:T,setStatusIn:A,from:N,setFrom:k,to:L,setTo:P,showAbandoned:Y,setShowAbandoned:J,setUnfulfilledOnly:q,filters:se,refetch:ce}=d,ge=Pt.useCallback(()=>i.exportOrdersCsv(se),[i,se]),[$,te]=Pt.useState("list"),[U,Pe]=Pt.useState(null),[ue,at]=Pt.useState(""),[Te,He]=Pt.useState(""),[Ye,Le]=Pt.useState(!l&&a?"needs_shipping":"all"),[Et,D]=Pt.useState(!1),[M,F]=Pt.useState(!!s&&!l),[ye,Ne]=Pt.useState(null);Pt.useEffect(()=>{if(!s||l)return;let X=!1;return F(!0),Ne(null),i.getOrder(s).then(jt=>{X||(Pe(jt),te("detail"))}).catch(()=>{X||Ne("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{X||F(!1)}),()=>{X=!0}},[i,s,l]);let Ee=Pt.useCallback(X=>{Le(X);let jt=Co[X];A(jt.statusIn),q(jt.unfulfilledOnly)},[A,q]);Pt.useEffect(()=>{a&&!l&&q(!0)},[]);let Me=Pt.useRef(!a);Pt.useEffect(()=>{Me.current||c||(Me.current=!0,b.length===0&&Ee("all"))},[c,b.length,Ee]);let ot=$==="detail"&&!!U;Pt.useEffect(()=>{o?.(ot)},[ot,o]);let $e=(N?1:0)+(L?1:0)+(Y?1:0),gt=$e>0||!!_||!!Te,me=!!N&&!!L&&N>L,Ie=!l||!!g,lt=X=>{if(l){g?.();return}Pe(X),te("detail")},la=()=>{te("list"),Pe(null),ce()},Ot=X=>{let jt=X.trim();if(!jt){He(""),_&&T("");return}if(jt.startsWith("#")||/^\d+$/.test(jt)){He(jt),_&&T("");return}He(""),T(jt)},Jt=()=>{at(""),He(""),T(""),k(""),P(""),J(!1),D(!1)},Mt=Te.replace(/^#/,"").toLowerCase(),Ke=Mt?b.filter(X=>String(X.order_number??"")===Mt||X.id.toLowerCase().startsWith(Mt)):b,ct=l?Ke.slice(0,u):Ke,Ua=U?b.findIndex(X=>X.id===U.id):-1,kn=Ua>0,Yt=Ua>=0&&Ua<b.length-1;if(M)return(0,I.jsx)("div",{className:t,children:(0,I.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,I.jsx)(Sa.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if($==="detail"&&U)return(0,I.jsx)("div",{className:t,children:(0,I.jsx)(Fs,{order:U,onBack:la,onRefund:e,onOrderUpdated:X=>Pe(X),allowFulfillment:a,onPrevOrder:kn?()=>Pe(b[Ua-1]):void 0,onNextOrder:Yt?()=>Pe(b[Ua+1]):void 0,hasPrevOrder:kn,hasNextOrder:Yt},U.id)});let W=(0,I.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[ye&&(0,I.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:ye}),(0,I.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,I.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:(a?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(X=>(0,I.jsx)("button",{type:"button","aria-pressed":Ye===X,onClick:()=>Ee(X),className:ee("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",Ye===X?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Oc[X]},X))}),(0,I.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,I.jsx)(Sa.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,I.jsx)(pe,{type:"text",value:ue,onChange:X=>at(X.target.value),onBlur:()=>Ot(ue),onKeyDown:X=>{X.key==="Enter"&&(X.preventDefault(),Ot(ue))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,I.jsxs)(R,{type:"button",variant:$e>0?"secondary":"ghost",size:"sm",onClick:()=>D(X=>!X),"aria-expanded":Et,children:[(0,I.jsx)(Sa.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",$e>0&&(0,I.jsx)(ne,{variant:"secondary",className:"af-ml-2",children:$e})]}),gt&&(0,I.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:Jt,children:"Clear filters"}),(0,I.jsx)(Bt,{fetchCsv:ge,filename:"orders",disabled:!!Te,className:"af-ml-auto"})]}),(Et||!!N||!!L)&&(0,I.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,I.jsx)(ke,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,I.jsx)(pe,{id:"orders-from",type:"date",value:N,max:L||void 0,onChange:X=>k(X.target.value),className:"af-w-[170px]"}),(0,I.jsx)(ke,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,I.jsx)(pe,{id:"orders-to",type:"date",value:L,min:N||void 0,onChange:X=>P(X.target.value),className:"af-w-[170px]"}),!Co[Ye].statusIn&&(0,I.jsx)(R,{type:"button",variant:Y?"secondary":"ghost",size:"sm",onClick:()=>J(!Y),"aria-pressed":Y,children:Y?"Hide abandoned":"Show abandoned"})]}),me&&(0,I.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,I.jsxs)("div",{className:t,children:[l?null:W,(0,I.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(X=>(0,I.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,I.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,I.jsx)(ie,{className:"af-h-4 af-w-16"}),(0,I.jsx)(ie,{className:"af-h-4 af-w-14"})]}),(0,I.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-40"}),(0,I.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-24"})]},X))}),(0,I.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,I.jsxs)(qe,{children:[(0,I.jsx)(je,{children:(0,I.jsxs)(Re,{children:[(0,I.jsx)(j,{children:"Order"}),(0,I.jsx)(j,{children:"Date"}),(0,I.jsx)(j,{children:"Customer"}),(0,I.jsx)(j,{children:"Items"}),(0,I.jsx)(j,{className:"af-text-right",children:"Total"}),(0,I.jsx)(j,{children:"Status"}),(0,I.jsx)(j,{className:"af-w-8"})]})}),(0,I.jsx)(Ge,{"aria-hidden":"true",children:[0,1,2,3,4].map(X=>(0,I.jsxs)(Re,{children:[(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-4 af-w-14"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-4 af-w-24"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-4 af-w-40"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-4 af-w-32"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-5 af-w-16"})}),(0,I.jsx)(G,{})]},X))})]})}),(0,I.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(m)return(0,I.jsxs)("div",{className:t,children:[l?null:W,(0,I.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,I.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,I.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>ce(),children:"Try again"})]})]});let Xe=Ye!=="all";if(Ke.length===0&&p===0)return gt||Xe?(0,I.jsxs)("div",{className:t,children:[!l&&W,(0,I.jsx)(za,{children:"No orders match these filters."})]}):(0,I.jsx)("div",{className:t,children:(0,I.jsx)(ts,{icon:Sa.Receipt,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!l&&(0,I.jsx)(R,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>J(!0),children:"Show abandoned checkouts"})})});let Ga=p*y+1,Wr=Math.min((p+1)*y,f);return(0,I.jsxs)("div",{className:t,children:[l?null:W,(0,I.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ct.map(X=>(0,I.jsxs)("button",{type:"button",onClick:()=>lt(X),disabled:!Ie,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ie?" hover:af-bg-muted/50":""}`,children:[(0,I.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,I.jsx)("span",{className:"af-font-medium",children:dn(X)}),(0,I.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:K(Ja(X),X.currency)})]}),(0,I.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,I.jsxs)("div",{className:"af-truncate af-text-sm",children:[X.customer_email||(0,I.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),xr(X)&&(0,I.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",xr(X)]})]}),(0,I.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ko(X)}),X.amount_refunded>0&&(0,I.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",K(X.amount_refunded,X.currency)," refunded"]})]}),(0,I.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,I.jsx)(Ln,{status:X.status}),(0,I.jsx)(hs,{deliveries:X.email_deliveries}),X.is_test&&(0,I.jsx)(ne,{variant:"outline",children:"Test"}),a&&(0,I.jsx)(es,{order:X}),(0,I.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:To(X.created_at)})]})]},X.id))}),(0,I.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,I.jsxs)(qe,{children:[(0,I.jsx)(je,{children:(0,I.jsxs)(Re,{children:[(0,I.jsx)(j,{children:"Order"}),(0,I.jsx)(j,{children:"Date"}),(0,I.jsx)(j,{children:"Customer"}),(0,I.jsx)(j,{children:"Items"}),(0,I.jsx)(j,{className:"af-text-right",children:"Total"}),(0,I.jsx)(j,{children:"Status"}),(0,I.jsx)(j,{className:"af-w-8"})]})}),(0,I.jsx)(Ge,{children:ct.map(X=>(0,I.jsxs)(Re,{onClick:Ie?()=>lt(X):void 0,className:Ie?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,I.jsxs)(G,{className:"af-whitespace-nowrap af-font-medium",children:[(0,I.jsx)("button",{type:"button",onClick:jt=>{jt.stopPropagation(),lt(X)},disabled:!Ie,"aria-label":`Open order ${dn(X)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ie?" hover:af-underline":""}`,children:dn(X)}),X.is_test&&(0,I.jsx)(ne,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,I.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:To(X.created_at)}),(0,I.jsxs)(G,{className:"af-max-w-[220px]",children:[(0,I.jsx)("div",{className:"af-truncate",children:X.customer_email||(0,I.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),xr(X)&&(0,I.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:xr(X)})]}),(0,I.jsx)(G,{className:"af-max-w-[220px]",children:(0,I.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:ko(X)})}),(0,I.jsxs)(G,{className:"af-whitespace-nowrap af-text-right",children:[(0,I.jsx)("div",{className:"af-font-medium af-tabular-nums",children:K(Ja(X),X.currency)}),X.amount_refunded>0&&(0,I.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",K(X.amount_refunded,X.currency)," ","refunded"]})]}),(0,I.jsx)(G,{children:(0,I.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,I.jsx)(Ln,{status:X.status}),(0,I.jsx)(hs,{deliveries:X.email_deliveries}),a&&(0,I.jsx)(es,{order:X})]})}),(0,I.jsx)(G,{className:"af-w-8 af-text-right",children:(0,I.jsx)(Sa.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},X.id))})]})}),l?null:(0,I.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,I.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,I.jsx)("span",{children:Mt?`${Ke.length} matching this page`:`Showing ${Ga}-${Wr} of ${f}`}),(0,I.jsxs)(Pa,{value:String(y),onValueChange:X=>v(Number(X)),children:[(0,I.jsx)(ua,{className:"af-w-[70px] af-h-8",children:(0,I.jsx)(Ca,{})}),(0,I.jsxs)(da,{children:[(0,I.jsx)(et,{value:"10",children:"10"}),(0,I.jsx)(et,{value:"25",children:"25"}),(0,I.jsx)(et,{value:"50",children:"50"}),(0,I.jsx)(et,{value:"100",children:"100"})]})]}),(0,I.jsx)("span",{children:"per page"})]}),(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,I.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>E(p-1),disabled:!C,children:[(0,I.jsx)(Sa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,I.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>E(p+1),disabled:!S,children:["Next",(0,I.jsx)(Sa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function fn(e){return(0,I.jsx)(Bc,{...e},e.maxRows==null?"full":"compact")}var as=re(require("react"),1),Qa=require("lucide-react");var ta=re(require("react"),1);function Us({initialPageSize:e=25}={}){let{api:t}=ae(),[n,s]=ta.useState([]),[a,r]=ta.useState(0),[o,u]=ta.useState(!0),[g,l]=ta.useState(null),[i,d]=ta.useState(0),[b,f]=ta.useState(e),[c,m]=ta.useState(""),p=ta.useRef(0),y=ta.useCallback(async()=>{let C=++p.current;try{u(!0),l(null);let E={limit:b,offset:i*b};c.trim()&&(E.email=c.trim());let v=await t.getCustomers(E);if(C!==p.current)return;s(v.customers),r(v.total)}catch(E){if(C!==p.current)return;l(E instanceof Error?E:new Error("Failed to fetch customers"))}finally{C===p.current&&u(!1)}},[t,i,b,c]);ta.useEffect(()=>{y()},[y]);let S=Math.ceil(a/b);return{customers:n,total:a,isLoading:o,error:g,page:i,pageSize:b,hasNextPage:i<S-1,hasPreviousPage:i>0,setPage:d,setPageSize:C=>{f(C),d(0)},email:c,setEmail:C=>{m(C),d(0)},refetch:y}}var Bn=re(require("react"),1),wr=require("lucide-react");var be=require("react/jsx-runtime");function Eo(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 Fc(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let n=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return n&&t.push(n),e.country&&t.push(e.country),t}function Ms({customer:e,onBack:t,className:n}){let{api:s}=ae(),[a,r]=Bn.useState(null),[o,u]=Bn.useState([]),[g,l]=Bn.useState(!0),[i,d]=Bn.useState(null);Bn.useEffect(()=>{let c=!1;return l(!0),d(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([m,p])=>{c||(r(m),u(p.orders))}).catch(m=>{c||d(m instanceof Error?m.message:"Failed to load customer")}).finally(()=>{c||l(!1)}),()=>{c=!0}},[s,e.id,e.email]);let b=a?.addresses??[],f=a?.order_count??o.length;return(0,be.jsxs)("div",{className:n,children:[(0,be.jsxs)("div",{className:"af-mb-6",children:[(0,be.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,be.jsx)(wr.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,be.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,be.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Eo(e.created_at)]})]}),g?(0,be.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,be.jsx)(wr.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):i?(0,be.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i}):(0,be.jsxs)("div",{className:"af-space-y-6",children:[(0,be.jsx)(Ka,{deliveries:a?.email_deliveries}),(0,be.jsxs)("div",{children:[(0,be.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,be.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,be.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,be.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,be.jsx)("span",{children:e.email})]}),e.name&&(0,be.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,be.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,be.jsx)("span",{children:e.name})]}),e.phone&&(0,be.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,be.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,be.jsx)("span",{children:e.phone})]}),(0,be.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,be.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,be.jsx)("span",{children:f})]})]})]}),b.length>0&&(0,be.jsxs)("div",{children:[(0,be.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,be.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(c=>(0,be.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[c.is_default&&(0,be.jsx)(ne,{variant:"secondary",className:"af-mb-1",children:"Default"}),Fc(c).map((m,p)=>(0,be.jsx)("div",{children:m},p))]},c.id))})]}),(0,be.jsxs)("div",{children:[(0,be.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,be.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,be.jsxs)(qe,{children:[(0,be.jsx)(je,{children:(0,be.jsxs)(Re,{children:[(0,be.jsx)(j,{children:"Date"}),(0,be.jsx)(j,{children:"Amount"}),(0,be.jsx)(j,{children:"Status"})]})}),(0,be.jsx)(Ge,{children:o.map(c=>(0,be.jsxs)(Re,{children:[(0,be.jsx)(G,{className:"af-text-muted-foreground",children:Eo(c.created_at)}),(0,be.jsx)(G,{children:K(Ja(c),c.currency)}),(0,be.jsx)(G,{children:(0,be.jsx)(_n,{status:c.status})})]},c.id))})]})]})]})]})}var fe=require("react/jsx-runtime");function Uc(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 $s({className:e}){let{customers:t,total:n,isLoading:s,error:a,page:r,pageSize:o,hasNextPage:u,hasPreviousPage:g,setPage:l,setPageSize:i,email:d,setEmail:b,refetch:f}=Us(),{api:c}=ae(),m=as.useCallback(()=>c.exportCustomersCsv(),[c]),[p,y]=as.useState("list"),[S,C]=as.useState(null),[E,v]=as.useState(""),_=L=>{C(L),y("detail")},T=()=>{y("list"),C(null),f()};if(p==="detail"&&S)return(0,fe.jsx)("div",{className:e,children:(0,fe.jsx)(Ms,{customer:S,onBack:T})});let A=(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,fe.jsx)(pe,{type:"email",value:E,onChange:L=>v(L.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),b(E.trim()))}}),(0,fe.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>b(E.trim()),children:[(0,fe.jsx)(Qa.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),d&&(0,fe.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>{v(""),b("")},children:"Clear"}),(0,fe.jsx)(Bt,{fetchCsv:m,filename:"customers",className:"af-ml-auto"})]});if(s)return(0,fe.jsxs)("div",{className:e,children:[A,(0,fe.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,fe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(a)return(0,fe.jsxs)("div",{className:e,children:[A,(0,fe.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,fe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",a.message]})})]});if(t.length===0&&r===0)return(0,fe.jsxs)("div",{className:e,children:[d&&A,(0,fe.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,fe.jsx)(Qa.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,fe.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:d?"No customers match that email.":(0,fe.jsxs)(fe.Fragment,{children:["No customers yet.",(0,fe.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let N=r*o+1,k=Math.min((r+1)*o,n);return(0,fe.jsxs)("div",{className:e,children:[A,(0,fe.jsxs)(qe,{children:[(0,fe.jsx)(je,{children:(0,fe.jsxs)(Re,{children:[(0,fe.jsx)(j,{children:"Email"}),(0,fe.jsx)(j,{children:"Name"}),(0,fe.jsx)(j,{children:"Phone"}),(0,fe.jsx)(j,{children:"Customer since"}),(0,fe.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,fe.jsx)(Ge,{children:t.map(L=>(0,fe.jsxs)(Re,{children:[(0,fe.jsx)(G,{className:"af-font-medium",children:L.email}),(0,fe.jsx)(G,{children:L.name||(0,fe.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,fe.jsx)(G,{children:L.phone||(0,fe.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,fe.jsx)(G,{className:"af-text-muted-foreground",children:Uc(L.created_at)}),(0,fe.jsx)(G,{className:"af-text-right",children:(0,fe.jsx)(R,{variant:"ghost",size:"icon",onClick:()=>_(L),title:"View customer",children:(0,fe.jsx)(Qa.Eye,{className:"af-h-4 af-w-4"})})})]},L.id))})]}),(0,fe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,fe.jsxs)("span",{children:["Showing ",N,"-",k," of ",n]}),(0,fe.jsxs)(Pa,{value:String(o),onValueChange:L=>i(Number(L)),children:[(0,fe.jsx)(ua,{className:"af-w-[70px] af-h-8",children:(0,fe.jsx)(Ca,{})}),(0,fe.jsxs)(da,{children:[(0,fe.jsx)(et,{value:"10",children:"10"}),(0,fe.jsx)(et,{value:"25",children:"25"}),(0,fe.jsx)(et,{value:"50",children:"50"}),(0,fe.jsx)(et,{value:"100",children:"100"})]})]}),(0,fe.jsx)("span",{children:"per page"})]}),(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,fe.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>l(r-1),disabled:!g,children:[(0,fe.jsx)(Qa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,fe.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>l(r+1),disabled:!u,children:["Next",(0,fe.jsx)(Qa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var De=re(require("react"),1),Nt=require("lucide-react");var St=re(require("react"),1);function Fn({initialPageSize:e=25,refreshKey:t,includeAggregates:n=!1}={}){let{api:s}=ae(),[a,r]=St.useState([]),[o,u]=St.useState(0),[g,l]=St.useState(null),[i,d]=St.useState(!0),[b,f]=St.useState(null),[c,m]=St.useState(0),[p,y]=St.useState(e),[S,C]=St.useState(void 0),[E,v]=St.useState(""),[_,T]=St.useState(""),[A,N]=St.useState(""),[k,L]=St.useState(""),[P,Y]=St.useState(""),J=S?S.join(","):"",q=St.useRef(0),se=St.useCallback(async()=>{let ge=++q.current;d(!0),f(null);try{let $={labels:J?J.split(","):void 0,customerEmail:E||void 0,q:_||void 0,from:A||void 0,to:k||void 0,retainerId:P||void 0,includeAggregates:n,limit:p,offset:c*p},te=await s.getInvoices($);if(ge!==q.current)return;if(c>0&&c*p>=te.total){m(Math.max(0,Math.ceil(te.total/p)-1));return}r(te.invoices),u(te.total),n&&l(te.aggregates??null)}catch($){if(ge!==q.current)return;f($ instanceof Error?$:new Error("Failed to fetch invoices"))}finally{ge===q.current&&d(!1)}},[s,J,E,_,A,k,P,c,p,n]);St.useEffect(()=>{se()},[se,t]);let ce=ge=>$=>{m(0),ge($)};return{invoices:a,total:o,aggregates:g,isLoading:i,error:b,page:c,pageSize:p,hasNextPage:(c+1)*p<o,hasPreviousPage:c>0,setPage:m,setPageSize:ce(y),labels:S,setLabels:ce(C),customerEmail:E,setCustomerEmail:ce(v),q:_,setQ:ce(T),from:A,setFrom:ce(N),to:k,setTo:ce(L),retainerId:P,setRetainerId:ce(Y),clearFilters:()=>{m(0),C(void 0),v(""),T(""),N(""),L(""),Y("")},refetch:se}}var x=require("react/jsx-runtime"),Mc={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 ui(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Mc[e.label]??e.label}function $c(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 ci={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Vc={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function ss({invoice:e,className:t}){return(0,x.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,x.jsx)(ne,{variant:$c(e.label),className:t,children:ui(e)}),e.collection_method==="charge_automatically"&&(0,x.jsx)(ne,{variant:"secondary",children:"Managed in Stripe"})]})}function Rr({delivery:e,className:t}){if(!e)return null;let n=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,x.jsx)(ne,{variant:n,className:t,children:ci[e.state]??e.state})}function ns(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function Da(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,n=new Date(t);return Number.isNaN(n.getTime())?e:n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Io={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Sr={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},oi=100,li=5e3;async function Hc(e,t){let n=[],s=0;for(let a=0;a<li;a+=oi){let r=await e.getInvoices({...t,limit:oi,offset:a});if(s=r.total,n.push(...r.invoices),r.invoices.length<oi||n.length>=s)break}return{invoices:n.slice(0,li),total:s,truncated:s>n.length||s>li}}function Do(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"],n=e.map(s=>[s.id,ns(s),ui(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),K(s.amount_subtotal,s.currency),K(s.tax_total,s.currency),K(s.amount_total,s.currency),s.amount_due===null?"":K(s.amount_due,s.currency),s.amount_paid===null?"":K(s.amount_paid,s.currency),K(s.amount_refunded,s.currency),s.payment_method??"",s.pay_url??"",s.retainer_id??"",s.replaces_order_id??"",s.replaced_by_order_id??"",s.tax_behavior??"",s.discount_total===void 0?"":K(s.discount_total,s.currency),s.collection_method??""]);return[t,...n].map(s=>s.map(fo).join(",")).join(`
5
+ `)}function zc(e){dr(new Blob([Do(e)],{type:"text/csv;charset=utf-8"}),ur("invoices"))}function qc({className:e,refreshKey:t,initialInvoiceId:n,onDetailOpenChange:s,onConnectStripe:a,onUpgradePlan:r,needsPaidPlan:o=!1,retainerFilter:u=null,onClearRetainerFilter:g,maxRows:l,onViewAll:i}){let d=typeof l=="number",{api:b}=ae(),{invoices:f,total:c,isLoading:m,error:p,page:y,pageSize:S,hasNextPage:C,hasPreviousPage:E,setPage:v,labels:_,setLabels:T,customerEmail:A,setCustomerEmail:N,q:k,setQ:L,from:P,setFrom:Y,to:J,setTo:q,retainerId:se,setRetainerId:ce,refetch:ge}=Fn({refreshKey:t}),[$,te]=De.useState(typeof l=="number"?"all":"open"),[U,Pe]=De.useState(""),[ue,at]=De.useState(null),Te=De.useRef(0),He=!d||!!i,Ye=De.useCallback(W=>{if(d){i?.();return}Te.current++,Et(!1),at(W)},[d,i]),[Le,Et]=De.useState(!1),[D,M]=De.useState(0),[F,ye]=De.useState(null),[Ne,Ee]=De.useState(!1),[Me,ot]=De.useState(0);De.useEffect(()=>{at(W=>{if(!W)return W;let Xe=f.find(Ga=>Ga.id===W.id);return Xe&&Xe!==W?Xe:W})},[f]);let[$e,gt]=De.useState(!1),[me,Ie]=De.useState(null),lt=async()=>{if(!$e){gt(!0),Ie(null);try{let{invoices:W,total:Xe,truncated:Ga}=await Hc(b,{labels:_,customerEmail:A,q:k,from:P,to:J,retainerId:se});zc(W),Ie(Ga?`Exported the first ${W.length.toLocaleString()} of ${Xe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ie("Couldn't export \u2014 try again.")}finally{gt(!1)}}},la=!A&&!k&&!P&&!J&&!se,[Ot,Jt]=De.useState(null);De.useEffect(()=>{if(m||c>0||!la||$!=="open")return;let W=!1;return b.getInvoices({limit:1}).then(Xe=>{W||Jt(Xe.total>0)}).catch(()=>{W||Jt(!0)}),()=>{W=!0}},[b,m,c,la,$,t]),De.useEffect(()=>{T(d?Sr.all:Sr.open)},[]),De.useEffect(()=>{let W=u?.id??"";W!==se&&(ce(W),W&&(te("all"),T(Sr.all),N(""),L(""),Pe(""),Y(""),q("")))},[u?.id]),De.useEffect(()=>{let W=!1;return Ee(!1),b.getInvoiceSettings().then(Xe=>{W||ye({payments_active:Xe.payments_active,blocked:Xe.blocked})}).catch(()=>{W||Ee(!0)}),()=>{W=!0}},[b,t,Me]),De.useEffect(()=>{if(!n||d)return;let W=!1,Xe=Te.current;return Et(!1),b.getInvoice(n).then(Ga=>{!W&&Xe===Te.current&&at(Ga)}).catch(()=>{!W&&Xe===Te.current&&Et(!0)}),()=>{W=!0}},[b,n,D,d]),De.useEffect(()=>{s?.(ue!==null)},[ue,s]);let Mt=W=>{te(W),T(Sr[W])},Ke=W=>{let Xe=W.trim();if(!Xe){k&&L(""),A&&N("");return}if(Xe.includes("@")){k&&L(""),N(Xe);return}A&&N(""),L(Xe.replace(/^#/,""))},ct=f,Ua=d?ct.slice(0,l):ct,kn=Le&&(0,x.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,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>M(W=>W+1),children:"Retry opening invoice"})]});if(ue)return(0,x.jsxs)("div",{className:e,children:[kn,(0,x.jsx)(_r,{invoice:ue,refreshKey:t,onBack:()=>{Ye(null),ge()}},ue.id)]});let Yt=(0,x.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[Ne&&(0,x.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>ot(W=>W+1),children:"Retry setup check"})]}),kn,F?.blocked&&(0,x.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",F.blocked.reason?`: ${F.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),u&&(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,x.jsxs)(ne,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",u.label]}),g&&(0,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:g,children:"Clear schedule filter"})]}),(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,x.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(Io).map(W=>(0,x.jsx)("button",{type:"button","aria-pressed":$===W,onClick:()=>Mt(W),className:ee("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",$===W?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Io[W]},W))}),(0,x.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,x.jsx)(Nt.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,x.jsx)(pe,{type:"text",value:U,onChange:W=>Pe(W.target.value),onBlur:()=>Ke(U),onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),Ke(U))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,x.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,x.jsx)(ke,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,x.jsx)(pe,{id:"invoices-from",type:"date",value:P,max:J||void 0,onChange:W=>Y(W.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,x.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,x.jsx)(ke,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,x.jsx)(pe,{id:"invoices-to",type:"date",value:J,min:P||void 0,onChange:W=>q(W.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,x.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>void lt(),disabled:$e||m||!!p||c===0,"aria-busy":$e,children:[(0,x.jsx)(Nt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),$e?"Exporting\u2026":"Export CSV (all matching)"]})]}),me&&(0,x.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:me})]});return m?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(W=>(0,x.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,x.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,x.jsx)(ie,{className:"af-h-4 af-w-20"}),(0,x.jsx)(ie,{className:"af-h-4 af-w-16"})]}),(0,x.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-40"})]},W))})]}):p?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>void ge(),children:"Retry"})]})]}):c===0&&la&&($==="all"||Ot===!1)&&($==="open"||$==="all")?F?.blocked?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)(Nr,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)(Nr,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):F&&!F.payments_active?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)(Nr,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:a?{label:"Payment setup",onClick:a}:void 0})]}):(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)(Nr,{heading:"No invoices yet",body:!F||Ne?"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,x.jsxs)("div",{className:e,children:[d?null:Yt,Ua.length===0?(0,x.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,x.jsxs)(x.Fragment,{children:[(0,x.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Ua.map(W=>(0,x.jsxs)("button",{type:"button",onClick:()=>Ye(W),disabled:!He,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${He?" hover:af-bg-muted/50":""}`,children:[(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,x.jsx)("span",{className:"af-font-medium",children:ns(W)}),(0,x.jsx)(ss,{invoice:W})]}),(0,x.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:W.customer_name??W.customer_email??"\u2014"}),W.delivery&&(0,x.jsx)("div",{className:"af-mt-1",children:(0,x.jsx)(Rr,{delivery:W.delivery})}),(0,x.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,x.jsx)("span",{children:W.collection_method==="charge_automatically"?"Automatic collection":W.due_at?`Due ${Da(W.due_at)}`:"Due on receipt"}),(0,x.jsx)("span",{className:"af-font-medium af-tabular-nums",children:K(W.amount_due??W.amount_total,W.currency)})]})]},W.id))}),(0,x.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,x.jsxs)(qe,{children:[(0,x.jsx)(je,{children:(0,x.jsxs)(Re,{children:[(0,x.jsx)(j,{children:"Invoice"}),(0,x.jsx)(j,{children:"Created"}),(0,x.jsx)(j,{children:"Customer"}),(0,x.jsx)(j,{children:"Due"}),(0,x.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,x.jsx)(j,{children:"Status"}),(0,x.jsx)(j,{children:"Delivery"}),(0,x.jsx)(j,{className:"af-w-8"})]})}),(0,x.jsx)(Ge,{children:Ua.map(W=>(0,x.jsxs)(Re,{className:He?"af-cursor-pointer":void 0,onClick:He?()=>Ye(W):void 0,children:[(0,x.jsx)(G,{className:"af-font-medium",children:(0,x.jsx)("button",{type:"button",disabled:!He,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${He?" hover:af-underline":""}`,onClick:Xe=>{Xe.stopPropagation(),Ye(W)},"aria-label":`Open invoice ${ns(W)}`,children:ns(W)})}),(0,x.jsx)(G,{children:Da(W.created_at)}),(0,x.jsxs)(G,{children:[(0,x.jsx)("div",{children:W.customer_name??"\u2014"}),(0,x.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:W.customer_email})]}),(0,x.jsx)(G,{children:W.collection_method==="charge_automatically"?"Automatic":W.due_at?Da(W.due_at):"On receipt"}),(0,x.jsx)(G,{className:"af-text-right af-tabular-nums",children:K(W.amount_due??W.amount_total,W.currency)}),(0,x.jsx)(G,{children:(0,x.jsx)(ss,{invoice:W})}),(0,x.jsx)(G,{children:(0,x.jsx)(Rr,{delivery:W.delivery})}),(0,x.jsx)(G,{children:(0,x.jsx)(Nt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},W.id))})]})}),d?null:(0,x.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,x.jsxs)("span",{children:[c," invoice",c===1?"":"s"]}),(0,x.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,x.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>v(y-1),disabled:!E,"aria-label":"Previous page",children:(0,x.jsx)(Nt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,x.jsxs)("span",{className:"af-tabular-nums",children:[y*S+1,"\u2013",Math.min((y+1)*S,c)]}),(0,x.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>v(y+1),disabled:!C,"aria-label":"Next page",children:(0,x.jsx)(Nt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Nr({heading:e,body:t,action:n}){return(0,x.jsx)(ts,{icon:Nt.FileText,heading:e,body:t,action:n})}function pn(e){return(0,x.jsx)(qc,{...e},e.maxRows==null?"full":"compact")}var mn="af-text-xs af-text-muted-foreground";function Ao(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function _r({invoice:e,onBack:t,refreshKey:n,className:s}){let{api:a}=ae(),r=De.useRef(null);De.useEffect(()=>{r.current?.focus()},[e.id]);let[o,u]=De.useState(!1),[g,l]=De.useState(null),[i,d]=De.useState(!1),[b,f]=De.useState(!1),c=De.useRef(0),[m,p]=De.useState(null),[y,S]=De.useState(!1),[C,E]=De.useState(0);De.useEffect(()=>{let P=!1;return S(!1),a.getInvoice(e.id).then(Y=>{P||p({source:e,value:Y})}).catch(()=>{P||S(!0)}),()=>{P=!0}},[a,e,n,C]);let v=m?.source===e?m.value:e,_=v.collection_method==="charge_automatically";De.useEffect(()=>(c.current++,l(null),d(!1),f(!1),u(!1),()=>{c.current++}),[a,v,n]);let T=P=>P==null?"\u2014":K(P,v.currency),A=async()=>{if(!(!v.pay_url||!Ao()))try{await navigator.clipboard.writeText(v.pay_url),u(!0),setTimeout(()=>u(!1),1500)}catch{}},N=async()=>{if(g){l(null);return}let P=++c.current;f(!1),d(!0);try{let Y=await a.getInvoicePreview(v.id);P===c.current&&l(Y)}catch{P===c.current&&f(!0)}finally{P===c.current&&d(!1)}},k=v.bill_to,L=k?[k.company,k.name,k.address?.line1,k.address?.line2,[k.address?.city,k.address?.state,k.address?.postal_code].filter(Boolean).join(", "),k.address?.country,k.tax_id?`${k.tax_id.value}`:null,k.po_number?`PO ${k.po_number}`:null,k.service_period?`Service period: ${k.service_period}`:null].filter(P=>!!P&&P.length>0):[];return(0,x.jsxs)("div",{className:s,children:[(0,x.jsxs)("div",{className:"af-mb-4",children:[(0,x.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,x.jsx)(Nt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,x.jsxs)("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",ns(v)]}),(0,x.jsx)(ss,{invoice:v}),(0,x.jsx)(Rr,{delivery:v.delivery})]}),(0,x.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[v.customer_name??v.customer_email,v.customer_name&&v.customer_email?` \xB7 ${v.customer_email}`:""]})]}),y&&(0,x.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,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>E(P=>P+1),children:"Retry details"})]}),v.label==="failed"&&(0,x.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."}),v.label==="creating"&&(0,x.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,x.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,x.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,x.jsxs)(qe,{children:[(0,x.jsx)(je,{children:(0,x.jsxs)(Re,{children:[(0,x.jsx)(j,{children:"Description"}),(0,x.jsx)(j,{className:"af-text-right",children:"Qty"}),(0,x.jsx)(j,{className:"af-text-right",children:"Amount"})]})}),(0,x.jsx)(Ge,{children:v.line_items.map((P,Y)=>(0,x.jsxs)(Re,{children:[(0,x.jsx)(G,{style:{overflowWrap:"anywhere"},children:P.description}),(0,x.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:P.quantity}),(0,x.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:T(P.amount)})]},Y))})]}),(0,x.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,x.jsx)(Pn,{label:"Subtotal",value:T(v.amount_subtotal)}),(v.discount_total??0)>0&&(0,x.jsx)(Pn,{label:"Discount",value:`-${T(v.discount_total)}`}),v.tax_total>0&&(0,x.jsx)(Pn,{label:v.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:T(v.tax_total)}),(0,x.jsx)(Pn,{label:"Total",value:T(v.amount_total),strong:!0}),v.credit_applied>0&&(0,x.jsx)(Pn,{label:"Credit applied",value:`-${T(v.credit_applied)}`}),v.amount_due!==null&&v.amount_due!==v.amount_total&&(0,x.jsx)(Pn,{label:"Amount due",value:T(v.amount_due),strong:!0}),v.amount_paid!==null&&v.amount_paid>0&&(0,x.jsx)(Pn,{label:"Amount paid",value:T(v.amount_paid)}),v.amount_refunded>0&&(0,x.jsx)(Pn,{label:"Refunded",value:T(v.amount_refunded)})]}),v.credit_notes?.length>0&&(0,x.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,x.jsx)("div",{className:mn,children:"Credit notes"}),v.credit_notes.map(P=>(0,x.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,x.jsxs)("span",{className:"af-text-muted-foreground",children:[Da(P.created_at)," \xB7 ",P.origin==="dashboard"?"issued in Stripe":"refund",P.stripe_credit_note_id?"":" \xB7 being created"]}),(0,x.jsxs)("span",{className:"af-tabular-nums",children:["-",K(P.amount,P.currency)]})]},P.id))]})]}),(v.note||v.footer)&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[v.note&&(0,x.jsxs)("div",{children:[(0,x.jsx)("div",{className:mn,children:"Note"}),(0,x.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:v.note})]}),v.footer&&(0,x.jsxs)("div",{children:[(0,x.jsx)("div",{className:mn,children:"Footer"}),(0,x.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:v.footer})]})]}),g&&!_&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,x.jsxs)("div",{className:ee(mn,"af-break-words"),children:["Email preview \u2014 ",g.subject]}),(0,x.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,x.jsx)("iframe",{title:"Invoice email preview",srcDoc:g.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,x.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,x.jsx)(Aa,{label:"Created",value:Da(v.created_at)}),(0,x.jsx)(Aa,{label:"Due",value:v.collection_method==="charge_automatically"?"Managed in Stripe":v.due_at?Da(v.due_at):"On receipt"}),v.paid_at&&(0,x.jsx)(Aa,{label:"Paid",value:Da(v.paid_at)}),v.payment_method&&(0,x.jsx)(Aa,{label:"Paid by",value:v.paid_out_of_band?`${v.payment_method} (recorded outside Stripe)`:v.payment_method}),v.payment_state!=="none"&&(0,x.jsx)(Aa,{label:"Payment",value:v.payment_state==="processing"?"Processing":v.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),v.delivery&&(0,x.jsx)(Aa,{label:"Delivery",value:`${ci[v.delivery.state]} \xB7 ${v.delivery.recipient}`}),v.marked_uncollectible_at&&(0,x.jsx)(Aa,{label:"Written off",value:Da(v.marked_uncollectible_at)}),v.correction_reason&&(0,x.jsx)(Aa,{label:"Correction",value:v.correction_reason}),v.replaced_by_order_id&&(0,x.jsx)(Aa,{label:"Replaced by",value:v.replaced_by_order_id}),v.collection_method==="charge_automatically"?(0,x.jsx)(Aa,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):v.retainer_id&&(0,x.jsx)(Aa,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),v.replaces_order_id&&(0,x.jsx)(Aa,{label:"Replaces",value:v.replaces_order_id})]}),(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,x.jsx)("div",{className:mn,children:"Reminders"}),_?(0,x.jsx)("div",{children:"View automatic payment reminders in Stripe."}):v.reminders.disabled?(0,x.jsx)("div",{children:"Off for this invoice."}):v.reminders.paused_until?(0,x.jsxs)("div",{children:["Paused until ",Da(v.reminders.paused_until),"."]}):v.reminders.next_at?(0,x.jsxs)("div",{children:["Next on ",Da(v.reminders.next_at),"."]}):v.reminders.final_sent_at?(0,x.jsxs)("div",{children:["Final reminder sent ",Da(v.reminders.final_sent_at),"."]}):(0,x.jsx)("div",{children:"None scheduled."}),!_&&(0,x.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",v.reminders.schedule.length===0?"none":v.reminders.schedule.map(P=>P<0?`${-P}d before`:P===0?"due day":`${P}d after`).join(", ")]})]}),v.communications&&v.communications.length>0&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,x.jsx)("div",{className:mn,children:"Email delivery history"}),v.communications.map(P=>(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,x.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[Vc[P.kind]??P.kind,P.kind==="reminder"&&P.slot!==null?` #${P.slot}`:"",(0,x.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",P.recipient]})]}),(0,x.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[ci[P.state]??P.state," \xB7 ",Da(P.state_at??P.created_at)]})]},P.id))]}),L.length>0&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,x.jsx)("div",{className:mn,children:"Bill to"}),L.map((P,Y)=>(0,x.jsx)("div",{className:"af-break-words",children:P},Y))]}),(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[v.pay_url&&(0,x.jsxs)(R,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void A(),disabled:!Ao(),children:[(0,x.jsx)(Nt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":_?"Copy invoice link":"Copy pay link"]}),v.pdf_url&&(0,x.jsx)(R,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,x.jsxs)("a",{href:v.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,x.jsx)(Nt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!_&&(0,x.jsxs)(R,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void N(),disabled:i,children:[i?(0,x.jsx)(Nt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,x.jsx)(Nt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),g?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!_&&(0,x.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),v.pay_url&&(0,x.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:v.pay_url}),(0,x.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:_?"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 Aa({label:e,value:t}){return(0,x.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,x.jsx)("span",{className:ee(mn,"af-shrink-0"),children:e}),(0,x.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function Pn({label:e,value:t,strong:n}){return(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,x.jsx)("dt",{className:ee(mn,n&&"af-font-medium af-text-foreground"),children:e}),(0,x.jsx)("dd",{className:ee("af-tabular-nums",n&&"af-font-semibold"),children:t})]})}var Oo=require("lucide-react");var Be=require("react/jsx-runtime"),jc={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Lo={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Gc(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 Bo(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>Lo[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>Lo[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":jc[e.status]}function Fo(e){let t=e.interval==="year"?"every year":"every month";return`${K(e.amount,e.currency)} ${t}`}function Wc(e){return e.status==="canceled"?`Ended ${Pr(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Pr(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 ${Pr(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Pr(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Pr(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),n=new Date(t);return Number.isNaN(n.getTime())?e.slice(0,10):n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Cr({retainer:e,className:t}){return(0,Be.jsx)(ne,{variant:Gc(e.status),className:ee("af-max-w-full af-whitespace-normal af-break-words",t),children:Bo(e)})}function Un({retainers:e,isLoading:t,error:n,onRetry:s,onShowCycles:a,activeRetainerId:r,total:o,endedTotal:u=0,isLoadingMore:g=!1,onLoadMore:l,includeEnded:i=!1,onIncludeEndedChange:d,exportCsv:b,className:f}){let c=!!d;if(!t&&!n&&e.length===0&&!(c&&(i||u>0)))return null;let m=o!==void 0?Math.max(0,o-e.length):0;return(0,Be.jsxs)("section",{className:ee("af-mb-6",f),"aria-label":"Recurring invoices",children:[(0,Be.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Be.jsx)(Oo.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,Be.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,Be.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."}),c&&(0,Be.jsx)(R,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":i,onClick:()=>d?.(!i),children:i?"Hide ended recurring invoices":u>0&&e.length===0?`Show ended recurring invoices (${u})`:"Show ended recurring invoices"}),b&&(0,Be.jsx)(Bt,{fetchCsv:b,filename:"retainers",className:c?void 0:"af-ml-auto"})]}),n?(0,Be.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,Be.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?(0,Be.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(p=>(0,Be.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,Be.jsx)(ie,{className:"af-h-4 af-w-48"}),(0,Be.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-32"})]},p))}):e.length===0?(0,Be.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:i?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,Be.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(p=>{let y=r===p.id;return(0,Be.jsxs)("li",{className:ee("af-rounded-md af-border af-p-3",y&&"af-border-primary af-bg-muted/40"),children:[(0,Be.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,Be.jsxs)("div",{className:"af-min-w-0",children:[(0,Be.jsx)("div",{className:"af-truncate af-font-medium",children:p.customer_name??p.customer_email??"\u2014"}),(0,Be.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:p.description})]}),(0,Be.jsx)(Cr,{retainer:p})]}),p.collection_method==="charge_automatically"?(0,Be.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,Be.jsx)(ne,{variant:"secondary",children:"Managed in Stripe"}),(0,Be.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,Be.jsx)("div",{className:"af-mt-2 af-text-sm",children:Fo(p)}),(0,Be.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,Be.jsxs)("span",{children:[Wc(p)," \xB7 ",p.cycles.count===0?"no invoices yet":`${p.cycles.paid} paid${p.cycles.open>0?`, ${p.cycles.open} open`:""}`]}),p.cycles.count>0&&(0,Be.jsx)(R,{type:"button",variant:y?"secondary":"ghost",size:"sm",onClick:()=>a(p),"aria-pressed":y,children:y?"Showing invoices":"View invoices"})]}),p.status==="failed"&&p.operation?.last_error&&(0,Be.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",p.operation.last_error,". Ask in the chat to try again."]})]},p.id)})}),!t&&!n&&m>0&&l&&(0,Be.jsx)("div",{className:"af-mt-2",children:(0,Be.jsx)(R,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:g,children:g?"Loading\u2026":`Load more (${m} more)`})})]})}var Uo=re(require("react"),1),Na=require("lucide-react");var _e=require("react/jsx-runtime");function Mn({onConnectStripe:e,onUpgradePlan:t,whenActive:n,className:s}){let{status:a,isLoading:r,error:o,refetch:u}=cn(),[g,l]=Uo.useState(!1),i=async()=>{l(!0);try{await u()}finally{l(!1)}};return r&&!a?(0,_e.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,_e.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):o||!a?(0,_e.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,_e.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o?.message||"Failed to load payment status"]})}):a.status==="active"?n!==void 0?(0,_e.jsx)("div",{className:s,children:n}):(0,_e.jsx)("div",{className:s,children:(0,_e.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,_e.jsx)(Na.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,_e.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,_e.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[a.reason==="needs_stripe"&&(0,_e.jsxs)("div",{className:"af-space-y-3",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,_e.jsx)(Na.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,_e.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,_e.jsxs)(R,{onClick:e,children:[(0,_e.jsx)(Na.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,_e.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,_e.jsxs)("div",{className:"af-space-y-3",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,_e.jsx)(Na.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,_e.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,_e.jsx)(R,{onClick:t,children:"Upgrade plan"}):(0,_e.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,_e.jsxs)("div",{className:"af-space-y-3",children:[(0,_e.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,_e.jsx)(Na.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?(0,_e.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,_e.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,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&(0,_e.jsxs)(R,{onClick:e,children:[(0,_e.jsx)(Na.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,_e.jsxs)(R,{variant:"outline",onClick:i,disabled:g,children:[g?(0,_e.jsx)(Na.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,_e.jsx)(Na.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var Wt=re(require("react"),1);function di(e,t,n){return e.map(s=>s.id===t?{...s,...n}:s)}function $n({includeStats:e=!1,refreshKey:t}={}){let{api:n}=ae(),[s,a]=Wt.useState([]),[r,o]=Wt.useState(!0),[u,g]=Wt.useState(null),l=Wt.useRef(0),i=Wt.useCallback(async()=>{let p=++l.current;try{o(!0),g(null);let y=await n.getProducts(e?{include:"stats"}:{});if(p!==l.current)return;a(y)}catch(y){if(p!==l.current)return;g(y instanceof Error?y:new Error("Failed to fetch products"))}finally{p===l.current&&o(!1)}},[n,e,t]);Wt.useEffect(()=>{i()},[i]);let d=Wt.useCallback(async p=>{let y=await n.createProduct(p);return a(S=>[y,...S]),y},[n]),b=Wt.useCallback(async(p,y)=>{let S=await n.updateProduct(p,y);return a(C=>di(C,p,S)),S},[n]),f=Wt.useCallback(async p=>{await n.deleteProduct(p),a(y=>y.filter(S=>S.id!==p))},[n]),c=Wt.useCallback(async(p,y)=>{let S=await n.attachProductFile(p,y);return a(C=>di(C,p,S)),S},[n]),m=Wt.useCallback(async(p,y)=>{let S=await n.attachProductFileFromUrl(p,y);return a(C=>di(C,p,S)),S},[n]);return{products:s,isLoading:r,error:u,refetch:i,createProduct:d,updateProduct:b,deleteProduct:f,attachProductFile:c,attachProductFileFromUrl:m}}var Kt=re(require("react"),1);var fi=["creating","active","paused","canceling"],Kc=["canceled","failed"],Zc={statuses:fi},Jc={};function Vn({refreshKey:e,includeEnded:t=!1,limit:n=50}={}){let{api:s}=ae(),[a,r]=Kt.useState([]),[o,u]=Kt.useState(0),[g,l]=Kt.useState(0),[i,d]=Kt.useState(!0),[b,f]=Kt.useState(!1),[c,m]=Kt.useState(null),[p,y]=Kt.useState(t),S=Kt.useRef(0),C=Kt.useCallback(async()=>{let v=++S.current;d(!0),f(!1),m(null);try{let _=await s.getRetainers({statuses:p?void 0:fi,limit:n,offset:0});if(v!==S.current)return;if(r(_.retainers),u(_.total),!p&&_.total===0){let T=await s.getRetainers({statuses:Kc,limit:1,offset:0});if(v!==S.current)return;l(T.total)}else l(0)}catch(_){if(v!==S.current)return;m(_ instanceof Error?_:new Error("Failed to fetch retainers"))}finally{v===S.current&&d(!1)}},[s,p,n]);Kt.useEffect(()=>{C()},[C,e]);let E=Kt.useCallback(async()=>{if(i||b||a.length>=o)return;let v=S.current;f(!0);try{let _=await s.getRetainers({statuses:p?void 0:fi,limit:n,offset:a.length});if(v!==S.current)return;r(T=>{let A=new Set(T.map(N=>N.id));return[...T,..._.retainers.filter(N=>!A.has(N.id))]}),u(_.total)}catch(_){if(v!==S.current)return;m(_ instanceof Error?_:new Error("Failed to fetch retainers"))}finally{v===S.current&&f(!1)}},[s,p,n,i,b,a.length,o]);return{retainers:a,total:o,endedTotal:g,hasMore:a.length<o,isLoading:i,isLoadingMore:b,error:c,includeEnded:p,setIncludeEnded:y,loadMore:E,refetch:C,filters:p?Jc:Zc}}var Se=require("react/jsx-runtime");function mi({className:e,defaultTab:t="products",onConnectStripe:n,onRefund:s,onUpgradePlan:a}){let[r,o]=rs.useState(t),[u,g]=rs.useState("list"),[l,i]=rs.useState(null),d=$n(),{status:b,error:f}=cn(),c=b?.currency,m=C=>{i(C),g("edit")},p=()=>{i(null),g("create")},y=()=>{g("list"),i(null)},S=C=>{i(C),g("edit")};return(0,Se.jsxs)("div",{className:e,children:[(0,Se.jsxs)("div",{className:"af-mb-6",children:[(0,Se.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Se.jsxs)(ir,{value:r,onValueChange:C=>o(C),children:[(0,Se.jsxs)(vs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Se.jsxs)($a,{value:"products",className:"af-gap-2",children:[(0,Se.jsx)(La.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Se.jsxs)($a,{value:"orders",className:"af-gap-2",children:[(0,Se.jsx)(La.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Se.jsxs)($a,{value:"invoices",className:"af-gap-2",children:[(0,Se.jsx)(La.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Se.jsxs)($a,{value:"customers",className:"af-gap-2",children:[(0,Se.jsx)(La.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Se.jsx)($a,{value:"promos",children:"Promo codes"}),(0,Se.jsxs)($a,{value:"setup",className:"af-gap-2",children:[(0,Se.jsx)(La.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Se.jsx)(Va,{value:"products",children:u==="list"?(0,Se.jsx)(Is,{productsState:d,onSelectProduct:m,onCreateProduct:p}):(0,Se.jsxs)("div",{children:[(0,Se.jsxs)("div",{className:"af-mb-6",children:[(0,Se.jsxs)(R,{variant:"ghost",size:"sm",onClick:y,className:"af-mb-2 af--ml-2",children:[(0,Se.jsx)(La.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Se.jsx)("h3",{className:"af-text-lg af-font-semibold",children:u==="create"?"New Product":l?.name})]}),u==="create"&&!c?(0,Se.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:f?(0,Se.jsxs)("div",{className:"af-text-destructive",children:["Error: ",f.message]}):(0,Se.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Se.jsx)(Ds,{productsState:d,product:u==="edit"?l:null,currency:c??"usd",onSaved:S},u==="edit"?l?.id??"edit":"new")]})}),(0,Se.jsx)(Va,{value:"orders",children:(0,Se.jsx)(fn,{onRefund:s})}),(0,Se.jsx)(Va,{value:"invoices",children:(0,Se.jsx)(Yc,{onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:b?.reason==="needs_paid_plan"})}),(0,Se.jsx)(Va,{value:"customers",children:(0,Se.jsx)($s,{})}),(0,Se.jsx)(Va,{value:"promos",children:(0,Se.jsx)(Dn,{})}),(0,Se.jsx)(Va,{value:"setup",children:(0,Se.jsx)(Mn,{onConnectStripe:n,onUpgradePlan:a})})]})]})}function Yc({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:n}){let s=Vn(),[a,r]=rs.useState(null),[o,u]=rs.useState(!1);return(0,Se.jsxs)(Se.Fragment,{children:[!o&&(0,Se.jsx)(Un,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:a?.id??null,onShowCycles:g=>r(l=>l?.id===g.id?null:g),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),(0,Se.jsx)(pn,{onDetailOpenChange:u,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:n,retainerFilter:a?{id:a.id,label:`${a.customer_name??a.customer_email??"Recurring invoices"} \u2014 ${a.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}var $o=re(require("react"),1);var en=re(require("react"),1);function Hn({refreshKey:e}={}){let{api:t}=ae(),[n,s]=en.useState(null),[a,r]=en.useState(!0),[o,u]=en.useState(null),g=en.useRef(0),l=en.useCallback(async()=>{let i=++g.current;try{r(!0),u(null);let d=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(i!==g.current)return;s(d)}catch(d){if(i!==g.current)return;u(d instanceof Error?d:new Error("Failed to fetch summary"))}finally{i===g.current&&r(!1)}},[t,e]);return en.useEffect(()=>{l()},[l]),{summary:n,isLoading:a,error:o,refetch:l}}var We=require("react/jsx-runtime");function Mo(e,t){if(e.settled.complete)return{headline:K(e.settled.gross,e.settled.currency),extra:[]};let n=e.totals[0];return n?{headline:K(n.gross,n.currency),extra:e.totals.slice(1).map(s=>`+ ${K(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:K(0,t),extra:[]}}function pi({refreshKey:e,initialOrderId:t,isOwner:n=!1,onRefund:s,onBackToWebsite:a,className:r}){let{summary:o,isLoading:u,error:g,refetch:l}=Hn({refreshKey:e}),[i,d]=$o.useState(!1),b=(0,We.jsx)("div",{className:"af-mb-6",children:g&&!o?(0,We.jsx)(wa,{message:"Couldn't load your revenue summary.",onRetry:()=>l()}):(0,We.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:u||!o?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(dt,{label:"This week",children:(0,We.jsx)(ie,{className:"af-h-6 af-w-24"})}),(0,We.jsx)(dt,{label:"Today",children:(0,We.jsx)(ie,{className:"af-h-6 af-w-24"})}),(0,We.jsx)(dt,{label:"Needs attention",children:(0,We.jsx)(ie,{className:"af-h-6 af-w-10"})})]}):(0,We.jsx)(We.Fragment,{children:(()=>{let f=Mo(o.revenue.d7,o.currency),c=Mo(o.revenue.today,o.currency);return(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(dt,{label:"This week",detail:f.extra.length>0?(0,We.jsx)("div",{children:f.extra.map(m=>(0,We.jsx)("div",{children:m},m))}):void 0,children:f.headline}),(0,We.jsx)(dt,{label:"Today",detail:c.extra.length>0?(0,We.jsx)("div",{children:c.extra.map(m=>(0,We.jsx)("div",{children:m},m))}):void 0,children:c.headline}),(0,We.jsx)(dt,{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)(wt,{title:"Orders",onBackToWebsite:a,hideBackButton:i,className:r,children:[b,(0,We.jsx)(fn,{refreshKey:e,initialOrderId:t,onDetailOpenChange:d,showFulfillment:!0,onRefund:n?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Oa=re(require("react"),1),is=require("lucide-react");var tn=re(require("react"),1),Dr=require("lucide-react");var At=require("react/jsx-runtime"),Vo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Cn="af-text-xs af-text-muted-foreground",Tr="af-text-sm af-font-medium af-tabular-nums",Xc=3;function Qc(e){let t=e.pricing,n=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let g=e.min_amount??t?.min_amount??null,l=e.max_amount??t?.max_amount??null;return g!==null&&l!==null?{text:`Buyer chooses (${K(g,n)} \u2013 ${K(l,n)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let a=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(a===null||r===null)return{text:"Varies by variant",compareAt:null};let o=a===r?K(a,n):`${K(a,n)} \u2013 ${K(r,n)}`,u=t?.compare_at_amount??null;return{text:o,compareAt:u!==null&&u>r?K(u,n):null}}function kr({product:e,className:t}){let n=Qc(e);return(0,At.jsxs)("div",{className:t,children:[(0,At.jsx)("span",{className:Tr,children:n.text}),n.compareAt&&(0,At.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:n.compareAt})]})}function Er({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,At.jsx)(ne,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,At.jsxs)(ne,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,At.jsx)(ne,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,At.jsxs)(ne,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,At.jsx)(ne,{variant:"warning",children:"Low stock"}):null}function Ir(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Ar(e){return e.map(t=>K(t.amount,t.currency)).join(" + ")}function Ho(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${K(e.min_amount,e.currency)} \u2013 ${K(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":K(e.unit_amount,e.currency)}function zo({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,At.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let n=t.available??0;return t.allow_backorder?(0,At.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,At.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,n)}),(0,At.jsx)(ne,{variant:"secondary",children:n<0?`${Math.abs(n)} on backorder`:"Backorder"})]}):n<=0?(0,At.jsx)(ne,{variant:"destructive",children:"Out of stock"}):(0,At.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,At.jsx)("span",{className:"af-tabular-nums",children:n}),n<=Xc&&(0,At.jsx)(ne,{variant:"warning",children:"Low"})]})}var Q=require("react/jsx-runtime");function Vs({title:e,children:t,className:n}){return(0,Q.jsxs)("section",{className:ee("af-rounded-lg af-border af-p-4",n),children:[(0,Q.jsx)("h4",{className:Vo,children:e}),(0,Q.jsx)("div",{className:"af-mt-3",children:t})]})}function qo({src:e,className:t}){let[n,s]=tn.useState(!1);return tn.useEffect(()=>s(!1),[e]),!e||n?(0,Q.jsx)("div",{"aria-hidden":"true",className:ee("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,Q.jsx)(Dr.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,Q.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:ee("af-object-cover",t)})}function jo({product:e,showStats:t=!1,onBack:n}){let{api:s}=ae(),[a,r]=tn.useState(null),[o,u]=tn.useState(!0),[g,l]=tn.useState(null),[i,d]=tn.useState(0),[b,f]=tn.useState(0);tn.useEffect(()=>{let v=!1;return u(!0),l(null),s.getProduct(e.id).then(_=>{v||r(_)}).catch(_=>{v||l(_ instanceof Error?_:new Error("Failed to load product"))}).finally(()=>{v||u(!1)}),()=>{v=!0}},[s,e.id,i]);let c=a?{...e,...a}:e,m=c.images.length>0?c.images:e.images,p=m[b]??m[0],y=Ir(c),S=t?c.stats:void 0,C=a?.variants??[],E=C.length>1;return(0,Q.jsxs)("div",{children:[(0,Q.jsxs)("div",{className:"af-mb-6",children:[(0,Q.jsxs)(R,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[(0,Q.jsx)(Dr.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)(ne,{variant:c.active?"success":"secondary",children:c.active?"Active":"Draft"}),(0,Q.jsx)(Er,{product:c})]}),(0,Q.jsx)(kr,{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)(qo,{src:p,className:"af-h-48 af-w-full af-rounded-md af-border"}),m.length>1&&(0,Q.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:m.map((v,_)=>(0,Q.jsx)("button",{type:"button",onClick:()=>f(_),"aria-label":`Show photo ${_+1} of ${m.length}`,"aria-pressed":_===b,className:ee("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",_===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,Q.jsx)(qo,{src:v,className:"af-h-12 af-w-12 af-rounded-md"})},`${v}-${_}`))})]}),(0,Q.jsxs)("div",{className:"af-space-y-6",children:[c.description&&(0,Q.jsx)(Vs,{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)(Vs,{title:"Variants",children:[(0,Q.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(v=>(0,Q.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,Q.jsx)(ie,{className:"af-h-4 af-w-28"}),(0,Q.jsx)(ie,{className:"af-h-4 af-w-20"}),(0,Q.jsx)(ie,{className:"af-h-4 af-w-16"})]},v))}),(0,Q.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):g?(0,Q.jsx)(wa,{message:"Couldn't load this product's variants.",onRetry:()=>d(v=>v+1)}):E?(0,Q.jsx)(Vs,{title:`Variants \xB7 ${C.length}`,children:(0,Q.jsx)("div",{className:"af-overflow-x-auto",children:(0,Q.jsxs)(qe,{children:[(0,Q.jsx)(je,{children:(0,Q.jsxs)(Re,{children:[(0,Q.jsx)(j,{children:"Variant"}),(0,Q.jsx)(j,{children:"SKU"}),(0,Q.jsx)(j,{className:"af-text-right",children:"Price"}),(0,Q.jsx)(j,{children:"Stock"})]})}),(0,Q.jsx)(Ge,{children:C.map(v=>(0,Q.jsxs)(Re,{children:[(0,Q.jsxs)(G,{className:"af-font-medium",children:[v.title||v.option_values.map(_=>_.value).join(" / ")||"\u2014",!v.active&&(0,Q.jsx)(ne,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,Q.jsx)(G,{className:"af-text-muted-foreground",children:v.sku?(0,Q.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:v.sku}):"\u2014"}),(0,Q.jsxs)(G,{className:"af-whitespace-nowrap af-text-right",children:[(0,Q.jsx)("div",{className:Tr,children:Ho(v)}),v.compare_at_amount!==null&&v.unit_amount!==null&&v.compare_at_amount>v.unit_amount&&(0,Q.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:K(v.compare_at_amount,v.currency)})]}),(0,Q.jsx)(G,{className:"af-text-sm",children:(0,Q.jsx)(zo,{variant:v})})]},v.id))})]})})}):null,(0,Q.jsx)(Vs,{title:"Details",children:(0,Q.jsxs)("dl",{className:"af-space-y-2",children:[(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:Cn,children:"Delivery"}),(0,Q.jsx)("dd",{className:"af-text-sm",children:y==="Digital download"?c.fulfillment.filename??"Digital download":y??"Nothing to deliver"})]}),c.fulfillment.type==="redirect"&&c.fulfillment.url&&(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:Cn,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:Cn,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:Cn,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)(Vs,{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:Cn,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:Cn,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:Cn,children:"Gross"}),(0,Q.jsx)("dd",{className:Tr,children:S.gross.length>0?Ar(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 z=require("react/jsx-runtime"),eu={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},tu=["all","active","draft","low_stock","out_of_stock"];function Go(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,n=new Date(t).getTime();return Number.isNaN(n)?0:n}function Wo(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function au(e){return e.inventory?.out_of_stock??!1}function nu(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Wo(e);case"out_of_stock":return au(e);default:return!0}}function su({product:e,showStats:t,onOpen:n}){let s=e.images[0],a=t?e.stats:void 0,r=Ir(e),o=e.variant_count??0;return(0,z.jsxs)("button",{type:"button",onClick:n,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?(0,z.jsx)("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,z.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,z.jsx)(is.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,z.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,z.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,z.jsxs)("div",{className:"af-min-w-0",children:[(0,z.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,z.jsx)(kr,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,z.jsx)(ne,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,z.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,z.jsx)(Er,{product:e}),o>1&&(0,z.jsxs)(ne,{variant:"outline",children:[o," variants"]}),r&&(0,z.jsx)(ne,{variant:"outline",children:r})]}),a&&(0,z.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[a.units_sold," sold",a.gross.length>0?` \xB7 ${Ar(a.gross)}`:""," ",(0,z.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function ru(){return(0,z.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,z.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,z.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,z.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,z.jsx)(ie,{className:"af-w-32"}),(0,z.jsx)(ie,{className:"af-w-16"}),(0,z.jsx)(ie,{className:"af-h-5 af-w-24"})]})]},e))})}function gi({refreshKey:e,showStats:t=!1,onBackToWebsite:n,className:s}){let{products:a,isLoading:r,error:o,refetch:u}=$n({includeStats:t,refreshKey:e}),[g,l]=Oa.useState(!1),[i,d]=Oa.useState(null),[b,f]=Oa.useState("all"),{api:c}=ae(),m=Oa.useCallback(()=>c.exportProductsCsv(),[c]),[p,y]=Oa.useState(""),[S,C]=Oa.useState("newest"),E=Oa.useMemo(()=>{if(!t)return null;let J=null;for(let q of a)!q.stats||q.stats.units_sold===0||(!J||q.stats.units_sold>(J.stats?.units_sold??0))&&(J=q);return J},[a,t]),v=Oa.useMemo(()=>a.filter(Wo).length,[a]),_=p.trim().toLowerCase(),T=Oa.useMemo(()=>{let q=[...a.filter(se=>nu(se,b)&&(!_||se.name.toLowerCase().includes(_)))];return S==="name"?q.sort((se,ce)=>se.name.localeCompare(ce.name)):S==="best_selling"?q.sort((se,ce)=>(ce.stats?.units_sold??0)-(se.stats?.units_sold??0)):q.sort((se,ce)=>Go(ce.created_at)-Go(se.created_at)),q},[a,b,_,S]),A=b!=="all"||!!_,N=()=>{f("all"),y("")},k=r||o!==null&&a.length===0,L=(0,z.jsx)("div",{className:"af-mb-6",children:(0,z.jsx)("div",{className:ee("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:k?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(dt,{label:"Products",children:(0,z.jsx)(ie,{className:"af-h-6 af-w-10"})}),t?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(dt,{label:"Best seller",children:(0,z.jsx)(ie,{className:"af-h-6 af-w-28"})}),(0,z.jsx)(dt,{label:"Low stock",children:(0,z.jsx)(ie,{className:"af-h-6 af-w-10"})})]}):(0,z.jsx)(dt,{label:"Active",children:(0,z.jsx)(ie,{className:"af-h-6 af-w-10"})})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(dt,{label:"Products",children:a.length}),t?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(dt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:E?`${E.stats?.units_sold??0} sold, last 30 days`:void 0,children:E?(0,z.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:E.name}):(0,z.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,z.jsx)(dt,{label:"Low stock",children:v})]}):(0,z.jsx)(dt,{label:"Active",children:a.filter(J=>J.active).length})]})})}),P=(0,z.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,z.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,z.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:tu.map(J=>(0,z.jsx)("button",{type:"button","aria-pressed":b===J,onClick:()=>f(J),className:ee("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",b===J?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:eu[J]},J))}),(0,z.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,z.jsx)(is.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,z.jsx)(pe,{type:"text",value:p,onChange:J=>y(J.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,z.jsxs)(Pa,{value:S,onValueChange:J=>C(J),children:[(0,z.jsx)(ua,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,z.jsx)(Ca,{})}),(0,z.jsxs)(da,{children:[(0,z.jsx)(et,{value:"newest",children:"Newest"}),(0,z.jsx)(et,{value:"name",children:"Name A\u2013Z"}),t&&(0,z.jsx)(et,{value:"best_selling",children:"Best selling"})]})]}),A&&(0,z.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:N,children:"Clear filters"}),(0,z.jsx)(Bt,{fetchCsv:m,filename:"products",label:A?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&a.length===0?(0,z.jsx)(ie,{className:"af-h-4 af-w-28"}):(0,z.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:A?`${T.length} of ${a.length} products`:`${a.length} ${a.length===1?"product":"products"}${v>0?` \xB7 ${v} low stock`:""}`})]}),Y;return i?Y=(0,z.jsx)(jo,{product:i,showStats:t,onBack:()=>{d(null),u()}},i.id):r&&a.length===0?Y=(0,z.jsxs)(z.Fragment,{children:[P,(0,z.jsx)(ru,{}),(0,z.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&a.length===0?Y=(0,z.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,z.jsx)(wa,{message:"Couldn't load your products.",onRetry:()=>u()})}):a.length===0?Y=(0,z.jsxs)(za,{icon:(0,z.jsx)(is.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,z.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):Y=(0,z.jsxs)(z.Fragment,{children:[P,o&&(0,z.jsx)("div",{className:"af-mb-4",children:(0,z.jsx)(wa,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>u()})}),T.length===0?(0,z.jsxs)(za,{children:["No products match these filters.",(0,z.jsx)("br",{}),(0,z.jsx)(R,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:N,children:"Show all products"})]}):(0,z.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:T.map(J=>(0,z.jsx)(su,{product:J,showStats:t,onOpen:()=>d(J)},J.id))})]}),(0,z.jsx)(wt,{title:"Products",onBackToWebsite:n,hideBackButton:!!i,className:s,children:g?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(R,{variant:"ghost",onClick:()=>l(!1),children:"Back to products"}),(0,z.jsx)(Dn,{})]}):(0,z.jsxs)(z.Fragment,{children:[!i&&(0,z.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,z.jsx)(R,{variant:"outline",onClick:()=>l(!0),children:"Promo codes"})}),!i&&L,Y]})})}var na=re(require("react"),1),yt=require("lucide-react");var aa=re(require("react"),1);function Hs({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ae(),[s,a]=aa.useState([]),[r,o]=aa.useState(!0),[u,g]=aa.useState(null),[l,i]=aa.useState(0),[d]=aa.useState(e),[b,f]=aa.useState(""),[c,m]=aa.useState(void 0),p=aa.useRef(0),y=aa.useCallback(async({afterRemoval:S=!1}={})=>{let C=++p.current;try{o(!0),g(null);let E={limit:d,offset:l*d};b.trim()&&(E.q=b.trim()),c&&(E.source=c);let v=await n.getPeople(E);if(C!==p.current)return;if(S&&v.people.length===0&&l>0){i(l-1);return}a(v.people)}catch(E){if(C!==p.current)return;g(E instanceof Error?E:new Error("Failed to fetch people"))}finally{C===p.current&&o(!1)}},[n,l,d,b,c,t]);return aa.useEffect(()=>{y()},[y]),{people:s,isLoading:r,error:u,page:l,pageSize:d,hasNextPage:s.length===d,hasPreviousPage:l>0,setPage:i,q:b,setQ:S=>{f(S),i(0)},source:c,setSource:S=>{m(S),i(0)},refetch:()=>y(),refetchAfterRemoval:()=>y({afterRemoval:!0})}}var an=re(require("react"),1);function zs(e,{refreshKey:t}={}){let{api:n}=ae(),[s,a]=an.useState(null),[r,o]=an.useState(e!==null),[u,g]=an.useState(null),l=an.useRef(0),i=an.useCallback(async()=>{if(e===null){a(null),o(!1),g(null);return}let d=++l.current;try{o(!0),g(null);let b=await n.getPerson(e);if(d!==l.current)return;a(b)}catch(b){if(d!==l.current)return;g(b instanceof Error?b:new Error("Failed to fetch person"))}finally{d===l.current&&o(!1)}},[n,e,t]);return an.useEffect(()=>{i()},[i]),{person:s,isLoading:r,error:u,refetch:i}}var w=require("react/jsx-runtime"),vi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",iu="af-text-xs af-text-muted-foreground";function os(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 bi(e,t){let n=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(n)}`}function ou(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function lu({value:e,label:t}){let[n,s]=na.useState(!1);return ou()?(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[n?(0,w.jsx)(yt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,w.jsx)(yt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),n?"Copied":"Copy email"]}):null}function Ko(e){return(0,w.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,w.jsxs)(ne,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,w.jsx)(ne,{variant:"secondary",children:"Contact form"})]})}function Zo(e){return e.name?e.name:e.email?e.email:(0,w.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var cu=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,uu=40;function du(e){let t=Object.entries(e).filter(([a])=>!a.startsWith("_")),s=t.find(([a,r])=>cu.test(a)&&typeof r=="string"&&r.trim())??t.filter(([,a])=>typeof a=="string"&&a.trim().length>=uu).sort((a,r)=>String(r[1]).trim().length-String(a[1]).trim().length)[0];return s?{message:String(s[1]),rest:t.filter(([a])=>a!==s[0])}:{message:null,rest:t}}function fu(e){return e.replace(/_/g," ")}function mu(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function pu({data:e}){let{message:t,rest:n}=du(e);return t===null&&n.length===0?(0,w.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,w.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,w.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),n.length>0&&(0,w.jsx)("dl",{className:"af-space-y-1",children:n.map(([s,a])=>(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,w.jsx)("dt",{className:ee(iu,"af-w-28 af-shrink-0 af-capitalize"),children:fu(s)}),(0,w.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:mu(a)})]},s))})]})}function Yo({formName:e,createdAt:t,data:n,onDelete:s}){return(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,w.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)(ne,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,w.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,w.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:os(t)}),(0,w.jsx)(Yn,{iconOnly:!0,onDelete:s})]}),(0,w.jsx)(pu,{data:n})]})}function gu(e){return e.charged_total??e.amount_total}function vu({email:e,refreshKey:t,onBack:n,onRemoved:s}){let{api:a}=ae(),{person:r,isLoading:o,error:u,refetch:g}=zs(e,{refreshKey:t}),l=async d=>{await a.deleteSubmission(d),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?g():n()},i=bi(e,r?.submissions[0]?.form_name);return(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"af-mb-6",children:[(0,w.jsxs)(R,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[(0,w.jsx)(yt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,w.jsxs)("div",{className:"af-min-w-0",children:[o?(0,w.jsx)(ie,{className:"af-h-7 af-w-48"}):(0,w.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),(0,w.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,w.jsx)(lu,{value:e,label:"Copy email address"})]})]}),(0,w.jsx)(R,{asChild:!0,children:(0,w.jsxs)("a",{href:i,children:[(0,w.jsx)(yt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),o?(0,w.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(d=>(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,w.jsx)(ie,{className:"af-w-40"}),(0,w.jsx)(ie,{className:"af-mt-2 af-w-64"})]},d)),(0,w.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):u||!r?(0,w.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,w.jsx)(wa,{message:"Couldn't load this person.",onRetry:()=>g()})}):(0,w.jsxs)("div",{className:"af-space-y-6",children:[r.customer&&(0,w.jsxs)("div",{children:[(0,w.jsx)("h4",{className:ee(vi,"af-mb-3"),children:"Customer"}),(0,w.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&(0,w.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,w.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,w.jsx)("dd",{children:r.customer.name})]}),r.customer.phone&&(0,w.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,w.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,w.jsx)("dd",{children:r.customer.phone})]}),(0,w.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,w.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,w.jsx)("dd",{children:os(r.customer.created_at)})]})]})]}),r.orders.length>0&&(0,w.jsxs)("div",{children:[(0,w.jsx)("h4",{className:ee(vi,"af-mb-3"),children:"Purchases"}),(0,w.jsx)("div",{className:"af-overflow-x-auto",children:(0,w.jsxs)(qe,{children:[(0,w.jsx)(je,{children:(0,w.jsxs)(Re,{children:[(0,w.jsx)(j,{children:"Order"}),(0,w.jsx)(j,{children:"Date"}),(0,w.jsx)(j,{className:"af-text-right",children:"Total"}),(0,w.jsx)(j,{children:"Status"})]})}),(0,w.jsx)(Ge,{children:r.orders.map(d=>(0,w.jsxs)(Re,{children:[(0,w.jsx)(G,{className:"af-whitespace-nowrap af-font-medium",children:dn(d)}),(0,w.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:os(d.created_at)}),(0,w.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:K(gu(d),d.currency)}),(0,w.jsx)(G,{children:(0,w.jsx)(_n,{status:d.status})})]},d.id))})]})}),(0,w.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."})]}),r.submissions.length>0&&(0,w.jsxs)("div",{children:[(0,w.jsx)("h4",{className:ee(vi,"af-mb-3"),children:"Messages"}),(0,w.jsx)("div",{className:"af-space-y-3",children:r.submissions.map(d=>(0,w.jsx)(Yo,{formName:d.form_name,createdAt:d.created_at,data:d.data,onDelete:()=>l(d.id)},d.id))})]})]})]})}function bu({submissionId:e,onBack:t,onRemoved:n}){let{api:s}=ae(),[a,r]=na.useState(null),[o,u]=na.useState(!0),[g,l]=na.useState(null),[i,d]=na.useState(0);return na.useEffect(()=>{let b=!1;return u(!0),l(null),s.getSubmission(e).then(f=>{b||r(f)}).catch(f=>{b||l(f instanceof Error?f:new Error("Failed to load submission"))}).finally(()=>{b||u(!1)}),()=>{b=!0}},[s,e,i]),(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"af-mb-6",children:[(0,w.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,w.jsx)(yt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,w.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),o?(0,w.jsx)(ie,{className:"af-mt-1 af-h-4 af-w-32"}):a&&(0,w.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:os(a.metadata.submitted_at)})]}),o?(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,w.jsx)(ie,{className:"af-w-40"}),(0,w.jsx)(ie,{className:"af-mt-2 af-w-64"}),(0,w.jsx)(ie,{className:"af-mt-2 af-w-52"}),(0,w.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):g||!a?(0,w.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,w.jsx)(wa,{message:"Couldn't load this submission.",onRetry:()=>d(b=>b+1)})}):(0,w.jsxs)("div",{className:"af-space-y-3",children:[(0,w.jsx)(Yo,{formName:null,createdAt:a.metadata.submitted_at,data:a.data,onDelete:async()=>{await s.deleteSubmission(e),n(),t()}}),(0,w.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 yu={all:"All",customers:"Customers",leads:"Leads"},hu=["all","customers","leads"],Jo={all:void 0,customers:"customer",leads:"lead"};function xu({refreshKey:e,onBackToWebsite:t,className:n,maxRows:s,onViewAll:a}){let r=typeof s=="number",{people:o,isLoading:u,error:g,page:l,pageSize:i,hasNextPage:d,hasPreviousPage:b,setPage:f,q:c,setQ:m,source:p,setSource:y,refetch:S,refetchAfterRemoval:C}=Hs({refreshKey:e}),[E,v]=na.useState({kind:"list"}),[_,T]=na.useState(""),A=p==="customer"?"customers":p==="lead"?"leads":"all",N=te=>{Jo[te]!==p&&y(Jo[te])},{api:k}=ae(),L=na.useCallback(()=>k.exportPeopleCsv({...c?{q:c}:{},...p?{source:p}:{}}),[k,c,p]),P=!r||!!a,Y=te=>{if(r){a?.();return}te.email?v({kind:"person",email:te.email}):te.submission_id&&v({kind:"submission",submissionId:te.submission_id})},J=na.useRef(!1),q=()=>{J.current=!0},se=()=>{v({kind:"list"}),J.current?(J.current=!1,C()):S()},ce=te=>{let U=te.trim();U!==c&&m(U)},ge=r?o.slice(0,s):o,$;if(E.kind==="person")$=(0,w.jsx)(vu,{email:E.email,refreshKey:e,onBack:se,onRemoved:q});else if(E.kind==="submission")$=(0,w.jsx)(bu,{submissionId:E.submissionId,onBack:se,onRemoved:q});else{let te=(0,w.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.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:hu.map(U=>(0,w.jsx)("button",{type:"button","aria-pressed":A===U,onClick:()=>N(U),className:ee("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",A===U?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:yu[U]},U))}),(0,w.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,w.jsx)(yt.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,w.jsx)(pe,{type:"text",value:_,onChange:U=>T(U.target.value),onBlur:()=>ce(_),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),ce(_))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),c&&(0,w.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>{T(""),m("")},children:"Clear search"}),(0,w.jsx)(Bt,{fetchCsv:L,filename:"people",className:"af-ml-auto"})]});if(u)$=(0,w.jsxs)("div",{children:[r?null:te,(0,w.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,w.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,w.jsx)(ie,{className:"af-h-4 af-w-32"}),(0,w.jsx)(ie,{className:"af-h-4 af-w-16"})]}),(0,w.jsx)(ie,{className:"af-mt-2 af-h-5 af-w-28"}),(0,w.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-56"})]},U))}),(0,w.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,w.jsxs)(qe,{children:[(0,w.jsx)(je,{children:(0,w.jsxs)(Re,{children:[(0,w.jsx)(j,{children:"Person"}),(0,w.jsx)(j,{children:"Came from"}),(0,w.jsx)(j,{children:"Latest message"}),(0,w.jsx)(j,{children:"Last activity"}),(0,w.jsx)(j,{className:"af-w-8"}),(0,w.jsx)(j,{className:"af-w-8"})]})}),(0,w.jsx)(Ge,{"aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,w.jsxs)(Re,{children:[(0,w.jsx)(G,{children:(0,w.jsx)(ie,{className:"af-h-4 af-w-40"})}),(0,w.jsx)(G,{children:(0,w.jsx)(ie,{className:"af-h-5 af-w-24"})}),(0,w.jsx)(G,{children:(0,w.jsx)(ie,{className:"af-h-4 af-w-56"})}),(0,w.jsx)(G,{children:(0,w.jsx)(ie,{className:"af-h-4 af-w-24"})}),(0,w.jsx)(G,{}),(0,w.jsx)(G,{})]},U))})]})}),(0,w.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(g)$=(0,w.jsxs)("div",{children:[r?null:te,(0,w.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,w.jsx)(wa,{message:"Couldn't load your leads.",onRetry:()=>S()})})]});else if(ge.length===0&&l===0){let U=!!c||A!=="all";$=(0,w.jsxs)("div",{children:[U&&te,U?(0,w.jsx)(za,{children:c?"Nobody matches that search.":A==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,w.jsx)(ts,{icon:yt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)$=(0,w.jsxs)("div",{children:[r?null:te,(0,w.jsx)(za,{children:"No more results."}),(0,w.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>f(l-1),children:[(0,w.jsx)(yt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let U=l*i+1,Pe=l*i+o.length;$=(0,w.jsxs)("div",{children:[r?null:te,(0,w.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ge.map((ue,at)=>(0,w.jsxs)("div",{onClick:P?()=>Y(ue):void 0,className:`af-rounded-md af-border af-p-3${P?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,w.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,w.jsxs)("div",{className:"af-min-w-0",children:[(0,w.jsx)("button",{type:"button",onClick:Te=>{Te.stopPropagation(),Y(ue)},disabled:!P,"aria-label":`Open ${ue.name||ue.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${P?" hover:af-underline":""}`,children:Zo(ue)}),ue.name&&ue.email&&(0,w.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ue.email})]}),(0,w.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,w.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:os(ue.last_activity_at)}),ue.email&&(0,w.jsx)(R,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,w.jsx)("a",{href:bi(ue.email),onClick:Te=>Te.stopPropagation(),"aria-label":`Email ${ue.email}`,children:(0,w.jsx)(yt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,w.jsx)("div",{className:"af-mt-2",children:Ko(ue)}),ue.latest_message_excerpt&&(0,w.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:ue.latest_message_excerpt})]},ue.email??ue.submission_id??at))}),(0,w.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,w.jsxs)(qe,{children:[(0,w.jsx)(je,{children:(0,w.jsxs)(Re,{children:[(0,w.jsx)(j,{children:"Person"}),(0,w.jsx)(j,{children:"Came from"}),(0,w.jsx)(j,{children:"Latest message"}),(0,w.jsx)(j,{children:"Last activity"}),(0,w.jsx)(j,{className:"af-w-8",children:(0,w.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,w.jsx)(j,{className:"af-w-8"})]})}),(0,w.jsx)(Ge,{children:ge.map((ue,at)=>(0,w.jsxs)(Re,{onClick:P?()=>Y(ue):void 0,className:P?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,w.jsxs)(G,{className:"af-max-w-[260px] af-font-medium",children:[(0,w.jsx)("button",{type:"button",onClick:Te=>{Te.stopPropagation(),Y(ue)},disabled:!P,"aria-label":`Open ${ue.name||ue.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${P?" hover:af-underline":""}`,children:Zo(ue)}),ue.name&&ue.email&&(0,w.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:ue.email})]}),(0,w.jsx)(G,{children:Ko(ue)}),(0,w.jsx)(G,{className:"af-max-w-[320px]",children:ue.latest_message_excerpt?(0,w.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:ue.latest_message_excerpt}):(0,w.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,w.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:os(ue.last_activity_at)}),(0,w.jsx)(G,{className:"af-w-8",children:ue.email&&(0,w.jsx)(R,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,w.jsx)("a",{href:bi(ue.email),onClick:Te=>Te.stopPropagation(),"aria-label":`Email ${ue.email}`,children:(0,w.jsx)(yt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,w.jsx)(G,{className:"af-w-8 af-text-right",children:(0,w.jsx)(yt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},ue.email??ue.submission_id??at))})]})}),!r&&(0,w.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,w.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${U}-${Pe}`}),(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>f(l-1),disabled:!b,children:[(0,w.jsx)(yt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>f(l+1),disabled:!d,children:["Next",(0,w.jsx)(yt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?(0,w.jsx)("div",{className:n,children:$}):(0,w.jsx)(wt,{title:"Leads",onBackToWebsite:t,hideBackButton:E.kind!=="list",className:n,children:$})}function qs(e){return(0,w.jsx)(xu,{...e},e.maxRows==null?"full":"compact")}var al=re(require("react"),1),zn=require("lucide-react");var sa=re(require("react"),1);function js({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ae(),[s,a]=sa.useState([]),[r,o]=sa.useState(0),[u,g]=sa.useState(!0),[l,i]=sa.useState(null),[d,b]=sa.useState(0),[f,c]=sa.useState(e),[m,p]=sa.useState(void 0),y=sa.useRef(0),S=sa.useCallback(async()=>{let E=++y.current;try{g(!0),i(null);let v={limit:f,offset:d*f};m&&(v.status=m);let _=await n.getSubscriptions(v);if(E!==y.current)return;a(_.subscriptions),o(_.total)}catch(v){if(E!==y.current)return;i(v instanceof Error?v:new Error("Failed to fetch subscriptions"))}finally{E===y.current&&g(!1)}},[n,d,f,m,t]);sa.useEffect(()=>{S()},[S]);let C=Math.ceil(r/f);return{subscriptions:s,total:r,isLoading:u,error:l,page:d,pageSize:f,hasNextPage:d<C-1,hasPreviousPage:d>0,setPage:b,setPageSize:E=>{c(E),b(0)},status:m,setStatus:E=>{p(E),b(0)},refetch:S}}var V=require("react/jsx-runtime");function Xo(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 Qo({sub:e}){return e.status==="canceled"?(0,V.jsx)(ne,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,V.jsx)(ne,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,V.jsx)(ne,{variant:"warning",children:"Scheduled to cancel"}):(0,V.jsx)(ne,{variant:"success",children:"Active"}):(0,V.jsx)(ne,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function wu(e,t){let n=K(t,e.currency);return e.plan_interval_count===1?`${n} / ${e.plan_interval}`:`${n} every ${e.plan_interval_count} ${e.plan_interval}s`}function el({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-font-medium af-tabular-nums",children:wu(e,e.current_amount)}),t&&(0,V.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",K(e.plan_amount,e.currency)]})]})}function tl(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Xo(e.current_period_end)}`:"Ends at period end":e.current_period_end?Xo(e.current_period_end):"\u2014"}function yi({refreshKey:e,onBackToWebsite:t,className:n}){let{subscriptions:s,total:a,isLoading:r,error:o,page:u,pageSize:g,hasNextPage:l,hasPreviousPage:i,setPage:d,status:b,refetch:f}=js({refreshKey:e}),{api:c}=ae(),m=al.useCallback(()=>c.exportSubscriptionsCsv(b?{status:b}:{}),[c,b]),p;if(r)p=(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(y=>(0,V.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,V.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,V.jsx)(ie,{className:"af-h-4 af-w-40"}),(0,V.jsx)(ie,{className:"af-h-4 af-w-20"})]}),(0,V.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-32"}),(0,V.jsx)(ie,{className:"af-mt-2 af-h-5 af-w-24"})]},y))}),(0,V.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,V.jsxs)(qe,{children:[(0,V.jsx)(je,{children:(0,V.jsxs)(Re,{children:[(0,V.jsx)(j,{children:"Subscriber"}),(0,V.jsx)(j,{children:"Plan"}),(0,V.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,V.jsx)(j,{children:"Renews"}),(0,V.jsx)(j,{children:"Status"})]})}),(0,V.jsx)(Ge,{"aria-hidden":"true",children:[0,1,2,3,4].map(y=>(0,V.jsxs)(Re,{children:[(0,V.jsx)(G,{children:(0,V.jsx)(ie,{className:"af-h-4 af-w-44"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ie,{className:"af-h-4 af-w-32"})}),(0,V.jsx)(G,{className:"af-text-right",children:(0,V.jsx)(ie,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ie,{className:"af-h-4 af-w-24"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ie,{className:"af-h-5 af-w-20"})})]},y))})]})}),(0,V.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=(0,V.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,V.jsx)(wa,{message:"Couldn't load your subscriptions.",onRetry:()=>f()})});else if(s.length===0&&u===0)p=(0,V.jsx)(za,{icon:(0,V.jsx)(zn.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(s.length===0)p=(0,V.jsxs)("div",{children:[(0,V.jsx)(za,{children:"No more results."}),(0,V.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,V.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>d(u-1),children:[(0,V.jsx)(zn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let y=u*g+1,S=u*g+s.length;p=(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,V.jsx)(Bt,{fetchCsv:m,filename:"subscriptions"})}),(0,V.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(C=>(0,V.jsxs)("div",{className:"af-rounded-md af-border 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",children:C.customer_email||(0,V.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,V.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:C.plan_title||"Untitled plan"})]}),(0,V.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,V.jsx)(el,{sub:C})})]}),(0,V.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Qo,{sub:C}),C.is_test&&(0,V.jsx)(ne,{variant:"outline",children:"Test"}),(0,V.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:tl(C)})]}),(0,V.jsx)(Ka,{deliveries:C.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},C.id))}),(0,V.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,V.jsxs)(qe,{children:[(0,V.jsx)(je,{children:(0,V.jsxs)(Re,{children:[(0,V.jsx)(j,{children:"Subscriber"}),(0,V.jsx)(j,{children:"Plan"}),(0,V.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,V.jsx)(j,{children:"Renews"}),(0,V.jsx)(j,{children:"Status"})]})}),(0,V.jsx)(Ge,{children:s.map(C=>(0,V.jsxs)(Re,{children:[(0,V.jsx)(G,{className:"af-max-w-[240px]",children:(0,V.jsx)("div",{className:"af-truncate af-font-medium",children:C.customer_email||(0,V.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,V.jsx)(G,{className:"af-max-w-[220px]",children:(0,V.jsx)("div",{className:"af-truncate",children:C.plan_title||(0,V.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,V.jsx)(G,{className:"af-whitespace-nowrap af-text-right",children:(0,V.jsx)(el,{sub:C})}),(0,V.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:tl(C)}),(0,V.jsxs)(G,{children:[(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Qo,{sub:C}),C.is_test&&(0,V.jsx)(ne,{variant:"outline",children:"Test"})]}),(0,V.jsx)(Ka,{deliveries:C.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},C.id))})]})}),(0,V.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,V.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${y}-${S} of ${a}`}),(0,V.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,V.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>d(u-1),disabled:!i,children:[(0,V.jsx)(zn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,V.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>d(u+1),disabled:!l,children:["Next",(0,V.jsx)(zn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,V.jsx)(wt,{title:"Subscriptions",onBackToWebsite:t,className:n,children:p})}var sn=re(require("react"),1),bl=require("lucide-react");var zt=re(require("react"),1);var Lr=re(require("react"),1),qn=typeof window>"u"?Lr.useEffect:Lr.useLayoutEffect;var Or=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},Su=(e,t)=>e instanceof Error?e:new Error(t);function Nu(e){let t={};return e.due_days!==void 0&&(t.invoice_due_days=e.due_days),e.reminder_schedule!==void 0&&(t.invoice_reminder_schedule=e.reminder_schedule),e.footer!==void 0&&(t.invoice_footer=e.footer),t}function nl(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function gn({siteId:e,refreshKey:t,onSaveInvoiceSettings:n}){let{api:s}=ae(),[a,r]=zt.useState(null),[o,u]=zt.useState(!0),[g,l]=zt.useState(null),i=zt.useRef(null),[d,b]=zt.useState(()=>nl(s,e)),f=d.api!==s||d.siteId!==e,c=d;f&&(c=nl(s,e),b(c),r(null),u(!0),l(null));let m=zt.useRef(c);qn(()=>{m.current!==c&&(m.current=c,i.current=null)},[c]);let p=(N,k)=>m.current===N&&k>N.applied,y=(N,k,L)=>p(N,k)?(N.applied=k,i.current=L,r(L),u(!1),!0):!1,S=async N=>{for(;N.writing;)await N.idle;let k=++N.seq;try{let L=await N.api.getSite(N.siteId);return y(N,k,L)&&l(null),{seq:k,error:null}}catch(L){return{seq:k,error:Su(L,"Failed to load store settings")}}},C=(N,k)=>{let L=async()=>{if(m.current!==N)throw new Error("Not saved: the store switched to another site first.");N.writing=!0,N.idle=new Promise(Y=>{N.markIdle=Y});try{return await k(++N.seq)}finally{N.writing=!1,N.markIdle()}},P=N.queue.then(L,L);return N.queue=P.catch(()=>{}),P},E=zt.useCallback(async()=>{let N=await S(c);N.error&&p(c,N.seq)&&(l(N.error),u(!1))},[c]);zt.useEffect(()=>{E()},[E,t]);let v=zt.useCallback(N=>C(c,async k=>{let L=await c.api.updateSite(c.siteId,N),{currency_restatement:P,...Y}=L;return y(c,k,Y)&&l(J=>J instanceof Or?J:null),L}),[c]),_=zt.useRef(n);qn(()=>{_.current=n});let T=zt.useCallback(async(N,k)=>{await C(c,()=>N());let L=await S(c);return L.error&&p(c,L.seq)&&i.current&&(y(c,L.seq,{...i.current,...k}),l(new Or(`Saved, but couldn't refresh settings: ${L.error.message}`))),m.current===c?i.current:null},[c]),A=zt.useCallback(N=>{let k=_.current;return T(()=>k(N),Nu(N))},[T]);return{site:f?null:a,isLoading:f||o,error:f?null:g,refetch:E,updateSite:v,saveInvoiceSettings:n?A:null}}var Ct=re(require("react"),1),wi=require("lucide-react");var it=require("react/jsx-runtime");function Br(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var qa="af-grid af-gap-1 af-text-sm",sl="af-h-9 af-rounded-md af-border af-border-input af-bg-background af-px-3 af-text-sm disabled:af-cursor-not-allowed disabled:af-opacity-50",rl="af-min-h-[72px] 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 disabled:af-cursor-not-allowed disabled:af-opacity-50";function ra({children:e}){return(0,it.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Gs({children:e}){return(0,it.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var nn=Ct.forwardRef(function({id:t,title:n,description:s,children:a},r){let o=`af-store-${t}-title`;return(0,it.jsxs)("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":o,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[(0,it.jsxs)("div",{className:"af-space-y-1",children:[(0,it.jsx)("h3",{id:o,className:"af-text-sm af-font-semibold",children:n}),s&&(0,it.jsx)(ra,{children:s})]}),a]})});function Si({label:e,description:t,checked:n,onSave:s,disabled:a=!1,disabledReason:r}){let[o,u]=Ct.useState(null),[g,l]=Ct.useState(null),i=o??n,d=async b=>{u(b),l(null);try{await s(b)}catch(f){l(Br(f))}finally{u(null)}};return(0,it.jsxs)("div",{className:"af-space-y-1",children:[(0,it.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,it.jsx)("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":i,checked:i,disabled:a||o!==null,onChange:b=>void d(b.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),(0,it.jsxs)("span",{className:"af-space-y-0.5",children:[(0,it.jsxs)("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,o!==null&&(0,it.jsx)(wi.Loader2,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&(0,it.jsx)(ra,{children:t})]})]}),(a&&r||g)&&(0,it.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[a&&r&&(0,it.jsx)(ra,{children:r}),g&&(0,it.jsx)(Gs,{children:g})]})]})}var xi=(e,t)=>JSON.stringify(e)===JSON.stringify(t),hi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ru(e,t,n,s=[]){if(!hi(e)||!hi(t)||!hi(n))return{draft:xi(e,t)?n:e,dropped:[]};let a=[],r={...n};for(let o of Object.keys(n))xi(e[o],t[o])||(s.includes(o)?a.push(o):r[o]=e[o]);return{draft:r,dropped:a}}function ls(e,t){let n=JSON.stringify(e),[s,a]=Ct.useState(e),[r,o]=Ct.useState([]),u=Ct.useRef(e),g=Ct.useRef(e),l=Ct.useRef(s);qn(()=>{g.current=e,l.current=s});let i=Ct.useRef(t?.when);Ct.useEffect(()=>{let b=Object.is(i.current,t?.when)?[]:t?.fields??[];if(i.current=t?.when,xi(u.current,g.current)&&b.length===0)return;let f=Ru(l.current,u.current,g.current,b);u.current=g.current,a(f.draft),f.dropped.length&&o(f.dropped)},[n,t?.when]);let d=Ct.useCallback(b=>{a(b??g.current),o([])},[]);return{draft:s,setDraft:a,dirty:JSON.stringify(s)!==n,reset:d,dropped:r}}function cs({dirty:e,saving:t,error:n,onSave:s,onDiscard:a}){return e?(0,it.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,it.jsxs)(R,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&(0,it.jsx)(wi.Loader2,{className:"af-animate-spin"}),"Save"]}),(0,it.jsx)(R,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:a,children:"Discard"}),n&&(0,it.jsx)("p",{role:"alert",className:ee("af-text-sm af-text-destructive"),children:n})]}):null}function us(){let[e,t]=Ct.useState(!1),[n,s]=Ct.useState(null),a=Ct.useCallback(async r=>{t(!0),s(null);try{await r()}catch(o){s(Br(o))}finally{t(!1)}},[]);return{saving:e,error:n,setError:s,run:a}}function il({what:e}){return(0,it.jsxs)(ra,{children:["Only the site owner can change ",e,"."]})}var Ba=re(require("react"),1),jn=require("lucide-react");var H=require("react/jsx-runtime"),Ri=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ul({site:e,updateSite:t}){return(0,H.jsx)("div",{className:"af-space-y-4",children:(0,H.jsx)(Si,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:n=>t({collect_phone_at_checkout:n})})})}function ol(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(nt(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(nt(e.free_shipping_over,e.currency))}}function dl({site:e,updateSite:t,refetch:n,providerSlot:s,currencyChanging:a=!1}){let{draft:r,setDraft:o,dirty:u,reset:g,dropped:l}=ls(ol(e),{when:e.currency,fields:["rates","threshold"]}),{saving:i,error:d,setError:b,run:f}=us(),c=e.currency.toUpperCase(),m=()=>f(async()=>{let y={},S=[...new Set(r.countries.split(/[\s,]+/).map(N=>N.trim().toUpperCase()).filter(Boolean))],C=S.find(N=>!/^[A-Z]{2}$/.test(N));if(C)throw new Error(`"${C}" isn't a two-letter country code (e.g. US, CA).`);let E=S.length?S:null;Ri(E,e.shipping_countries)||(y.shipping_countries=E);let v=[];for(let N of r.rates){let k=N.label.trim(),L=It(N.amount,e.currency);if(!k)throw new Error("Every rate needs a name.");if(N.amount.trim()===""||L===null)throw new Error(`Enter a price for "${k}" (0 for free).`);v.push({label:k,amount:L})}let _=v.length?v:null;Ri(_,e.shipping_rates)||(y.shipping_rates=_);let T=null;if(r.threshold.trim()!==""&&(T=It(r.threshold,e.currency),T===null||T===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(T!==e.free_shipping_over&&(y.free_shipping_over=T),Object.keys(y).length===0){g();return}("shipping_rates"in y||"free_shipping_over"in y)&&(y.expected_currency=e.currency);let A;try{A=await t(y)}catch(N){throw N instanceof ht&&N.details?.code==="currency_changed"&&await n?.(),N}g(ol(A))}),p=(y,S)=>o({...r,rates:r.rates.map((C,E)=>E===y?{...C,...S}:C)});return(0,H.jsxs)("fieldset",{disabled:i||a,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:qa,children:["Countries you ship to",(0,H.jsx)(pe,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:y=>o({...r,countries:y.target.value})}),(0,H.jsx)(ra,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),(0,H.jsxs)("div",{className:"af-space-y-2",children:[(0,H.jsxs)("p",{className:"af-text-sm",children:["Flat shipping rates (",c,")"]}),r.rates.length===0&&(0,H.jsx)(ra,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((y,S)=>(0,H.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,H.jsx)(pe,{"aria-label":`Rate ${S+1} name`,value:y.label,placeholder:"Standard",onChange:C=>p(S,{label:C.target.value})}),(0,H.jsx)(pe,{"aria-label":`Rate ${S+1} price`,type:"number",min:"0",step:"any",value:y.amount,placeholder:"0",className:"af-w-32",onChange:C=>p(S,{amount:C.target.value})}),(0,H.jsx)(R,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${S+1}`,onClick:()=>o({...r,rates:r.rates.filter((C,E)=>E!==S)}),children:(0,H.jsx)(jn.X,{})})]},S)),(0,H.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>o({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[(0,H.jsx)(jn.Plus,{})," Add rate"]}),(0,H.jsx)(ra,{children:"Buyers pick one at checkout. The first is preselected."})]}),(0,H.jsxs)("label",{className:qa,children:["Free shipping over (",c,")",(0,H.jsx)(pe,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:y=>o({...r,threshold:y.target.value})}),(0,H.jsx)(ra,{children:"Orders at or above this get the cheapest rate free."})]}),l.length>0&&(0,H.jsxs)("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",c,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),(0,H.jsx)(cs,{dirty:u,saving:i,error:d,onSave:()=>void m(),onDiscard:()=>{b(null),g()}}),s]})}var Ni="exclusive",_u=[{href:"https://docs.stripe.com/tax/set-up",label:"Set up Stripe Tax"},{href:"https://docs.stripe.com/tax/registering",label:"Add tax registrations"},{href:"https://docs.stripe.com/tax/zero-tax",label:"Why tax can be zero"},{href:"https://stripe.com/tax/pricing",label:"Stripe Tax pricing"}];function Pu({href:e,children:t}){return(0,H.jsxs)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"af-inline-flex af-items-center af-gap-1 af-font-medium af-underline af-underline-offset-2 hover:af-text-foreground",children:[t,(0,H.jsx)(jn.ExternalLink,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function fl({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(e.tax_behavior??Ni),{saving:o,error:u,setError:g,run:l}=us(),[i,d]=Ba.useState(!1),b=e.stripe_tax_enabled,f=b||i,c=()=>l(async()=>{let y=n;if(y===e.tax_behavior){r();return}let S={tax_behavior:y};y!=="inclusive"&&e.tax_rate_bps!=null&&(S.tax_rate_bps=null);let C=await t(S);r(C.tax_behavior??Ni)}),m=()=>l(async()=>{let y={stripe_tax_enabled:!0,tax_behavior:n};n!=="inclusive"&&e.tax_rate_bps!=null&&(y.tax_rate_bps=null);let S=await t(y);r(S.tax_behavior??Ni),d(!1)}),p=(a||i)&&n!=="inclusive"&&e.tax_rate_bps!=null;return(0,H.jsxs)("div",{className:"af-space-y-5",children:[(0,H.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[(0,H.jsx)("p",{children:"Tax at checkout is calculated by Stripe Tax, which you set up in your Stripe Dashboard (Settings \u2192 Tax): your business address, a default product tax code, and the places you're registered to collect tax."}),(0,H.jsx)("p",{children:"Stripe only collects tax where you've added a registration; anywhere else the tax comes out as zero. Stripe Tax has its own fees, and what it covers (such as filing) depends on your Stripe Tax plan."}),(0,H.jsx)("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:_u.map(y=>(0,H.jsx)("li",{children:(0,H.jsx)(Pu,{href:y.href,children:y.label})},y.href))})]}),(0,H.jsx)(Si,{label:"Stripe automatic tax",description:b?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:f,onSave:async y=>{if(i){d(!1),g(null),r();return}if(y&&!e.tax_behavior){d(!0);return}return t({stripe_tax_enabled:y})}}),f&&(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4 af-pl-6",children:[(0,H.jsxs)("label",{className:qa,children:["Do your prices already include tax?",(0,H.jsxs)("select",{"aria-label":"Your prices",className:sl,value:n,onChange:y=>s(y.target.value),children:[(0,H.jsx)("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),(0,H.jsx)("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),(0,H.jsx)(ra,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),p&&(0,H.jsxs)(ra,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),i?(0,H.jsxs)("div",{className:"af-space-y-2",children:[(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(R,{type:"button",size:"sm",disabled:o,onClick:()=>void m(),children:"Turn on"}),(0,H.jsx)(R,{type:"button",size:"sm",variant:"outline",disabled:o,onClick:()=>{d(!1),g(null),r()},children:"Cancel"})]}),u&&(0,H.jsx)(Gs,{children:u})]}):(0,H.jsx)(cs,{dirty:a,saving:o,error:u,onSave:()=>void c(),onDiscard:()=>{g(null),r()}})]})]})}function ll(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function ml({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(ll(e)),{saving:o,error:u,setError:g,run:l}=us(),i=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),d=()=>l(async()=>{let b={},f=null;if(i&&n.rate.trim()!==""){let y=Number(n.rate);if(!Number.isFinite(y)||y<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");f=Math.round(y*100)}i&&f!==e.tax_rate_bps&&(b.tax_rate_bps=f),f!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let c=n.taxId.trim()||null;c!==e.tax_id&&(b.tax_id=c);let m=n.label.trim()||null;if(m!==e.tax_label&&(b.tax_label=m),Object.keys(b).length===0){r();return}let p=await t(b);r(ll(p))});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:qa,children:["Tax rate (%)",(0,H.jsx)(pe,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!i,value:i?n.rate:"",onChange:b=>s({...n,rate:b.target.value})}),(0,H.jsx)(ra,{children:i?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),(0,H.jsxs)("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[(0,H.jsxs)("label",{className:qa,children:["Tax ID",(0,H.jsx)(pe,{"aria-label":"Tax ID",value:n.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...n,taxId:b.target.value})})]}),(0,H.jsxs)("label",{className:qa,children:["Tax label",(0,H.jsx)(pe,{"aria-label":"Tax label",value:n.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...n,label:b.target.value})})]})]}),(0,H.jsx)(cs,{dirty:a,saving:o,error:u,onSave:()=>void d(),onDiscard:()=>{g(null),r()}})]})}function pl({site:e,updateSite:t,onChangeStart:n}){let[s,a]=Ba.useState(e.currency.toUpperCase()),[r,o]=Ba.useState(!1),[u,g]=Ba.useState(!1),[l,i]=Ba.useState(null),d=e.currency.toUpperCase(),b=Ba.useRef(d);Ba.useEffect(()=>{b.current!==d&&(a(y=>y===b.current?d:y),b.current=d)},[d]);let f=s.trim().toUpperCase(),c=f!==d,m=/^[A-Z]{3}$/.test(f),p=async()=>{g(!0);let y=n?.(),S=!1;i(null);try{let C=await t({currency:f.toLowerCase()});S=!0;let E=C.currency_restatement;E&&!E.applied?i(E.reason?`Not changed: ${E.reason}.`:"The currency was not changed."):(a(C.currency.toUpperCase()),b.current=C.currency.toUpperCase()),o(!1)}catch(C){i(Br(C))}finally{g(!1),y?.(S)}};return(0,H.jsxs)("div",{className:"af-space-y-3",children:[(0,H.jsxs)("div",{className:"af-flex af-items-end af-gap-2",children:[(0,H.jsxs)("label",{className:qa,children:["Store currency",(0,H.jsx)(pe,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:u||r,onChange:y=>{a(y.target.value),i(null)}})]}),c&&!r&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(R,{type:"button",size:"sm",disabled:!m,onClick:()=>o(!0),children:"Change currency"}),(0,H.jsx)(R,{type:"button",size:"sm",variant:"ghost",onClick:()=>{a(d),i(null)},children:"Discard"})]})]}),(0,H.jsx)(ra,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&(0,H.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,H.jsxs)("p",{className:"af-text-sm",children:["Change the store currency from ",d," to ",f,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",f,":"," ",K(2e3,d)," becomes ",K(2e3,f),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(R,{type:"button",size:"sm",disabled:u,onClick:()=>void p(),children:"Confirm change"}),(0,H.jsx)(R,{type:"button",size:"sm",variant:"ghost",disabled:u,onClick:()=>o(!1),children:"Cancel"})]})]}),l&&(0,H.jsx)(Gs,{children:l})]})}function cl(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function Cu(e){return e.length===0?"Off":e.map(t=>t===0?"on the due date":t<0?`${-t} day${t===-1?"":"s"} before`:`${t} day${t===1?"":"s"} after`).join(", ")}function gl({site:e,save:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(cl(e)),{saving:o,error:u,setError:g,run:l}=us();if(!t)return(0,H.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,H.jsxs)("p",{children:["Due ",e.invoice_due_days," days after sending"]}),(0,H.jsxs)("p",{children:["Reminders: ",Cu(e.invoice_reminder_schedule)]}),(0,H.jsxs)("p",{children:["Footer: ",e.invoice_footer||"None"]}),(0,H.jsx)(il,{what:"invoice defaults"})]});let i=()=>l(async()=>{let d={},b=Number(n.dueDays);if(n.dueDays.trim()===""||!Number.isInteger(b)||b<0||b>90)throw new Error("Due days must be a whole number from 0 to 90.");b!==e.invoice_due_days&&(d.due_days=b);let c=n.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(c.some(S=>!Number.isInteger(S)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let m=[...new Set(c)].sort((S,C)=>S-C);Ri(m,e.invoice_reminder_schedule)||(d.reminder_schedule=m);let p=n.footer.trim()||null;if(p!==e.invoice_footer&&(d.footer=p),Object.keys(d).length===0){r();return}let y=await t(d);r(y?cl(y):void 0)});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:qa,children:["Days until due",(0,H.jsx)(pe,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:n.dueDays,onChange:d=>s({...n,dueDays:d.target.value})})]}),(0,H.jsxs)("label",{className:qa,children:["Reminder schedule",(0,H.jsx)(pe,{"aria-label":"Reminder schedule",value:n.reminders,placeholder:"Off",onChange:d=>s({...n,reminders:d.target.value})}),(0,H.jsx)(ra,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),(0,H.jsxs)("label",{className:qa,children:["Invoice footer",(0,H.jsx)("textarea",{"aria-label":"Invoice footer",className:rl,maxLength:300,value:n.footer,onChange:d=>s({...n,footer:d.target.value})})]}),(0,H.jsx)(cs,{dirty:a,saving:o,error:u,onSave:()=>void i(),onDiscard:()=>{g(null),r()}})]})}function vl({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(e.default_email_recipients),{saving:o,error:u,setError:g,run:l}=us(),[i,d]=Ba.useState(""),[b,f]=Ba.useState(null),c=()=>{let p=i.trim().toLowerCase();if(p){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p)){f("Enter a valid email address.");return}if(n.some(y=>y.toLowerCase()===p)){f("Already added.");return}s([...n,p]),d(""),f(null)}},m=()=>l(async()=>{let p=await t({default_email_recipients:n});r(p.default_email_recipients)});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-3",children:[(0,H.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[n.map(p=>(0,H.jsxs)(ne,{variant:"secondary",className:"af-gap-1",children:[p,(0,H.jsx)("button",{type:"button","aria-label":`Remove ${p}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(n.filter(y=>y!==p)),children:(0,H.jsx)(jn.X,{className:"af-h-3 af-w-3"})})]},p)),n.length===0&&(0,H.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(pe,{"aria-label":"Add notification email",type:"email",value:i,placeholder:"Add email address",onChange:p=>{d(p.target.value),f(null)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),c())}}),(0,H.jsx)(R,{type:"button",variant:"outline",disabled:!i.trim(),onClick:c,children:"Add"})]}),b&&(0,H.jsx)(Gs,{children:b}),(0,H.jsx)(cs,{dirty:a,saving:o,error:u,onSave:()=>void m(),onDiscard:()=>{g(null),r()}})]})}var Ft=require("react/jsx-runtime");function _i({siteId:e,refreshKey:t,section:n,shippingProviderSlot:s,onConnectStripe:a,onUpgradePlan:r,className:o}){let{site:u,isLoading:g,error:l,refetch:i,updateSite:d}=gn({siteId:e,refreshKey:t}),b=sn.useRef(i),f=sn.useRef(e);qn(()=>{b.current=i,f.current=e});let c=sn.useRef({}),[m,p]=sn.useState([]),y=m.some(_=>_.siteId===e),S=sn.useCallback(()=>{let _={siteId:e},T=b.current;return p(A=>[...A,_]),A=>{let N=()=>p(L=>L.filter(P=>P!==_));!(f.current===_.siteId)||A&&b.current===T?N():b.current().finally(N)}},[e]),C=_=>T=>{c.current[_]=T},E=u!==null&&u.payments_active;if(sn.useEffect(()=>{if(!E||!n)return;let _=c.current[n];_&&(_.scrollIntoView?.({behavior:"smooth",block:"start"}),_.focus({preventScroll:!0}))},[E,n]),g)return(0,Ft.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Ft.jsx)(bl.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!u)return(0,Ft.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l?.message??"Could not load store settings."});if(!u.payments_active)return(0,Ft.jsx)(Mn,{className:o,onConnectStripe:a,onUpgradePlan:r,whenActive:(0,Ft.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let v={site:u,updateSite:d,refetch:i};return(0,Ft.jsxs)("div",{className:`af-space-y-6 ${o??""}`,children:[l&&(0,Ft.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l.message}),(0,Ft.jsx)(nn,{ref:C("checkout"),id:"checkout",title:"Checkout",children:(0,Ft.jsx)(ul,{...v})}),(0,Ft.jsx)(nn,{ref:C("shipping"),id:"shipping",title:"Shipping",children:(0,Ft.jsx)(dl,{...v,providerSlot:s,currencyChanging:y})}),(0,Ft.jsx)(nn,{ref:C("tax"),id:"tax",title:"Tax",children:(0,Ft.jsx)(fl,{...v})}),(0,Ft.jsx)(nn,{ref:C("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:(0,Ft.jsx)(pl,{...v,onChangeStart:S})})]},e)}var yl=require("lucide-react");var ja=require("react/jsx-runtime");function Ws({siteId:e,refreshKey:t,onSaveInvoiceSettings:n,className:s}){let{site:a,isLoading:r,error:o,updateSite:u,refetch:g,saveInvoiceSettings:l}=gn({siteId:e,refreshKey:t,onSaveInvoiceSettings:n});return r?(0,ja.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ja.jsx)(yl.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):a?(0,ja.jsxs)("div",{className:`af-space-y-6 ${s??""}`,children:[o&&(0,ja.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o.message}),(0,ja.jsx)(nn,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:(0,ja.jsx)(gl,{site:a,save:l})}),(0,ja.jsx)(nn,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:(0,ja.jsx)(ml,{site:a,updateSite:u,refetch:g})})]},e):(0,ja.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o?.message??"Could not load invoice settings."})}var hl=require("lucide-react");var vn=require("react/jsx-runtime");function Pi({siteId:e,refreshKey:t,className:n}){let{site:s,isLoading:a,error:r,updateSite:o,refetch:u}=gn({siteId:e,refreshKey:t});return a?(0,vn.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,vn.jsx)(hl.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?(0,vn.jsxs)("div",{className:`af-space-y-3 ${n??""}`,children:[r&&(0,vn.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r.message}),(0,vn.jsx)(nn,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:(0,vn.jsx)(vl,{site:s,updateSite:o,refetch:u})})]},e):(0,vn.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r?.message??"Could not load notification settings."})}var ds=re(require("react"),1);var Je=require("react/jsx-runtime");function Ci({refreshKey:e,initialInvoiceId:t,onBackToWebsite:n,onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:r,siteId:o,onSaveInvoiceSettings:u,className:g}){let{aggregates:l,isLoading:i,error:d,refetch:b}=Fn({refreshKey:e,initialPageSize:1,includeAggregates:!0}),f=Vn({refreshKey:e}),{api:c}=ae(),m=f.filters,p=ds.useCallback(()=>c.exportRetainersCsv(m),[c,m]),[y,S]=ds.useState(!1),[C,E]=ds.useState(null),[v,_]=ds.useState(!1),T=(0,Je.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:d||!i&&!l?(0,Je.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,Je.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):i||!l?(0,Je.jsxs)(Je.Fragment,{children:[(0,Je.jsx)(dt,{label:"Outstanding",children:(0,Je.jsx)(ie,{className:"af-h-6 af-w-24"})}),(0,Je.jsx)(dt,{label:"Overdue",children:(0,Je.jsx)(ie,{className:"af-h-6 af-w-24"})}),(0,Je.jsx)(dt,{label:"Paid this month",children:(0,Je.jsx)(ie,{className:"af-h-6 af-w-24"})})]}):(0,Je.jsxs)(Je.Fragment,{children:[(0,Je.jsx)(dt,{label:"Outstanding",detail:`${l.outstanding.count} open`,children:K(l.outstanding.amount,l.currency)}),(0,Je.jsx)(dt,{label:"Overdue",detail:l.overdue.count===0?"Nothing overdue":`${l.overdue.count} overdue`,valueClassName:l.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:K(l.overdue.amount,l.currency)}),(0,Je.jsx)(dt,{label:"Paid this month",detail:`${l.paid_this_month.count} paid`,children:K(l.paid_this_month.amount,l.currency)})]})});return(0,Je.jsxs)(wt,{title:"Invoices",onBackToWebsite:n,hideBackButton:y,className:g,children:[T,o&&!y&&(0,Je.jsxs)("div",{className:"af-mb-6",children:[(0,Je.jsx)(R,{type:"button",variant:"outline",size:"sm","aria-expanded":v,"aria-controls":"af-invoice-settings",onClick:()=>_(A=>!A),children:"Invoice settings"}),v&&(0,Je.jsx)("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:(0,Je.jsx)(Ws,{siteId:o,refreshKey:e,onSaveInvoiceSettings:u})})]}),!y&&(0,Je.jsx)(Un,{retainers:f.retainers,isLoading:f.isLoading,error:f.error,onRetry:()=>void f.refetch(),activeRetainerId:C?.id??null,onShowCycles:A=>E(N=>N?.id===A.id?null:A),total:f.total,endedTotal:f.endedTotal,isLoadingMore:f.isLoadingMore,onLoadMore:()=>void f.loadMore(),includeEnded:f.includeEnded,onIncludeEndedChange:f.setIncludeEnded,exportCsv:p}),(0,Je.jsx)(pn,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:S,onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:r,retainerFilter:C?{id:C.id,label:`${C.customer_name??C.customer_email??"Recurring invoices"} \u2014 ${C.description}`}:null,onClearRetainerFilter:()=>E(null)})]})}var Tt=re(require("react"),1);var Tu=2e3,Ut=()=>({data:null,error:null,isLoading:!0});function Gn(e,{refreshKey:t,breakdowns:n=[],filters:s=[]}={}){let{api:a}=ae(),[r,o]=Tt.useState(Ut),[u,g]=Tt.useState(Ut),[l,i]=Tt.useState(Ut),[d,b]=Tt.useState(Ut),[f,c]=Tt.useState(Ut),m=$=>Object.fromEntries($.map(te=>[te,Ut()])),[p,y]=Tt.useState(()=>m(n)),S=Tt.useRef(0),C=Tt.useRef(0),E=Tt.useRef("idle"),v=n.join(","),_=hn()??"",T=JSON.stringify(s),A=`${e}:${v}:${T}:${_}`,[N,k]=Tt.useState({api:a,fetchIdentity:A});(N.api!==a||N.fetchIdentity!==A)&&(k({api:a,fetchIdentity:A}),S.current+=1,o(Ut),g(Ut),i(Ut),b(Ut),y(m(v?v.split(","):[])));let L=`${e}:${String(t??"")}:${_}`,[P,Y]=Tt.useState({api:a,conversionsIdentity:L});(P.api!==a||P.conversionsIdentity!==L)&&(Y({api:a,conversionsIdentity:L}),C.current+=1,E.current="idle",c(Ut));let J=Tt.useCallback(async $=>{let te=++S.current,U=v?v.split(","):[];o(Ut),g(Ut),i(Ut),b(Ut),y(Object.fromEntries(U.map(D=>[D,Ut()])));let Pe=E.current!=="pending"&&($?.force===!0||E.current==="idle"),ue=(D,M)=>M.then(F=>{te===S.current&&D({data:F,error:null,isLoading:!1})},F=>{te===S.current&&D({data:null,error:F instanceof Error?F:new Error("Failed to fetch report"),isLoading:!1})}),at=a.getAnalyticsStatus(),Te=ue(o,at),He=Symbol("status-timeout"),Ye,Le=await Promise.race([at.then(D=>D,()=>null),new Promise(D=>{Ye=setTimeout(()=>D(He),Tu)})]);if(clearTimeout(Ye),te!==S.current)return;if(Le===He&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Le!==null&&Le!==He&&(Le.collecting!==!0||Le.first_seen===null&&!Le.first_seen_unavailable||Le.first_seen!==null&&Le.first_seen_in_reports===!1)){let D={data:null,error:null,isLoading:!1};g(D),i(D),b(D),y(Object.fromEntries(U.map(M=>[M,{...D}]))),Pe&&(c(D),E.current="done"),await Te;return}await Promise.all([Le===He?Promise.resolve():Te,ue(g,a.getAnalyticsSummary(e,s)),ue(i,a.getAnalyticsTimeseries(e,s)),ue(b,a.getAnalyticsChannels(e,s)),Pe?(()=>{E.current="pending";let D=++C.current;return c(Ut),a.getAnalyticsConversions(e).then(M=>{D===C.current&&(c({data:M,error:null,isLoading:!1}),E.current="done")},M=>{D===C.current&&(c({data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}),E.current="done")})})():Promise.resolve(),...U.map(D=>a.getAnalyticsBreakdown(D,e,s).then(M=>{te===S.current&&y(F=>({...F,[D]:{data:M,error:null,isLoading:!1}}))},M=>{te===S.current&&y(F=>({...F,[D]:{data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[a,e,v,T,L,_]),q=Tt.useCallback(async()=>{let $=S.current;try{let te=await a.getAnalyticsStatus();if($!==S.current)return;o({data:te,error:null,isLoading:!1})}catch(te){if($!==S.current)return;o(U=>({data:U.data,error:te instanceof Error?te:new Error("Failed to fetch status"),isLoading:!1}))}},[a]),se=Tt.useCallback(()=>J({force:!0}),[J]);Tt.useEffect(()=>{J()},[J,t]);let ce=r.isLoading||u.isLoading||l.isLoading||d.isLoading||f.isLoading||Object.values(p).some($=>$.isLoading),ge=[l,u,d,f,...Object.values(p)].map($=>$.data?.status==="ok"?$.data.timezone:void 0).find($=>$!==void 0);return{status:r,summary:u,timeseries:l,channels:d,conversions:f,breakdowns:p,reportedZone:ge,isLoading:ce,refetch:se,refetchStatus:q}}var kt=re(require("react"),1);var Fr=3e4,Ur=3;function Ks(e={}){let t="collecting"in e,{collecting:n,statusFailed:s=!1,identity:a}=e,{api:r}=ae(),[o,u]=kt.useState(null),[g,l]=kt.useState(null),[i,d]=kt.useState(!1),[b,f]=kt.useState(null),[c,m]=kt.useState(!1),[p,y]=kt.useState(!0),[S,C]=kt.useState(0),E=kt.useRef(0),v=kt.useRef(0),_=kt.useRef(void 0);n!==void 0&&(_.current=n);let T=t?_.current===!0||_.current===void 0&&s:!0,[A,N]=kt.useState({api:r,identity:a}),k=a!==void 0&&a!==A.identity;(A.api!==r||k)&&(_.current=void 0,N({api:r,identity:a}),v.current+=1,E.current=0,u(null),l(null),d(!1),f(null),m(!1),y(!0),C(0));let L=kt.useRef(()=>{}),P=kt.useRef(null),Y=kt.useCallback(async()=>{if(P.current!==null&&P.current===v.current)return;let J=++v.current;P.current=J;try{let q=await r.getAnalyticsRealtime();if(J!==v.current)return;if(q.status==="unreachable"){m(!0),d(!0),y(!1),C(se=>se+1);return}E.current=0,m(!1),u(q.data.current_visitors),l(q.as_of),d(!1),f(null),y(!1),C(se=>se+1)}catch(q){if(J!==v.current)return;E.current+=1,y(!1),C(se=>se+1),d(!0),E.current>=Ur&&f(q instanceof Error?q:new Error("Realtime unavailable"))}finally{P.current===J&&(P.current=null)}},[r]);return L.current=()=>void Y(),kt.useEffect(()=>{let J,q=()=>{J===void 0&&(J=setInterval(()=>L.current(),Fr))},se=()=>{J!==void 0&&(clearInterval(J),J=void 0)},ce=()=>{typeof document<"u"&&document.hidden?se():(L.current(),q())};return T?((typeof document>"u"||!document.hidden)&&(L.current(),q()),document?.addEventListener("visibilitychange",ce),()=>{se(),document?.removeEventListener("visibilitychange",ce),v.current+=1}):()=>{document?.removeEventListener("visibilitychange",ce)}},[A.api,A.identity,T]),{currentVisitors:o,asOf:g,isStale:i,error:b,isUnreachable:c,isInitialLoad:p,polls:S}}var mt=re(require("react"),1);var xl=re(require("react"),1);var Wn=require("react/jsx-runtime");function ku(){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 Ti({value:e,chosen:t,onChange:n}){let s=ps(),a=t===null&&s!==null&&e===s,r=xl.useMemo(()=>{let o=ku();return o.includes(e)?o:[e,...o]},[e]);return(0,Wn.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,Wn.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,Wn.jsxs)("select",{value:a?"":e,onChange:o=>n(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,Wn.jsx)("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(o=>(0,Wn.jsx)("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var Mr=(e,{published:t}={})=>{let n=t===!1,s=e!=null&&(!e.collecting||n&&e.first_seen===null&&!e.first_seen_unavailable),a=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=a||r;return{notCollecting:s,awaitingFirstVisit:a,firstVisitTooRecent:r,holdingForFirstData:o,nothingToReport:s||o}};var Zs=re(require("react"),1),Eu=3e4;function $r({status:e,holdingForFirstData:t,refetchStatus:n,refetch:s}){Zs.useEffect(()=>{if(!t)return;let r,o=()=>{r===void 0&&(r=setInterval(()=>void n(),Eu))},u=()=>{r!==void 0&&(clearInterval(r),r=void 0)},g=()=>{typeof document<"u"&&document.hidden?u():(n(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",g),()=>{u(),document?.removeEventListener("visibilitychange",g)}},[t,n]);let a=Zs.useRef(void 0);Zs.useEffect(()=>{if(!e){a.current=void 0;return}let r=a.current;a.current=t,r===!0&&!t&&s()},[e,t,s])}var Kn=re(require("react"),1);var Iu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Zt(e){let t=Math.abs(e);if(t<1e3)return String(e);let n=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[s,a]of n)if(t>=s){let r=e/s,o=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(o)>=1e3&&s!==1e9?Zt(o*s):`${o}${a}`}return String(e)}function fs(e){return`${(e*100).toFixed(1)}%`}function Js(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`}function Sl(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`:Js(t)}function Nl(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Rl(e,t){if(!(!Number.isFinite(e)||e<=0))for(let n of t){let s=Math.ceil(e/n);if(s<=5)return Array.from({length:s+1},(a,r)=>Number((r*n).toPrecision(12)))}}function Ys(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function _l(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 ki(e){let t=Number(e.slice(5,7)),n=Number(e.slice(8,10));return`${Iu[t-1]} ${n}`}function wl(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Au(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Pl(e,t,n="UTC"){let s=new Map(t.map(o=>[o.date,o])),a=[],r=wl(e.to,n);for(let o=wl(e.from,n);o<r;o=Au(o))a.push(s.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return a}function Cl(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=new Date(`${e}T00:00:00Z`);if(Number.isNaN(s.getTime()))return e;let a=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${a} ${n[s.getUTCMonth()]}`}var Ra=require("react/jsx-runtime");function Tl({what:e="This report",onRetry:t,collecting:n}){return(0,Ra.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,Ra.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,Ra.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:n===!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,Ra.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 Vr({what:e="No data"}){return(0,Ra.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 bn({sourced:e,error:t,isLoading:n,what:s,onRetry:a,collecting:r,children:o}){return n?(0,Ra.jsx)("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,Ra.jsx)(Tl,{what:s,onRetry:a,collecting:r}):!e||e.status==="unreachable"?(0,Ra.jsx)(Tl,{what:s,onRetry:a,collecting:r}):(0,Ra.jsx)(Ra.Fragment,{children:o(e.data)})}var tt=require("react/jsx-runtime");function Ei({rows:e,dimension:t,metric:n,metricLabel:s,secondary:a,emptyCopy:r="No data for this period",onFilter:o,canFilter:u,maxRows:g=9}){let[l,i]=Kn.useState(!1);if(e.length===0)return(0,tt.jsx)(Vr,{what:r});let d=e.reduce((c,m)=>Math.max(c,Number(m[n]??0)),0)||1,b=Math.max(0,e.length-g),f=l?e:e.slice(0,g);return(0,tt.jsxs)(tt.Fragment,{children:[(0,tt.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,tt.jsx)("thead",{children:(0,tt.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,tt.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,tt.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),(0,tt.jsx)("tbody",{children:f.map((c,m)=>{let p=Number(c[n]??0),y=c[t]??null,S=Ys(y),C=a?c[a]:null,E=y!==null&&(u?u(y,C):!0);return(0,tt.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,tt.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,tt.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,p/d*100)}%`}}),y!==null&&o&&E?(0,tt.jsx)("button",{type:"button",onClick:()=>o(y,C),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,tt.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:S}),C?(0,tt.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:C}):null]}),(0,tt.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Zt(p)})]},`${S}-${C??""}-${m}`)})})]}),b>0?(0,tt.jsx)("button",{type:"button",onClick:()=>i(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:l?"Show fewer":`Show all ${e.length}`}):null]})}function Xs({title:e,tabs:t,defaultTabId:n,headerRight:s}){let[a,r]=Kn.useState(n),o=t.find(f=>f.id===a)??t[0],u=Kn.useId(),g=f=>`${u}-tab-${f}`,l=f=>`${u}-panel-${f}`,i=Kn.useRef(null),d=(f,c)=>{f.preventDefault();let m=(c+t.length)%t.length;r(t[m].id),i.current?.querySelectorAll('[role="tab"]')?.[m]?.focus()};return(0,tt.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,tt.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,tt.jsx)("div",{ref:i,role:"tablist","aria-label":e,onKeyDown:f=>{let c=t.findIndex(m=>m.id===a);f.key==="ArrowRight"&&d(f,c+1),f.key==="ArrowLeft"&&d(f,c-1),f.key==="Home"&&d(f,0),f.key==="End"&&d(f,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(f=>(0,tt.jsx)("button",{id:g(f.id),role:"tab",type:"button","aria-selected":f.id===a,"aria-controls":l(f.id),tabIndex:f.id===a?0:-1,onClick:()=>r(f.id),className:f.id===a?"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:f.label},f.id))}),s]}),o?(0,tt.jsx)("div",{id:l(o.id),role:"tabpanel","aria-labelledby":g(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var ia=re(require("react"),1),Tn=re(require("@radix-ui/react-popover"),1);var Zn=3,Jn=100;var Fe=require("react/jsx-runtime"),Qs={channel:"Channel",source:"Source",campaign:"Campaign",utm_source:"UTM source",utm_medium:"UTM medium",utm_content:"UTM content",utm_term:"UTM term",page:"Page",entry_page:"Entry page",exit_page:"Exit page",country:"Country",region:"Region",city:"City",browser:"Browser",os:"Operating system",device:"Device"},Du=Object.keys(Qs);function kl(e){let t=Qs[e.dimension],n=e.operator==="is_not"?"is not":"is",s=e.values.map(a=>Ys(a)).join(" or ");return`${t} ${n} ${s}`}function Ii(e,t){let n=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));if(n>=0){let s=[...new Set([...e[n].values,...t.values])];return s.length>100||s.length===e[n].values.length?e:e.map((a,r)=>r===n?{...a,values:s}:a)}return t.values.length>100||e.length>=3?e:[...e,t]}function Lu(e,t){let n={};for(let[s,a]of Object.entries(t)){let r=e.get(s)??new Set;for(let o of a)r.add(o);e.set(s,r),n[s]=[...r]}return n}function El(e,t){let n=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));return n>=0?e.map((s,a)=>a===n?t:s):t.values.length>100||e.length>=3?e:[...e,t]}function Ou(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Il(e,t,n,s={}){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 a=Lu(e.byDimension,n);for(let[r,o]of Object.entries(s)){let u=e.foldsByLabel.get(r)??new Set;for(let g of o)u.add(g);e.foldsByLabel.set(r,u)}return{suggestions:a,folds:new Map([...e.foldsByLabel].map(([r,o])=>[r,[...o]]))}}function Al(e){let{filters:t,onChange:n}=e,s=t.length>=3;return ia.useEffect(()=>{if(t.length===0)return;let a=r=>{let o=r.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||r.key==="Escape"&&n([])};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[t.length,n]),(0,Fe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((a,r)=>(0,Fe.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,Fe.jsx)("span",{className:"af-text-foreground",children:kl(a)}),(0,Fe.jsx)("button",{type:"button","aria-label":`Remove filter ${kl(a)}`,onClick:()=>n(t.filter((o,u)=>u!==r)),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"})]},`${a.dimension}-${a.operator??"is"}`)),(0,Fe.jsx)(Bu,{...e,disabled:s}),t.length>0?(0,Fe.jsx)("button",{type:"button",onClick:()=>n([]),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 Bu({filters:e,onChange:t,suggestions:n,resetKey:s,disabled:a,expandValues:r}){let[o,u]=ia.useState(!1),g=ia.useRef(null),[l,i]=ia.useState(null);ia.useEffect(()=>{i(g.current?.closest(".aifeatures-admin")??null)},[]);let[d,b]=ia.useState(null),[f,c]=ia.useState("is"),[m,p]=ia.useState(""),[y,S]=ia.useState([]);ia.useEffect(()=>{o||(b(null),c("is"),p(""),S([]))},[o]);let C=ia.useRef(s);C.current!==s&&(C.current=s,o&&u(!1),d!==null&&b(null),y.length>0&&S([]),m!==""&&p(""),f!=="is"&&c("is"));let E=k=>{let L=Ou(k);b(L.dimension),S(L.picked),p(L.search),c(L.operator)},_=(d?n[d]??[]:[]).filter(k=>k.toLowerCase().includes(m.trim().toLowerCase())),T=d===null||y.length===0?null:Ii(e,{dimension:d,operator:f,values:r?r(d,y):y}),A=T!==null&&T!==e,N=()=>{let k=T;!k||k===e||(t(k),u(!1))};return(0,Fe.jsxs)(Tn.Root,{open:o,onOpenChange:u,children:[(0,Fe.jsx)(Tn.Trigger,{asChild:!0,children:(0,Fe.jsx)("button",{ref:g,type:"button",disabled:!1,title:a?`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,Fe.jsx)(Tn.Portal,{container:l,children:(0,Fe.jsx)(Tn.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:d===null?(0,Fe.jsxs)("div",{children:[(0,Fe.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Fe.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:Du.filter(k=>n[k]!==void 0).map(k=>{let L=n[k]?.length??0,P=!e.some(Y=>Y.dimension===k)&&e.length>=3;return(0,Fe.jsxs)("button",{type:"button",onClick:()=>E(k),disabled:L===0||P,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,Fe.jsx)("span",{children:Qs[k]}),(0,Fe.jsx)("span",{className:"af-text-muted-foreground",children:L===0?"no data":P?"no room":L})]},k)})})]}):(0,Fe.jsxs)("div",{children:[(0,Fe.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Fe.jsx)("button",{type:"button",onClick:()=>E(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Fe.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Qs[d]}),(0,Fe.jsxs)("select",{"aria-label":"Operator",value:f,onChange:k=>c(k.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,Fe.jsx)("option",{value:"is",children:"is"}),(0,Fe.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Fe.jsx)("input",{type:"text",value:m,onChange:k=>p(k.target.value),placeholder:"Search\u2026","aria-label":`Search ${Qs[d]}`,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,Fe.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:_.length===0?(0,Fe.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",m,"\u201D."]}):_.map(k=>(0,Fe.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,Fe.jsx)("input",{type:"checkbox",checked:y.includes(k),disabled:!y.includes(k)&&y.length>=100,onChange:L=>S(P=>L.target.checked?[...P,k]:P.filter(Y=>Y!==k))}),(0,Fe.jsx)("span",{className:"af-break-all",children:Ys(k)})]},k))}),(0,Fe.jsx)("button",{type:"button",onClick:N,disabled:!A,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:y.length<=1?"Apply filter":y.length>=100?`Apply filter (${y.length} values \u2014 the maximum)`:`Apply filter (${y.length} values)`})]})})})]})}var ft=require("react/jsx-runtime"),Fu=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Zt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Zt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Zt,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:Js,chart:"visit_duration_seconds"}];function Uu({current:e,previous:t,downIsGood:n}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let a=s>0,r=n?!a:a,o=`${a?"+":""}${(s*100).toFixed(1)}%`;return(0,ft.jsx)("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:o})}function Dl({summary:e,selected:t,onSelect:n}){return(0,ft.jsx)("div",{className:"af-@container",children:(0,ft.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Fu.map(s=>{let a=s.chart===t,r=n!==void 0,o=(0,ft.jsxs)(ft.Fragment,{children:[(0,ft.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),(0,ft.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,ft.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?(0,ft.jsx)(Uu,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?(0,ft.jsx)("button",{type:"button","aria-pressed":a,onClick:()=>n(s.chart),className:a?"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},s.key):(0,ft.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},s.key)})})})}function Ai({currentVisitors:e,asOf:t,isStale:n,isUnreachable:s,isInitialLoad:a=!1,scopeIsSiteWide:r=!1}){if(a&&!s)return(0,ft.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,ft.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,ft.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return(0,ft.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?_l(t):"freshness unknown",u=r?" across the whole site, not the current filter,":"",g=n?`${e} current visitors${u} ${o} (not updating)`:`${e} current visitors${u} ${o}`;return(0,ft.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:g,children:[(0,ft.jsx)("span",{"aria-hidden":"true",className:n?"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,ft.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,ft.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),(0,ft.jsx)("span",{className:"af-sr-only",children:g})]})}var Ll=re(require("react"),1),Ol=require("lucide-react");var Ve=require("react/jsx-runtime");function Hr(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function zr({rows:e,denominator:t,windowPrecedesCollection:n=!1,coverageUnknown:s=!1,emptyCopy:a="No conversions in this period",maxRows:r=9,primaryConversion:o}){let[u,g]=Ll.useState(!1),l=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||Hr(p,o)),i=n?(0,Ve.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."}):s?(0,Ve.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(l.length===0)return(0,Ve.jsxs)(Ve.Fragment,{children:[(0,Ve.jsx)(Vr,{what:a}),i]});let d=l.slice(0,r),b=o?l.find(p=>Hr(p,o)):void 0,f=b&&!d.includes(b)?l.filter(p=>d.includes(p)||p===b).slice(0,Math.max(0,r-1)).concat(b):d,c=u?e:f,m=Math.max(0,e.length-f.length);return(0,Ve.jsxs)(Ve.Fragment,{children:[(0,Ve.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Ve.jsx)("thead",{children:(0,Ve.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Ve.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,Ve.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,Ve.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,Ve.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,Ve.jsx)("tbody",{children:c.map((p,y)=>(0,Ve.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":Hr(p,o)?"true":void 0,children:[(0,Ve.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Hr(p,o)?(0,Ve.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,Ve.jsx)(Ol.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,Ve.jsx)("span",{className:"af-font-medium af-text-foreground",children:p.goal}),(0,Ve.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):p.goal}),(0,Ve.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Zt(p.visitors)}),(0,Ve.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Zt(p.events)}),(0,Ve.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:p.conversion_rate===null?(0,Ve.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):fs(p.conversion_rate)})]},`${p.goal}-${y}`))})]}),m>0?(0,Ve.jsx)("button",{type:"button",onClick:()=>g(p=>!p),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:u?"Show fewer":`Show all ${e.length} goals`}):null,(0,Ve.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Zt(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),i]})}var oa=require("recharts");var pt=require("react/jsx-runtime"),qr={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Li={visitors:Zt,visits:Zt,pageviews:Zt,views_per_visit:e=>e.toFixed(2),bounce_rate:fs,visit_duration_seconds:Js},Mu=31,$u=new Set(["visitors","visits","pageviews"]),Vu={...Li,bounce_rate:Nl,visit_duration_seconds:Sl},Di=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Hu=[5,10,15,30,60,120,300,600,900,1800,3600,7200],zu=[.01,.02,.05,.1,.2,.25,.5,1],qu=[.25,.5,1,2,5,10,25,50],ju={visitors:Di,visits:Di,pageviews:Di,views_per_visit:qu,bounce_rate:zu,visit_duration_seconds:Hu};function Gu({active:e,payload:t,label:n,metric:s}){if(!e||!t||t.length===0)return null;let a=t[0].payload;return(0,pt.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,pt.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:qr[s]}),(0,pt.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,pt.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,pt.jsx)("span",{className:"af-text-muted-foreground",children:Cl(String(n))}),(0,pt.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Li[s](Number(a[s]??0))})]})]})}function jr({rows:e,window:t,metric:n,timeZone:s="UTC",height:a=260}){let r=Pl(t,e,s),o=Li[n],u=Vu[n],g=Rl(r.reduce((i,d)=>Math.max(i,Number(d[n]??0)),0),ju[n]),l=`${qr[n]} by day: ${r.map(i=>`${ki(i.date)}: ${o(Number(i[n]??0))}`).join("; ")}.`;return(0,pt.jsxs)("figure",{"aria-label":`${qr[n]} over time`,className:"af-m-0",children:[(0,pt.jsx)(oa.ResponsiveContainer,{width:"100%",height:a,children:(0,pt.jsxs)(oa.AreaChart,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,pt.jsx)("defs",{children:(0,pt.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,pt.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,pt.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,pt.jsx)(oa.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,pt.jsx)(oa.XAxis,{dataKey:"date",tickFormatter:ki,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,pt.jsx)(oa.YAxis,{allowDecimals:!$u.has(n),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...g?{ticks:g,domain:[0,g[g.length-1]]}:{},tickFormatter:i=>u(i),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,pt.jsx)(oa.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,pt.jsx)(Gu,{metric:n})}),(0,pt.jsx)(oa.Area,{type:"linear",dataKey:n,name:qr[n],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=Mu?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,pt.jsx)("figcaption",{className:"af-sr-only",children:l})]})}var oe=require("react/jsx-runtime"),Wu="2026-08-13",Ku=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Zu=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Bl({filters:e,onFiltersChange:t,refreshKey:n,onBackToWebsite:s,primaryConversion:a,className:r,published:o,lastPublishedAt:u}){let[g,l]=mt.useState(30),[i,d]=mt.useState(()=>Yr()),b=e!==void 0&&t!==void 0,[f,c]=mt.useState(e??[]),{api:m}=ae(),[p,y]=mt.useState(m);p!==m&&(y(m),!b&&f.length>0&&c([]));let S=b?e:f,C=mt.useCallback(F=>{t&&t(F),b||c(F)},[t,b]),E=mt.useCallback((F,ye,Ne)=>{let Ee=Array.isArray(ye)?ye:[ye];if(Ee.length===0)return null;let Me=Ii(S,{dimension:F,operator:"is",values:Ee});if(Ne&&(!Ne.value||(Me=El(Me,{dimension:Ne.dimension,operator:"is",values:[Ne.value]}),!Me.find(gt=>gt.dimension===Ne.dimension&&gt.operator!=="is_not")?.values.includes(Ne.value))))return null;let ot=Me.find($e=>$e.dimension===F&&$e.operator!=="is_not");return Ee.every($e=>ot?.values.includes($e))?JSON.stringify(Me)===JSON.stringify(S)?null:Me:null},[S]),v=mt.useCallback((F,ye,Ne)=>E(F,ye,Ne)!==null,[E]),_=mt.useCallback((F,ye,Ne)=>{let Ee=E(F,ye,Ne);Ee&&C(Ee)},[E,C]),[T,A]=mt.useState("visitors"),N=Gn(g,{refreshKey:n,breakdowns:Zu,filters:S}),k=N.status.data,L=N.reportedZone??k?.timezone,P=L??i??ps()??"UTC",{notCollecting:Y,awaitingFirstVisit:J,firstVisitTooRecent:q,holdingForFirstData:se}=Mr(k,{published:o}),ce=o===!1,ge=Ks({collecting:J||Y?!1:k?.collecting,statusFailed:N.status.error!=null,identity:k?.analytics_id}),$=mt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),te=mt.useMemo(()=>{let F=N.breakdowns.sources?.data,ye={};if(!F||F.status!=="ok")return ye;for(let Ne of F.data){let Ee=Ne.source,Me=Ne.sources;typeof Ee=="string"&&Array.isArray(Me)&&Me.length>0&&(ye[Ee]=Me)}return ye},[N.breakdowns.sources?.data]),U=mt.useMemo(()=>{let F=(Ee,Me)=>{let ot=N.breakdowns[Ee]?.data;return!ot||ot.status!=="ok"?[]:[...new Set(ot.data.map($e=>$e[Me]).filter($e=>typeof $e=="string"&&$e!==""))]};return{channel:N.channels.data?.status==="ok"?[...new Set(N.channels.data.data.map(Ee=>Ee.channel))]:[],source:F("sources","source"),campaign:F("utm/campaign","campaign"),page:F("pages","pathname"),entry_page:F("entry-pages","pathname"),exit_page:F("exit-pages","pathname"),country:F("countries","country"),browser:F("browsers","browser"),os:F("operating-systems","os"),device:F("devices","device")}},[N.breakdowns,N.channels.data]),[Pe,ue]=mt.useState({}),at=JSON.stringify(U),[Te,He]=mt.useState(new Map),Ye=JSON.stringify(te);mt.useEffect(()=>{let{suggestions:F,folds:ye}=Il($.current,{api:m,period:g},JSON.parse(at),JSON.parse(Ye));ue(F),He(ye)},[at,Ye,m,g]);let Le=mt.useCallback((F,ye)=>F!=="source"?ye:[...new Set(ye.flatMap(Ne=>{let Ee=[...Te.get(Ne)??[],...te[Ne]??[]];return Ee.length>0?Ee:[Ne]}))],[Te,te]),Et=mt.useMemo(()=>{let F=N.conversions.error;return F instanceof ht&&F.details?.code==="goals_exceed_report_budget"?F.message:null},[N.conversions.error]),D=mt.useMemo(()=>{let F=[N.summary,N.timeseries,N.channels,...Object.values(N.breakdowns)];for(let ye of F){let Ne=ye?.error;if(Ne instanceof ht&&Ne.details?.code==="filter_unsupported")return Ne.message}return null},[N.summary,N.timeseries,N.channels,N.breakdowns]),M=(F,ye,Ne,Ee,Me,ot,$e,gt,me)=>()=>{let Ie=N.breakdowns[F];return(0,oe.jsx)(bn,{sourced:Ie?.data??null,error:Ie?.error,isLoading:Ie?.isLoading,what:ye,collecting:k?.collecting,onRetry:N.refetch,children:lt=>{let la=Ot=>gt?Le(gt,[Ot]):Ot;return(0,oe.jsx)(Ei,{rows:lt,dimension:Ne,metric:Ee,metricLabel:Me,secondary:ot,emptyCopy:S.length>0?"No data for this filter":$e,canFilter:gt?(Ot,Jt)=>v(gt,la(Ot),me?{dimension:me,value:Jt}:void 0):()=>!1,onFilter:gt?(Ot,Jt)=>_(gt,la(Ot),me?{dimension:me,value:Jt}:void 0):void 0})}})};if($r({status:k,holdingForFirstData:se,refetchStatus:N.refetchStatus,refetch:N.refetch}),Y){let F=!!u&&String(u).slice(0,10)<Wu;return(0,oe.jsx)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,oe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,oe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:ce?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":F?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return J?(0,oe.jsx)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,oe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,oe.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,oe.jsxs)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:[(0,oe.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,oe.jsx)(Ti,{value:P,chosen:i,onChange:F=>{Xr(F),d(F)}})}),(0,oe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,oe.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",k?.timezone?` ${k.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,oe.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,oe.jsx)(Ai,{currentVisitors:ge.currentVisitors,asOf:ge.asOf,isStale:ge.isStale,isUnreachable:ge.isUnreachable||ge.error!==null,isInitialLoad:ge.isInitialLoad})})]})]}):(0,oe.jsx)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,oe.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,oe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,oe.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Ku.map(F=>(0,oe.jsx)("button",{type:"button","aria-pressed":F.value===g,onClick:()=>l(F.value),className:F.value===g?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:F.label},F.value))}),(0,oe.jsx)(Ti,{value:P,chosen:i,onChange:F=>{Xr(F),d(F)}}),(0,oe.jsx)(Ai,{currentVisitors:ge.currentVisitors,asOf:ge.asOf,isStale:ge.isStale,isUnreachable:ge.isUnreachable||ge.error!==null,isInitialLoad:ge.isInitialLoad,scopeIsSiteWide:S.length>0})]}),(0,oe.jsx)(Al,{filters:S,onChange:C,suggestions:Pe,expandValues:Le,resetKey:m}),D?(0,oe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,oe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:D}),(0,oe.jsx)("button",{type:"button",onClick:()=>C([]),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,!D&&k?.timezone_defaulted?(0,oe.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,D?null:(0,oe.jsxs)(oe.Fragment,{children:[(0,oe.jsx)(bn,{sourced:N.summary.data,error:N.summary.error,isLoading:N.summary.isLoading,what:"The traffic summary",collecting:k?.collecting,onRetry:N.refetch,children:F=>(0,oe.jsxs)(oe.Fragment,{children:[(0,oe.jsx)(Dl,{summary:F,selected:T,onSelect:A}),F.previous_unavailable?(0,oe.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[F.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,oe.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,oe.jsx)(bn,{sourced:N.timeseries.data,error:N.timeseries.error,isLoading:N.timeseries.isLoading,what:"The visitors chart",collecting:k?.collecting,onRetry:N.refetch,children:F=>{let ye=N.timeseries.data?.status==="ok"?N.timeseries.data.window:{from:"",to:""};return(0,oe.jsx)(jr,{rows:F,window:ye,metric:T,timeZone:L??"UTC"})}})}),(0,oe.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,oe.jsx)(Xs,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,oe.jsx)(bn,{sourced:N.channels.data,error:N.channels.error,isLoading:N.channels.isLoading,what:"Channels",collecting:k?.collecting,onRetry:N.refetch,children:F=>(0,oe.jsx)(Ei,{rows:F,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:S.length>0?"No data for this filter":"No data for this period",canFilter:ye=>v("channel",ye),onFilter:ye=>_("channel",ye)})})},{id:"sources",label:"Sources",render:M("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:M("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,oe.jsx)(Xs,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:M("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:M("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:M("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,oe.jsx)(Xs,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:M("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:M("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:M("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,oe.jsx)(Xs,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:M("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:M("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:M("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,oe.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,oe.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,oe.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,oe.jsxs)("div",{className:"af-px-3 af-py-2",children:[S.length>0?(0,oe.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,oe.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,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,oe.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,oe.jsx)(bn,{sourced:N.conversions.data,error:N.conversions.error,isLoading:N.conversions.isLoading,what:"Conversions",collecting:k?.collecting,onRetry:N.refetch,children:F=>{let ye=N.conversions.data?.status==="ok"?N.conversions.data:null;return(0,oe.jsx)(oe.Fragment,{children:(0,oe.jsx)(zr,{rows:F,primaryConversion:a,denominator:ye?.denominator??0,windowPrecedesCollection:ye?.window_precedes_collection??!1,coverageUnknown:ye?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var Hl=re(require("react"),1),Dt=require("lucide-react");var Fa=re(require("react"),1),yn=require("lucide-react");var xe=require("react/jsx-runtime"),Fl=90,Ul=100;function Ju(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Ml(e){return!!e.label&&e.label!==e.target}function Yu(e,t,n){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:s,with_a_value:a}=t;return s===0?e===0?"Nothing specific has converted here yet.":null:a===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":a<s?n?`These cover ${a.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${a.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function er(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function $l({current:e,onChange:t,onClose:n}){let{api:s}=ae(),[a,r]=Fa.useState(null),[o,u]=Fa.useState(!1),[g,l]=Fa.useState({at:"goals"}),[i,d]=Fa.useState(null),[b,f]=Fa.useState(null),[c,m]=Fa.useState(!1),[p,y]=Fa.useState(null),S=Fa.useRef(0);Fa.useEffect(()=>{let _=!0;return r(null),u(!1),l({at:"goals"}),d(null),f(null),m(!1),y(null),S.current+=1,s.getAnalyticsConversions(Fl).then(T=>{if(_){if(T.status!=="ok"){u(!0);return}r(T.data)}}).catch(()=>{_&&u(!0)}),()=>{_=!1}},[s]);let C=_=>{l({at:"targets",row:_}),d(null),f(null),m(!1),y(null);let T=++S.current;s.getAnalyticsGoalTargets(_.goal,Fl,Ul).then(A=>{if(T===S.current){if(A.status!=="ok"){f("failed");return}d(A.data),m(A.truncated===!0),y(A.coverage??null)}}).catch(A=>{if(T!==S.current)return;let N=A instanceof ht?A.details?.code:void 0;f(N==="goal_has_no_targets"?"no-values":"failed")})},E=_=>{t(_),n()};if(o)return(0,xe.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(!a)return(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,xe.jsx)(yn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,xe.jsx)("span",{children:"Loading your conversions\u2026"})]});if(g.at==="targets"){let _=g.row,T=new Map;for(let A of i??[])T.set(A.label,(T.get(A.label)??0)+1);return(0,xe.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,xe.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,xe.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>l({at:"goals"}),children:[(0,xe.jsx)(yn.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,xe.jsx)("span",{children:"All conversions"})]})}),(0,xe.jsxs)("button",{type:"button","aria-current":e&&er(_,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:()=>E({goal:_.goal,implicit:_.implicit}),children:[e&&er(_,e)&&!e.target&&(0,xe.jsx)(yn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,xe.jsxs)("span",{children:["Any ",_.goal.toLowerCase()]})]}),b==="no-values"&&(0,xe.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."}),b==="failed"&&(0,xe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,xe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,xe.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>C(_),children:"Try again"})]}),!i&&b===null&&(0,xe.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,xe.jsx)(yn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,xe.jsx)("span",{children:"Loading\u2026"})]}),i&&(0,xe.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Yu(i.length,p,c)}),c&&(0,xe.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Ul,". If what you want isn\u2019t here, pick the conversion itself instead."]}),i?.some(Ml)&&(0,xe.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."}),i?.map(A=>{let N=!!(e&&er(_,e)&&e.target===A.target),k=T.get(A.label)>1;return Ml(A)?(0,xe.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,xe.jsxs)("span",{className:"af-min-w-0",children:[(0,xe.jsx)("span",{className:"af-block af-truncate",children:A.label}),k&&(0,xe.jsx)("span",{className:"af-block af-truncate af-text-xs",children:A.target})]}),(0,xe.jsx)("span",{className:"af-shrink-0 af-text-xs",children:A.visitors.toLocaleString()})]},A.target):(0,xe.jsxs)("button",{type:"button","aria-current":N?"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:()=>E({goal:_.goal,implicit:_.implicit,target:A.target,...A.label&&A.label!==A.target?{label:A.label}:{}}),children:[(0,xe.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[N&&(0,xe.jsx)(yn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,xe.jsxs)("span",{className:"af-min-w-0",children:[(0,xe.jsx)("span",{className:"af-block af-truncate",children:A.label}),k&&(0,xe.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:A.target})]})]}),(0,xe.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:A.visitors.toLocaleString()})]},A.target)})]})}let v=e?.goal&&!a.some(_=>er(_,e));return(0,xe.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:[v&&(0,xe.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."]}),a.length===0&&(0,xe.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."}),a.map(_=>{let T=e?er(_,e):!1;return(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,xe.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:()=>E({goal:_.goal,implicit:_.implicit}),children:[(0,xe.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[T&&(0,xe.jsx)(yn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,xe.jsx)("span",{className:"af-truncate",children:_.goal})]}),(0,xe.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:_.visitors.toLocaleString()})]}),Ju(_)&&(0,xe.jsx)(R,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${_.goal}`,onClick:()=>C(_),children:"Narrow"})]},_.goal)}),e?.goal&&(0,xe.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:()=>E(null),children:"No main conversion"})]})}var _a=require("react/jsx-runtime");function Xu(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let n of t)try{let{hostname:s}=new URL(n);if(s)return s.toLowerCase().replace(/^www\./,"")}catch{}return null}function Qu(e){if(Oi(e,"whatsapp"))return!0;let t=Xu(e);return t===null?!1:["wa.me","whatsapp.com"].some(n=>t===n||t.endsWith(`.${n}`))}function Oi(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var Vl=[{goal:"Contact",target:e=>Oi(e,"tel"),icon:Dt.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Oi(e,"mailto"),icon:Dt.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:Dt.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Qu(e),icon:Dt.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:Dt.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Dt.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Dt.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:Dt.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:Dt.Download,line:"This site is set up to get your file downloaded."}];function zl(e){let{goal:t,target:n}=e;return e.implicit!==!0?null:(n?Vl.find(a=>a.goal===t&&a.target?.(n)):void 0)??Vl.find(a=>a.goal===t&&!a.target)??null}function ed(e){return zl(e)?.icon??Dt.Target}function ql({primaryConversion:e,onChange:t}){let[n,s]=Hl.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?zl(e):null,o=e?.label?.trim(),u=e?ed(e):Dt.Target,g=e?.goal?o?`Your main conversion is ${o}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",l=(0,_a.jsxs)(_a.Fragment,{children:[(0,_a.jsx)(u,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,_a.jsx)("span",{children:g})]});return t?(0,_a.jsxs)(gr,{open:n,onOpenChange:s,children:[(0,_a.jsx)(vr,{asChild:!0,children:(0,_a.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:l})}),(0,_a.jsx)(Os,{align:"start",className:"af-w-80 af-p-1",children:n&&(0,_a.jsx)($l,{current:e,onChange:t,onClose:()=>s(!1)})})]}):(0,_a.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:l})}var qt=require("react/jsx-runtime");function jl({refreshKey:e,onViewAll:t,primaryConversion:n}){let s=Gn(7,{refreshKey:e,breakdowns:[]}),a=s.status.data??void 0,{nothingToReport:r,notCollecting:o,holdingForFirstData:u}=Mr(a);return $r({status:a,holdingForFirstData:u,refetchStatus:s.refetchStatus,refetch:s.refetch}),(0,qt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,qt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,qt.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,qt.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?(0,qt.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,qt.jsxs)(qt.Fragment,{children:[(0,qt.jsx)(bn,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:a?.collecting,onRetry:s.refetch,children:g=>{let l=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return(0,qt.jsx)(jr,{rows:g,window:l?.window??{from:"",to:""},metric:"visitors",timeZone:l?.timezone,height:140})}}),(0,qt.jsxs)("div",{className:"af-mt-3",children:[(0,qt.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,qt.jsx)(bn,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:a?.collecting,onRetry:s.refetch,children:g=>{let l=s.conversions.data?.status==="ok"?s.conversions.data:null;return(0,qt.jsx)(zr,{rows:g,primaryConversion:n,denominator:l?.denominator??0,windowPrecedesCollection:l?.window_precedes_collection??!1,coverageUnknown:l?.first_seen_unavailable??!1})}})]})]})]})}var Lt=require("react/jsx-runtime"),Bi=5;function Fi({title:e,viewAllLabel:t,onViewAll:n}){return(0,Lt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Lt.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),n&&(0,Lt.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:n,children:t})]})}function Gl({refreshKey:e,onBackToWebsite:t,primaryConversion:n,onChangePrimaryConversion:s,onOpenSurface:a,needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:u}){let g=Hn({refreshKey:e}),l=(g.summary?.products.count??0)>0||(g.summary?.commerce?.storefront_orders??!1),i=l||(g.summary?.commerce?.invoicing??!1);return(0,Lt.jsx)(wt,{title:"Dashboard",onBackToWebsite:t,children:(0,Lt.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,Lt.jsx)(ql,{primaryConversion:n,onChange:s}),(0,Lt.jsx)(jl,{refreshKey:e,onViewAll:a&&(()=>a("analytics")),primaryConversion:n}),(0,Lt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Lt.jsx)(Fi,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:a&&(()=>a("leads"))}),(0,Lt.jsx)(qs,{refreshKey:e,maxRows:Bi,onViewAll:a&&(()=>a("leads"))})]}),l&&(0,Lt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Lt.jsx)(Fi,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:a&&(()=>a("orders"))}),(0,Lt.jsx)(fn,{refreshKey:e,maxRows:Bi,onViewAll:a&&(()=>a("orders"))})]}),i&&(0,Lt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Lt.jsx)(Fi,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:a&&(()=>a("invoices"))}),(0,Lt.jsx)(pn,{refreshKey:e,maxRows:Bi,onViewAll:a&&(()=>a("invoices")),needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:u})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,DashboardView,ExportCsvButton,FormSettings,FormSubmissions,FormsDashboard,FormsList,InvoiceDetail,InvoiceLabelBadge,InvoiceSettingsPanel,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,NotificationRecipientsSettings,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,PromosPanel,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,StoreSettings,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,chargedTotal,createApiClient,formatPrice,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useBusinessSummary,useCsvExport,useCustomers,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSiteSettings,useSubmissions,useSubscriptions});