@aifeatures/admin-react 0.22.0 → 0.24.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,8 @@
1
1
  "use client";
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});
2
+ "use strict";var Yd=Object.create;var ti=Object.defineProperty;var Jd=Object.getOwnPropertyDescriptor;var Xd=Object.getOwnPropertyNames;var Qd=Object.getPrototypeOf,eu=Object.prototype.hasOwnProperty;var tu=(e,t)=>{for(var a in t)ti(e,a,{get:t[a],enumerable:!0})},xl=(e,t,a,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Xd(t))!eu.call(e,n)&&n!==a&&ti(e,n,{get:()=>t[n],enumerable:!(s=Jd(t,n))||s.enumerable});return e};var ce=(e,t,a)=>(a=e!=null?Yd(Qd(e)):{},xl(t||!e||!e.__esModule?ti(a,"default",{value:e,enumerable:!0}):a,e)),au=e=>xl(ti({},"__esModule",{value:!0}),e);var Km={};tu(Km,{AUDIENCE_PAGE_SIZE:()=>Cs,AifeaturesApiError:()=>jt,AifeaturesProvider:()=>_l,AnalyticsView:()=>Md,ContactImport:()=>Hr,CustomerDetail:()=>Er,CustomersList:()=>Ir,DOUBLE_OPT_IN_HELP:()=>Gr,DashboardView:()=>Kd,EMAIL_ORG_ACTIONS:()=>Mi,EMAIL_READINESS_TEXT:()=>Fo,EmailView:()=>sl,ExportCsvButton:()=>da,FormSettings:()=>xr,FormSubmissions:()=>gr,FormsDashboard:()=>co,FormsList:()=>cr,IMPORT_ATTESTATION:()=>Vi,InvoiceDetail:()=>_i,InvoiceLabelBadge:()=>Ws,InvoiceSettingsPanel:()=>Mr,InvoicesList:()=>Gn,InvoicesView:()=>Bo,LeadsView:()=>Or,MAX_ANALYTICS_FILTERS:()=>ls,MAX_ANALYTICS_FILTER_VALUES:()=>cs,NotificationRecipientsSettings:()=>Oo,OrderDetail:()=>Cr,OrderStatusBadge:()=>ss,OrdersList:()=>jn,OrdersView:()=>Ro,PaymentsDashboard:()=>No,PaymentsSetup:()=>xs,ProductSettings:()=>Rr,ProductsList:()=>Sr,ProductsView:()=>_o,PromosPanel:()=>ps,REALTIME_FAILURES_BEFORE_ERROR:()=>Zi,REALTIME_POLL_MS:()=>Ki,RetainerStatusBadge:()=>ki,RetainersPanel:()=>ys,StoreSettings:()=>Lo,SubmissionDetail:()=>mr,SubscriptionsView:()=>Co,VariantsEditor:()=>Nr,ViewShell:()=>Lt,WebhookDeliveries:()=>hr,WebhookSettings:()=>yr,buildEmailOrgRequest:()=>Jc,chargedTotal:()=>Cn,createApiClient:()=>si,emailReadinessText:()=>ks,formatPrice:()=>ee,isEmailOrgAction:()=>Yc,isZeroDecimalCurrency:()=>Ga,toMajorUnits:()=>kt,toMinorUnits:()=>ia,useAifeatures:()=>W,useAifeaturesContext:()=>W,useAnalytics:()=>Os,useAudience:()=>$r,useBroadcasts:()=>Es,useBusinessSummary:()=>Ns,useCsvExport:()=>pr,useCustomers:()=>Tr,useEmailDrafts:()=>Is,useEventDestinations:()=>vr,useForms:()=>us,useInvoices:()=>hs,useOrders:()=>_r,usePaymentsStatus:()=>Hn,usePeople:()=>Ar,usePerson:()=>Lr,useProducts:()=>ws,useRealtimeVisitors:()=>Kr,useRetainers:()=>Ss,useSiteSettings:()=>Kn,useSubmissions:()=>ur,useSubscriptions:()=>Br});module.exports=au(Km);var es=ce(require("react"),1);var so="aifeatures:analytics:timezone",ro;function rr(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function wl(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function Xn(){return io()??rr()}function io(){if(ro!==void 0)return ro;try{let e=window.localStorage.getItem(so);return wl(e)?e:null}catch{return null}}function oo(e){if(!(e!==null&&!wl(e))){ro=e;try{e===null?window.localStorage.removeItem(so):window.localStorage.setItem(so,e)}catch{}}}function ai(e,t){let a=new URLSearchParams({period:String(e)}),s=Xn();return s&&a.set("timezone",s),t&&t.length>0&&a.set("filters",JSON.stringify(t)),a.toString()}var jt=class extends Error{constructor(a,s,n){super(a);this.status=s;this.details=n;this.name="AifeaturesApiError"}};function ni(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 ir(e,t){let a=t.toString();return a?`${e}?${a}`:e}function Sl(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 Nl(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 si(e,t="https://aifeatures.dev"){async function a(n,r={}){let i=`${t}${n}`,l=await fetch(i,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!l.ok){let u;try{u=await l.json()}catch{}throw new jt(ni(u?.error,l.status),l.status,u)}if(l.status!==204)return l.json()}async function s(n){let r=await fetch(`${t}${n}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let i;try{i=await r.json()}catch{}throw new jt(ni(i?.error,r.status),r.status,i)}return r.blob()}return{async getForms(){return(await a("/api/v1/forms")).forms},async getForm(n){return a(`/api/v1/forms/${n}`)},async createForm(n){return a("/api/v1/forms",{method:"POST",body:JSON.stringify(n)})},async updateForm(n,r){return a(`/api/v1/forms/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(n){await a(`/api/v1/forms/${n}`,{method:"DELETE"})},async getSubmissions(n,r={}){let i=new URLSearchParams;r.limit!==void 0&&i.set("limit",String(r.limit)),r.offset!==void 0&&i.set("offset",String(r.offset));let l=i.toString(),u=`/api/v1/forms/${n}/submissions${l?`?${l}`:""}`;return a(u)},async getSubmission(n){return a(`/api/v1/submissions/${n}`)},async exportSubmissionsCsv(n,r={}){let i=new URLSearchParams;return r.includeSpam&&i.set("include_spam","true"),s(ir(`/api/v1/forms/${encodeURIComponent(n)}/submissions/export`,i))},async deleteSubmission(n){await a(`/api/v1/submissions/${n}`,{method:"DELETE"})},async downloadAttachment(n,r){let i=typeof r=="string"?{name:r}:r,l=i.name,u=i.id??i.name,d=`${t}/api/v1/submissions/${n}/attachments/${encodeURIComponent(u)}`,o=await fetch(d,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let m;try{m=await o.json()}catch{}throw new jt(ni(m?.error,o.status),o.status,m)}let c=await o.blob(),b=URL.createObjectURL(c),g=document.createElement("a");g.href=b,g.download=l,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(b)},async getSite(n){return a(`/api/v1/sites/${encodeURIComponent(n)}`)},async updateSite(n,r){return a(`/api/v1/sites/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return a("/api/v1/payments/status")},getPromos(n){let r=new URLSearchParams({limit:"10"});return n&&r.set("cursor",n),a(`/api/v1/promos?${r}`)},getPromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}`)},createPromo(n){return a("/api/v1/promos",{method:"POST",body:JSON.stringify(n)})},disablePromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}/disable`,{method:"POST"})},replacePromo(n,r){return a(`/api/v1/promos/${encodeURIComponent(n)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(n={}){let r=new URLSearchParams;n.include&&r.set("include",n.include);let i=r.toString();return(await a(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(n){return a(`/api/v1/products/${n}`)},async createProduct(n){return a("/api/v1/products",{method:"POST",body:JSON.stringify(n)})},async updateProduct(n,r){return a(`/api/v1/products/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(n){await a(`/api/v1/products/${n}`,{method:"DELETE"})},async attachProductFile(n,r){let i=new FormData;i.append("file",r);let l=await fetch(`${t}/api/v1/products/${n}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!l.ok){let u;try{u=await l.json()}catch{}throw new jt(ni(u?.error,l.status),l.status,u)}return l.json()},async attachProductFileFromUrl(n,r){return a(`/api/v1/products/${n}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(n,r){return a(`/api/v1/products/${n}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(n,r){return a(`/api/v1/options/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(n){await a(`/api/v1/options/${n}`,{method:"DELETE"})},async createVariant(n,r){return a(`/api/v1/products/${n}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(n,r){return a(`/api/v1/variants/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(n){await a(`/api/v1/variants/${n}`,{method:"DELETE"})},async setVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(n={}){let r=new URLSearchParams;n.email?r.set("email",n.email):n.q&&r.set("q",n.q),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(n){return a(`/api/v1/customers/${n}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(n={}){let r=Sl(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/orders${i?`?${i}`:""}`)},async exportOrdersCsv(n={}){return s(ir("/api/v1/orders/export",Sl(n)))},async getOrder(n){return a(`/api/v1/orders/${n}`)},async getInvoices(n={}){let r=new URLSearchParams;n.labels?.length&&r.set("label",n.labels.join(",")),n.customerEmail&&r.set("customer_email",n.customerEmail),n.customerId&&r.set("customer_id",n.customerId),n.q&&r.set("q",n.q),n.from&&r.set("from",n.from),n.to&&r.set("to",n.to),n.includeAggregates&&r.set("include","aggregates"),n.retainerId&&r.set("retainer_id",n.retainerId),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(n){return a(`/api/v1/invoices/${n}`)},async getInvoicePreview(n){return a(`/api/v1/invoices/${n}/preview`)},async getInvoiceSettings(){return a("/api/v1/invoice-settings")},async getRetainers(n={}){let r=Nl(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/retainers${i?`?${i}`:""}`)},async exportRetainersCsv(n={}){return s(ir("/api/v1/retainers/export",Nl(n)))},async getRetainer(n){return a(`/api/v1/retainers/${n}`)},async resendOrderReceipt(n){await a(`/api/v1/orders/${n}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(n){return a(`/api/v1/orders/${n}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(n,r){return a(`/api/v1/orders/${n}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(n={}){let r=new URLSearchParams;n.status&&r.set("status",n.status),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/subscriptions${i?`?${i}`:""}`)},async exportSubscriptionsCsv(n={}){let r=new URLSearchParams;return n.status&&r.set("status",n.status),s(ir("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let n=new URLSearchParams,r=Xn();r&&n.set("timezone",r);let i=n.toString();return a(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(n,r){return a(`/api/v1/analytics/summary?${ai(n,r)}`)},async getAnalyticsTimeseries(n,r){return a(`/api/v1/analytics/timeseries?${ai(n,r)}`)},async getAnalyticsRealtime(){return a("/api/v1/analytics/realtime")},async getAnalyticsChannels(n,r){return a(`/api/v1/analytics/channels?${ai(n,r)}`)},async getAnalyticsConversions(n){return a((()=>{let r=new URLSearchParams({period:String(n)}),i=Xn();return i&&r.set("timezone",i),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(n,r,i){let l=new URLSearchParams({goal:n,period:String(r)}),u=Xn();return u&&l.set("timezone",u),i!==void 0&&l.set("limit",String(i)),a(`/api/v1/analytics/conversions/targets?${l.toString()}`)},async getAnalyticsBreakdown(n,r,i){let l=n.split("/").map(encodeURIComponent).join("/");return a(`/api/v1/analytics/${l}?${ai(r,i)}`)},async getBusinessSummary(n){let r=new URLSearchParams;r.set("tz_offset_minutes",String(n.tzOffsetMinutes));let i=Xn();return i&&r.set("timezone",i),a(`/api/v1/summary?${r.toString()}`)},async getPeople(n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/people${i?`?${i}`:""}`)},async exportPeopleCsv(n={}){let r=new URLSearchParams;return n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),s(ir("/api/v1/people/export",r))},async getPerson(n){return a(`/api/v1/people/${encodeURIComponent(n)}`)},async getEventDestinations(){return(await a("/api/v1/event-destinations")).destinations},async createEventDestination(n){return a("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(n)})},async updateEventDestination(n,r){return a(`/api/v1/event-destinations/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(n){await a(`/api/v1/event-destinations/${n}`,{method:"DELETE"})},async rotateEventDestinationSecret(n){return a(`/api/v1/event-destinations/${n}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(n){return(await a(`/api/v1/event-destinations/${n}/secret`)).secret},async getEventDeliveries(n,r){let i=r===void 0?"":`?limit=${r}`;return(await a(`/api/v1/event-destinations/${n}/deliveries${i}`)).deliveries},async retryEventDelivery(n,r){return a(`/api/v1/event-destinations/${n}/deliveries/${r}/retry`,{method:"POST"})},async getMarketingSettings(n){return a(`${Ba(n)}/marketing`)},async getMarketingContacts(n,r={}){let i=new URLSearchParams;r.q&&i.set("q",r.q),r.limit&&i.set("limit",String(r.limit)),r.offset&&i.set("offset",String(r.offset));let l=i.toString();return a(`${Ba(n)}/contacts${l?`?${l}`:""}`)},async getMarketingContactStats(n){return a(`${Ba(n)}/contacts/stats`)},async getMarketingTags(n){return(await a(`${Ba(n)}/contact-tags`)).tags},async getEmailDrafts(n,r){let i=r?`?kind=${r}`:"";return(await a(`${Ba(n)}/marketing/drafts${i}`)).drafts},async getEmailDraft(n,r){return a(`${Ba(n)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(n,r,i){let l=i?.editable?"?mode=editable":"";return a(`${Ba(n)}/marketing/drafts/${encodeURIComponent(r)}/preview${l}`)},async getEmailTemplates(n){return(await a(`${Ba(n)}/marketing/templates`)).templates},async previewEmailTemplate(n,r,i){let l=i?`?draft_id=${encodeURIComponent(i)}`:"";return a(`${Ba(n)}/marketing/templates/${encodeURIComponent(r)}/preview${l}`)},async getBroadcasts(n){return(await a(`${Ba(n)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(n,r){return a(`${Ba(n)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getWelcomeSequence(n){return a(`${Ba(n)}/marketing/welcome`)},async getRecoveryFlow(n){return a(`${Ba(n)}/marketing/recovery`)}}}function Ba(e){return`/api/v1/sites/${encodeURIComponent(e)}`}var Qn=require("react/jsx-runtime"),Rl=es.createContext(null);function nu(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 _l({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:n}){let r=es.useMemo(()=>nu(e),[e]),i=es.useMemo(()=>si(e,t),[e,t]),l=es.useMemo(()=>({siteToken:e,apiUrl:t,api:i}),[e,t,i]);return r?(0,Qn.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:(0,Qn.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Qn.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Qn.jsx)("p",{className:"af-text-sm af-text-destructive",children:r})]})}):(0,Qn.jsx)(Rl.Provider,{value:l,children:(0,Qn.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:n})})}function W(){let e=es.useContext(Rl);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var Vn=ce(require("react"),1),Vs=require("lucide-react");var ri=ce(require("react"),1),gn=ce(require("@radix-ui/react-tabs"),1);var Pl=require("clsx"),kl=require("tailwind-merge"),su=(0,kl.extendTailwindMerge)({prefix:"af-"});function X(...e){return su((0,Pl.clsx)(e))}var oi=require("react/jsx-runtime"),ii=gn.Root,or=ri.forwardRef(({className:e,...t},a)=>(0,oi.jsx)(gn.List,{ref:a,className:X("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));or.displayName=gn.List.displayName;var vn=ri.forwardRef(({className:e,...t},a)=>(0,oi.jsx)(gn.Trigger,{ref:a,className:X("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));vn.displayName=gn.Trigger.displayName;var bn=ri.forwardRef(({className:e,...t},a)=>(0,oi.jsx)(gn.Content,{ref:a,className:X("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));bn.displayName=gn.Content.displayName;var Cl=ce(require("react"),1),Tl=require("@radix-ui/react-slot"),El=require("class-variance-authority");var Il=require("react/jsx-runtime"),ru=(0,El.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"}}),y=Cl.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...n},r)=>(0,Il.jsx)(s?Tl.Slot:"button",{className:X(ru({variant:t,size:a,className:e})),ref:r,...n}));y.displayName="Button";var lr=require("lucide-react");var Un=ce(require("react"),1);var _n=require("react/jsx-runtime"),ft=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,_n.jsx)("table",{ref:a,className:X("af-w-full af-caption-bottom af-text-sm",e),...t})}));ft.displayName="Table";var mt=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("thead",{ref:a,className:X("[&_tr]:af-border-b",e),...t}));mt.displayName="TableHeader";var pt=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("tbody",{ref:a,className:X("[&_tr:last-child]:af-border-0",e),...t}));pt.displayName="TableBody";var iu=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("tfoot",{ref:a,className:X("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));iu.displayName="TableFooter";var Fe=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("tr",{ref:a,className:X("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Fe.displayName="TableRow";var Z=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("th",{ref:a,className:X("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));Z.displayName="TableHead";var Y=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("td",{ref:a,className:X("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));Y.displayName="TableCell";var ou=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("caption",{ref:a,className:X("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));ou.displayName="TableCaption";var hn=ce(require("react"),1);function us(){let{api:e}=W(),[t,a]=hn.useState([]),[s,n]=hn.useState(!0),[r,i]=hn.useState(null),l=hn.useCallback(async()=>{try{n(!0),i(null);let c=await e.getForms();a(c)}catch(c){i(c instanceof Error?c:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);hn.useEffect(()=>{l()},[l]);let u=hn.useCallback(async c=>{let b=await e.createForm(c);return a(g=>[...g,b]),b},[e]),d=hn.useCallback(async(c,b)=>{let g=await e.updateForm(c,b);return a(m=>m.map(p=>p.id===c?g:p)),g},[e]),o=hn.useCallback(async c=>{await e.deleteForm(c),a(b=>b.filter(g=>g.id!==c))},[e]);return{forms:t,isLoading:s,error:r,refetch:l,createForm:u,updateForm:d,deleteForm:o}}var Nt=require("react/jsx-runtime");function cr({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:n}=us();return s?(0,Nt.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Nt.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,Nt.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Nt.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):a.length===0?(0,Nt.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,Nt.jsx)(lr.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Nt.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Nt.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Nt.jsx)("div",{className:t,children:(0,Nt.jsxs)(ft,{children:[(0,Nt.jsx)(mt,{children:(0,Nt.jsxs)(Fe,{children:[(0,Nt.jsx)(Z,{children:"Name"}),(0,Nt.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,Nt.jsx)(pt,{children:a.map(r=>(0,Nt.jsxs)(Fe,{children:[(0,Nt.jsx)(Y,{className:"af-font-medium",children:r.name}),(0,Nt.jsx)(Y,{className:"af-text-right",children:(0,Nt.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Nt.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[(0,Nt.jsx)(lr.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Nt.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[(0,Nt.jsx)(lr.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}var Ll=require("lucide-react");var Dl=require("class-variance-authority");var Al=require("react/jsx-runtime"),lu=(0,Dl.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,...a}){return(0,Al.jsx)("div",{className:X(lu({variant:t}),e),...a})}var Fa=require("react/jsx-runtime"),cu={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 li(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 lo(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function du(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 dr({deliveries:e,label:t="Email needs attention"}){return lo(e)?(0,Fa.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,Fa.jsx)(Ll.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Pn({deliveries:e,problemsOnly:t=!1,className:a=""}){let s=(e??[]).filter(n=>!t||lo([n]));return s.length?(0,Fa.jsx)("div",{className:`af-space-y-3 ${a}`,"aria-label":"Email delivery",children:s.map(n=>{let r=li(n),i=du(n);return(0,Fa.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Fa.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Fa.jsx)("span",{className:"af-font-medium",children:cu[n.kind]??"Email notification"}),(0,Fa.jsx)(ie,{variant:r.variant,children:r.label})]}),(0,Fa.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&lo([n])&&(0,Fa.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,Fa.jsx)("p",{className:"af-mt-1",children:r.detail}),i&&(0,Fa.jsx)("p",{className:"af-mt-1",children:i})]},n.id)})}):null}var as=ce(require("react"),1),sn=require("lucide-react");var ts=ce(require("react"),1),We=ce(require("@radix-ui/react-select"),1),fs=require("lucide-react");var Vt=require("react/jsx-runtime"),tn=We.Root;var an=We.Value,Ma=ts.forwardRef(({className:e,children:t,...a},s)=>(0,Vt.jsxs)(We.Trigger,{ref:s,className:X("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...a,children:[t,(0,Vt.jsx)(We.Icon,{asChild:!0,children:(0,Vt.jsx)(fs.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Ma.displayName=We.Trigger.displayName;var Ol=ts.forwardRef(({className:e,...t},a)=>(0,Vt.jsx)(We.ScrollUpButton,{ref:a,className:X("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,Vt.jsx)(fs.ChevronUp,{className:"af-h-4 af-w-4"})}));Ol.displayName=We.ScrollUpButton.displayName;var Bl=ts.forwardRef(({className:e,...t},a)=>(0,Vt.jsx)(We.ScrollDownButton,{ref:a,className:X("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,Vt.jsx)(fs.ChevronDown,{className:"af-h-4 af-w-4"})}));Bl.displayName=We.ScrollDownButton.displayName;var Ua=ts.forwardRef(({className:e,children:t,position:a="popper",...s},n)=>(0,Vt.jsx)(We.Portal,{children:(0,Vt.jsxs)(We.Content,{ref:n,className:X("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:a,...s,children:[(0,Vt.jsx)(Ol,{}),(0,Vt.jsx)(We.Viewport,{className:X("af-p-1",a==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,Vt.jsx)(Bl,{})]})}));Ua.displayName=We.Content.displayName;var uu=ts.forwardRef(({className:e,...t},a)=>(0,Vt.jsx)(We.Label,{ref:a,className:X("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));uu.displayName=We.Label.displayName;var Rt=ts.forwardRef(({className:e,children:t,...a},s)=>(0,Vt.jsxs)(We.Item,{ref:s,className:X("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...a,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)(We.ItemIndicator,{children:(0,Vt.jsx)(fs.Check,{className:"af-h-4 af-w-4"})})}),(0,Vt.jsx)(We.ItemText,{children:t})]}));Rt.displayName=We.Item.displayName;var fu=ts.forwardRef(({className:e,...t},a)=>(0,Vt.jsx)(We.Separator,{ref:a,className:X("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));fu.displayName=We.Separator.displayName;var xa=ce(require("react"),1);function ur({formId:e,initialPageSize:t=25}){let{api:a}=W(),[s,n]=xa.useState([]),[r,i]=xa.useState(0),[l,u]=xa.useState(!0),[d,o]=xa.useState(null),[c,b]=xa.useState(0),[g,m]=xa.useState(t),p=xa.useRef(0),f=xa.useCallback(async()=>{if(!e)return;let T=++p.current;try{u(!0),o(null);let h={limit:g,offset:c*g},R=await a.getSubmissions(e,h);if(T!==p.current)return;if(R.submissions.length===0&&c>0){b(Math.max(0,Math.ceil(R.total/g)-1));return}n(R.submissions),i(R.total)}catch(h){if(T!==p.current)return;o(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{T===p.current&&u(!1)}},[a,e,c,g]);xa.useEffect(()=>{f()},[f]);let v=xa.useRef(f);v.current=f;let x=xa.useCallback(async T=>{await a.deleteSubmission(T),v.current()},[a]),k=Math.ceil(r/g);return{submissions:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<k-1,hasPreviousPage:c>0,setPage:b,setPageSize:T=>{m(T),b(0)},refetch:f,deleteSubmission:x}}var ci=ce(require("react"),1),Ul=require("lucide-react");var fr=ce(require("react"),1),Jt=ce(require("@radix-ui/react-dialog"),1),Fl=require("lucide-react");var Pa=require("react/jsx-runtime"),nn=Jt.Root;var mu=Jt.Portal;var Ml=fr.forwardRef(({className:e,...t},a)=>(0,Pa.jsx)(Jt.Overlay,{ref:a,className:X("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Ml.displayName=Jt.Overlay.displayName;var $a=fr.forwardRef(({className:e,children:t,...a},s)=>(0,Pa.jsx)(mu,{children:(0,Pa.jsxs)("div",{className:"aifeatures-admin",children:[(0,Pa.jsx)(Ml,{}),(0,Pa.jsxs)(Jt.Content,{ref:s,className:X("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...a,children:[t,(0,Pa.jsxs)(Jt.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,Pa.jsx)(Fl.X,{className:"af-h-4 af-w-4"}),(0,Pa.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));$a.displayName=Jt.Content.displayName;var Va=({className:e,...t})=>(0,Pa.jsx)("div",{className:X("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Va.displayName="DialogHeader";var Ha=({className:e,...t})=>(0,Pa.jsx)("div",{className:X("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ha.displayName="DialogFooter";var za=fr.forwardRef(({className:e,...t},a)=>(0,Pa.jsx)(Jt.Title,{ref:a,className:X("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));za.displayName=Jt.Title.displayName;var qa=fr.forwardRef(({className:e,...t},a)=>(0,Pa.jsx)(Jt.Description,{ref:a,className:X("af-text-sm af-text-muted-foreground",e),...t}));qa.displayName=Jt.Description.displayName;var ma=require("react/jsx-runtime");function Us({onDelete:e,iconOnly:t}){let[a,s]=ci.useState(!1),[n,r]=ci.useState(!1),[i,l]=ci.useState(null);return(0,ma.jsxs)(ma.Fragment,{children:[(0,ma.jsxs)(y,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{l(null),s(!0)},children:[(0,ma.jsx)(Ul.Trash2,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),(0,ma.jsx)(nn,{open:a,onOpenChange:d=>{!d&&!n&&s(!1)},children:(0,ma.jsxs)($a,{children:[(0,ma.jsxs)(Va,{children:[(0,ma.jsx)(za,{children:"Delete this submission?"}),(0,ma.jsx)(qa,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),i&&(0,ma.jsx)("p",{className:"af-text-sm af-text-destructive",children:i}),(0,ma.jsxs)(Ha,{children:[(0,ma.jsx)(y,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),(0,ma.jsx)(y,{variant:"destructive",onClick:async()=>{r(!0),l(null);try{await e(),s(!1)}catch(d){l(d instanceof Error?d.message:"Failed to delete submission")}finally{r(!1)}},disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}var Vl=ce(require("react"),1),pa=require("lucide-react");var De=require("react/jsx-runtime");function $l(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function pu(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function mr({submission:e,onBack:t,onDelete:a}){let{api:s}=W(),[n,r]=Vl.useState(null),i=d=>d.id??d.name,l=async d=>{r(i(d));try{await s.downloadAttachment(e.id,d)}catch(o){console.error("Download failed:",o)}finally{r(null)}},u=Object.entries(e.data).filter(([d])=>!d.startsWith("_"));return(0,De.jsxs)("div",{children:[(0,De.jsxs)("div",{className:"af-mb-6",children:[(0,De.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,De.jsx)(pa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,De.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,De.jsxs)("div",{children:[(0,De.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,De.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",$l(e.metadata.submitted_at)]})]}),a&&(0,De.jsx)(Us,{onDelete:a})]})]}),(0,De.jsxs)("div",{className:"af-space-y-6",children:[(0,De.jsx)(Pn,{deliveries:e.email_deliveries}),(0,De.jsxs)("div",{children:[(0,De.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,De.jsxs)("div",{className:"af-space-y-3",children:[u.map(([d,o])=>(0,De.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,De.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:d.replace(/_/g," ")}),(0,De.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof o=="string"&&o.includes(`
3
+ `)?(0,De.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:o}):String(o)})]},d)),u.length===0&&(0,De.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,De.jsxs)("div",{children:[(0,De.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,De.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((d,o)=>(0,De.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,De.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,De.jsx)(pa.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,De.jsx)("span",{className:"af-text-sm",children:d.name}),(0,De.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",pu(d.size),")"]})]}),(0,De.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>l(d),disabled:n===i(d),children:[n===i(d)?(0,De.jsx)(pa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,De.jsx)(pa.Download,{className:"af-h-4 af-w-4 af-mr-1"}),n===i(d)?"Downloading...":"Download"]})]},o))})]}),(0,De.jsxs)("div",{children:[(0,De.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,De.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,De.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,De.jsx)(pa.Clock,{className:"af-h-4 af-w-4"}),(0,De.jsx)("span",{children:$l(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,De.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,De.jsx)(pa.Globe,{className:"af-h-4 af-w-4"}),(0,De.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,De.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,De.jsx)(pa.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,De.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,De.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,De.jsx)(pa.Mail,{className:"af-h-4 af-w-4"}),(0,De.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var zl=require("lucide-react");var ms=ce(require("react"),1);var gu=/^\+[1-9]\d{1,14}$/;function Hl(e){let t=e==null?"":String(e),a=!gu.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),s=a?`'${t}`:t;return a||/[",;\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function di(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function ui(e,t){if(typeof document>"u")return;let a=URL.createObjectURL(e),s=document.createElement("a");s.href=a,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(a)}function pr({fetchCsv:e,filename:t}){let[a,s]=ms.useState(!1),[n,r]=ms.useState(null),i=ms.useRef(!1);return{exportCsv:ms.useCallback(async()=>{if(!i.current){i.current=!0,s(!0),r(null);try{let u=await e();ui(u,di(t))}catch(u){r(u instanceof Error?u:new Error("Export failed"))}finally{i.current=!1,s(!1)}}},[e,t]),exporting:a,error:n}}var $s=require("react/jsx-runtime");function da({fetchCsv:e,filename:t,label:a="Export CSV",disabled:s,className:n}){let{exportCsv:r,exporting:i,error:l}=pr({fetchCsv:e,filename:t});return(0,$s.jsxs)("span",{className:n,children:[(0,$s.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||i,"aria-busy":i,children:[(0,$s.jsx)(zl.Download,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Exporting\u2026":a]}),l&&(0,$s.jsx)("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}var xe=require("react/jsx-runtime");function vu(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function bu(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let a of t)if(typeof e[a]=="string")return e[a];return null}var hu=["message","comments","comment","inquiry","question","details","body","notes"];function yu(e){let t=Object.entries(e).filter(([r,i])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof i=="string"&&i.trim()),a=new Map(t.map(([r,i])=>[r.toLowerCase(),i])),n=(hu.map(r=>a.get(r)).find(Boolean)??t.reduce((r,[,i])=>i.length>r.length?i:r,"")).trim().replace(/\s+/g," ");return n.length>80?n.slice(0,80)+"\u2026":n}function gr({formId:e,className:t,defaultSubmissionId:a,submissionId:s,onSelectSubmission:n}){let{api:r}=W(),{submissions:i,total:l,isLoading:u,error:d,page:o,pageSize:c,hasNextPage:b,hasPreviousPage:g,setPage:m,setPageSize:p,deleteSubmission:f}=ur({formId:e}),v=as.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[x,k]=as.useState(a??null),T=n?s??null:x,h=n??k,R=H=>!!H&&H.id===T&&H.form_id===e,P=i.find(R),[D,N]=as.useState(null),E=R(D)?D:null,[A,C]=as.useState(null);if(as.useEffect(()=>{if(C(null),!T||P||E)return;let H=!1;return r.getSubmission(T).then(de=>{if(!H){if(de.form_id!==e){C("This submission could not be found.");return}N(de)}}).catch(()=>{H||C("This submission could not be found.")}),()=>{H=!0}},[r,e,T,P,E]),T){let H=P??E;return H?(0,xe.jsx)("div",{className:t,children:(0,xe.jsx)(mr,{submission:H,onBack:()=>h(null),onDelete:async()=>{await f(H.id),h(null)}})}):A?(0,xe.jsxs)("div",{className:t,children:[(0,xe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>h(null),className:"af-mb-2 af--ml-2",children:[(0,xe.jsx)(sn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,xe.jsx)("p",{className:"af-text-sm af-text-destructive",children:A})]}):(0,xe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,xe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(u)return(0,xe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,xe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(d)return(0,xe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,xe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",d.message]})});if(i.length===0&&o===0)return(0,xe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,xe.jsx)(sn.Inbox,{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",children:["No submissions yet.",(0,xe.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let K=o*c+1,Q=Math.min((o+1)*c,l);return(0,xe.jsxs)("div",{className:t,children:[(0,xe.jsx)("div",{className:"af-mb-2 af-flex af-justify-end",children:(0,xe.jsx)(da,{fetchCsv:v,filename:"submissions"})}),(0,xe.jsxs)(ft,{children:[(0,xe.jsx)(mt,{children:(0,xe.jsxs)(Fe,{children:[(0,xe.jsx)(Z,{children:"Email"}),(0,xe.jsx)(Z,{children:"Preview"}),(0,xe.jsx)(Z,{children:"Date"}),(0,xe.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,xe.jsx)(pt,{children:i.map(H=>{let de=bu(H.data),me=yu(H.data);return(0,xe.jsxs)(Fe,{children:[(0,xe.jsxs)(Y,{className:"af-font-medium",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[de||(0,xe.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),H.attachments.length>0&&(0,xe.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${H.attachments.length} attachment(s)`,children:[(0,xe.jsx)(sn.Paperclip,{className:"af-h-3 af-w-3"}),(0,xe.jsx)("span",{className:"af-text-xs",children:H.attachments.length})]})]}),(0,xe.jsx)(dr,{deliveries:H.email_deliveries,label:"Notification email needs attention"})]}),(0,xe.jsx)(Y,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:me||(0,xe.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,xe.jsx)(Y,{className:"af-text-muted-foreground",children:vu(H.metadata.submitted_at)}),(0,xe.jsxs)(Y,{className:"af-text-right",children:[(0,xe.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>h(H.id),title:"View details",children:(0,xe.jsx)(sn.Eye,{className:"af-h-4 af-w-4"})}),(0,xe.jsx)(Us,{iconOnly:!0,onDelete:()=>f(H.id)})]})]},H.id)})})]}),(0,xe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,xe.jsxs)("span",{children:["Showing ",K,"-",Q," of ",l]}),(0,xe.jsxs)(tn,{value:String(c),onValueChange:H=>p(Number(H)),children:[(0,xe.jsx)(Ma,{className:"af-w-[70px] af-h-8",children:(0,xe.jsx)(an,{})}),(0,xe.jsxs)(Ua,{children:[(0,xe.jsx)(Rt,{value:"10",children:"10"}),(0,xe.jsx)(Rt,{value:"25",children:"25"}),(0,xe.jsx)(Rt,{value:"50",children:"50"}),(0,xe.jsx)(Rt,{value:"100",children:"100"})]})]}),(0,xe.jsx)("span",{children:"per page"})]}),(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,xe.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>m(o-1),disabled:!g,children:[(0,xe.jsx)(sn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,xe.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>m(o+1),disabled:!b,children:["Next",(0,xe.jsx)(sn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Wa=ce(require("react"),1),ns=require("lucide-react");var ql=ce(require("react"),1);var jl=require("react/jsx-runtime"),oe=ql.forwardRef(({className:e,type:t,...a},s)=>(0,jl.jsx)("input",{type:t,className:X("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...a}));oe.displayName="Input";var Wl=ce(require("react"),1),Gl=require("class-variance-authority");var Kl=require("react/jsx-runtime"),xu=(0,Gl.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Ve=Wl.forwardRef(({className:e,...t},a)=>(0,Kl.jsx)("label",{ref:a,className:X(xu(),e),...t}));Ve.displayName="Label";var rn=ce(require("react"),1),ga=require("lucide-react");var ja=ce(require("react"),1);function vr(){let{api:e}=W(),[t,a]=ja.useState([]),[s,n]=ja.useState(!0),[r,i]=ja.useState(null),l=ja.useCallback(async()=>{try{n(!0),i(null),a(await e.getEventDestinations())}catch(g){i(g instanceof Error?g:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);ja.useEffect(()=>{l()},[l]);let u=ja.useCallback(async g=>{let m=await e.createEventDestination(g);return a(p=>[m,...p]),m},[e]),d=ja.useCallback(async(g,m)=>{let p=await e.updateEventDestination(g,m);return a(f=>f.map(v=>v.id===g?p:v)),p},[e]),o=ja.useCallback(async g=>{await e.deleteEventDestination(g),a(m=>m.filter(p=>p.id!==g))},[e]),c=ja.useCallback(async g=>{let m=await e.rotateEventDestinationSecret(g);return a(p=>p.map(f=>f.id===g?m:f)),m},[e]),b=ja.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:s,error:r,refetch:l,createDestination:u,updateDestination:d,deleteDestination:o,rotateSecret:c,getSecret:b}}var $n=ce(require("react"),1),br=require("lucide-react");var Xt=require("react/jsx-runtime");function hr({destinationId:e,limit:t=25,className:a}){let{api:s}=W(),[n,r]=$n.useState([]),[i,l]=$n.useState(!0),[u,d]=$n.useState(null),[o,c]=$n.useState(null),b=$n.useCallback(async()=>{try{l(!0),d(null),r(await s.getEventDeliveries(e,t))}catch(m){d(m instanceof Error?m.message:"Failed to load deliveries")}finally{l(!1)}},[s,e,t]);$n.useEffect(()=>{b()},[b]);let g=async m=>{try{c(m.id),d(null);let p=await s.retryEventDelivery(e,m.id);r(f=>f.map(v=>v.id===m.id?p:v))}catch(p){d(p instanceof Error?p.message:"Retry failed")}finally{c(null)}};return i?(0,Xt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,Xt.jsx)(br.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):u?(0,Xt.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:u}):n.length===0?(0,Xt.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,Xt.jsx)("div",{className:a,children:(0,Xt.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(m=>{let p=m.delivered_at!==null;return(0,Xt.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,Xt.jsxs)("div",{className:"af-min-w-0",children:[(0,Xt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[p?(0,Xt.jsx)(ie,{variant:"secondary",children:m.last_status??200}):(0,Xt.jsx)(ie,{variant:"destructive",children:m.last_status??"failed"}),(0,Xt.jsx)("span",{className:"af-text-sm af-truncate",children:m.type})]}),(0,Xt.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[m.event_id," \xB7 ",m.created_at,m.attempts>0&&` \xB7 ${m.attempts} failed ${m.attempts===1?"attempt":"attempts"}`]}),!p&&m.last_error&&(0,Xt.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:m.last_error})]}),(0,Xt.jsx)(y,{variant:"ghost",size:"sm",title:"Send this event again",disabled:o===m.id,onClick:()=>g(m),children:o===m.id?(0,Xt.jsx)(br.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Xt.jsx)(br.RotateCw,{className:"af-h-4 af-w-4"})})]},m.id)})})})}var Ce=require("react/jsx-runtime");function yr({formId:e,topics:t,description:a,className:s}){let{destinations:n,isLoading:r,error:i,createDestination:l,updateDestination:u,deleteDestination:d,rotateSecret:o,getSecret:c}=vr(),[b,g]=rn.useState(""),[m,p]=rn.useState(!1),[f,v]=rn.useState(null),[x,k]=rn.useState(null),[T,h]=rn.useState(null),[R,P]=rn.useState(!1),[D,N]=rn.useState(null),[E,A]=rn.useState(null),[C,K]=rn.useState(null),Q=rn.useMemo(()=>n.filter(F=>F.form_id===e),[n,e]),H=async()=>{let F=b.trim();if(F){if(!F.startsWith("https://")){v("Webhook URLs must start with https://");return}try{p(!0),v(null),await l({url:F,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(ge){v(ge instanceof Error?ge.message:"Failed to add webhook")}finally{p(!1)}}},de=async F=>{try{A(F.id),v(null),await o(F.id),P(!1),h(await c(F.id))}catch(ge){v(ge instanceof Error?ge.message:"Failed to rotate secret")}finally{A(null)}},me=async F=>{try{A(F.id),v(null),await u(F.id,{status:"active"})}catch(ge){v(ge instanceof Error?ge.message:"Failed to re-enable")}finally{A(null)}},be=async()=>{if(D)try{A(D.id),await d(D.id),N(null)}catch(F){v(F instanceof Error?F.message:"Failed to delete")}finally{A(null)}},V=async F=>{if(x===F.id){k(null),h(null);return}try{A(F.id),v(null),P(!1),k(F.id),h(await c(F.id))}catch(ge){k(null),v(ge instanceof Error?ge.message:"Failed to read secret")}finally{A(null)}},J=async()=>{if(T)try{await navigator.clipboard.writeText(T),P(!0)}catch{}};return(0,Ce.jsxs)("div",{className:s,children:[(0,Ce.jsxs)("div",{className:"af-space-y-1",children:[(0,Ce.jsx)(Ve,{children:"Webhooks"}),(0,Ce.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:a??"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,Ce.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,Ce.jsx)(oe,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:F=>g(F.target.value),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),H())},disabled:m}),(0,Ce.jsxs)(y,{onClick:H,disabled:m||!b.trim(),children:[m?(0,Ce.jsx)(ga.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ce.jsx)(ga.Plus,{className:"af-h-4 af-w-4"}),(0,Ce.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(f||i)&&(0,Ce.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:f||i?.message}),(0,Ce.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[r&&(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Ce.jsx)(ga.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&Q.length===0&&(0,Ce.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),Q.map(F=>(0,Ce.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,Ce.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Ce.jsxs)("div",{className:"af-min-w-0",children:[(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Ce.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:F.url}),F.status==="disabled"?(0,Ce.jsx)(ie,{variant:"destructive",children:"Disabled"}):(0,Ce.jsx)(ie,{variant:"secondary",children:"Active"})]}),(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:F.topics.includes("*")?"All events":F.topics.join(", ")})]}),(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,Ce.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>K(C===F.id?null:F.id),children:C===F.id?"Hide log":"Deliveries"}),(0,Ce.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>V(F),disabled:E===F.id,children:x===F.id?"Hide secret":"Show secret"}),(0,Ce.jsx)(y,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:E===F.id,onClick:()=>N(F),children:(0,Ce.jsx)(ga.Trash2,{className:"af-h-4 af-w-4"})})]})]}),F.status==="disabled"&&(0,Ce.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,Ce.jsx)(ga.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,Ce.jsxs)("div",{className:"af-text-sm",children:[(0,Ce.jsxs)("p",{children:["We stopped sending after repeated failures."," ",F.disabled_reason]}),(0,Ce.jsx)(y,{variant:"outline",size:"sm",className:"af-mt-2",disabled:E===F.id,onClick:()=>me(F),children:"Re-enable"})]})]}),x===F.id&&T&&(0,Ce.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,Ce.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,Ce.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ce.jsx)(oe,{readOnly:!0,value:T,className:"af-font-mono"}),(0,Ce.jsx)(y,{variant:"outline",title:"Copy signing secret",onClick:J,children:R?(0,Ce.jsx)(ga.Check,{className:"af-h-4 af-w-4"}):(0,Ce.jsx)(ga.Copy,{className:"af-h-4 af-w-4"})}),(0,Ce.jsx)(y,{variant:"outline",title:"Rotate signing secret",disabled:E===F.id,onClick:()=>de(F),children:E===F.id?(0,Ce.jsx)(ga.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ce.jsx)(ga.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),C===F.id&&(0,Ce.jsx)(hr,{destinationId:F.id})]},F.id))]}),(0,Ce.jsx)(nn,{open:!!D,onOpenChange:F=>{!F&&!E&&N(null)},children:(0,Ce.jsxs)($a,{children:[(0,Ce.jsxs)(Va,{children:[(0,Ce.jsx)(za,{children:"Delete this webhook?"}),(0,Ce.jsxs)(qa,{children:["New submissions will stop being sent to ",D?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),(0,Ce.jsxs)(Ha,{children:[(0,Ce.jsx)(y,{variant:"outline",onClick:()=>N(null),disabled:!!E,children:"Cancel"}),(0,Ce.jsx)(y,{variant:"destructive",onClick:be,disabled:!!E,children:E?"Deleting...":"Delete"})]})]})})]})}var $e=require("react/jsx-runtime");function xr({form:e,onSaved:t,className:a}){let{updateForm:s}=us(),[n,r]=Wa.useState(!1),[i,l]=Wa.useState(null),[u,d]=Wa.useState(null),[o,c]=Wa.useState(e.name),[b,g]=Wa.useState(e.redirect_url||""),[m,p]=Wa.useState(e.email_recipients),[f,v]=Wa.useState("");Wa.useEffect(()=>{c(e.name),g(e.redirect_url||""),p(e.email_recipients),d(null)},[e]);let x=Wa.useCallback(async P=>{try{r(!0),d(null);let D=await s(e.id,P);l(new Date),t?.(D)}catch(D){d(D instanceof Error?D.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);Wa.useEffect(()=>{if(i){let P=setTimeout(()=>l(null),2e3);return()=>clearTimeout(P)}},[i]);let k=async()=>{let P=f.trim().toLowerCase();if(!P)return;if(!P.includes("@")){d("Please enter a valid email address");return}if(m.includes(P)){d("This email is already added");return}let D=[...m,P];p(D),v(""),d(null),await x({email_recipients:D})},T=async P=>{let D=m.filter(N=>N!==P);p(D),await x({email_recipients:D})},h=async()=>{o!==e.name&&await x({name:o})},R=async()=>{let P=b||null;P!==e.redirect_url&&await x({redirect_url:P})};return(0,$e.jsxs)("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(n||i)&&(0,$e.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,$e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-background af-border af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,$e.jsx)(ns.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,$e.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,$e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-green-50 af-border af-border-green-200 af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,$e.jsx)(ns.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,$e.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{htmlFor:"form-name",children:"Form Name"}),(0,$e.jsx)(oe,{id:"form-name",value:o,onChange:P=>c(P.target.value),onBlur:h,placeholder:"Contact Form"}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{children:"Email Recipients"}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,$e.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[m.map(P=>(0,$e.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[P,(0,$e.jsx)("button",{type:"button",onClick:()=>T(P),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,$e.jsx)(ns.X,{className:"af-h-3 af-w-3"})})]},P)),m.length===0&&(0,$e.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,$e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,$e.jsx)(oe,{type:"email",value:f,onChange:P=>v(P.target.value),placeholder:"Add email address",onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),k())},disabled:n}),(0,$e.jsx)(y,{type:"button",variant:"outline",onClick:k,disabled:!f.trim()||n,children:(0,$e.jsx)(ns.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,$e.jsx)(oe,{id:"redirect-url",value:b,onChange:P=>g(P.target.value),onBlur:R,placeholder:"/thank-you"}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Where to send visitors after a successful submission. Use a site path (/thank-you) or a full URL (https://example.com/thank-you). Leave empty for a default success page."})]}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{children:"Form Endpoint"}),(0,$e.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,$e.jsx)("code",{className:"af-flex-1 af-text-xs af-bg-muted af-px-3 af-py-2 af-rounded af-border",children:e.endpoint_url})}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{children:"Captcha Protection"}),(0,$e.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,$e.jsx)(ie,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,$e.jsx)(yr,{formId:e.id}),u&&(0,$e.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})]})}var yt=require("react/jsx-runtime");function co({className:e,location:t,onNavigate:a,submissionId:s}){let{api:n}=W(),[r,i]=Vn.useState({submissionId:s});Vn.useEffect(()=>{s&&i({submissionId:s})},[s]);let l=a?t??{}:r,u=a??i,[d,o]=Vn.useState(null),c=`${l.formId??""}|${l.submissionId??""}`,[b,g]=Vn.useState(null),m=b?.key===c?b.message:null,p=l.formId??(d&&d.submissionId===l.submissionId?d.formId:void 0);Vn.useEffect(()=>{let P=l.submissionId;if(!P||l.formId)return;let D=!1;return n.getSubmission(P).then(N=>{D||(g(null),o({submissionId:P,formId:N.form_id}))}).catch(()=>{D||g({key:c,message:"This submission could not be found."})}),()=>{D=!0}},[n,l.submissionId,l.formId,c]);let[f,v]=Vn.useState(null);Vn.useEffect(()=>{if(!p||f?.id===p)return;let P=!1;return n.getForm(p).then(D=>{P||(g(null),v(D))}).catch(()=>{P||g({key:c,message:"This form could not be found."})}),()=>{P=!0}},[n,p,f?.id,c]);let x=(P,D)=>{v(P),u({formId:P.id,tab:D})},k=()=>u({});if(!l.formId&&!l.submissionId)return(0,yt.jsxs)("div",{className:e,children:[(0,yt.jsxs)("div",{className:"af-mb-6",children:[(0,yt.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,yt.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,yt.jsx)(cr,{onSelectForm:x})]});let h=(0,yt.jsxs)(y,{variant:"ghost",size:"sm",onClick:k,className:"af-mb-2 af--ml-2",children:[(0,yt.jsx)(Vs.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(m)return(0,yt.jsxs)("div",{className:e,children:[h,(0,yt.jsx)("p",{className:"af-text-sm af-text-destructive",children:m})]});if(!p||f?.id!==p)return(0,yt.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,yt.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let R=l.submissionId?"submissions":l.tab??"submissions";return(0,yt.jsxs)("div",{className:e,children:[(0,yt.jsxs)("div",{className:"af-mb-6",children:[h,(0,yt.jsx)("h2",{className:"af-text-lg af-font-semibold",children:f.name})]}),(0,yt.jsxs)(ii,{value:R,onValueChange:P=>u({formId:p,tab:P}),children:[(0,yt.jsxs)(or,{className:"af-mb-4",children:[(0,yt.jsxs)(vn,{value:"submissions",className:"af-gap-2",children:[(0,yt.jsx)(Vs.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,yt.jsxs)(vn,{value:"settings",className:"af-gap-2",children:[(0,yt.jsx)(Vs.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,yt.jsx)(bn,{value:"submissions",children:(0,yt.jsx)(gr,{formId:p,submissionId:l.submissionId,onSelectSubmission:P=>u({formId:p,tab:"submissions",submissionId:P??void 0})})}),(0,yt.jsx)(bn,{value:"settings",children:(0,yt.jsx)(xr,{form:f,onSaved:v})})]})]})}var rt=ce(require("react"),1);var kn=ce(require("react"),1);function Hn(){let{api:e}=W(),[t,a]=kn.useState(null),[s,n]=kn.useState(!0),[r,i]=kn.useState(null),l=kn.useRef(0),u=kn.useCallback(async()=>{let d=++l.current;try{n(!0),i(null);let o=await e.getPaymentsStatus();if(d!==l.current)return;a(o)}catch(o){if(d!==l.current)return;i(o instanceof Error?o:new Error("Failed to fetch payments status"))}finally{d===l.current&&n(!1)}},[e]);return kn.useEffect(()=>{u()},[u]),{status:t,isLoading:s,error:r,refetch:u}}var wu=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Ga(e){return wu.has(e.toLowerCase())}function ee(e,t,a){let s=Ga(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Cn(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 ia(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=Ga(t)?a:a*100;return Math.round(s)}function kt(e,t){return Ga(t)?e:e/100}function fi(e){return e.amount_paid??Math.max(0,Cn(e)-(e.credit_applied??0))}var ye=require("react/jsx-runtime");function wr(e){return e instanceof jt&&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 Zl(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${ee(e.amount_off,e.currency)} off`:"Discount unavailable"}function ps(){let{api:e,siteToken:t}=W();return(0,ye.jsx)(Su,{api:e},t)}function Su({api:e}){let{status:t,error:a}=Hn(),[s,n]=rt.useState([]),[r,i]=rt.useState(null),[l,u]=rt.useState(null),[d,o]=rt.useState(!1),[c,b]=rt.useState(!1),[g,m]=rt.useState(""),[p,f]=rt.useState(null),[v,x]=rt.useState(null),[k,T]=rt.useState(!1),h=rt.useRef(0),R=rt.useCallback(async N=>{let E=++h.current;o(!0),m("");try{let A=await e.getPromos(N);if(E!==h.current)return;n(C=>N?[...C,...A.promos.filter(K=>!C.some(Q=>Q.id===K.id))]:A.promos),i(A.next_cursor),u(A.checkout_enabled)}catch(A){E===h.current&&m(wr(A))}finally{E===h.current&&o(!1)}},[e]);rt.useEffect(()=>(R(),()=>{h.current++}),[R]);async function P(N){let E=++h.current;o(!0),m(""),T(!1);try{let A=await e.getPromo(N);E===h.current&&f(A)}catch(A){E===h.current&&m(wr(A))}finally{E===h.current&&o(!1)}}async function D(){if(p){b(!0),o(!0),m("");try{let N=await e.disablePromo(p.id);if(f(N),!["inactive","expired","exhausted"].includes(N.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");T(!1),await R()}catch(N){m(wr(N))}finally{b(!1),o(!1)}}}return v?(0,ye.jsx)(Nu,{currency:t?.currency??void 0,replaces:v.replaces,onCancel:()=>x(null),onSave:async N=>{let E=v.replaces?await e.replacePromo(v.replaces.id,N):await e.createPromo(N),A=await e.getPromo(E.id);if(A.status==="pending"||A.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");f(A),x(null),await R()}}):(0,ye.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,ye.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,ye.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,ye.jsx)(y,{disabled:d||!t?.currency,onClick:()=>{m(""),x({})},children:"Create promo code"})]}),(0,ye.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."}),l===!1&&(0,ye.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,ye.jsx)("p",{className:"af-text-sm",children:a?wr(a):"Connect Stripe and set the payment currency before creating codes."}),g&&(0,ye.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",(0,ye.jsx)(y,{variant:"outline",disabled:d,onClick:()=>p?void P(p.id):void R(),children:"Refresh"})]}),p?(0,ye.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,ye.jsx)(y,{variant:"ghost",disabled:c,onClick:()=>{f(null),T(!1),R()},children:"Back to codes"}),(0,ye.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[p.code," \xB7 ",p.name]}),(0,ye.jsxs)("p",{children:[Zl(p)," \xB7 ",p.status]}),(0,ye.jsxs)("p",{className:"af-text-sm",children:[p.times_redeemed==null?"Usage unavailable":`${p.times_redeemed} redemptions`,p.max_redemptions!=null?` / ${p.max_redemptions} maximum`:""]}),(0,ye.jsxs)("p",{className:"af-text-sm",children:[p.minimum_amount!=null&&p.currency?`Minimum order: ${ee(p.minimum_amount,p.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,ye.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",p.duration==="repeating"?`${p.duration_in_months} months`:p.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,ye.jsx)("p",{className:"af-text-sm",children:p.expires_at?`Expires ${new Date(p.expires_at).toLocaleString()}`:"No expiry"}),(0,ye.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ye.jsx)(y,{variant:"outline",disabled:d,onClick:()=>void P(p.id),children:"Refresh details"}),(0,ye.jsx)(y,{variant:"outline",disabled:d||p.status==="pending"||p.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:p}),children:"Replace with new code"}),(0,ye.jsx)(y,{variant:"outline",disabled:d||!["active","pending","unavailable"].includes(p.status),onClick:()=>T(!0),children:p.status==="pending"?"Cancel pending offer":"Disable code"})]}),k&&(0,ye.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,ye.jsxs)("p",{className:"af-text-sm",children:[p.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${p.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,ye.jsx)(y,{disabled:d,onClick:()=>void D(),children:p.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,ye.jsx)(y,{variant:"ghost",disabled:d,onClick:()=>T(!1),children:"Cancel"})]})]}):(0,ye.jsxs)(ye.Fragment,{children:[s.map(N=>(0,ye.jsxs)("button",{type:"button",disabled:d,onClick:()=>void P(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,ye.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,ye.jsx)("span",{className:"af-font-semibold af-break-all",children:N.code}),(0,ye.jsx)("span",{className:"af-text-sm",children:N.status})]}),(0,ye.jsxs)("div",{className:"af-text-sm",children:[Zl(N)," \xB7"," ",N.times_redeemed==null?"Usage unavailable":`${N.times_redeemed} redemptions`]})]},N.id)),!d&&!g&&s.length===0&&(0,ye.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."}),d&&(0,ye.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),r&&(0,ye.jsx)(y,{variant:"outline",disabled:d,onClick:()=>void R(r),children:"Load more"})]})]})}function Nu({currency:e,replaces:t,onCancel:a,onSave:s}){let[n,r]=rt.useState(""),[i,l]=rt.useState(t?.name??""),[u,d]=rt.useState(t?.amount_off!=null?"fixed":"percent"),[o,c]=rt.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(kt(t.amount_off,e)):"")),[b,g]=rt.useState(t?.minimum_amount!=null&&e?String(kt(t.minimum_amount,e)):""),[m,p]=rt.useState(()=>{if(!t?.expires_at)return"";let me=new Date(t.expires_at);return Number.isFinite(me.getTime())?new Date(me.getTime()-me.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[f,v]=rt.useState(t?.max_redemptions?.toString()??""),[x,k]=rt.useState(t?.duration??"once"),[T,h]=rt.useState(t?.duration_in_months?.toString()??"3"),[R,P]=rt.useState(null),[D,N]=rt.useState(!1),[E,A]=rt.useState(""),C=rt.useRef(!1),K=e&&Ga(e)?"1":"0.01";async function Q(me){if(me.preventDefault(),C.current)return;A("");let be=R;if(!be){if(!e){A("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){A("Choose a different code for the replacement.");return}let V=ia(o,e),J=b?ia(b,e):null;if(u==="fixed"&&(!V||V>999999999999)||b&&(!J||J>999999999999)){A("Enter a positive amount within the supported range.");return}if(m&&new Date(m).getTime()<=Date.now()){A("Choose a future expiry.");return}be={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:i.trim(),duration:x,...u==="percent"?{percent_off:Number(o)}:{amount_off:V,currency:e},...b?{minimum_amount:J,currency:e}:{},...m?{expires_at:new Date(m).toISOString()}:{},...f?{max_redemptions:Number(f)}:{},...x==="repeating"?{duration_in_months:Number(T)}:{}},P(be)}C.current=!0,N(!0);try{await s(be)}catch(V){A(wr(V)),V instanceof jt&&V.status>=400&&V.status<500&&V.details?.retryable!==!0&&P(null)}finally{C.current=!1,N(!1)}}let H=(me,be,V,J={})=>(0,ye.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[me,(0,ye.jsx)(oe,{"aria-label":me,value:be,onChange:F=>V(F.target.value),...J})]}),de="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,ye.jsxs)("form",{onSubmit:Q,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,ye.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,ye.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,ye.jsxs)("fieldset",{disabled:D||!!R,className:"af-grid af-gap-4",children:[H("Code",n,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),H("Name",i,l,{required:!0,maxLength:40}),(0,ye.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,ye.jsxs)("select",{"aria-label":"Discount type",className:de,value:u,onChange:me=>d(me.target.value),children:[(0,ye.jsx)("option",{value:"percent",children:"Percentage"}),(0,ye.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),H("Discount",o,c,{type:"number",required:!0,min:u==="percent"?"0.01":K,max:u==="percent"?"100":void 0,step:u==="percent"?"0.01":K}),H("Minimum order amount",b,g,{type:"number",min:K,step:K,placeholder:e?.toUpperCase()}),(0,ye.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."]}),H("Expires at (local time)",m,p,{type:"datetime-local",step:1}),H("Maximum redemptions",f,v,{type:"number",min:1,max:1e6,step:1}),(0,ye.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,ye.jsxs)("select",{"aria-label":"Subscription duration",className:de,value:x,onChange:me=>k(me.target.value),children:[(0,ye.jsx)("option",{value:"once",children:"First invoice only"}),(0,ye.jsx)("option",{value:"forever",children:"Every invoice"}),(0,ye.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&H("Months",T,h,{type:"number",required:!0,min:1,max:36,step:1})]}),E&&(0,ye.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:E}),R&&!D&&(0,ye.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,ye.jsx)("span",{className:"af-break-all",children:R.request_id})]}),(0,ye.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ye.jsx)(y,{type:"submit",disabled:D,children:D?"Saving\u2026":R?"Retry same request":t?"Create replacement":"Create code"}),(0,ye.jsx)(y,{type:"button",variant:"ghost",disabled:D||!!R,onClick:a,children:"Cancel"})]})]})}var Gs=ce(require("react"),1),dn=require("lucide-react");var mi=ce(require("react"),1),zn=require("lucide-react");var Oe=require("react/jsx-runtime");function Ru(e){if(e.allow_custom_amount){let t=e.min_amount!==null?ee(e.min_amount,e.currency):"?",a=e.max_amount!==null?ee(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":ee(e.unit_amount,e.currency)}function _u(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Sr({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:n,isLoading:r,error:i,deleteProduct:l}=e,[u,d]=mi.useState(null),[o,c]=mi.useState(!1),[b,g]=mi.useState(null),m=async()=>{if(u)try{c(!0),g(null),await l(u.id),d(null)}catch(p){g(p instanceof Error?p.message:"Failed to delete product")}finally{c(!1)}};return r?(0,Oe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Oe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):i?(0,Oe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Oe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i.message]})}):n.length===0?(0,Oe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[(0,Oe.jsx)(zn.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Oe.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,Oe.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,Oe.jsxs)(y,{variant:"outline",onClick:()=>a?.(),children:[(0,Oe.jsx)(zn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,Oe.jsxs)("div",{className:s,children:[(0,Oe.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,Oe.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[(0,Oe.jsx)(zn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,Oe.jsxs)(ft,{children:[(0,Oe.jsx)(mt,{children:(0,Oe.jsxs)(Fe,{children:[(0,Oe.jsx)(Z,{children:"Name"}),(0,Oe.jsx)(Z,{children:"Price"}),(0,Oe.jsx)(Z,{children:"Fulfillment"}),(0,Oe.jsx)(Z,{children:"Status"}),(0,Oe.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,Oe.jsx)(pt,{children:n.map(p=>(0,Oe.jsxs)(Fe,{children:[(0,Oe.jsx)(Y,{className:"af-font-medium",children:p.name}),(0,Oe.jsx)(Y,{children:Ru(p)}),(0,Oe.jsx)(Y,{className:"af-text-muted-foreground",children:_u(p)}),(0,Oe.jsx)(Y,{children:(0,Oe.jsx)(ie,{variant:p.active?"success":"secondary",children:p.active?"Active":"Inactive"})}),(0,Oe.jsx)(Y,{className:"af-text-right",children:(0,Oe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Oe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>t?.(p),children:[(0,Oe.jsx)(zn.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,Oe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>{g(null),d(p)},children:[(0,Oe.jsx)(zn.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},p.id))})]}),(0,Oe.jsx)(nn,{open:!!u,onOpenChange:p=>{!p&&!o&&d(null)},children:(0,Oe.jsxs)($a,{children:[(0,Oe.jsxs)(Va,{children:[(0,Oe.jsx)(za,{children:"Delete product?"}),(0,Oe.jsxs)(qa,{children:['"',u?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&(0,Oe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),(0,Oe.jsxs)(Ha,{children:[(0,Oe.jsx)(y,{variant:"outline",onClick:()=>d(null),disabled:o,children:"Cancel"}),(0,Oe.jsx)(y,{variant:"destructive",onClick:m,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})}var Ct=ce(require("react"),1),Ka=require("lucide-react");var Wt=ce(require("react"),1),on=require("lucide-react");var B=require("react/jsx-runtime");function uo(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Nr({productId:e,currency:t,className:a}){let{api:s}=W(),n=Ga(t)?"1":"0.01",[r,i]=Wt.useState(null),[l,u]=Wt.useState(!0),[d,o]=Wt.useState(null),[c,b]=Wt.useState(null),[g,m]=Wt.useState(!1),p=Wt.useRef(!0);Wt.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);let f=Wt.useCallback(async()=>{try{let L=await s.getProduct(e);if(!p.current)return;i(L)}catch(L){if(!p.current)return;o(L instanceof Error?L.message:"Failed to load product")}finally{p.current&&u(!1)}},[s,e]);Wt.useEffect(()=>{f()},[f]);let v=async L=>{b(null),m(!0);try{await L(),await f()}catch(M){p.current&&b(M instanceof Error?M.message:"Something went wrong")}finally{p.current&&m(!1)}},[x,k]=Wt.useState(""),[T,h]=Wt.useState(""),[R,P]=Wt.useState({}),D=()=>v(async()=>{let L=x.trim(),M=T.split(",").map(U=>U.trim()).filter(Boolean);if(!L)throw new Error("Option name is required");if(M.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:L,values:M}),p.current&&(k(""),h(""))}),N=L=>v(async()=>{let M=(R[L.id]??"").trim();if(!M)throw new Error("Enter a value");await s.updateOption(L.id,{add_values:[M]}),p.current&&P(U=>({...U,[L.id]:""}))}),E=(L,M)=>v(()=>s.updateOption(L.id,{remove_values:[M]})),A=L=>v(()=>s.deleteOption(L.id)),[C,K]=Wt.useState(null),[Q,H]=Wt.useState(null),[de,me]=Wt.useState(!1),[be,V]=Wt.useState(null),J=r?.options??[],F=r?.variants??[],ge=()=>{H(null),K({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(J.map(L=>[L.id,L.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},pe=L=>{H(null);let M=L.inventory?.on_hand??0,U=M<0?"":String(M);K({variant:L,title:L.title??"",sku:L.sku??"",unitAmount:L.unit_amount!=null?String(kt(L.unit_amount,t)):"",compareAt:L.compare_at_amount!=null?String(kt(L.compare_at_amount,t)):"",active:L.active,optionValues:{},tracked:L.inventory?.tracked??!1,onHand:U,initialOnHand:U,allowBackorder:L.inventory?.allow_backorder??!1})},He=async()=>{if(!C)return;H(null);let L=C.variant?.allow_custom_amount??!1,M=null,U=null;if(!L){if(M=ia(C.unitAmount,t),M===null||M<=0){H("Enter a valid price");return}if(C.compareAt.trim()&&(U=ia(C.compareAt,t),U===null||U<=M)){H("Compare-at price must be greater than the price");return}}let Te=C.onHand.trim()!==C.initialOnHand.trim(),ne=parseInt(C.onHand,10);if(C.tracked&&Te&&(!Number.isFinite(ne)||ne<0)){H("On-hand quantity must be zero or more");return}try{if(me(!0),C.variant)await s.updateVariant(C.variant.id,{title:C.title.trim()||null,sku:C.sku.trim()||null,...L?{}:{unit_amount:M,compare_at_amount:U},active:C.active}),await s.setVariantInventory(C.variant.id,{tracked:C.tracked,on_hand:C.tracked&&Te?ne:void 0,allow_backorder:C.allowBackorder});else{let Re={};for(let je of J){let wt=C.optionValues[je.id];if(!wt){H(`Choose a ${je.title}`),me(!1);return}Re[je.title]=wt}await s.createVariant(e,{title:C.title.trim()||null,sku:C.sku.trim()||null,unit_amount:M,compare_at_amount:U,active:C.active,option_values:J.length>0?Re:void 0,inventory:C.tracked?{tracked:!0,on_hand:ne,allow_backorder:C.allowBackorder}:{tracked:!1,allow_backorder:C.allowBackorder}})}await f(),p.current&&K(null)}catch(Re){if(p.current&&H(Re instanceof Error?Re.message:"Failed to save variant"),C.variant)try{let je=await s.getProduct(e);p.current&&i(je)}catch{}}finally{p.current&&me(!1)}},Pe=()=>v(async()=>{be&&(await s.deleteVariant(be.id),p.current&&V(null))}),Ue=C?.variant?.allow_custom_amount??!1,ze=C?.variant!=null&&C.variant.option_values.length===0&&J.length>0&&!C.variant.active,fe=C?.variant?.inventory!=null&&C.variant.inventory.on_hand<0?-C.variant.inventory.on_hand:null;function lt(L){let M=L.inventory;if(!M||!M.tracked)return(0,B.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let U=M.available??M.on_hand;return U<0?(0,B.jsxs)("span",{children:[-U," backordered"]}):(0,B.jsxs)("span",{children:[U," in stock",M.allow_backorder&&(0,B.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return l?(0,B.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:(0,B.jsx)(on.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):d?(0,B.jsx)("div",{className:a,children:(0,B.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})}):(0,B.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,B.jsxs)("div",{className:"af-space-y-3",children:[(0,B.jsxs)("div",{children:[(0,B.jsx)(Ve,{children:"Options"}),(0,B.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."})]}),J.length>0&&(0,B.jsx)("div",{className:"af-space-y-3",children:J.map(L=>(0,B.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,B.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,B.jsx)("span",{className:"af-text-sm af-font-medium",children:L.title}),(0,B.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>A(L),disabled:g,children:(0,B.jsx)(on.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,B.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:L.values.map(M=>(0,B.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[M.value,(0,B.jsx)("button",{type:"button",onClick:()=>E(L,M.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:(0,B.jsx)(on.X,{className:"af-h-3 af-w-3"})})]},M.id))}),(0,B.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,B.jsx)(oe,{value:R[L.id]??"",onChange:M=>P(U=>({...U,[L.id]:M.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),N(L))},disabled:g}),(0,B.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>N(L),disabled:g||!(R[L.id]??"").trim(),children:(0,B.jsx)(on.Plus,{className:"af-h-4 af-w-4"})})]})]},L.id))}),(0,B.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,B.jsx)(oe,{id:"new-option-title",value:x,onChange:L=>k(L.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),(0,B.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,B.jsx)(Ve,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,B.jsx)(oe,{id:"new-option-values",value:T,onChange:L=>h(L.target.value),placeholder:"S, M, L",disabled:g})]}),(0,B.jsxs)(y,{type:"button",variant:"outline",onClick:D,disabled:g||!x.trim()||!T.trim(),children:[(0,B.jsx)(on.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,B.jsxs)("div",{className:"af-space-y-3",children:[(0,B.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,B.jsx)(Ve,{children:"Variants"}),(0,B.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:ge,disabled:g||J.length===0,children:[(0,B.jsx)(on.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),J.length===0&&(0,B.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),F.length===0?(0,B.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,B.jsxs)(ft,{children:[(0,B.jsx)(mt,{children:(0,B.jsxs)(Fe,{children:[(0,B.jsx)(Z,{children:"Variant"}),(0,B.jsx)(Z,{children:"SKU"}),(0,B.jsx)(Z,{children:"Price"}),(0,B.jsx)(Z,{children:"Stock"}),(0,B.jsx)(Z,{children:"Status"}),(0,B.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,B.jsx)(pt,{children:F.map(L=>(0,B.jsxs)(Fe,{children:[(0,B.jsx)(Y,{className:"af-font-medium",children:uo(L)}),(0,B.jsx)(Y,{className:"af-text-muted-foreground",children:L.sku||"-"}),(0,B.jsx)(Y,{children:L.unit_amount!=null?(0,B.jsxs)("span",{children:[L.compare_at_amount!=null&&(0,B.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:ee(L.compare_at_amount,L.currency)}),ee(L.unit_amount,L.currency)]}):L.allow_custom_amount?(0,B.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,B.jsx)(Y,{children:lt(L)}),(0,B.jsx)(Y,{children:(0,B.jsx)(ie,{variant:L.active?"success":"secondary",children:L.active?"Active":"Inactive"})}),(0,B.jsx)(Y,{className:"af-text-right",children:(0,B.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,B.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>pe(L),disabled:g,children:"Edit"}),(0,B.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>V(L),disabled:g,title:"Delete variant",children:(0,B.jsx)(on.Trash2,{className:"af-h-4 af-w-4"})})]})})]},L.id))})]})]}),c&&(0,B.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c}),(0,B.jsx)(nn,{open:C!==null,onOpenChange:L=>{!L&&!de&&K(null)},children:(0,B.jsxs)($a,{children:[(0,B.jsxs)(Va,{children:[(0,B.jsx)(za,{children:C?.variant?"Edit variant":"Add variant"}),(0,B.jsx)(qa,{children:"Price, markdown, and stock live on the variant."})]}),C&&(0,B.jsxs)("div",{className:"af-space-y-3",children:[C.variant?C.variant.option_values.length>0&&(0,B.jsxs)("div",{className:"af-text-sm",children:[(0,B.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),uo(C.variant)]}):J.map(L=>(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{className:"af-text-xs af-text-muted-foreground",children:L.title}),(0,B.jsxs)(tn,{value:C.optionValues[L.id]??"",onValueChange:M=>K(U=>U&&{...U,optionValues:{...U.optionValues,[L.id]:M}}),children:[(0,B.jsx)(Ma,{children:(0,B.jsx)(an,{placeholder:`Choose ${L.title}`})}),(0,B.jsx)(Ua,{children:L.values.map(M=>(0,B.jsx)(Rt,{value:M.value,children:M.value},M.id))})]})]},L.id)),Ue?(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,B.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,B.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsxs)(Ve,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,B.jsx)(oe,{id:"variant-price",type:"number",min:"0",step:n,value:C.unitAmount,onChange:L=>K(M=>M&&{...M,unitAmount:L.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,B.jsx)(oe,{id:"variant-compare",type:"number",min:"0",step:n,value:C.compareAt,onChange:L=>K(M=>M&&{...M,compareAt:L.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,B.jsx)(oe,{id:"variant-sku",value:C.sku,onChange:L=>K(M=>M&&{...M,sku:L.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,B.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,B.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,B.jsx)("input",{type:"checkbox",checked:C.tracked,onChange:L=>K(M=>M&&{...M,tracked:L.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),C.tracked&&(0,B.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,B.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,B.jsx)(oe,{id:"variant-onhand",type:"number",min:"0",step:"1",value:C.onHand,onChange:L=>K(M=>M&&{...M,onHand:L.target.value}),placeholder:fe!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,B.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,B.jsx)("input",{type:"checkbox",checked:C.allowBackorder,onChange:L=>K(M=>M&&{...M,allowBackorder:L.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),fe!=null&&(0,B.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",fe," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,B.jsx)("input",{type:"checkbox",checked:C.active,onChange:L=>K(M=>M&&{...M,active:L.target.checked}),className:"af-h-4 af-w-4",disabled:ze}),"Active (buyers can purchase this variant)"]}),ze&&(0,B.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."})]}),Q&&(0,B.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Q})]}),(0,B.jsxs)(Ha,{children:[(0,B.jsx)(y,{variant:"outline",onClick:()=>K(null),disabled:de,children:"Cancel"}),(0,B.jsxs)(y,{onClick:He,disabled:de,children:[de?(0,B.jsx)(on.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,C?.variant?"Save":"Add variant"]})]})]})}),(0,B.jsx)(nn,{open:be!==null,onOpenChange:L=>{!L&&!g&&V(null)},children:(0,B.jsxs)($a,{children:[(0,B.jsxs)(Va,{children:[(0,B.jsx)(za,{children:"Delete variant?"}),(0,B.jsx)(qa,{children:be&&`"${uo(be)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,B.jsxs)(Ha,{children:[(0,B.jsx)(y,{variant:"outline",onClick:()=>V(null),disabled:g,children:"Cancel"}),(0,B.jsx)(y,{variant:"destructive",onClick:Pe,disabled:g,children:"Delete"})]})]})})]})}var se=require("react/jsx-runtime");function Pu(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function Rr({productsState:e,product:t,currency:a,onSaved:s,className:n}){let{createProduct:r,updateProduct:i,attachProductFile:l,attachProductFileFromUrl:u}=e,d=!!t,o=t?.currency??a,c=Ga(o)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,m]=Ct.useState(!1),[p,f]=Ct.useState(null),v=Ct.useRef(!0);Ct.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);let[x,k]=Ct.useState(t?.name??""),[T,h]=Ct.useState(t?.description??""),[R,P]=Ct.useState(t?.allow_custom_amount?"custom":"fixed"),[D,N]=Ct.useState(t?.unit_amount!=null?String(kt(t.unit_amount,o)):""),[E,A]=Ct.useState(t?.min_amount!=null?String(kt(t.min_amount,o)):""),[C,K]=Ct.useState(t?.max_amount!=null?String(kt(t.max_amount,o)):""),[Q,H]=Ct.useState(String(t?.max_quantity??10)),de=Ct.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(kt(t.unit_amount,o)):"",minAmount:t?.min_amount!=null?String(kt(t.min_amount,o)):"",maxAmount:t?.max_amount!=null?String(kt(t.max_amount,o)):"",maxQuantity:String(t?.max_quantity??10)}).current,[me,be]=Ct.useState(t?.collect_shipping_address??!1),[V,J]=Ct.useState(t?.active??!0),[F,ge]=Ct.useState(t?.images??[]),[pe,He]=Ct.useState(""),[Pe,Ue]=Ct.useState(t?.fulfillment??null),[ze,fe]=Ct.useState(!1),[lt,L]=Ct.useState(""),[M,U]=Ct.useState(null),Te=Ct.useRef(null),ne=g||ze,Re=()=>{let Ne=pe.trim();if(Ne){if(F.includes(Ne)){f("This image URL is already added");return}ge(Le=>[...Le,Ne]),He(""),f(null)}},je=Ne=>{ge(Le=>Le.filter(ct=>ct!==Ne))},wt=async()=>{if(f(null),!x.trim()){f("Product name is required");return}let Ne=null,Le=null,ct=null,at=!d||R!==de.pricingMode||(R==="fixed"?D!==de.unitAmount:E!==de.minAmount||C!==de.maxAmount),qt=!d||Q!==de.maxQuantity,Ut=b||R==="fixed";if(!(b||!at))if(R==="fixed"){if(Ne=ia(D,o),Ne===null||Ne<=0){f("Enter a valid price");return}}else{if(Le=ia(E,o),ct=ia(C,o),Le===null||ct===null){f("Enter valid minimum and maximum amounts");return}if(ct<Le){f("Maximum amount must be at least the minimum amount");return}}let sa=parseInt(Q,10);if(Ut&&qt&&(!Number.isFinite(sa)||sa<1)){f("Max quantity must be at least 1");return}try{m(!0);let dt;if(d&&t){let ht={name:x.trim(),description:T.trim()||null,images:F,collect_shipping_address:me,active:V};!b&&at&&(ht.allow_custom_amount=R==="custom",R==="fixed"?ht.unit_amount=Ne:(ht.min_amount=Le,ht.max_amount=ct)),Ut&&qt&&(ht.max_quantity=sa),dt=await i(t.id,ht),de.pricingMode=dt.allow_custom_amount?"custom":"fixed",de.unitAmount=dt.unit_amount!=null?String(kt(dt.unit_amount,o)):"",de.minAmount=dt.min_amount!=null?String(kt(dt.min_amount,o)):"",de.maxAmount=dt.max_amount!=null?String(kt(dt.max_amount,o)):"",de.maxQuantity=String(dt.max_quantity)}else{let ht={name:x.trim(),allow_custom_amount:R==="custom",collect_shipping_address:me,active:V};T.trim()&&(ht.description=T.trim()),F.length>0&&(ht.images=F),R==="fixed"?(ht.unit_amount=Ne,ht.max_quantity=sa):(ht.min_amount=Le,ht.max_amount=ct),dt=await r(ht)}if(!v.current)return;Ue(dt.fulfillment),s?.(dt)}catch(dt){if(!v.current)return;f(dt instanceof Error?dt.message:"Failed to save product")}finally{v.current&&m(!1)}},et=async Ne=>{let Le=Ne.target.files?.[0];if(!(!Le||!t))try{fe(!0),U(null);let ct=await l(t.id,Le);if(!v.current)return;Ue(ct.fulfillment),s?.(ct)}catch(ct){if(!v.current)return;U(ct instanceof Error?ct.message:"Failed to upload file")}finally{v.current&&(fe(!1),Te.current&&(Te.current.value=""))}},Dt=async()=>{let Ne=lt.trim();if(!(!Ne||!t))try{fe(!0),U(null);let Le=await u(t.id,Ne);if(!v.current)return;Ue(Le.fulfillment),L(""),s?.(Le)}catch(Le){if(!v.current)return;U(Le instanceof Error?Le.message:"Failed to fetch file")}finally{v.current&&fe(!1)}};return(0,se.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{htmlFor:"product-name",children:"Name"}),(0,se.jsx)(oe,{id:"product-name",value:x,onChange:Ne=>k(Ne.target.value),placeholder:"My product"})]}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{htmlFor:"product-description",children:"Description"}),(0,se.jsx)("textarea",{id:"product-description",value:T,onChange:Ne=>h(Ne.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,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{children:"Pricing"}),b?(0,se.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,se.jsxs)(se.Fragment,{children:[(0,se.jsxs)(tn,{value:R,onValueChange:Ne=>P(Ne),children:[(0,se.jsx)(Ma,{className:"af-w-[260px]",children:(0,se.jsx)(an,{})}),(0,se.jsxs)(Ua,{children:[(0,se.jsx)(Rt,{value:"fixed",children:"Fixed price"}),(0,se.jsx)(Rt,{value:"custom",children:"Buyer chooses the amount"})]})]}),R==="fixed"?(0,se.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsxs)(Ve,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",o.toUpperCase(),")"]}),(0,se.jsx)(oe,{id:"product-price",type:"number",min:"0",step:c,value:D,onChange:Ne=>N(Ne.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsxs)(Ve,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",o.toUpperCase(),")"]}),(0,se.jsx)(oe,{id:"product-min-amount",type:"number",min:"0",step:c,value:E,onChange:Ne=>A(Ne.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsxs)(Ve,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",o.toUpperCase(),")"]}),(0,se.jsx)(oe,{id:"product-max-amount",type:"number",min:"0",step:c,value:C,onChange:Ne=>K(Ne.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,se.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,se.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",o.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||R==="fixed")&&(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsx)(Ve,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,se.jsx)(oe,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:Q,onChange:Ne=>H(Ne.target.value),className:"af-w-[140px]"})]})]}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{children:"Images"}),(0,se.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,se.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[F.map(Ne=>(0,se.jsxs)(ie,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,se.jsx)("span",{className:"af-truncate",children:Ne}),(0,se.jsx)("button",{type:"button",onClick:()=>je(Ne),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:(0,se.jsx)(Ka.X,{className:"af-h-3 af-w-3"})})]},Ne)),F.length===0&&(0,se.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,se.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,se.jsx)(oe,{type:"url",value:pe,onChange:Ne=>He(Ne.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:Ne=>{Ne.key==="Enter"&&(Ne.preventDefault(),Re())},disabled:g}),(0,se.jsx)(y,{type:"button",variant:"outline",onClick:Re,disabled:!pe.trim()||g,children:(0,se.jsx)(Ka.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{children:"Digital File"}),(0,se.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."}),d?(0,se.jsxs)("div",{className:"af-space-y-3",children:[Pe?.type==="download"&&(0,se.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,se.jsx)(Ka.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,se.jsx)("span",{className:"af-text-sm",children:Pe.filename}),Pe.size!=null&&(0,se.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Pu(Pe.size),")"]})]}),Pe?.type==="redirect"&&Pe.url&&(0,se.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,se.jsx)(Ka.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,se.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Pe.url]})]}),(0,se.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,se.jsx)("input",{ref:Te,type:"file",onChange:et,className:"af-hidden",disabled:ne}),(0,se.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>Te.current?.click(),disabled:ne,children:[ze?(0,se.jsx)(Ka.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,se.jsx)(Ka.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Pe?.type==="download"?"Replace file":"Upload file"]}),(0,se.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,se.jsx)(oe,{type:"url",value:lt,onChange:Ne=>L(Ne.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:ze}),(0,se.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:Dt,disabled:!lt.trim()||ne,children:"Fetch from URL"})]}),M&&(0,se.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:M})]}):(0,se.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{children:"Settings"}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,se.jsx)("input",{type:"checkbox",checked:me,onChange:Ne=>be(Ne.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,se.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,se.jsx)("input",{type:"checkbox",checked:V,onChange:Ne=>J(Ne.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),d&&t&&(0,se.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,se.jsx)(Ve,{children:"Options & Variants"}),(0,se.jsx)(Nr,{productId:t.id,currency:o})]}),p&&(0,se.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:p}),(0,se.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,se.jsxs)(y,{type:"button",onClick:wt,disabled:ne,children:[g?(0,se.jsx)(Ka.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?"Save changes":"Create product"]})})]})}var Qt=ce(require("react"),1),Za=require("lucide-react");var At=ce(require("react"),1);var ku=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function _r({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=W(),[s,n]=At.useState([]),[r,i]=At.useState(0),[l,u]=At.useState(!0),[d,o]=At.useState(null),[c,b]=At.useState(0),[g,m]=At.useState(e),[p,f]=At.useState(void 0),[v,x]=At.useState(""),[k,T]=At.useState(""),[h,R]=At.useState(""),[P,D]=At.useState(!1),[N,E]=At.useState(!1),[A,C]=At.useState(void 0),K=A?A.join(","):"",Q=At.useMemo(()=>{if(!K)return;let V=new Set(K.split(","));return ku.filter(J=>!V.has(J))},[K]),H=At.useMemo(()=>{let V={};return p?V.status=p:Q?V.excludeStatus=Q:P||(V.excludeStatus=["pending","expired"]),v.trim()&&(V.customerEmail=v.trim()),k.trim()&&(V.from=k.trim()),h.trim()&&(V.to=h.trim()),N&&(V.unfulfilledOnly=!0),V},[p,Q,P,v,k,h,N]),de=At.useRef(0),me=At.useCallback(async()=>{let V=++de.current;try{u(!0),o(null);let J={...H,limit:g,offset:c*g},F=await a.getOrders(J);if(V!==de.current)return;n(F.orders),i(F.total)}catch(J){if(V!==de.current)return;o(J instanceof Error?J:new Error("Failed to fetch orders"))}finally{V===de.current&&u(!1)}},[a,c,g,H,t]);At.useEffect(()=>{me()},[me]);let be=Math.ceil(r/g);return{orders:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<be-1,hasPreviousPage:c>0,setPage:b,setPageSize:V=>{m(V),b(0)},status:p,setStatus:V=>{f(V),b(0)},statusIn:A,setStatusIn:V=>{C(V&&V.length>0?V:void 0),b(0)},customerEmail:v,setCustomerEmail:V=>{x(V),b(0)},from:k,setFrom:V=>{T(V),b(0)},to:h,setTo:V=>{R(V),b(0)},showAbandoned:P,setShowAbandoned:V=>{D(V),b(0)},unfulfilledOnly:N,setUnfulfilledOnly:V=>{E(V),b(0)},clearFilters:()=>{f(void 0),C(void 0),D(!1),E(!1),x(""),T(""),R(""),b(0)},filters:H,refetch:me}}var Ht=ce(require("react"),1),Ye=require("lucide-react");var Yl=ce(require("react"),1),Tn=ce(require("@radix-ui/react-popover"),1);var pi=require("react/jsx-runtime"),gi=Tn.Root,vi=Tn.Trigger;var Pr=Yl.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},n)=>(0,pi.jsx)(Tn.Portal,{children:(0,pi.jsx)("div",{className:"aifeatures-admin",children:(0,pi.jsx)(Tn.Content,{ref:n,align:t,sideOffset:a,className:X("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...s})})}));Pr.displayName=Tn.Content.displayName;var kr=require("react/jsx-runtime"),Cu={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Tu(e){return Cu[e]??e}function Jl(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 gs({status:e,className:t}){return(0,kr.jsx)(ie,{variant:Jl(e),className:t,children:Tu(e)})}function ss({status:e}){return(0,kr.jsx)(gs,{status:e})}function Hs({order:e,className:t}){return e.line_items.some(a=>a.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,kr.jsx)(ie,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,kr.jsx)(ie,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function qn(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var w=require("react/jsx-runtime"),tc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",vs="af-text-xs af-text-muted-foreground";function fo(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 Eu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ac(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 bi=24,Iu=["paid","partially_refunded"],Du=["paid","partially_refunded","disputed"],Au=/^[A-Za-z0-9 _-]*$/,Xl=100;function go(e,t,a,s,n){let r=Iu.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 ${a} of ${bi} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${bi} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?a<bi&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:a<bi&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${a} attempt${a===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${s==="refunded"?"because the order was refunded":s==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function Ql({title:e,recipient:t,status:a,attempts:s,side:n,orderStatus:r,action:i,delivery:l}){if(l)return(0,w.jsxs)("div",{children:[(0,w.jsx)(Pn,{deliveries:[l]}),i&&(0,w.jsx)("div",{className:"af-mt-2",children:i})]});let u=go(n,a,s,r,t);return(0,w.jsxs)("div",{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)("div",{className:"af-text-sm",children:e}),t&&(0,w.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,w.jsx)(ie,{variant:u.variant,className:"af-shrink-0",children:u.label})]}),u.detail&&(0,w.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:u.detail}),i&&(0,w.jsx)("div",{className:"af-mt-2",children:i})]})}function ec(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=Eu(e.address)?e.address:null;if(a){for(let n of["line1","line2"]){let r=a[n];typeof r=="string"&&r&&t.push(r)}let s=["city","state","postal_code"].map(n=>a[n]).filter(n=>typeof n=="string"&&!!n).join(", ");s&&t.push(s),typeof a.country=="string"&&a.country&&t.push(a.country)}return t.length>0?t:Object.entries(e).map(([s,n])=>`${s}: ${ac(n)}`)}function Lu(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function vo({value:e,label:t,children:a,className:s,size:n="icon"}){let[r,i]=Ht.useState(!1);if(!Lu())return null;let l=async()=>{try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},u=r?(0,w.jsx)(Ye.Check,{className:"af-h-3 af-w-3"}):(0,w.jsx)(Ye.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,w.jsx)(y,{variant:"ghost",size:"icon",className:X("af-h-6 af-w-6 af-shrink-0",s),onClick:l,title:t,"aria-label":t,children:u}):(0,w.jsxs)(y,{variant:"outline",size:"sm",className:s,onClick:l,"aria-label":t,children:[r?(0,w.jsx)(Ye.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,w.jsx)(Ye.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":a]})}function mo({label:e,value:t}){return(0,w.jsxs)("div",{children:[(0,w.jsx)("div",{className:vs,children:e}),(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,w.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,w.jsx)(vo,{value:t,label:`Copy ${e}`})]})]})}function Ou({src:e}){let[t,a]=Ht.useState(!1);return!e||t?(0,w.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,w.jsx)(Ye.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,w.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>a(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function En({title:e,action:t,children:a,className:s}){return(0,w.jsxs)("section",{className:X("af-rounded-lg af-border af-p-4",s),children:[(0,w.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,w.jsx)("h4",{className:tc,children:e}),t]}),(0,w.jsx)("div",{className:"af-mt-3",children:a})]})}function ka({label:e,emphasis:t,divider:a,children:s}){return(0,w.jsxs)("div",{className:X("af-flex af-items-baseline af-justify-between af-gap-6",a&&"af-mt-2 af-border-t af-pt-2"),children:[(0,w.jsx)("span",{className:t?"af-text-base af-font-semibold":vs,children:e}),(0,w.jsx)("span",{className:X("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function po({onSelect:e,disabled:t,icon:a,children:s}){return(0,w.jsxs)(y,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,w.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function Bu(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 ${ee(fi(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),s=a?li(a):go("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),s=a?li(a):go("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${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 ${ee(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 Cr({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:n=!1,onPrevOrder:r,onNextOrder:i,hasPrevOrder:l=!1,hasNextOrder:u=!1}){let{api:d}=W(),[o,c]=Ht.useState(e),[b,g]=Ht.useState(null),[m,p]=Ht.useState(null),[f,v]=Ht.useState(!1),[x,k]=Ht.useState(!1),[T,h]=Ht.useState(!1),[R,P]=Ht.useState(!1),[D,N]=Ht.useState(""),[E,A]=Ht.useState(!1),[C,K]=Ht.useState(null),[Q,H]=Ht.useState(!1),[de,me]=Ht.useState(""),[be,V]=Ht.useState([]),[J,F]=Ht.useState(!1),[ge,pe]=Ht.useState(!1),[He,Pe]=Ht.useState(null);Ht.useEffect(()=>{c(e)},[e]);let Ue=$=>{let nt=$.id===o.id&&$.email_deliveries===void 0?{...$,email_deliveries:o.email_deliveries}:$;c(nt),s?.(nt)},ze=Object.entries(o.metadata??{}),fe=Math.max(0,fi(o)-o.amount_refunded),lt=(o.status==="paid"||o.status==="partially_refunded")&&fe>0,L=o.exclusive_tax_total!=null,M=$=>typeof $.amountNet=="number"?$.amountNet+($.exclusiveTax??0):(typeof $.unitAmount=="number"?$.unitAmount:0)*(typeof $.quantity=="number"&&$.quantity>0?$.quantity:1),U=Math.max(0,(o.shipping_total??0)-(o.shipping_refunded??0)),Te=be.reduce(($,nt)=>$+M(o.line_items[nt]??{}),0)+(J?U:0),ne=o.tax_total??0,Re=Math.max(0,(o.exclusive_tax_total??0)-o.line_items.reduce(($,nt)=>$+(nt.exclusiveTax??0),0)),je=L?J&&U>0?Re:0:o.automatic_tax&&o.tax_behavior==="exclusive"&&ne>0&&o.amount_total+(o.shipping_total??0)>0?Math.min(Math.max(0,ne-(o.tax_refunded??0)),Math.round(ne*Te/(o.amount_total+(o.shipping_total??0)))):0,wt=o.source==="subscription"&&(o.credit_applied??0)>0&&o.line_items.length===1?Math.min(Te+je,fe):Te+je,et=be.length>0||J,Dt=et?wt:ia(de,o.currency),Ne=Ga(o.currency)?"1":"0.01",Le=async()=>{try{v(!0),g(null),p(null),await d.resendOrderReceipt(o.id);let $=await d.getOrder(o.id);Ue($),p("Receipt email queued.")}catch($){g($ instanceof Error?$.message:"Failed to resend receipt")}finally{v(!1)}},ct=async()=>{try{k(!0),g(null),p(null);let $=await d.resetOrderDownloads(o.id);Ue($),h(!1),p("Download count reset.")}catch($){g($ instanceof Error?$.message:"Failed to reset downloads")}finally{k(!1)}},at=o.line_items.some($=>$.collectShippingAddress===!0&&!$.refunded&&!$.unavailableReason),qt=typeof o.merchant_fulfilled_at=="string",Ut=Du.includes(o.status)||o.status==="refunded"&&o.line_items.some($=>$.collectShippingAddress===!0&&$.amountNet===0&&!$.refunded&&!$.unavailableReason),sa=D.trim(),dt=Au.test(sa)&&sa.length<=Xl,ht=async $=>{try{A(!0),K(null),p(null);let nt=await d.setOrderFulfillment(o.id,{fulfilled:$,...$&&sa?{trackingNumber:sa}:{}});Ue(nt),N(""),p($?"Marked as shipped.":"Marked as not shipped.")}catch(nt){nt instanceof jt&&nt.status===409?K(`This order is ${o.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):K(nt instanceof Error?nt.message:"Failed to update the order")}finally{A(!1)}},ke=()=>{Pe(null),me(String(kt(fe,o.currency))),V([]),F(!1),H(!0)},ut=$=>V(nt=>nt.includes($)?nt.filter(_a=>_a!==$):[...nt,$]),tt=async($,nt)=>{if(a)try{pe(!0),Pe(null),await a(o,$,nt);let _a=await d.getOrder(o.id);Ue(_a),H(!1),p("Refund issued.")}catch(_a){Pe(_a instanceof Error?_a.message:"Refund failed")}finally{pe(!1)}},St=async()=>{if(et){if(wt<=0){Pe("The lines you picked were charged nothing");return}if(wt>fe){Pe(`That selection exceeds the refundable remainder (${ee(fe,o.currency)})`);return}await tt(wt,{...be.length>0?{line_items:[...be].sort((nt,_a)=>nt-_a)}:{},...J?{shipping:!0}:{}});return}let $=ia(de,o.currency);if($===null||$<=0){Pe("Enter a valid refund amount");return}if($>fe){Pe(`Amount exceeds the refundable remainder (${ee(fe,o.currency)})`);return}await tt($,{amount:$})},z=()=>tt(fe,{full:!0}),Xe=!o.subscription_history_only&&o.fulfillment_type==="download",ra=!o.subscription_history_only&&n&&at,Ms=Bu(o),re=o.shipping_address?ec(o.shipping_address).join(`
4
+ `):"",ya=o.shipping_total!=null,no=o.exclusive_tax_total??(o.automatic_tax&&o.tax_behavior==="exclusive"?o.tax_total??0:0),gl=o.exclusive_tax_total!=null?Math.max(0,(o.tax_total??0)-no):o.automatic_tax&&o.tax_behavior==="exclusive"?0:o.tax_total??0,vl=no>0,Zd=gl>0,bl=o.amount_subtotal!=null||ya||vl||(o.discount_total??0)>0,sr=[];return o.subscription_history_only||sr.push((0,w.jsx)(po,{icon:f?(0,w.jsx)(Ye.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,w.jsx)(Ye.Mail,{className:"af-h-4 af-w-4"}),disabled:f||o.fulfillment_status!=="fulfilled",onSelect:()=>{P(!1),Le()},children:"Resend receipt"},"resend")),Xe&&sr.push((0,w.jsx)(po,{icon:(0,w.jsx)(Ye.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{P(!1),h(!0)},children:"Reset download count"},"reset")),lt&&sr.push((0,w.jsxs)("div",{children:[(0,w.jsx)(po,{icon:(0,w.jsx)(Ye.Undo2,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{P(!1),ke()},children:"Refund\u2026"}),!a&&(0,w.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,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"af-mb-6",children:[(0,w.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,w.jsx)(Ye.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(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:[(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)("h3",{className:"af-text-xl af-font-semibold",children:qn(o)}),(0,w.jsx)(gs,{status:o.status}),n&&!o.subscription_history_only&&(0,w.jsx)(Hs,{order:o}),o.is_test&&(0,w.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,w.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",fo(o.created_at)]}),o.is_test&&(0,w.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,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||i)&&(0,w.jsxs)("div",{className:"af-flex af-items-center",children:[(0,w.jsx)(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!l,"aria-label":"Previous order",children:(0,w.jsx)(Ye.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,w.jsx)(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:i,disabled:!u,"aria-label":"Next order",children:(0,w.jsx)(Ye.ChevronRight,{className:"af-h-4 af-w-4"})})]}),ra&&(qt?(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,w.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",o.merchant_fulfilled_at?` \xB7 ${fo(o.merchant_fulfilled_at)}`:""]}),Ut&&(0,w.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>ht(!1),disabled:E,children:[E?(0,w.jsx)(Ye.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,w.jsx)(Ye.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Ut?(0,w.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,w.jsx)(oe,{value:D,onChange:$=>N($.target.value),placeholder:"Tracking number (optional)",maxLength:Xl,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:E}),(0,w.jsxs)(y,{variant:"default",className:"af-shrink-0",onClick:()=>ht(!0),disabled:E||!dt,children:[E?(0,w.jsx)(Ye.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,w.jsx)(Ye.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),sr.length>0&&(0,w.jsxs)(gi,{open:R,onOpenChange:P,children:[(0,w.jsx)(vi,{asChild:!0,children:(0,w.jsx)(y,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,w.jsx)(Ye.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,w.jsx)(Pr,{children:(0,w.jsx)("div",{className:"af-space-y-0.5",children:sr})})]})]})]}),ra&&!qt&&!dt&&(0,w.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,w.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}),m&&(0,w.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:m}),b&&(0,w.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,w.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,w.jsxs)("div",{className:"af-space-y-6",children:[o.line_items.length>0&&(0,w.jsx)(En,{title:"Items",children:(0,w.jsx)("ul",{className:"af-space-y-3",children:o.line_items.map(($,nt)=>{let _a=typeof $.name=="string"&&$.name?$.name:"Item",hl=typeof $.quantity=="number"&&$.quantity>0?$.quantity:1,yl=typeof $.unitAmount=="number";return(0,w.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,w.jsx)(Ou,{src:typeof $.imageUrl=="string"&&$.imageUrl?$.imageUrl:void 0}),(0,w.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,w.jsxs)("div",{className:"af-text-sm af-font-medium",children:[_a,typeof $.variantTitle=="string"&&$.variantTitle&&(0,w.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",$.variantTitle]})]}),(0,w.jsxs)("div",{className:vs,children:[hl," \xD7"," ",yl?ee($.unitAmount,o.currency):"\u2014"]}),$.unavailableReason==="oversold"&&!$.refunded&&(0,w.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:$.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),$.refunded===!0&&(0,w.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:$.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,w.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof $.amountNet=="number"||yl?ee($.amountNet??$.unitAmount*hl,o.currency):"\u2014"})]},nt)})})}),ze.length>0&&(0,w.jsx)(En,{title:"Order details",children:(0,w.jsx)("dl",{className:"af-space-y-2",children:ze.map(([$,nt])=>(0,w.jsxs)("div",{children:[(0,w.jsx)("dt",{className:X(vs,"af-capitalize"),children:$.replace(/_/g," ")}),(0,w.jsx)("dd",{className:"af-text-sm af-break-words",children:ac(nt)})]},$))})}),(0,w.jsx)(En,{title:"Totals",children:(0,w.jsxs)("div",{className:"af-w-full",children:[bl&&(0,w.jsx)(ka,{label:"Subtotal",children:ee(o.amount_subtotal??o.amount_total+(o.discount_total??0),o.currency)}),(o.discount_total??0)>0&&(0,w.jsxs)(ka,{label:"Discount",children:["\u2212",ee(o.discount_total,o.currency)]}),ya&&(0,w.jsx)(ka,{label:"Shipping",children:o.shipping_total===0?"Free":ee(o.shipping_total??0,o.currency)}),vl&&(0,w.jsx)(ka,{label:"Tax",children:ee(no,o.currency)}),(0,w.jsx)(ka,{label:"Total",emphasis:!0,divider:bl,children:ee(Cn(o),o.currency)}),(o.credit_applied??0)>0&&(0,w.jsxs)(ka,{label:"Credit applied",children:["\u2212",ee(o.credit_applied,o.currency)]}),o.amount_paid!=null&&(0,w.jsx)(ka,{label:"Amount paid",children:ee(o.amount_paid,o.currency)}),Zd&&(0,w.jsx)(ka,{label:"incl. tax",children:ee(gl,o.currency)}),o.base_currency!=null&&o.base_amount_total!=null&&(0,w.jsxs)(ka,{label:"Your price",children:[ee(o.base_amount_total,o.base_currency),(0,w.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",o.currency.toUpperCase()]})]}),o.amount_refunded>0&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(ka,{label:"Refunded",children:["\u2212",ee(o.amount_refunded,o.currency),(o.shipping_refunded??0)>0&&(0,w.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",ee(o.shipping_refunded??0,o.currency)," ","shipping"]})]}),(0,w.jsx)(ka,{label:"Net",children:(0,w.jsx)("span",{className:"af-font-medium",children:ee(Math.max(0,fi(o)-o.amount_refunded),o.currency)})})]})]})}),o.application_fee_state&&(0,w.jsxs)(En,{title:"Platform fee",children:[o.application_fee_original!=null&&(0,w.jsx)(ka,{label:"Collected",children:ee(o.application_fee_original,o.application_fee_currency??o.currency)}),o.application_fee_returned!=null&&(0,w.jsx)(ka,{label:"Returned",children:ee(o.application_fee_returned,o.application_fee_currency??o.currency)}),o.application_fee_retained!=null&&(0,w.jsx)(ka,{label:"Retained",children:ee(o.application_fee_retained,o.application_fee_currency??o.currency)}),o.application_fee_state!=="complete"&&(0,w.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:o.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,w.jsx)(En,{title:"Timeline",children:(0,w.jsx)("ol",{className:"af-space-y-3",children:Ms.map($=>(0,w.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,w.jsx)("span",{"aria-hidden":"true",className:X("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",$.tone==="destructive"?"af-bg-destructive":$.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,w.jsxs)("div",{className:"af-min-w-0",children:[(0,w.jsx)("div",{className:"af-text-sm af-break-words",children:$.text}),$.at&&(0,w.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:fo($.at)})]})]},$.key))})})]}),(0,w.jsxs)("div",{className:"af-space-y-6",children:[(0,w.jsx)(En,{title:"Customer",children:(0,w.jsxs)("div",{className:"af-space-y-2",children:[(0,w.jsxs)("div",{children:[(0,w.jsx)("div",{className:vs,children:"Email"}),(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,w.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:o.customer_email||(0,w.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),o.customer_email&&(0,w.jsx)(vo,{value:o.customer_email,label:"Copy email"})]})]}),o.customer_name&&(0,w.jsxs)("div",{children:[(0,w.jsx)("div",{className:vs,children:"Name"}),(0,w.jsx)("div",{className:"af-text-sm",children:o.customer_name})]}),o.customer&&(0,w.jsxs)("div",{children:[(0,w.jsx)("div",{className:vs,children:"Customer record"}),(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)("span",{className:"af-break-all af-text-sm",children:o.customer.name||o.customer.email}),(0,w.jsx)(ie,{variant:"secondary",children:"Linked"})]})]})]})}),o.shipping_address&&(0,w.jsx)(En,{title:"Ship to",action:(0,w.jsx)(vo,{value:re,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,w.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:ec(o.shipping_address).map(($,nt)=>(0,w.jsx)("div",{children:$},nt))})}),o.subscription_history_only?(0,w.jsx)(En,{title:"Subscription history",children:(0,w.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,w.jsxs)(En,{title:"Emails",children:[(0,w.jsx)(Pn,{deliveries:o.email_deliveries?.filter($=>!["purchase_receipt","merchant_sale"].includes($.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,w.jsxs)("div",{className:"af-space-y-4",children:[(0,w.jsx)(Ql,{side:"buyer",title:"Receipt to buyer",delivery:o.email_deliveries?.find($=>$.kind==="purchase_receipt"),recipient:o.customer_email,status:o.buyer_email_status,attempts:o.buyer_email_attempts,orderStatus:o.status,action:(0,w.jsxs)(y,{variant:"outline",size:"sm",onClick:Le,disabled:f||o.fulfillment_status!=="fulfilled",children:[f?(0,w.jsx)(Ye.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,w.jsx)(Ye.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,w.jsx)(Ql,{side:"merchant",title:"Sale alert to you",delivery:o.email_deliveries?.find($=>$.kind==="merchant_sale"),recipient:null,status:o.merchant_email_status,attempts:o.merchant_email_attempts,orderStatus:o.status})]})]}),Xe&&(0,w.jsx)(En,{title:"Download",children:(0,w.jsxs)("div",{className:"af-space-y-2",children:[(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,w.jsx)(Ye.Download,{className:"af-h-4 af-w-4"}),(0,w.jsxs)("span",{children:["Downloaded ",o.download_count," time",o.download_count===1?"":"s"]})]}),o.download_url&&(0,w.jsx)("a",{href:o.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,w.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,w.jsx)("summary",{className:X(tc,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,w.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,w.jsx)(mo,{label:"Order ID",value:o.id}),o.stripe_checkout_session_id&&(0,w.jsx)(mo,{label:"Checkout session",value:o.stripe_checkout_session_id}),o.stripe_payment_intent_id&&(0,w.jsx)(mo,{label:"Payment",value:o.stripe_payment_intent_id})]})]})]})]}),(0,w.jsx)(nn,{open:T,onOpenChange:$=>{!$&&!x&&h(!1)},children:(0,w.jsxs)($a,{children:[(0,w.jsxs)(Va,{children:[(0,w.jsx)(za,{children:"Reset download count?"}),(0,w.jsx)(qa,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,w.jsxs)(Ha,{children:[(0,w.jsx)(y,{variant:"outline",onClick:()=>h(!1),disabled:x,children:"Cancel"}),(0,w.jsx)(y,{onClick:ct,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),(0,w.jsx)(nn,{open:Q,onOpenChange:$=>{!$&&!ge&&H(!1)},children:(0,w.jsxs)($a,{children:[(0,w.jsxs)(Va,{children:[(0,w.jsx)(za,{children:"Refund order"}),(0,w.jsxs)(qa,{children:["Refund up to ",ee(fe,o.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,w.jsxs)("div",{className:"af-space-y-4",children:[(o.line_items.length>0||U>0)&&(0,w.jsxs)("div",{className:"af-space-y-2",children:[(0,w.jsx)(Ve,{children:"Items"}),(0,w.jsxs)("div",{className:"af-space-y-2",children:[o.line_items.map(($,nt)=>{let _a=$.refunded===!0;return(0,w.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,w.jsx)("input",{type:"checkbox",checked:be.includes(nt),onChange:()=>ut(nt),disabled:ge||_a||!!$.unavailableReason||M($)<=0,className:"af-h-4 af-w-4"}),(0,w.jsxs)("span",{className:_a?"af-text-muted-foreground af-line-through":void 0,children:[typeof $.name=="string"&&$.name?$.name:"Item",typeof $.variantTitle=="string"&&$.variantTitle?` \u2014 ${$.variantTitle}`:"",typeof $.quantity=="number"&&$.quantity>1?` \xD7 ${$.quantity}`:""]}),(0,w.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:_a?"Refunded":ee(M($),o.currency)})]},nt)}),U>0&&(0,w.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,w.jsx)("input",{type:"checkbox",checked:J,onChange:$=>F($.target.checked),disabled:ge,className:"af-h-4 af-w-4"}),(0,w.jsx)("span",{children:"Shipping"}),(0,w.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:ee(U,o.currency)})]})]})]}),(0,w.jsxs)("div",{className:"af-space-y-2",children:[(0,w.jsxs)(Ve,{htmlFor:"refund-amount",children:["Amount (",o.currency.toUpperCase(),")"]}),(0,w.jsx)(oe,{id:"refund-amount",type:"number",min:"0",step:Ne,value:et?String(kt(wt,o.currency)):de,onChange:$=>me($.target.value),disabled:ge||et}),et&&(0,w.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),He&&(0,w.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:He}),(0,w.jsxs)(Ha,{children:[(0,w.jsx)(y,{variant:"outline",onClick:()=>H(!1),disabled:ge,children:"Cancel"}),(0,w.jsx)(y,{variant:"outline",onClick:z,disabled:ge,children:"Refund everything"}),(0,w.jsx)(y,{variant:"destructive",onClick:St,disabled:ge,children:ge?"Refunding...":Dt!==null&&Dt>0?`Refund ${ee(Dt,o.currency)}`:"Refund"})]})]})})]})}var hi=ce(require("react"),1),yi=require("lucide-react");var Tt=require("react/jsx-runtime");function Lt({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:n}){let r=hi.useRef(null);return hi.useEffect(()=>{r.current?.focus()},[]),(0,Tt.jsxs)("div",{className:X("af-bg-background",n),children:[(0,Tt.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,Tt.jsx)("h2",{ref: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&&!a&&(0,Tt.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,Tt.jsx)(yi.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,Tt.jsx)("div",{className:"af-p-4",children:s})]})}function ae({className:e}){return(0,Tt.jsx)("div",{"aria-hidden":"true",className:X("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function gt({label:e,children:t,detail:a,valueClassName:s}){return(0,Tt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,Tt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,Tt.jsx)("div",{className:X("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&(0,Tt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function Et({message:e,onRetry:t}){return(0,Tt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Tt.jsx)("span",{children:e}),(0,Tt.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,Tt.jsx)(yi.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function va({icon:e,children:t}){return(0,Tt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,Tt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function zs({icon:e,heading:t,body:a,action:s,className:n,children:r}){return(0,Tt.jsxs)("div",{className:X("af-px-6 af-py-10 af-text-center",n),children:[(0,Tt.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,Tt.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,Tt.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&(0,Tt.jsx)(y,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}var O=require("react/jsx-runtime"),Fu={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},nc={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function sc(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 rc(e){let t=Array.isArray(e.line_items)?e.line_items:[],a=t[0];if(!a)return"\u2014";let s=typeof a.name=="string"&&a.name?a.name:"Item",n=typeof a.quantity=="number"&&a.quantity>0?a.quantity:1,r=n>1?`${s} \xD7${n}`:s;return t.length>1?`${r} +${t.length-1} more`:r}function xi(e){return e.customer?.name||e.customer_name||null}function Mu({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:n=!1,emptyMessage:r,onDetailOpenChange:i,maxRows:l,onViewAll:u}){let d=typeof l=="number",{api:o}=W(),c=_r({refreshKey:a}),{orders:b,total:g,isLoading:m,error:p,page:f,pageSize:v,hasNextPage:x,hasPreviousPage:k,setPage:T,setPageSize:h,customerEmail:R,setCustomerEmail:P,setStatusIn:D,from:N,setFrom:E,to:A,setTo:C,showAbandoned:K,setShowAbandoned:Q,setUnfulfilledOnly:H,filters:de,refetch:me}=c,be=Qt.useCallback(()=>o.exportOrdersCsv(de),[o,de]),[V,J]=Qt.useState("list"),[F,ge]=Qt.useState(null),[pe,He]=Qt.useState(""),[Pe,Ue]=Qt.useState(""),[ze,fe]=Qt.useState(!d&&n?"needs_shipping":"all"),[lt,L]=Qt.useState(!1),[M,U]=Qt.useState(!!s&&!d),[Te,ne]=Qt.useState(null);Qt.useEffect(()=>{if(!s||d)return;let re=!1;return U(!0),ne(null),o.getOrder(s).then(ya=>{re||(ge(ya),J("detail"))}).catch(()=>{re||ne("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{re||U(!1)}),()=>{re=!0}},[o,s,d]);let Re=Qt.useCallback(re=>{fe(re);let ya=nc[re];D(ya.statusIn),H(ya.unfulfilledOnly)},[D,H]);Qt.useEffect(()=>{n&&!d&&H(!0)},[]);let je=Qt.useRef(!n);Qt.useEffect(()=>{je.current||m||(je.current=!0,b.length===0&&Re("all"))},[m,b.length,Re]);let wt=V==="detail"&&!!F;Qt.useEffect(()=>{i?.(wt)},[wt,i]);let et=(N?1:0)+(A?1:0)+(K?1:0),Dt=et>0||!!R||!!Pe,Ne=!!N&&!!A&&N>A,Le=!d||!!u,ct=re=>{if(d){u?.();return}ge(re),J("detail")},at=()=>{J("list"),ge(null),me()},qt=re=>{let ya=re.trim();if(!ya){Ue(""),R&&P("");return}if(ya.startsWith("#")||/^\d+$/.test(ya)){Ue(ya),R&&P("");return}Ue(""),P(ya)},Ut=()=>{He(""),Ue(""),P(""),E(""),C(""),Q(!1),L(!1)},sa=Pe.replace(/^#/,"").toLowerCase(),dt=sa?b.filter(re=>String(re.order_number??"")===sa||re.id.toLowerCase().startsWith(sa)):b,ht=d?dt.slice(0,l):dt,ke=F?b.findIndex(re=>re.id===F.id):-1,ut=ke>0,tt=ke>=0&&ke<b.length-1;if(M)return(0,O.jsx)("div",{className:t,children:(0,O.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,O.jsx)(Za.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(V==="detail"&&F)return(0,O.jsx)("div",{className:t,children:(0,O.jsx)(Cr,{order:F,onBack:at,onRefund:e,onOrderUpdated:re=>ge(re),allowFulfillment:n,onPrevOrder:ut?()=>ge(b[ke-1]):void 0,onNextOrder:tt?()=>ge(b[ke+1]):void 0,hasPrevOrder:ut,hasNextOrder:tt},F.id)});let z=(0,O.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[Te&&(0,O.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:Te}),(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,O.jsx)("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(re=>(0,O.jsx)("button",{type:"button","aria-pressed":ze===re,onClick:()=>Re(re),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",ze===re?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Fu[re]},re))}),(0,O.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,O.jsx)(Za.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,O.jsx)(oe,{type:"text",value:pe,onChange:re=>He(re.target.value),onBlur:()=>qt(pe),onKeyDown:re=>{re.key==="Enter"&&(re.preventDefault(),qt(pe))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,O.jsxs)(y,{type:"button",variant:et>0?"secondary":"ghost",size:"sm",onClick:()=>L(re=>!re),"aria-expanded":lt,children:[(0,O.jsx)(Za.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",et>0&&(0,O.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:et})]}),Dt&&(0,O.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:Ut,children:"Clear filters"}),(0,O.jsx)(da,{fetchCsv:be,filename:"orders",disabled:!!Pe,className:"af-ml-auto"})]}),(lt||!!N||!!A)&&(0,O.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,O.jsx)(Ve,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,O.jsx)(oe,{id:"orders-from",type:"date",value:N,max:A||void 0,onChange:re=>E(re.target.value),className:"af-w-[170px]"}),(0,O.jsx)(Ve,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,O.jsx)(oe,{id:"orders-to",type:"date",value:A,min:N||void 0,onChange:re=>C(re.target.value),className:"af-w-[170px]"}),!nc[ze].statusIn&&(0,O.jsx)(y,{type:"button",variant:K?"secondary":"ghost",size:"sm",onClick:()=>Q(!K),"aria-pressed":K,children:K?"Hide abandoned":"Show abandoned"})]}),Ne&&(0,O.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(m)return(0,O.jsxs)("div",{className:t,children:[d?null:z,(0,O.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(re=>(0,O.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)(ae,{className:"af-h-4 af-w-16"}),(0,O.jsx)(ae,{className:"af-h-4 af-w-14"})]}),(0,O.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-40"}),(0,O.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-24"})]},re))}),(0,O.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,O.jsxs)(ft,{children:[(0,O.jsx)(mt,{children:(0,O.jsxs)(Fe,{children:[(0,O.jsx)(Z,{children:"Order"}),(0,O.jsx)(Z,{children:"Date"}),(0,O.jsx)(Z,{children:"Customer"}),(0,O.jsx)(Z,{children:"Items"}),(0,O.jsx)(Z,{className:"af-text-right",children:"Total"}),(0,O.jsx)(Z,{children:"Status"}),(0,O.jsx)(Z,{className:"af-w-8"})]})}),(0,O.jsx)(pt,{"aria-hidden":"true",children:[0,1,2,3,4].map(re=>(0,O.jsxs)(Fe,{children:[(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-4 af-w-14"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-4 af-w-40"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-4 af-w-32"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-5 af-w-16"})}),(0,O.jsx)(Y,{})]},re))})]})}),(0,O.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(p)return(0,O.jsxs)("div",{className:t,children:[d?null:z,(0,O.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,O.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,O.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>me(),children:"Try again"})]})]});let Xe=ze!=="all";if(dt.length===0&&f===0)return Dt||Xe?(0,O.jsxs)("div",{className:t,children:[!d&&z,(0,O.jsx)(va,{children:"No orders match these filters."})]}):(0,O.jsx)("div",{className:t,children:(0,O.jsx)(zs,{icon:Za.Receipt,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!d&&(0,O.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>Q(!0),children:"Show abandoned checkouts"})})});let ra=f*v+1,Ms=Math.min((f+1)*v,g);return(0,O.jsxs)("div",{className:t,children:[d?null:z,(0,O.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ht.map(re=>(0,O.jsxs)("button",{type:"button",onClick:()=>ct(re),disabled:!Le,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Le?" hover:af-bg-muted/50":""}`,children:[(0,O.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,O.jsx)("span",{className:"af-font-medium",children:qn(re)}),(0,O.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:ee(Cn(re),re.currency)})]}),(0,O.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,O.jsxs)("div",{className:"af-truncate af-text-sm",children:[re.customer_email||(0,O.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),xi(re)&&(0,O.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",xi(re)]})]}),(0,O.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:rc(re)}),re.amount_refunded>0&&(0,O.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",ee(re.amount_refunded,re.currency)," refunded"]})]}),(0,O.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,O.jsx)(gs,{status:re.status}),(0,O.jsx)(dr,{deliveries:re.email_deliveries}),re.is_test&&(0,O.jsx)(ie,{variant:"outline",children:"Test"}),n&&(0,O.jsx)(Hs,{order:re}),(0,O.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:sc(re.created_at)})]})]},re.id))}),(0,O.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,O.jsxs)(ft,{children:[(0,O.jsx)(mt,{children:(0,O.jsxs)(Fe,{children:[(0,O.jsx)(Z,{children:"Order"}),(0,O.jsx)(Z,{children:"Date"}),(0,O.jsx)(Z,{children:"Customer"}),(0,O.jsx)(Z,{children:"Items"}),(0,O.jsx)(Z,{className:"af-text-right",children:"Total"}),(0,O.jsx)(Z,{children:"Status"}),(0,O.jsx)(Z,{className:"af-w-8"})]})}),(0,O.jsx)(pt,{children:ht.map(re=>(0,O.jsxs)(Fe,{onClick:Le?()=>ct(re):void 0,className:Le?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,O.jsxs)(Y,{className:"af-whitespace-nowrap af-font-medium",children:[(0,O.jsx)("button",{type:"button",onClick:ya=>{ya.stopPropagation(),ct(re)},disabled:!Le,"aria-label":`Open order ${qn(re)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Le?" hover:af-underline":""}`,children:qn(re)}),re.is_test&&(0,O.jsx)(ie,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,O.jsx)(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:sc(re.created_at)}),(0,O.jsxs)(Y,{className:"af-max-w-[220px]",children:[(0,O.jsx)("div",{className:"af-truncate",children:re.customer_email||(0,O.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),xi(re)&&(0,O.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:xi(re)})]}),(0,O.jsx)(Y,{className:"af-max-w-[220px]",children:(0,O.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:rc(re)})}),(0,O.jsxs)(Y,{className:"af-whitespace-nowrap af-text-right",children:[(0,O.jsx)("div",{className:"af-font-medium af-tabular-nums",children:ee(Cn(re),re.currency)}),re.amount_refunded>0&&(0,O.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",ee(re.amount_refunded,re.currency)," ","refunded"]})]}),(0,O.jsx)(Y,{children:(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,O.jsx)(gs,{status:re.status}),(0,O.jsx)(dr,{deliveries:re.email_deliveries}),n&&(0,O.jsx)(Hs,{order:re})]})}),(0,O.jsx)(Y,{className:"af-w-8 af-text-right",children:(0,O.jsx)(Za.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},re.id))})]})}),d?null:(0,O.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,O.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,O.jsx)("span",{children:sa?`${dt.length} matching this page`:`Showing ${ra}-${Ms} of ${g}`}),(0,O.jsxs)(tn,{value:String(v),onValueChange:re=>h(Number(re)),children:[(0,O.jsx)(Ma,{className:"af-w-[70px] af-h-8",children:(0,O.jsx)(an,{})}),(0,O.jsxs)(Ua,{children:[(0,O.jsx)(Rt,{value:"10",children:"10"}),(0,O.jsx)(Rt,{value:"25",children:"25"}),(0,O.jsx)(Rt,{value:"50",children:"50"}),(0,O.jsx)(Rt,{value:"100",children:"100"})]})]}),(0,O.jsx)("span",{children:"per page"})]}),(0,O.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,O.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>T(f-1),disabled:!k,children:[(0,O.jsx)(Za.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,O.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>T(f+1),disabled:!x,children:["Next",(0,O.jsx)(Za.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function jn(e){return(0,O.jsx)(Mu,{...e},e.maxRows==null?"full":"compact")}var qs=ce(require("react"),1),In=require("lucide-react");var Ca=ce(require("react"),1);function Tr({initialPageSize:e=25}={}){let{api:t}=W(),[a,s]=Ca.useState([]),[n,r]=Ca.useState(0),[i,l]=Ca.useState(!0),[u,d]=Ca.useState(null),[o,c]=Ca.useState(0),[b,g]=Ca.useState(e),[m,p]=Ca.useState(""),f=Ca.useRef(0),v=Ca.useCallback(async()=>{let k=++f.current;try{l(!0),d(null);let T={limit:b,offset:o*b};m.trim()&&(T.email=m.trim());let h=await t.getCustomers(T);if(k!==f.current)return;s(h.customers),r(h.total)}catch(T){if(k!==f.current)return;d(T instanceof Error?T:new Error("Failed to fetch customers"))}finally{k===f.current&&l(!1)}},[t,o,b,m]);Ca.useEffect(()=>{v()},[v]);let x=Math.ceil(n/b);return{customers:a,total:n,isLoading:i,error:u,page:o,pageSize:b,hasNextPage:o<x-1,hasPreviousPage:o>0,setPage:c,setPageSize:k=>{g(k),c(0)},email:m,setEmail:k=>{p(k),c(0)},refetch:v}}var bs=ce(require("react"),1),wi=require("lucide-react");var Ie=require("react/jsx-runtime");function ic(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 Uu(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let a=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return a&&t.push(a),e.country&&t.push(e.country),t}function Er({customer:e,onBack:t,className:a}){let{api:s}=W(),[n,r]=bs.useState(null),[i,l]=bs.useState([]),[u,d]=bs.useState(!0),[o,c]=bs.useState(null);bs.useEffect(()=>{let m=!1;return d(!0),c(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([p,f])=>{m||(r(p),l(f.orders))}).catch(p=>{m||c(p instanceof Error?p.message:"Failed to load customer")}).finally(()=>{m||d(!1)}),()=>{m=!0}},[s,e.id,e.email]);let b=n?.addresses??[],g=n?.order_count??i.length;return(0,Ie.jsxs)("div",{className:a,children:[(0,Ie.jsxs)("div",{className:"af-mb-6",children:[(0,Ie.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,Ie.jsx)(wi.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,Ie.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,Ie.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",ic(e.created_at)]})]}),u?(0,Ie.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,Ie.jsx)(wi.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):o?(0,Ie.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o}):(0,Ie.jsxs)("div",{className:"af-space-y-6",children:[(0,Ie.jsx)(Pn,{deliveries:n?.email_deliveries}),(0,Ie.jsxs)("div",{children:[(0,Ie.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,Ie.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,Ie.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ie.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,Ie.jsx)("span",{children:e.email})]}),e.name&&(0,Ie.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ie.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,Ie.jsx)("span",{children:e.name})]}),e.phone&&(0,Ie.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ie.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,Ie.jsx)("span",{children:e.phone})]}),(0,Ie.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ie.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,Ie.jsx)("span",{children:g})]})]})]}),b.length>0&&(0,Ie.jsxs)("div",{children:[(0,Ie.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,Ie.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(m=>(0,Ie.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[m.is_default&&(0,Ie.jsx)(ie,{variant:"secondary",className:"af-mb-1",children:"Default"}),Uu(m).map((p,f)=>(0,Ie.jsx)("div",{children:p},f))]},m.id))})]}),(0,Ie.jsxs)("div",{children:[(0,Ie.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),i.length===0?(0,Ie.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,Ie.jsxs)(ft,{children:[(0,Ie.jsx)(mt,{children:(0,Ie.jsxs)(Fe,{children:[(0,Ie.jsx)(Z,{children:"Date"}),(0,Ie.jsx)(Z,{children:"Amount"}),(0,Ie.jsx)(Z,{children:"Status"})]})}),(0,Ie.jsx)(pt,{children:i.map(m=>(0,Ie.jsxs)(Fe,{children:[(0,Ie.jsx)(Y,{className:"af-text-muted-foreground",children:ic(m.created_at)}),(0,Ie.jsx)(Y,{children:ee(Cn(m),m.currency)}),(0,Ie.jsx)(Y,{children:(0,Ie.jsx)(ss,{status:m.status})})]},m.id))})]})]})]})]})}var we=require("react/jsx-runtime");function $u(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 Ir({className:e}){let{customers:t,total:a,isLoading:s,error:n,page:r,pageSize:i,hasNextPage:l,hasPreviousPage:u,setPage:d,setPageSize:o,email:c,setEmail:b,refetch:g}=Tr(),{api:m}=W(),p=qs.useCallback(()=>m.exportCustomersCsv(),[m]),[f,v]=qs.useState("list"),[x,k]=qs.useState(null),[T,h]=qs.useState(""),R=A=>{k(A),v("detail")},P=()=>{v("list"),k(null),g()};if(f==="detail"&&x)return(0,we.jsx)("div",{className:e,children:(0,we.jsx)(Er,{customer:x,onBack:P})});let D=(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,we.jsx)(oe,{type:"email",value:T,onChange:A=>h(A.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),b(T.trim()))}}),(0,we.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>b(T.trim()),children:[(0,we.jsx)(In.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),c&&(0,we.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),b("")},children:"Clear"}),(0,we.jsx)(da,{fetchCsv:p,filename:"customers",className:"af-ml-auto"})]});if(s)return(0,we.jsxs)("div",{className:e,children:[D,(0,we.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,we.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,we.jsxs)("div",{className:e,children:[D,(0,we.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,we.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&r===0)return(0,we.jsxs)("div",{className:e,children:[c&&D,(0,we.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,we.jsx)(In.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,we.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:c?"No customers match that email.":(0,we.jsxs)(we.Fragment,{children:["No customers yet.",(0,we.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let N=r*i+1,E=Math.min((r+1)*i,a);return(0,we.jsxs)("div",{className:e,children:[D,(0,we.jsxs)(ft,{children:[(0,we.jsx)(mt,{children:(0,we.jsxs)(Fe,{children:[(0,we.jsx)(Z,{children:"Email"}),(0,we.jsx)(Z,{children:"Name"}),(0,we.jsx)(Z,{children:"Phone"}),(0,we.jsx)(Z,{children:"Customer since"}),(0,we.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,we.jsx)(pt,{children:t.map(A=>(0,we.jsxs)(Fe,{children:[(0,we.jsx)(Y,{className:"af-font-medium",children:A.email}),(0,we.jsx)(Y,{children:A.name||(0,we.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,we.jsx)(Y,{children:A.phone||(0,we.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,we.jsx)(Y,{className:"af-text-muted-foreground",children:$u(A.created_at)}),(0,we.jsx)(Y,{className:"af-text-right",children:(0,we.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>R(A),title:"View customer",children:(0,we.jsx)(In.Eye,{className:"af-h-4 af-w-4"})})})]},A.id))})]}),(0,we.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,we.jsxs)("span",{children:["Showing ",N,"-",E," of ",a]}),(0,we.jsxs)(tn,{value:String(i),onValueChange:A=>o(Number(A)),children:[(0,we.jsx)(Ma,{className:"af-w-[70px] af-h-8",children:(0,we.jsx)(an,{})}),(0,we.jsxs)(Ua,{children:[(0,we.jsx)(Rt,{value:"10",children:"10"}),(0,we.jsx)(Rt,{value:"25",children:"25"}),(0,we.jsx)(Rt,{value:"50",children:"50"}),(0,we.jsx)(Rt,{value:"100",children:"100"})]})]}),(0,we.jsx)("span",{children:"per page"})]}),(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,we.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>d(r-1),disabled:!u,children:[(0,we.jsx)(In.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,we.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>d(r+1),disabled:!l,children:["Next",(0,we.jsx)(In.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ge=ce(require("react"),1),Kt=require("lucide-react");var Gt=ce(require("react"),1);function hs({initialPageSize:e=25,refreshKey:t,includeAggregates:a=!1}={}){let{api:s}=W(),[n,r]=Gt.useState([]),[i,l]=Gt.useState(0),[u,d]=Gt.useState(null),[o,c]=Gt.useState(!0),[b,g]=Gt.useState(null),[m,p]=Gt.useState(0),[f,v]=Gt.useState(e),[x,k]=Gt.useState(void 0),[T,h]=Gt.useState(""),[R,P]=Gt.useState(""),[D,N]=Gt.useState(""),[E,A]=Gt.useState(""),[C,K]=Gt.useState(""),Q=x?x.join(","):"",H=Gt.useRef(0),de=Gt.useCallback(async()=>{let be=++H.current;c(!0),g(null);try{let V={labels:Q?Q.split(","):void 0,customerEmail:T||void 0,q:R||void 0,from:D||void 0,to:E||void 0,retainerId:C||void 0,includeAggregates:a,limit:f,offset:m*f},J=await s.getInvoices(V);if(be!==H.current)return;if(m>0&&m*f>=J.total){p(Math.max(0,Math.ceil(J.total/f)-1));return}r(J.invoices),l(J.total),a&&d(J.aggregates??null)}catch(V){if(be!==H.current)return;g(V instanceof Error?V:new Error("Failed to fetch invoices"))}finally{be===H.current&&c(!1)}},[s,Q,T,R,D,E,C,m,f,a]);Gt.useEffect(()=>{de()},[de,t]);let me=be=>V=>{p(0),be(V)};return{invoices:n,total:i,aggregates:u,isLoading:o,error:b,page:m,pageSize:f,hasNextPage:(m+1)*f<i,hasPreviousPage:m>0,setPage:p,setPageSize:me(v),labels:x,setLabels:me(k),customerEmail:T,setCustomerEmail:me(h),q:R,setQ:me(P),from:D,setFrom:me(N),to:E,setTo:me(A),retainerId:C,setRetainerId:me(K),clearFilters:()=>{p(0),k(void 0),h(""),P(""),N(""),A(""),K("")},refetch:de}}var S=require("react/jsx-runtime"),Vu={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 xo(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Vu[e.label]??e.label}function Hu(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 yo={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},zu={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Ws({invoice:e,className:t}){return(0,S.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,S.jsx)(ie,{variant:Hu(e.label),className:t,children:xo(e)}),e.collection_method==="charge_automatically"&&(0,S.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"})]})}function Ri({delivery:e,className:t}){if(!e)return null;let a=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,S.jsx)(ie,{variant:a,className:t,children:yo[e.state]??e.state})}function js(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function cn(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t);return Number.isNaN(a.getTime())?e:a.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var oc={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Si={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},bo=100,ho=5e3;async function qu(e,t){let a=[],s=0;for(let n=0;n<ho;n+=bo){let r=await e.getInvoices({...t,limit:bo,offset:n});if(s=r.total,a.push(...r.invoices),r.invoices.length<bo||a.length>=s)break}return{invoices:a.slice(0,ho),total:s,truncated:s>a.length||s>ho}}function cc(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"],a=e.map(s=>[s.id,js(s),xo(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),ee(s.amount_subtotal,s.currency),ee(s.tax_total,s.currency),ee(s.amount_total,s.currency),s.amount_due===null?"":ee(s.amount_due,s.currency),s.amount_paid===null?"":ee(s.amount_paid,s.currency),ee(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?"":ee(s.discount_total,s.currency),s.collection_method??""]);return[t,...a].map(s=>s.map(Hl).join(",")).join(`
5
+ `)}function ju(e){ui(new Blob([cc(e)],{type:"text/csv;charset=utf-8"}),di("invoices"))}function Wu({className:e,refreshKey:t,initialInvoiceId:a,onDetailOpenChange:s,onConnectStripe:n,onUpgradePlan:r,needsPaidPlan:i=!1,retainerFilter:l=null,onClearRetainerFilter:u,maxRows:d,onViewAll:o}){let c=typeof d=="number",{api:b}=W(),{invoices:g,total:m,isLoading:p,error:f,page:v,pageSize:x,hasNextPage:k,hasPreviousPage:T,setPage:h,labels:R,setLabels:P,customerEmail:D,setCustomerEmail:N,q:E,setQ:A,from:C,setFrom:K,to:Q,setTo:H,retainerId:de,setRetainerId:me,refetch:be}=hs({refreshKey:t}),[V,J]=Ge.useState(typeof d=="number"?"all":"open"),[F,ge]=Ge.useState(""),[pe,He]=Ge.useState(null),Pe=Ge.useRef(0),Ue=!c||!!o,ze=Ge.useCallback(z=>{if(c){o?.();return}Pe.current++,lt(!1),He(z)},[c,o]),[fe,lt]=Ge.useState(!1),[L,M]=Ge.useState(0),[U,Te]=Ge.useState(null),[ne,Re]=Ge.useState(!1),[je,wt]=Ge.useState(0);Ge.useEffect(()=>{He(z=>{if(!z)return z;let Xe=g.find(ra=>ra.id===z.id);return Xe&&Xe!==z?Xe:z})},[g]);let[et,Dt]=Ge.useState(!1),[Ne,Le]=Ge.useState(null),ct=async()=>{if(!et){Dt(!0),Le(null);try{let{invoices:z,total:Xe,truncated:ra}=await qu(b,{labels:R,customerEmail:D,q:E,from:C,to:Q,retainerId:de});ju(z),Le(ra?`Exported the first ${z.length.toLocaleString()} of ${Xe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Le("Couldn't export \u2014 try again.")}finally{Dt(!1)}}},at=!D&&!E&&!C&&!Q&&!de,[qt,Ut]=Ge.useState(null);Ge.useEffect(()=>{if(p||m>0||!at||V!=="open")return;let z=!1;return b.getInvoices({limit:1}).then(Xe=>{z||Ut(Xe.total>0)}).catch(()=>{z||Ut(!0)}),()=>{z=!0}},[b,p,m,at,V,t]),Ge.useEffect(()=>{P(c?Si.all:Si.open)},[]),Ge.useEffect(()=>{let z=l?.id??"";z!==de&&(me(z),z&&(J("all"),P(Si.all),N(""),A(""),ge(""),K(""),H("")))},[l?.id]),Ge.useEffect(()=>{let z=!1;return Re(!1),b.getInvoiceSettings().then(Xe=>{z||Te({payments_active:Xe.payments_active,blocked:Xe.blocked})}).catch(()=>{z||Re(!0)}),()=>{z=!0}},[b,t,je]),Ge.useEffect(()=>{if(!a||c)return;let z=!1,Xe=Pe.current;return lt(!1),b.getInvoice(a).then(ra=>{!z&&Xe===Pe.current&&He(ra)}).catch(()=>{!z&&Xe===Pe.current&&lt(!0)}),()=>{z=!0}},[b,a,L,c]),Ge.useEffect(()=>{s?.(pe!==null)},[pe,s]);let sa=z=>{J(z),P(Si[z])},dt=z=>{let Xe=z.trim();if(!Xe){E&&A(""),D&&N("");return}if(Xe.includes("@")){E&&A(""),N(Xe);return}D&&N(""),A(Xe.replace(/^#/,""))},ht=g,ke=c?ht.slice(0,d):ht,ut=fe&&(0,S.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,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>M(z=>z+1),children:"Retry opening invoice"})]});if(pe)return(0,S.jsxs)("div",{className:e,children:[ut,(0,S.jsx)(_i,{invoice:pe,refreshKey:t,onBack:()=>{ze(null),be()}},pe.id)]});let tt=(0,S.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[ne&&(0,S.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>wt(z=>z+1),children:"Retry setup check"})]}),ut,U?.blocked&&(0,S.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",U.blocked.reason?`: ${U.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),l&&(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,S.jsxs)(ie,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",l.label]}),u&&(0,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:u,children:"Clear schedule filter"})]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.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(oc).map(z=>(0,S.jsx)("button",{type:"button","aria-pressed":V===z,onClick:()=>sa(z),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",V===z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:oc[z]},z))}),(0,S.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,S.jsx)(Kt.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,S.jsx)(oe,{type:"text",value:F,onChange:z=>ge(z.target.value),onBlur:()=>dt(F),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),dt(F))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,S.jsx)(Ve,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,S.jsx)(oe,{id:"invoices-from",type:"date",value:C,max:Q||void 0,onChange:z=>K(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,S.jsx)(Ve,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,S.jsx)(oe,{id:"invoices-to",type:"date",value:Q,min:C||void 0,onChange:z=>H(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,S.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void ct(),disabled:et||p||!!f||m===0,"aria-busy":et,children:[(0,S.jsx)(Kt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),et?"Exporting\u2026":"Export CSV (all matching)"]})]}),Ne&&(0,S.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:Ne})]});return p?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(z=>(0,S.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,S.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,S.jsx)(ae,{className:"af-h-4 af-w-20"}),(0,S.jsx)(ae,{className:"af-h-4 af-w-16"})]}),(0,S.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-40"})]},z))})]}):f?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>void be(),children:"Retry"})]})]}):m===0&&at&&(V==="all"||qt===!1)&&(V==="open"||V==="all")?U?.blocked?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)(Ni,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):i?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)(Ni,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):U&&!U.payments_active?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)(Ni,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)(Ni,{heading:"No invoices yet",body:!U||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,S.jsxs)("div",{className:e,children:[c?null:tt,ke.length===0?(0,S.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,S.jsxs)(S.Fragment,{children:[(0,S.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ke.map(z=>(0,S.jsxs)("button",{type:"button",onClick:()=>ze(z),disabled:!Ue,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ue?" hover:af-bg-muted/50":""}`,children:[(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,S.jsx)("span",{className:"af-font-medium",children:js(z)}),(0,S.jsx)(Ws,{invoice:z})]}),(0,S.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:z.customer_name??z.customer_email??"\u2014"}),z.delivery&&(0,S.jsx)("div",{className:"af-mt-1",children:(0,S.jsx)(Ri,{delivery:z.delivery})}),(0,S.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,S.jsx)("span",{children:z.collection_method==="charge_automatically"?"Automatic collection":z.due_at?`Due ${cn(z.due_at)}`:"Due on receipt"}),(0,S.jsx)("span",{className:"af-font-medium af-tabular-nums",children:ee(z.amount_due??z.amount_total,z.currency)})]})]},z.id))}),(0,S.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,S.jsxs)(ft,{children:[(0,S.jsx)(mt,{children:(0,S.jsxs)(Fe,{children:[(0,S.jsx)(Z,{children:"Invoice"}),(0,S.jsx)(Z,{children:"Created"}),(0,S.jsx)(Z,{children:"Customer"}),(0,S.jsx)(Z,{children:"Due"}),(0,S.jsx)(Z,{className:"af-text-right",children:"Amount"}),(0,S.jsx)(Z,{children:"Status"}),(0,S.jsx)(Z,{children:"Delivery"}),(0,S.jsx)(Z,{className:"af-w-8"})]})}),(0,S.jsx)(pt,{children:ke.map(z=>(0,S.jsxs)(Fe,{className:Ue?"af-cursor-pointer":void 0,onClick:Ue?()=>ze(z):void 0,children:[(0,S.jsx)(Y,{className:"af-font-medium",children:(0,S.jsx)("button",{type:"button",disabled:!Ue,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ue?" hover:af-underline":""}`,onClick:Xe=>{Xe.stopPropagation(),ze(z)},"aria-label":`Open invoice ${js(z)}`,children:js(z)})}),(0,S.jsx)(Y,{children:cn(z.created_at)}),(0,S.jsxs)(Y,{children:[(0,S.jsx)("div",{children:z.customer_name??"\u2014"}),(0,S.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:z.customer_email})]}),(0,S.jsx)(Y,{children:z.collection_method==="charge_automatically"?"Automatic":z.due_at?cn(z.due_at):"On receipt"}),(0,S.jsx)(Y,{className:"af-text-right af-tabular-nums",children:ee(z.amount_due??z.amount_total,z.currency)}),(0,S.jsx)(Y,{children:(0,S.jsx)(Ws,{invoice:z})}),(0,S.jsx)(Y,{children:(0,S.jsx)(Ri,{delivery:z.delivery})}),(0,S.jsx)(Y,{children:(0,S.jsx)(Kt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},z.id))})]})}),c?null:(0,S.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,S.jsxs)("span",{children:[m," invoice",m===1?"":"s"]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(v-1),disabled:!T,"aria-label":"Previous page",children:(0,S.jsx)(Kt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,S.jsxs)("span",{className:"af-tabular-nums",children:[v*x+1,"\u2013",Math.min((v+1)*x,m)]}),(0,S.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(v+1),disabled:!k,"aria-label":"Next page",children:(0,S.jsx)(Kt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Ni({heading:e,body:t,action:a}){return(0,S.jsx)(zs,{icon:Kt.FileText,heading:e,body:t,action:a})}function Gn(e){return(0,S.jsx)(Wu,{...e},e.maxRows==null?"full":"compact")}var Wn="af-text-xs af-text-muted-foreground";function lc(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function _i({invoice:e,onBack:t,refreshKey:a,className:s}){let{api:n}=W(),r=Ge.useRef(null);Ge.useEffect(()=>{r.current?.focus()},[e.id]);let[i,l]=Ge.useState(!1),[u,d]=Ge.useState(null),[o,c]=Ge.useState(!1),[b,g]=Ge.useState(!1),m=Ge.useRef(0),[p,f]=Ge.useState(null),[v,x]=Ge.useState(!1),[k,T]=Ge.useState(0);Ge.useEffect(()=>{let C=!1;return x(!1),n.getInvoice(e.id).then(K=>{C||f({source:e,value:K})}).catch(()=>{C||x(!0)}),()=>{C=!0}},[n,e,a,k]);let h=p?.source===e?p.value:e,R=h.collection_method==="charge_automatically";Ge.useEffect(()=>(m.current++,d(null),c(!1),g(!1),l(!1),()=>{m.current++}),[n,h,a]);let P=C=>C==null?"\u2014":ee(C,h.currency),D=async()=>{if(!(!h.pay_url||!lc()))try{await navigator.clipboard.writeText(h.pay_url),l(!0),setTimeout(()=>l(!1),1500)}catch{}},N=async()=>{if(u){d(null);return}let C=++m.current;g(!1),c(!0);try{let K=await n.getInvoicePreview(h.id);C===m.current&&d(K)}catch{C===m.current&&g(!0)}finally{C===m.current&&c(!1)}},E=h.bill_to,A=E?[E.company,E.name,E.address?.line1,E.address?.line2,[E.address?.city,E.address?.state,E.address?.postal_code].filter(Boolean).join(", "),E.address?.country,E.tax_id?`${E.tax_id.value}`:null,E.po_number?`PO ${E.po_number}`:null,E.service_period?`Service period: ${E.service_period}`:null].filter(C=>!!C&&C.length>0):[];return(0,S.jsxs)("div",{className:s,children:[(0,S.jsxs)("div",{className:"af-mb-4",children:[(0,S.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,S.jsx)(Kt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.jsxs)("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",js(h)]}),(0,S.jsx)(Ws,{invoice:h}),(0,S.jsx)(Ri,{delivery:h.delivery})]}),(0,S.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[h.customer_name??h.customer_email,h.customer_name&&h.customer_email?` \xB7 ${h.customer_email}`:""]})]}),v&&(0,S.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,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>T(C=>C+1),children:"Retry details"})]}),h.label==="failed"&&(0,S.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."}),h.label==="creating"&&(0,S.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,S.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,S.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,S.jsxs)(ft,{children:[(0,S.jsx)(mt,{children:(0,S.jsxs)(Fe,{children:[(0,S.jsx)(Z,{children:"Description"}),(0,S.jsx)(Z,{className:"af-text-right",children:"Qty"}),(0,S.jsx)(Z,{className:"af-text-right",children:"Amount"})]})}),(0,S.jsx)(pt,{children:h.line_items.map((C,K)=>(0,S.jsxs)(Fe,{children:[(0,S.jsx)(Y,{style:{overflowWrap:"anywhere"},children:C.description}),(0,S.jsx)(Y,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:C.quantity}),(0,S.jsx)(Y,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:P(C.amount)})]},K))})]}),(0,S.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,S.jsx)(rs,{label:"Subtotal",value:P(h.amount_subtotal)}),(h.discount_total??0)>0&&(0,S.jsx)(rs,{label:"Discount",value:`-${P(h.discount_total)}`}),h.tax_total>0&&(0,S.jsx)(rs,{label:h.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:P(h.tax_total)}),(0,S.jsx)(rs,{label:"Total",value:P(h.amount_total),strong:!0}),h.credit_applied>0&&(0,S.jsx)(rs,{label:"Credit applied",value:`-${P(h.credit_applied)}`}),h.amount_due!==null&&h.amount_due!==h.amount_total&&(0,S.jsx)(rs,{label:"Amount due",value:P(h.amount_due),strong:!0}),h.amount_paid!==null&&h.amount_paid>0&&(0,S.jsx)(rs,{label:"Amount paid",value:P(h.amount_paid)}),h.amount_refunded>0&&(0,S.jsx)(rs,{label:"Refunded",value:P(h.amount_refunded)})]}),h.credit_notes?.length>0&&(0,S.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,S.jsx)("div",{className:Wn,children:"Credit notes"}),h.credit_notes.map(C=>(0,S.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,S.jsxs)("span",{className:"af-text-muted-foreground",children:[cn(C.created_at)," \xB7 ",C.origin==="dashboard"?"issued in Stripe":"refund",C.stripe_credit_note_id?"":" \xB7 being created"]}),(0,S.jsxs)("span",{className:"af-tabular-nums",children:["-",ee(C.amount,C.currency)]})]},C.id))]})]}),(h.note||h.footer)&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[h.note&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Wn,children:"Note"}),(0,S.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:h.note})]}),h.footer&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Wn,children:"Footer"}),(0,S.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:h.footer})]})]}),u&&!R&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,S.jsxs)("div",{className:X(Wn,"af-break-words"),children:["Email preview \u2014 ",u.subject]}),(0,S.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,S.jsx)("iframe",{title:"Invoice email preview",srcDoc:u.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,S.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,S.jsx)(ln,{label:"Created",value:cn(h.created_at)}),(0,S.jsx)(ln,{label:"Due",value:h.collection_method==="charge_automatically"?"Managed in Stripe":h.due_at?cn(h.due_at):"On receipt"}),h.paid_at&&(0,S.jsx)(ln,{label:"Paid",value:cn(h.paid_at)}),h.payment_method&&(0,S.jsx)(ln,{label:"Paid by",value:h.paid_out_of_band?`${h.payment_method} (recorded outside Stripe)`:h.payment_method}),h.payment_state!=="none"&&(0,S.jsx)(ln,{label:"Payment",value:h.payment_state==="processing"?"Processing":h.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),h.delivery&&(0,S.jsx)(ln,{label:"Delivery",value:`${yo[h.delivery.state]} \xB7 ${h.delivery.recipient}`}),h.marked_uncollectible_at&&(0,S.jsx)(ln,{label:"Written off",value:cn(h.marked_uncollectible_at)}),h.correction_reason&&(0,S.jsx)(ln,{label:"Correction",value:h.correction_reason}),h.replaced_by_order_id&&(0,S.jsx)(ln,{label:"Replaced by",value:h.replaced_by_order_id}),h.collection_method==="charge_automatically"?(0,S.jsx)(ln,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):h.retainer_id&&(0,S.jsx)(ln,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),h.replaces_order_id&&(0,S.jsx)(ln,{label:"Replaces",value:h.replaces_order_id})]}),(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,S.jsx)("div",{className:Wn,children:"Reminders"}),R?(0,S.jsx)("div",{children:"View automatic payment reminders in Stripe."}):h.reminders.disabled?(0,S.jsx)("div",{children:"Off for this invoice."}):h.reminders.paused_until?(0,S.jsxs)("div",{children:["Paused until ",cn(h.reminders.paused_until),"."]}):h.reminders.next_at?(0,S.jsxs)("div",{children:["Next on ",cn(h.reminders.next_at),"."]}):h.reminders.final_sent_at?(0,S.jsxs)("div",{children:["Final reminder sent ",cn(h.reminders.final_sent_at),"."]}):(0,S.jsx)("div",{children:"None scheduled."}),!R&&(0,S.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",h.reminders.schedule.length===0?"none":h.reminders.schedule.map(C=>C<0?`${-C}d before`:C===0?"due day":`${C}d after`).join(", ")]})]}),h.communications&&h.communications.length>0&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,S.jsx)("div",{className:Wn,children:"Email delivery history"}),h.communications.map(C=>(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,S.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[zu[C.kind]??C.kind,C.kind==="reminder"&&C.slot!==null?` #${C.slot}`:"",(0,S.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",C.recipient]})]}),(0,S.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[yo[C.state]??C.state," \xB7 ",cn(C.state_at??C.created_at)]})]},C.id))]}),A.length>0&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,S.jsx)("div",{className:Wn,children:"Bill to"}),A.map((C,K)=>(0,S.jsx)("div",{className:"af-break-words",children:C},K))]}),(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[h.pay_url&&(0,S.jsxs)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void D(),disabled:!lc(),children:[(0,S.jsx)(Kt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Copied":R?"Copy invoice link":"Copy pay link"]}),h.pdf_url&&(0,S.jsx)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,S.jsxs)("a",{href:h.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,S.jsx)(Kt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!R&&(0,S.jsxs)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void N(),disabled:o,children:[o?(0,S.jsx)(Kt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(Kt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),u?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!R&&(0,S.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),h.pay_url&&(0,S.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:h.pay_url}),(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:R?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function ln({label:e,value:t}){return(0,S.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,S.jsx)("span",{className:X(Wn,"af-shrink-0"),children:e}),(0,S.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function rs({label:e,value:t,strong:a}){return(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,S.jsx)("dt",{className:X(Wn,a&&"af-font-medium af-text-foreground"),children:e}),(0,S.jsx)("dd",{className:X("af-tabular-nums",a&&"af-font-semibold"),children:t})]})}var uc=require("lucide-react");var Je=require("react/jsx-runtime"),Gu={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},dc={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Ku(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 fc(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>dc[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>dc[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Gu[e.status]}function mc(e){let t=e.interval==="year"?"every year":"every month";return`${ee(e.amount,e.currency)} ${t}`}function Zu(e){return e.status==="canceled"?`Ended ${Pi(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Pi(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 ${Pi(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Pi(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Pi(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),a=new Date(t);return Number.isNaN(a.getTime())?e.slice(0,10):a.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ki({retainer:e,className:t}){return(0,Je.jsx)(ie,{variant:Ku(e.status),className:X("af-max-w-full af-whitespace-normal af-break-words",t),children:fc(e)})}function ys({retainers:e,isLoading:t,error:a,onRetry:s,onShowCycles:n,activeRetainerId:r,total:i,endedTotal:l=0,isLoadingMore:u=!1,onLoadMore:d,includeEnded:o=!1,onIncludeEndedChange:c,exportCsv:b,className:g}){let m=!!c;if(!t&&!a&&e.length===0&&!(m&&(o||l>0)))return null;let p=i!==void 0?Math.max(0,i-e.length):0;return(0,Je.jsxs)("section",{className:X("af-mb-6",g),"aria-label":"Recurring invoices",children:[(0,Je.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Je.jsx)(uc.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,Je.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,Je.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."}),m&&(0,Je.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":o,onClick:()=>c?.(!o),children:o?"Hide ended recurring invoices":l>0&&e.length===0?`Show ended recurring invoices (${l})`:"Show ended recurring invoices"}),b&&(0,Je.jsx)(da,{fetchCsv:b,filename:"retainers",className:m?void 0:"af-ml-auto"})]}),a?(0,Je.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,Je.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?(0,Je.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(f=>(0,Je.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,Je.jsx)(ae,{className:"af-h-4 af-w-48"}),(0,Je.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-32"})]},f))}):e.length===0?(0,Je.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:o?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,Je.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(f=>{let v=r===f.id;return(0,Je.jsxs)("li",{className:X("af-rounded-md af-border af-p-3",v&&"af-border-primary af-bg-muted/40"),children:[(0,Je.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,Je.jsxs)("div",{className:"af-min-w-0",children:[(0,Je.jsx)("div",{className:"af-truncate af-font-medium",children:f.customer_name??f.customer_email??"\u2014"}),(0,Je.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:f.description})]}),(0,Je.jsx)(ki,{retainer:f})]}),f.collection_method==="charge_automatically"?(0,Je.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,Je.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"}),(0,Je.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,Je.jsx)("div",{className:"af-mt-2 af-text-sm",children:mc(f)}),(0,Je.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,Je.jsxs)("span",{children:[Zu(f)," \xB7 ",f.cycles.count===0?"no invoices yet":`${f.cycles.paid} paid${f.cycles.open>0?`, ${f.cycles.open} open`:""}`]}),f.cycles.count>0&&(0,Je.jsx)(y,{type:"button",variant:v?"secondary":"ghost",size:"sm",onClick:()=>n(f),"aria-pressed":v,children:v?"Showing invoices":"View invoices"})]}),f.status==="failed"&&f.operation?.last_error&&(0,Je.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",f.operation.last_error,". Ask in the chat to try again."]})]},f.id)})}),!t&&!a&&p>0&&d&&(0,Je.jsx)("div",{className:"af-mt-2",children:(0,Je.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:d,disabled:u,children:u?"Loading\u2026":`Load more (${p} more)`})})]})}var pc=ce(require("react"),1),Ya=require("lucide-react");var Me=require("react/jsx-runtime");function xs({onConnectStripe:e,onUpgradePlan:t,whenActive:a,className:s}){let{status:n,isLoading:r,error:i,refetch:l}=Hn(),[u,d]=pc.useState(!1),o=async()=>{d(!0);try{await l()}finally{d(!1)}};return r&&!n?(0,Me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Me.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!n?(0,Me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Me.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):n.status==="active"?a!==void 0?(0,Me.jsx)("div",{className:s,children:a}):(0,Me.jsx)("div",{className:s,children:(0,Me.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,Me.jsx)(Ya.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Me.jsxs)("div",{children:[(0,Me.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Me.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",n.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,Me.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[n.reason==="needs_stripe"&&(0,Me.jsxs)("div",{className:"af-space-y-3",children:[(0,Me.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Me.jsx)(Ya.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Me.jsxs)("div",{children:[(0,Me.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Me.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,Me.jsxs)(y,{onClick:e,children:[(0,Me.jsx)(Ya.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),n.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),n.reason==="needs_paid_plan"&&(0,Me.jsxs)("div",{className:"af-space-y-3",children:[(0,Me.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Me.jsx)(Ya.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Me.jsxs)("div",{children:[(0,Me.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Me.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,Me.jsx)(y,{onClick:t,children:"Upgrade plan"}):(0,Me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),n.reason==="account_disabled"&&(0,Me.jsxs)("div",{className:"af-space-y-3",children:[(0,Me.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,Me.jsx)(Ya.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Me.jsxs)("div",{children:[(0,Me.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),n.stripe_account_connected?(0,Me.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,Me.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,Me.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&n.stripe_account_connected&&(0,Me.jsxs)(y,{onClick:e,children:[(0,Me.jsx)(Ya.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Me.jsxs)(y,{variant:"outline",onClick:o,disabled:u,children:[u?(0,Me.jsx)(Ya.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Me.jsx)(Ya.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var wa=ce(require("react"),1);function wo(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function ws({includeStats:e=!1,refreshKey:t}={}){let{api:a}=W(),[s,n]=wa.useState([]),[r,i]=wa.useState(!0),[l,u]=wa.useState(null),d=wa.useRef(0),o=wa.useCallback(async()=>{let f=++d.current;try{i(!0),u(null);let v=await a.getProducts(e?{include:"stats"}:{});if(f!==d.current)return;n(v)}catch(v){if(f!==d.current)return;u(v instanceof Error?v:new Error("Failed to fetch products"))}finally{f===d.current&&i(!1)}},[a,e,t]);wa.useEffect(()=>{o()},[o]);let c=wa.useCallback(async f=>{let v=await a.createProduct(f);return n(x=>[v,...x]),v},[a]),b=wa.useCallback(async(f,v)=>{let x=await a.updateProduct(f,v);return n(k=>wo(k,f,x)),x},[a]),g=wa.useCallback(async f=>{await a.deleteProduct(f),n(v=>v.filter(x=>x.id!==f))},[a]),m=wa.useCallback(async(f,v)=>{let x=await a.attachProductFile(f,v);return n(k=>wo(k,f,x)),x},[a]),p=wa.useCallback(async(f,v)=>{let x=await a.attachProductFileFromUrl(f,v);return n(k=>wo(k,f,x)),x},[a]);return{products:s,isLoading:r,error:l,refetch:o,createProduct:c,updateProduct:b,deleteProduct:g,attachProductFile:m,attachProductFileFromUrl:p}}var Sa=ce(require("react"),1);var So=["creating","active","paused","canceling"],Yu=["canceled","failed"],Ju={statuses:So},Xu={};function Ss({refreshKey:e,includeEnded:t=!1,limit:a=50}={}){let{api:s}=W(),[n,r]=Sa.useState([]),[i,l]=Sa.useState(0),[u,d]=Sa.useState(0),[o,c]=Sa.useState(!0),[b,g]=Sa.useState(!1),[m,p]=Sa.useState(null),[f,v]=Sa.useState(t),x=Sa.useRef(0),k=Sa.useCallback(async()=>{let h=++x.current;c(!0),g(!1),p(null);try{let R=await s.getRetainers({statuses:f?void 0:So,limit:a,offset:0});if(h!==x.current)return;if(r(R.retainers),l(R.total),!f&&R.total===0){let P=await s.getRetainers({statuses:Yu,limit:1,offset:0});if(h!==x.current)return;d(P.total)}else d(0)}catch(R){if(h!==x.current)return;p(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{h===x.current&&c(!1)}},[s,f,a]);Sa.useEffect(()=>{k()},[k,e]);let T=Sa.useCallback(async()=>{if(o||b||n.length>=i)return;let h=x.current;g(!0);try{let R=await s.getRetainers({statuses:f?void 0:So,limit:a,offset:n.length});if(h!==x.current)return;r(P=>{let D=new Set(P.map(N=>N.id));return[...P,...R.retainers.filter(N=>!D.has(N.id))]}),l(R.total)}catch(R){if(h!==x.current)return;p(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{h===x.current&&g(!1)}},[s,f,a,o,b,n.length,i]);return{retainers:n,total:i,endedTotal:u,hasMore:n.length<i,isLoading:o,isLoadingMore:b,error:m,includeEnded:f,setIncludeEnded:v,loadMore:T,refetch:k,filters:f?Xu:Ju}}var Be=require("react/jsx-runtime");function No({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:n}){let[r,i]=Gs.useState(t),[l,u]=Gs.useState("list"),[d,o]=Gs.useState(null),c=ws(),{status:b,error:g}=Hn(),m=b?.currency,p=k=>{o(k),u("edit")},f=()=>{o(null),u("create")},v=()=>{u("list"),o(null)},x=k=>{o(k),u("edit")};return(0,Be.jsxs)("div",{className:e,children:[(0,Be.jsxs)("div",{className:"af-mb-6",children:[(0,Be.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Be.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Be.jsxs)(ii,{value:r,onValueChange:k=>i(k),children:[(0,Be.jsxs)(or,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Be.jsxs)(vn,{value:"products",className:"af-gap-2",children:[(0,Be.jsx)(dn.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Be.jsxs)(vn,{value:"orders",className:"af-gap-2",children:[(0,Be.jsx)(dn.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Be.jsxs)(vn,{value:"invoices",className:"af-gap-2",children:[(0,Be.jsx)(dn.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Be.jsxs)(vn,{value:"customers",className:"af-gap-2",children:[(0,Be.jsx)(dn.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Be.jsx)(vn,{value:"promos",children:"Promo codes"}),(0,Be.jsxs)(vn,{value:"setup",className:"af-gap-2",children:[(0,Be.jsx)(dn.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Be.jsx)(bn,{value:"products",children:l==="list"?(0,Be.jsx)(Sr,{productsState:c,onSelectProduct:p,onCreateProduct:f}):(0,Be.jsxs)("div",{children:[(0,Be.jsxs)("div",{className:"af-mb-6",children:[(0,Be.jsxs)(y,{variant:"ghost",size:"sm",onClick:v,className:"af-mb-2 af--ml-2",children:[(0,Be.jsx)(dn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Be.jsx)("h3",{className:"af-text-lg af-font-semibold",children:l==="create"?"New Product":d?.name})]}),l==="create"&&!m?(0,Be.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?(0,Be.jsxs)("div",{className:"af-text-destructive",children:["Error: ",g.message]}):(0,Be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Be.jsx)(Rr,{productsState:c,product:l==="edit"?d:null,currency:m??"usd",onSaved:x},l==="edit"?d?.id??"edit":"new")]})}),(0,Be.jsx)(bn,{value:"orders",children:(0,Be.jsx)(jn,{onRefund:s})}),(0,Be.jsx)(bn,{value:"invoices",children:(0,Be.jsx)(Qu,{onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),(0,Be.jsx)(bn,{value:"customers",children:(0,Be.jsx)(Ir,{})}),(0,Be.jsx)(bn,{value:"promos",children:(0,Be.jsx)(ps,{})}),(0,Be.jsx)(bn,{value:"setup",children:(0,Be.jsx)(xs,{onConnectStripe:a,onUpgradePlan:n})})]})]})}function Qu({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a}){let s=Ss(),[n,r]=Gs.useState(null),[i,l]=Gs.useState(!1);return(0,Be.jsxs)(Be.Fragment,{children:[!i&&(0,Be.jsx)(ys,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:n?.id??null,onShowCycles:u=>r(d=>d?.id===u.id?null:u),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),(0,Be.jsx)(Gn,{onDetailOpenChange:l,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}var vc=ce(require("react"),1);var Dn=ce(require("react"),1);function Ns({refreshKey:e}={}){let{api:t}=W(),[a,s]=Dn.useState(null),[n,r]=Dn.useState(!0),[i,l]=Dn.useState(null),u=Dn.useRef(0),d=Dn.useCallback(async()=>{let o=++u.current;try{r(!0),l(null);let c=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(o!==u.current)return;s(c)}catch(c){if(o!==u.current)return;l(c instanceof Error?c:new Error("Failed to fetch summary"))}finally{o===u.current&&r(!1)}},[t,e]);return Dn.useEffect(()=>{d()},[d]),{summary:a,isLoading:n,error:i,refetch:d}}var vt=require("react/jsx-runtime");function gc(e,t){if(e.settled.complete)return{headline:ee(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:ee(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${ee(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:ee(0,t),extra:[]}}function Ro({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:n,className:r}){let{summary:i,isLoading:l,error:u,refetch:d}=Ns({refreshKey:e}),[o,c]=vc.useState(!1),b=(0,vt.jsx)("div",{className:"af-mb-6",children:u&&!i?(0,vt.jsx)(Et,{message:"Couldn't load your revenue summary.",onRetry:()=>d()}):(0,vt.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:l||!i?(0,vt.jsxs)(vt.Fragment,{children:[(0,vt.jsx)(gt,{label:"This week",children:(0,vt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,vt.jsx)(gt,{label:"Today",children:(0,vt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,vt.jsx)(gt,{label:"Needs attention",children:(0,vt.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,vt.jsx)(vt.Fragment,{children:(()=>{let g=gc(i.revenue.d7,i.currency),m=gc(i.revenue.today,i.currency);return(0,vt.jsxs)(vt.Fragment,{children:[(0,vt.jsx)(gt,{label:"This week",detail:g.extra.length>0?(0,vt.jsx)("div",{children:g.extra.map(p=>(0,vt.jsx)("div",{children:p},p))}):void 0,children:g.headline}),(0,vt.jsx)(gt,{label:"Today",detail:m.extra.length>0?(0,vt.jsx)("div",{children:m.extra.map(p=>(0,vt.jsx)("div",{children:p},p))}):void 0,children:m.headline}),(0,vt.jsx)(gt,{label:"Needs attention",valueClassName:i.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:i.needs_attention.count===0?"All clear":i.needs_attention.items[0]?.title??void 0,children:i.needs_attention.count})]})})()})})});return(0,vt.jsxs)(Lt,{title:"Orders",onBackToWebsite:n,hideBackButton:o,className:r,children:[b,(0,vt.jsx)(jn,{refreshKey:e,initialOrderId:t,onDetailOpenChange:c,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var un=ce(require("react"),1),Ks=require("lucide-react");var An=ce(require("react"),1),Ai=require("lucide-react");var oa=require("react/jsx-runtime"),bc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",is="af-text-xs af-text-muted-foreground",Ci="af-text-sm af-font-medium af-tabular-nums",ef=3;function tf(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let u=e.min_amount??t?.min_amount??null,d=e.max_amount??t?.max_amount??null;return u!==null&&d!==null?{text:`Buyer chooses (${ee(u,a)} \u2013 ${ee(d,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(n===null||r===null)return{text:"Varies by variant",compareAt:null};let i=n===r?ee(n,a):`${ee(n,a)} \u2013 ${ee(r,a)}`,l=t?.compare_at_amount??null;return{text:i,compareAt:l!==null&&l>r?ee(l,a):null}}function Ti({product:e,className:t}){let a=tf(e);return(0,oa.jsxs)("div",{className:t,children:[(0,oa.jsx)("span",{className:Ci,children:a.text}),a.compareAt&&(0,oa.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function Ei({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,oa.jsx)(ie,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,oa.jsxs)(ie,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,oa.jsx)(ie,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,oa.jsxs)(ie,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,oa.jsx)(ie,{variant:"warning",children:"Low stock"}):null}function Ii(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Di(e){return e.map(t=>ee(t.amount,t.currency)).join(" + ")}function hc(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${ee(e.min_amount,e.currency)} \u2013 ${ee(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":ee(e.unit_amount,e.currency)}function yc({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,oa.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?(0,oa.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,oa.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,a)}),(0,oa.jsx)(ie,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?(0,oa.jsx)(ie,{variant:"destructive",children:"Out of stock"}):(0,oa.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,oa.jsx)("span",{className:"af-tabular-nums",children:a}),a<=ef&&(0,oa.jsx)(ie,{variant:"warning",children:"Low"})]})}var le=require("react/jsx-runtime");function Dr({title:e,children:t,className:a}){return(0,le.jsxs)("section",{className:X("af-rounded-lg af-border af-p-4",a),children:[(0,le.jsx)("h4",{className:bc,children:e}),(0,le.jsx)("div",{className:"af-mt-3",children:t})]})}function xc({src:e,className:t}){let[a,s]=An.useState(!1);return An.useEffect(()=>s(!1),[e]),!e||a?(0,le.jsx)("div",{"aria-hidden":"true",className:X("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,le.jsx)(Ai.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,le.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:X("af-object-cover",t)})}function wc({product:e,showStats:t=!1,onBack:a}){let{api:s}=W(),[n,r]=An.useState(null),[i,l]=An.useState(!0),[u,d]=An.useState(null),[o,c]=An.useState(0),[b,g]=An.useState(0);An.useEffect(()=>{let h=!1;return l(!0),d(null),s.getProduct(e.id).then(R=>{h||r(R)}).catch(R=>{h||d(R instanceof Error?R:new Error("Failed to load product"))}).finally(()=>{h||l(!1)}),()=>{h=!0}},[s,e.id,o]);let m=n?{...e,...n}:e,p=m.images.length>0?m.images:e.images,f=p[b]??p[0],v=Ii(m),x=t?m.stats:void 0,k=n?.variants??[],T=k.length>1;return(0,le.jsxs)("div",{children:[(0,le.jsxs)("div",{className:"af-mb-6",children:[(0,le.jsxs)(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,le.jsx)(Ai.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,le.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,le.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:m.name}),(0,le.jsx)(ie,{variant:m.active?"success":"secondary",children:m.active?"Active":"Draft"}),(0,le.jsx)(Ei,{product:m})]}),(0,le.jsx)(Ti,{product:m,className:"af-mt-1"}),!m.active&&(0,le.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,le.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,le.jsxs)("div",{className:"af-space-y-2",children:[(0,le.jsx)(xc,{src:f,className:"af-h-48 af-w-full af-rounded-md af-border"}),p.length>1&&(0,le.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:p.map((h,R)=>(0,le.jsx)("button",{type:"button",onClick:()=>g(R),"aria-label":`Show photo ${R+1} of ${p.length}`,"aria-pressed":R===b,className:X("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",R===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,le.jsx)(xc,{src:h,className:"af-h-12 af-w-12 af-rounded-md"})},`${h}-${R}`))})]}),(0,le.jsxs)("div",{className:"af-space-y-6",children:[m.description&&(0,le.jsx)(Dr,{title:"Description",children:(0,le.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:m.description})}),i?(0,le.jsxs)(Dr,{title:"Variants",children:[(0,le.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(h=>(0,le.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,le.jsx)(ae,{className:"af-h-4 af-w-28"}),(0,le.jsx)(ae,{className:"af-h-4 af-w-20"}),(0,le.jsx)(ae,{className:"af-h-4 af-w-16"})]},h))}),(0,le.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):u?(0,le.jsx)(Et,{message:"Couldn't load this product's variants.",onRetry:()=>c(h=>h+1)}):T?(0,le.jsx)(Dr,{title:`Variants \xB7 ${k.length}`,children:(0,le.jsx)("div",{className:"af-overflow-x-auto",children:(0,le.jsxs)(ft,{children:[(0,le.jsx)(mt,{children:(0,le.jsxs)(Fe,{children:[(0,le.jsx)(Z,{children:"Variant"}),(0,le.jsx)(Z,{children:"SKU"}),(0,le.jsx)(Z,{className:"af-text-right",children:"Price"}),(0,le.jsx)(Z,{children:"Stock"})]})}),(0,le.jsx)(pt,{children:k.map(h=>(0,le.jsxs)(Fe,{children:[(0,le.jsxs)(Y,{className:"af-font-medium",children:[h.title||h.option_values.map(R=>R.value).join(" / ")||"\u2014",!h.active&&(0,le.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,le.jsx)(Y,{className:"af-text-muted-foreground",children:h.sku?(0,le.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:h.sku}):"\u2014"}),(0,le.jsxs)(Y,{className:"af-whitespace-nowrap af-text-right",children:[(0,le.jsx)("div",{className:Ci,children:hc(h)}),h.compare_at_amount!==null&&h.unit_amount!==null&&h.compare_at_amount>h.unit_amount&&(0,le.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:ee(h.compare_at_amount,h.currency)})]}),(0,le.jsx)(Y,{className:"af-text-sm",children:(0,le.jsx)(yc,{variant:h})})]},h.id))})]})})}):null,(0,le.jsx)(Dr,{title:"Details",children:(0,le.jsxs)("dl",{className:"af-space-y-2",children:[(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Delivery"}),(0,le.jsx)("dd",{className:"af-text-sm",children:v==="Digital download"?m.fulfillment.filename??"Digital download":v??"Nothing to deliver"})]}),m.fulfillment.type==="redirect"&&m.fulfillment.url&&(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Sends buyers to"}),(0,le.jsx)("dd",{className:"af-break-all af-text-sm",children:m.fulfillment.url})]}),(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Shipping address"}),(0,le.jsx)("dd",{className:"af-text-sm",children:m.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Most one buyer can order"}),(0,le.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:m.max_quantity})]})]})}),x&&(0,le.jsx)(Dr,{title:"Last 30 days",children:(0,le.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Units sold"}),(0,le.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Orders"}),(0,le.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Gross"}),(0,le.jsx)("dd",{className:Ci,children:x.gross.length>0?Di(x.gross):"\u2014"})]})]})}),(0,le.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var G=require("react/jsx-runtime"),af={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},nf=["all","active","draft","low_stock","out_of_stock"];function Sc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function Nc(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function sf(e){return e.inventory?.out_of_stock??!1}function rf(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Nc(e);case"out_of_stock":return sf(e);default:return!0}}function of({product:e,showStats:t,onOpen:a}){let s=e.images[0],n=t?e.stats:void 0,r=Ii(e),i=e.variant_count??0;return(0,G.jsxs)("button",{type:"button",onClick:a,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?(0,G.jsx)("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,G.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,G.jsx)(Ks.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,G.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,G.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,G.jsxs)("div",{className:"af-min-w-0",children:[(0,G.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,G.jsx)(Ti,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,G.jsx)(ie,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,G.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,G.jsx)(Ei,{product:e}),i>1&&(0,G.jsxs)(ie,{variant:"outline",children:[i," variants"]}),r&&(0,G.jsx)(ie,{variant:"outline",children:r})]}),n&&(0,G.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Di(n.gross)}`:""," ",(0,G.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function lf(){return(0,G.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,G.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,G.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,G.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,G.jsx)(ae,{className:"af-w-32"}),(0,G.jsx)(ae,{className:"af-w-16"}),(0,G.jsx)(ae,{className:"af-h-5 af-w-24"})]})]},e))})}function _o({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:n,isLoading:r,error:i,refetch:l}=ws({includeStats:t,refreshKey:e}),[u,d]=un.useState(!1),[o,c]=un.useState(null),[b,g]=un.useState("all"),{api:m}=W(),p=un.useCallback(()=>m.exportProductsCsv(),[m]),[f,v]=un.useState(""),[x,k]=un.useState("newest"),T=un.useMemo(()=>{if(!t)return null;let Q=null;for(let H of n)!H.stats||H.stats.units_sold===0||(!Q||H.stats.units_sold>(Q.stats?.units_sold??0))&&(Q=H);return Q},[n,t]),h=un.useMemo(()=>n.filter(Nc).length,[n]),R=f.trim().toLowerCase(),P=un.useMemo(()=>{let H=[...n.filter(de=>rf(de,b)&&(!R||de.name.toLowerCase().includes(R)))];return x==="name"?H.sort((de,me)=>de.name.localeCompare(me.name)):x==="best_selling"?H.sort((de,me)=>(me.stats?.units_sold??0)-(de.stats?.units_sold??0)):H.sort((de,me)=>Sc(me.created_at)-Sc(de.created_at)),H},[n,b,R,x]),D=b!=="all"||!!R,N=()=>{g("all"),v("")},E=r||i!==null&&n.length===0,A=(0,G.jsx)("div",{className:"af-mb-6",children:(0,G.jsx)("div",{className:X("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:E?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(gt,{label:"Products",children:(0,G.jsx)(ae,{className:"af-h-6 af-w-10"})}),t?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(gt,{label:"Best seller",children:(0,G.jsx)(ae,{className:"af-h-6 af-w-28"})}),(0,G.jsx)(gt,{label:"Low stock",children:(0,G.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,G.jsx)(gt,{label:"Active",children:(0,G.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(gt,{label:"Products",children:n.length}),t?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(gt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:T?`${T.stats?.units_sold??0} sold, last 30 days`:void 0,children:T?(0,G.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:T.name}):(0,G.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,G.jsx)(gt,{label:"Low stock",children:h})]}):(0,G.jsx)(gt,{label:"Active",children:n.filter(Q=>Q.active).length})]})})}),C=(0,G.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,G.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,G.jsx)("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:nf.map(Q=>(0,G.jsx)("button",{type:"button","aria-pressed":b===Q,onClick:()=>g(Q),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",b===Q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:af[Q]},Q))}),(0,G.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,G.jsx)(Ks.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,G.jsx)(oe,{type:"text",value:f,onChange:Q=>v(Q.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,G.jsxs)(tn,{value:x,onValueChange:Q=>k(Q),children:[(0,G.jsx)(Ma,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,G.jsx)(an,{})}),(0,G.jsxs)(Ua,{children:[(0,G.jsx)(Rt,{value:"newest",children:"Newest"}),(0,G.jsx)(Rt,{value:"name",children:"Name A\u2013Z"}),t&&(0,G.jsx)(Rt,{value:"best_selling",children:"Best selling"})]})]}),D&&(0,G.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:N,children:"Clear filters"}),(0,G.jsx)(da,{fetchCsv:p,filename:"products",label:D?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&n.length===0?(0,G.jsx)(ae,{className:"af-h-4 af-w-28"}):(0,G.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:D?`${P.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),K;return o?K=(0,G.jsx)(wc,{product:o,showStats:t,onBack:()=>{c(null),l()}},o.id):r&&n.length===0?K=(0,G.jsxs)(G.Fragment,{children:[C,(0,G.jsx)(lf,{}),(0,G.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):i&&n.length===0?K=(0,G.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,G.jsx)(Et,{message:"Couldn't load your products.",onRetry:()=>l()})}):n.length===0?K=(0,G.jsxs)(va,{icon:(0,G.jsx)(Ks.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,G.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):K=(0,G.jsxs)(G.Fragment,{children:[C,i&&(0,G.jsx)("div",{className:"af-mb-4",children:(0,G.jsx)(Et,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>l()})}),P.length===0?(0,G.jsxs)(va,{children:["No products match these filters.",(0,G.jsx)("br",{}),(0,G.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:N,children:"Show all products"})]}):(0,G.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:P.map(Q=>(0,G.jsx)(of,{product:Q,showStats:t,onOpen:()=>c(Q)},Q.id))})]}),(0,G.jsx)(Lt,{title:"Products",onBackToWebsite:a,hideBackButton:!!o,className:s,children:u?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(y,{variant:"ghost",onClick:()=>d(!1),children:"Back to products"}),(0,G.jsx)(ps,{})]}):(0,G.jsxs)(G.Fragment,{children:[!o&&(0,G.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,G.jsx)(y,{variant:"outline",onClick:()=>d(!0),children:"Promo codes"})}),!o&&A,K]})})}var Ea=ce(require("react"),1),zt=require("lucide-react");var Ta=ce(require("react"),1);function Ar({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=W(),[s,n]=Ta.useState([]),[r,i]=Ta.useState(!0),[l,u]=Ta.useState(null),[d,o]=Ta.useState(0),[c]=Ta.useState(e),[b,g]=Ta.useState(""),[m,p]=Ta.useState(void 0),f=Ta.useRef(0),v=Ta.useCallback(async({afterRemoval:x=!1}={})=>{let k=++f.current;try{i(!0),u(null);let T={limit:c,offset:d*c};b.trim()&&(T.q=b.trim()),m&&(T.source=m);let h=await a.getPeople(T);if(k!==f.current)return;if(x&&h.people.length===0&&d>0){o(d-1);return}n(h.people)}catch(T){if(k!==f.current)return;u(T instanceof Error?T:new Error("Failed to fetch people"))}finally{k===f.current&&i(!1)}},[a,d,c,b,m,t]);return Ta.useEffect(()=>{v()},[v]),{people:s,isLoading:r,error:l,page:d,pageSize:c,hasNextPage:s.length===c,hasPreviousPage:d>0,setPage:o,q:b,setQ:x=>{g(x),o(0)},source:m,setSource:x=>{p(x),o(0)},refetch:()=>v(),refetchAfterRemoval:()=>v({afterRemoval:!0})}}var Ln=ce(require("react"),1);function Lr(e,{refreshKey:t}={}){let{api:a}=W(),[s,n]=Ln.useState(null),[r,i]=Ln.useState(e!==null),[l,u]=Ln.useState(null),d=Ln.useRef(0),o=Ln.useCallback(async()=>{if(e===null){n(null),i(!1),u(null);return}let c=++d.current;try{i(!0),u(null);let b=await a.getPerson(e);if(c!==d.current)return;n(b)}catch(b){if(c!==d.current)return;u(b instanceof Error?b:new Error("Failed to fetch person"))}finally{c===d.current&&i(!1)}},[a,e,t]);return Ln.useEffect(()=>{o()},[o]),{person:s,isLoading:r,error:l,refetch:o}}var _=require("react/jsx-runtime"),Po="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",cf="af-text-xs af-text-muted-foreground";function Zs(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 ko(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function df(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function uf({value:e,label:t}){let[a,s]=Ea.useState(!1);return df()?(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[a?(0,_.jsx)(zt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,_.jsx)(zt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function Rc(e){return(0,_.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,_.jsxs)(ie,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,_.jsx)(ie,{variant:"secondary",children:"Contact form"})]})}function _c(e){return e.name?e.name:e.email?e.email:(0,_.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var ff=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,mf=40;function pf(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),s=t.find(([n,r])=>ff.test(n)&&typeof r=="string"&&r.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=mf).sort((n,r)=>String(r[1]).trim().length-String(n[1]).trim().length)[0];return s?{message:String(s[1]),rest:t.filter(([n])=>n!==s[0])}:{message:null,rest:t}}function gf(e){return e.replace(/_/g," ")}function vf(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function bf({data:e}){let{message:t,rest:a}=pf(e);return t===null&&a.length===0?(0,_.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,_.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,_.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),a.length>0&&(0,_.jsx)("dl",{className:"af-space-y-1",children:a.map(([s,n])=>(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,_.jsx)("dt",{className:X(cf,"af-w-28 af-shrink-0 af-capitalize"),children:gf(s)}),(0,_.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:vf(n)})]},s))})]})}function kc({formName:e,createdAt:t,data:a,onDelete:s}){return(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)(ie,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,_.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,_.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Zs(t)}),(0,_.jsx)(Us,{iconOnly:!0,onDelete:s})]}),(0,_.jsx)(bf,{data:a})]})}function hf(e){return e.charged_total??e.amount_total}function yf({email:e,refreshKey:t,onBack:a,onRemoved:s}){let{api:n}=W(),{person:r,isLoading:i,error:l,refetch:u}=Lr(e,{refreshKey:t}),d=async c=>{await n.deleteSubmission(c),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?u():a()},o=ko(e,r?.submissions[0]?.form_name);return(0,_.jsxs)("div",{children:[(0,_.jsxs)("div",{className:"af-mb-6",children:[(0,_.jsxs)(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,_.jsx)(zt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,_.jsxs)("div",{className:"af-min-w-0",children:[i?(0,_.jsx)(ae,{className:"af-h-7 af-w-48"}):(0,_.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),(0,_.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,_.jsx)(uf,{value:e,label:"Copy email address"})]})]}),(0,_.jsx)(y,{asChild:!0,children:(0,_.jsxs)("a",{href:o,children:[(0,_.jsx)(zt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),i?(0,_.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(c=>(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsx)(ae,{className:"af-w-40"}),(0,_.jsx)(ae,{className:"af-mt-2 af-w-64"})]},c)),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):l||!r?(0,_.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,_.jsx)(Et,{message:"Couldn't load this person.",onRetry:()=>u()})}):(0,_.jsxs)("div",{className:"af-space-y-6",children:[r.customer&&(0,_.jsxs)("div",{children:[(0,_.jsx)("h4",{className:X(Po,"af-mb-3"),children:"Customer"}),(0,_.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&(0,_.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,_.jsx)("dd",{children:r.customer.name})]}),r.customer.phone&&(0,_.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,_.jsx)("dd",{children:r.customer.phone})]}),(0,_.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,_.jsx)("dd",{children:Zs(r.customer.created_at)})]})]})]}),r.orders.length>0&&(0,_.jsxs)("div",{children:[(0,_.jsx)("h4",{className:X(Po,"af-mb-3"),children:"Purchases"}),(0,_.jsx)("div",{className:"af-overflow-x-auto",children:(0,_.jsxs)(ft,{children:[(0,_.jsx)(mt,{children:(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Z,{children:"Order"}),(0,_.jsx)(Z,{children:"Date"}),(0,_.jsx)(Z,{className:"af-text-right",children:"Total"}),(0,_.jsx)(Z,{children:"Status"})]})}),(0,_.jsx)(pt,{children:r.orders.map(c=>(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Y,{className:"af-whitespace-nowrap af-font-medium",children:qn(c)}),(0,_.jsx)(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Zs(c.created_at)}),(0,_.jsx)(Y,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:ee(hf(c),c.currency)}),(0,_.jsx)(Y,{children:(0,_.jsx)(ss,{status:c.status})})]},c.id))})]})}),(0,_.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,_.jsxs)("div",{children:[(0,_.jsx)("h4",{className:X(Po,"af-mb-3"),children:"Messages"}),(0,_.jsx)("div",{className:"af-space-y-3",children:r.submissions.map(c=>(0,_.jsx)(kc,{formName:c.form_name,createdAt:c.created_at,data:c.data,onDelete:()=>d(c.id)},c.id))})]})]})]})}function xf({submissionId:e,onBack:t,onRemoved:a}){let{api:s}=W(),[n,r]=Ea.useState(null),[i,l]=Ea.useState(!0),[u,d]=Ea.useState(null),[o,c]=Ea.useState(0);return Ea.useEffect(()=>{let b=!1;return l(!0),d(null),s.getSubmission(e).then(g=>{b||r(g)}).catch(g=>{b||d(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{b||l(!1)}),()=>{b=!0}},[s,e,o]),(0,_.jsxs)("div",{children:[(0,_.jsxs)("div",{className:"af-mb-6",children:[(0,_.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,_.jsx)(zt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,_.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,_.jsx)(ae,{className:"af-mt-1 af-h-4 af-w-32"}):n&&(0,_.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Zs(n.metadata.submitted_at)})]}),i?(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,_.jsx)(ae,{className:"af-w-40"}),(0,_.jsx)(ae,{className:"af-mt-2 af-w-64"}),(0,_.jsx)(ae,{className:"af-mt-2 af-w-52"}),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):u||!n?(0,_.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,_.jsx)(Et,{message:"Couldn't load this submission.",onRetry:()=>c(b=>b+1)})}):(0,_.jsxs)("div",{className:"af-space-y-3",children:[(0,_.jsx)(kc,{formName:null,createdAt:n.metadata.submitted_at,data:n.data,onDelete:async()=>{await s.deleteSubmission(e),a(),t()}}),(0,_.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 wf={all:"All",customers:"Customers",leads:"Leads"},Sf=["all","customers","leads"],Pc={all:void 0,customers:"customer",leads:"lead"};function Nf({refreshKey:e,onBackToWebsite:t,className:a,maxRows:s,onViewAll:n}){let r=typeof s=="number",{people:i,isLoading:l,error:u,page:d,pageSize:o,hasNextPage:c,hasPreviousPage:b,setPage:g,q:m,setQ:p,source:f,setSource:v,refetch:x,refetchAfterRemoval:k}=Ar({refreshKey:e}),[T,h]=Ea.useState({kind:"list"}),[R,P]=Ea.useState(""),D=f==="customer"?"customers":f==="lead"?"leads":"all",N=J=>{Pc[J]!==f&&v(Pc[J])},{api:E}=W(),A=Ea.useCallback(()=>E.exportPeopleCsv({...m?{q:m}:{},...f?{source:f}:{}}),[E,m,f]),C=!r||!!n,K=J=>{if(r){n?.();return}J.email?h({kind:"person",email:J.email}):J.submission_id&&h({kind:"submission",submissionId:J.submission_id})},Q=Ea.useRef(!1),H=()=>{Q.current=!0},de=()=>{h({kind:"list"}),Q.current?(Q.current=!1,k()):x()},me=J=>{let F=J.trim();F!==m&&p(F)},be=r?i.slice(0,s):i,V;if(T.kind==="person")V=(0,_.jsx)(yf,{email:T.email,refreshKey:e,onBack:de,onRemoved:H});else if(T.kind==="submission")V=(0,_.jsx)(xf,{submissionId:T.submissionId,onBack:de,onRemoved:H});else{let J=(0,_.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.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:Sf.map(F=>(0,_.jsx)("button",{type:"button","aria-pressed":D===F,onClick:()=>N(F),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",D===F?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:wf[F]},F))}),(0,_.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,_.jsx)(zt.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,_.jsx)(oe,{type:"text",value:R,onChange:F=>P(F.target.value),onBlur:()=>me(R),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),me(R))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),m&&(0,_.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{P(""),p("")},children:"Clear search"}),(0,_.jsx)(da,{fetchCsv:A,filename:"people",className:"af-ml-auto"})]});if(l)V=(0,_.jsxs)("div",{children:[r?null:J,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(F=>(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)(ae,{className:"af-h-4 af-w-32"}),(0,_.jsx)(ae,{className:"af-h-4 af-w-16"})]}),(0,_.jsx)(ae,{className:"af-mt-2 af-h-5 af-w-28"}),(0,_.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-56"})]},F))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(ft,{children:[(0,_.jsx)(mt,{children:(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Z,{children:"Person"}),(0,_.jsx)(Z,{children:"Came from"}),(0,_.jsx)(Z,{children:"Latest message"}),(0,_.jsx)(Z,{children:"Last activity"}),(0,_.jsx)(Z,{className:"af-w-8"}),(0,_.jsx)(Z,{className:"af-w-8"})]})}),(0,_.jsx)(pt,{"aria-hidden":"true",children:[0,1,2,3,4].map(F=>(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Y,{children:(0,_.jsx)(ae,{className:"af-h-4 af-w-40"})}),(0,_.jsx)(Y,{children:(0,_.jsx)(ae,{className:"af-h-5 af-w-24"})}),(0,_.jsx)(Y,{children:(0,_.jsx)(ae,{className:"af-h-4 af-w-56"})}),(0,_.jsx)(Y,{children:(0,_.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,_.jsx)(Y,{}),(0,_.jsx)(Y,{})]},F))})]})}),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(u)V=(0,_.jsxs)("div",{children:[r?null:J,(0,_.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,_.jsx)(Et,{message:"Couldn't load your leads.",onRetry:()=>x()})})]});else if(be.length===0&&d===0){let F=!!m||D!=="all";V=(0,_.jsxs)("div",{children:[F&&J,F?(0,_.jsx)(va,{children:m?"Nobody matches that search.":D==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,_.jsx)(zs,{icon:zt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(i.length===0)V=(0,_.jsxs)("div",{children:[r?null:J,(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)(y,{variant:"outline",size:"sm",onClick:()=>g(d-1),children:[(0,_.jsx)(zt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let F=d*o+1,ge=d*o+i.length;V=(0,_.jsxs)("div",{children:[r?null:J,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:be.map((pe,He)=>(0,_.jsxs)("div",{onClick:C?()=>K(pe):void 0,className:`af-rounded-md af-border af-p-3${C?" af-cursor-pointer hover:af-bg-muted/50":""}`,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)("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),K(pe)},disabled:!C,"aria-label":`Open ${pe.name||pe.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${C?" hover:af-underline":""}`,children:_c(pe)}),pe.name&&pe.email&&(0,_.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:pe.email})]}),(0,_.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,_.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:Zs(pe.last_activity_at)}),pe.email&&(0,_.jsx)(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,_.jsx)("a",{href:ko(pe.email),onClick:Pe=>Pe.stopPropagation(),"aria-label":`Email ${pe.email}`,children:(0,_.jsx)(zt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,_.jsx)("div",{className:"af-mt-2",children:Rc(pe)}),pe.latest_message_excerpt&&(0,_.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:pe.latest_message_excerpt})]},pe.email??pe.submission_id??He))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(ft,{children:[(0,_.jsx)(mt,{children:(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Z,{children:"Person"}),(0,_.jsx)(Z,{children:"Came from"}),(0,_.jsx)(Z,{children:"Latest message"}),(0,_.jsx)(Z,{children:"Last activity"}),(0,_.jsx)(Z,{className:"af-w-8",children:(0,_.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,_.jsx)(Z,{className:"af-w-8"})]})}),(0,_.jsx)(pt,{children:be.map((pe,He)=>(0,_.jsxs)(Fe,{onClick:C?()=>K(pe):void 0,className:C?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,_.jsxs)(Y,{className:"af-max-w-[260px] af-font-medium",children:[(0,_.jsx)("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),K(pe)},disabled:!C,"aria-label":`Open ${pe.name||pe.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${C?" hover:af-underline":""}`,children:_c(pe)}),pe.name&&pe.email&&(0,_.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:pe.email})]}),(0,_.jsx)(Y,{children:Rc(pe)}),(0,_.jsx)(Y,{className:"af-max-w-[320px]",children:pe.latest_message_excerpt?(0,_.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:pe.latest_message_excerpt}):(0,_.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,_.jsx)(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Zs(pe.last_activity_at)}),(0,_.jsx)(Y,{className:"af-w-8",children:pe.email&&(0,_.jsx)(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,_.jsx)("a",{href:ko(pe.email),onClick:Pe=>Pe.stopPropagation(),"aria-label":`Email ${pe.email}`,children:(0,_.jsx)(zt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,_.jsx)(Y,{className:"af-w-8 af-text-right",children:(0,_.jsx)(zt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},pe.email??pe.submission_id??He))})]})}),!r&&(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 ${F}-${ge}`}),(0,_.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>g(d-1),disabled:!b,children:[(0,_.jsx)(zt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>g(d+1),disabled:!c,children:["Next",(0,_.jsx)(zt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?(0,_.jsx)("div",{className:a,children:V}):(0,_.jsx)(Lt,{title:"Leads",onBackToWebsite:t,hideBackButton:T.kind!=="list",className:a,children:V})}function Or(e){return(0,_.jsx)(Nf,{...e},e.maxRows==null?"full":"compact")}var Dc=ce(require("react"),1),Rs=require("lucide-react");var Ia=ce(require("react"),1);function Br({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=W(),[s,n]=Ia.useState([]),[r,i]=Ia.useState(0),[l,u]=Ia.useState(!0),[d,o]=Ia.useState(null),[c,b]=Ia.useState(0),[g,m]=Ia.useState(e),[p,f]=Ia.useState(void 0),v=Ia.useRef(0),x=Ia.useCallback(async()=>{let T=++v.current;try{u(!0),o(null);let h={limit:g,offset:c*g};p&&(h.status=p);let R=await a.getSubscriptions(h);if(T!==v.current)return;n(R.subscriptions),i(R.total)}catch(h){if(T!==v.current)return;o(h instanceof Error?h:new Error("Failed to fetch subscriptions"))}finally{T===v.current&&u(!1)}},[a,c,g,p,t]);Ia.useEffect(()=>{x()},[x]);let k=Math.ceil(r/g);return{subscriptions:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<k-1,hasPreviousPage:c>0,setPage:b,setPageSize:T=>{m(T),b(0)},status:p,setStatus:T=>{f(T),b(0)},refetch:x}}var q=require("react/jsx-runtime");function Cc(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 Tc({sub:e}){return e.status==="canceled"?(0,q.jsx)(ie,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,q.jsx)(ie,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,q.jsx)(ie,{variant:"warning",children:"Scheduled to cancel"}):(0,q.jsx)(ie,{variant:"success",children:"Active"}):(0,q.jsx)(ie,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Rf(e,t){let a=ee(t,e.currency);return e.plan_interval_count===1?`${a} / ${e.plan_interval}`:`${a} every ${e.plan_interval_count} ${e.plan_interval}s`}function Ec({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,q.jsxs)("div",{children:[(0,q.jsx)("div",{className:"af-font-medium af-tabular-nums",children:Rf(e,e.current_amount)}),t&&(0,q.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",ee(e.plan_amount,e.currency)]})]})}function Ic(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Cc(e.current_period_end)}`:"Ends at period end":e.current_period_end?Cc(e.current_period_end):"\u2014"}function Co({refreshKey:e,onBackToWebsite:t,className:a}){let{subscriptions:s,total:n,isLoading:r,error:i,page:l,pageSize:u,hasNextPage:d,hasPreviousPage:o,setPage:c,status:b,refetch:g}=Br({refreshKey:e}),{api:m}=W(),p=Dc.useCallback(()=>m.exportSubscriptionsCsv(b?{status:b}:{}),[m,b]),f;if(r)f=(0,q.jsxs)("div",{children:[(0,q.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(v=>(0,q.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,q.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,q.jsx)(ae,{className:"af-h-4 af-w-40"}),(0,q.jsx)(ae,{className:"af-h-4 af-w-20"})]}),(0,q.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-32"}),(0,q.jsx)(ae,{className:"af-mt-2 af-h-5 af-w-24"})]},v))}),(0,q.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,q.jsxs)(ft,{children:[(0,q.jsx)(mt,{children:(0,q.jsxs)(Fe,{children:[(0,q.jsx)(Z,{children:"Subscriber"}),(0,q.jsx)(Z,{children:"Plan"}),(0,q.jsx)(Z,{className:"af-text-right",children:"Amount"}),(0,q.jsx)(Z,{children:"Renews"}),(0,q.jsx)(Z,{children:"Status"})]})}),(0,q.jsx)(pt,{"aria-hidden":"true",children:[0,1,2,3,4].map(v=>(0,q.jsxs)(Fe,{children:[(0,q.jsx)(Y,{children:(0,q.jsx)(ae,{className:"af-h-4 af-w-44"})}),(0,q.jsx)(Y,{children:(0,q.jsx)(ae,{className:"af-h-4 af-w-32"})}),(0,q.jsx)(Y,{className:"af-text-right",children:(0,q.jsx)(ae,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,q.jsx)(Y,{children:(0,q.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,q.jsx)(Y,{children:(0,q.jsx)(ae,{className:"af-h-5 af-w-20"})})]},v))})]})}),(0,q.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(i)f=(0,q.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,q.jsx)(Et,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(s.length===0&&l===0)f=(0,q.jsx)(va,{icon:(0,q.jsx)(Rs.Repeat,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(s.length===0)f=(0,q.jsxs)("div",{children:[(0,q.jsx)(va,{children:"No more results."}),(0,q.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,q.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>c(l-1),children:[(0,q.jsx)(Rs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let v=l*u+1,x=l*u+s.length;f=(0,q.jsxs)("div",{children:[(0,q.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,q.jsx)(da,{fetchCsv:p,filename:"subscriptions"})}),(0,q.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(k=>(0,q.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,q.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,q.jsxs)("div",{className:"af-min-w-0",children:[(0,q.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:k.customer_email||(0,q.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,q.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:k.plan_title||"Untitled plan"})]}),(0,q.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,q.jsx)(Ec,{sub:k})})]}),(0,q.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,q.jsx)(Tc,{sub:k}),k.is_test&&(0,q.jsx)(ie,{variant:"outline",children:"Test"}),(0,q.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Ic(k)})]}),(0,q.jsx)(Pn,{deliveries:k.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},k.id))}),(0,q.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,q.jsxs)(ft,{children:[(0,q.jsx)(mt,{children:(0,q.jsxs)(Fe,{children:[(0,q.jsx)(Z,{children:"Subscriber"}),(0,q.jsx)(Z,{children:"Plan"}),(0,q.jsx)(Z,{className:"af-text-right",children:"Amount"}),(0,q.jsx)(Z,{children:"Renews"}),(0,q.jsx)(Z,{children:"Status"})]})}),(0,q.jsx)(pt,{children:s.map(k=>(0,q.jsxs)(Fe,{children:[(0,q.jsx)(Y,{className:"af-max-w-[240px]",children:(0,q.jsx)("div",{className:"af-truncate af-font-medium",children:k.customer_email||(0,q.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,q.jsx)(Y,{className:"af-max-w-[220px]",children:(0,q.jsx)("div",{className:"af-truncate",children:k.plan_title||(0,q.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,q.jsx)(Y,{className:"af-whitespace-nowrap af-text-right",children:(0,q.jsx)(Ec,{sub:k})}),(0,q.jsx)(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ic(k)}),(0,q.jsxs)(Y,{children:[(0,q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,q.jsx)(Tc,{sub:k}),k.is_test&&(0,q.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,q.jsx)(Pn,{deliveries:k.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},k.id))})]})}),(0,q.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,q.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${v}-${x} of ${n}`}),(0,q.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,q.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>c(l-1),disabled:!o,children:[(0,q.jsx)(Rs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,q.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>c(l+1),disabled:!d,children:["Next",(0,q.jsx)(Rs.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,q.jsx)(Lt,{title:"Subscriptions",onBackToWebsite:t,className:a,children:f})}var Bn=ce(require("react"),1),Gc=require("lucide-react");var ba=ce(require("react"),1);var Li=ce(require("react"),1),_s=typeof window>"u"?Li.useEffect:Li.useLayoutEffect;var Oi=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},_f=(e,t)=>e instanceof Error?e:new Error(t);function Pf(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 Ac(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function Kn({siteId:e,refreshKey:t,onSaveInvoiceSettings:a}){let{api:s}=W(),[n,r]=ba.useState(null),[i,l]=ba.useState(!0),[u,d]=ba.useState(null),o=ba.useRef(null),[c,b]=ba.useState(()=>Ac(s,e)),g=c.api!==s||c.siteId!==e,m=c;g&&(m=Ac(s,e),b(m),r(null),l(!0),d(null));let p=ba.useRef(m);_s(()=>{p.current!==m&&(p.current=m,o.current=null)},[m]);let f=(N,E)=>p.current===N&&E>N.applied,v=(N,E,A)=>f(N,E)?(N.applied=E,o.current=A,r(A),l(!1),!0):!1,x=async N=>{for(;N.writing;)await N.idle;let E=++N.seq;try{let A=await N.api.getSite(N.siteId);return v(N,E,A)&&d(null),{seq:E,error:null}}catch(A){return{seq:E,error:_f(A,"Failed to load store settings")}}},k=(N,E)=>{let A=async()=>{if(p.current!==N)throw new Error("Not saved: the store switched to another site first.");N.writing=!0,N.idle=new Promise(K=>{N.markIdle=K});try{return await E(++N.seq)}finally{N.writing=!1,N.markIdle()}},C=N.queue.then(A,A);return N.queue=C.catch(()=>{}),C},T=ba.useCallback(async()=>{let N=await x(m);N.error&&f(m,N.seq)&&(d(N.error),l(!1))},[m]);ba.useEffect(()=>{T()},[T,t]);let h=ba.useCallback(N=>k(m,async E=>{let A=await m.api.updateSite(m.siteId,N),{currency_restatement:C,...K}=A;return v(m,E,K)&&d(Q=>Q instanceof Oi?Q:null),A}),[m]),R=ba.useRef(a);_s(()=>{R.current=a});let P=ba.useCallback(async(N,E)=>{await k(m,()=>N());let A=await x(m);return A.error&&f(m,A.seq)&&o.current&&(v(m,A.seq,{...o.current,...E}),d(new Oi(`Saved, but couldn't refresh settings: ${A.error.message}`))),p.current===m?o.current:null},[m]),D=ba.useCallback(N=>{let E=R.current;return P(()=>E(N),Pf(N))},[P]);return{site:g?null:n,isLoading:g||i,error:g?null:u,refetch:T,updateSite:h,saveInvoiceSettings:a?D:null}}var ea=ce(require("react"),1),Io=require("lucide-react");var It=require("react/jsx-runtime");function Bi(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var yn="af-grid af-gap-1 af-text-sm",Lc="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",Oc="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 Da({children:e}){return(0,It.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Fr({children:e}){return(0,It.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var On=ea.forwardRef(function({id:t,title:a,description:s,children:n},r){let i=`af-store-${t}-title`;return(0,It.jsxs)("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":i,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:i,className:"af-text-sm af-font-semibold",children:a}),s&&(0,It.jsx)(Da,{children:s})]}),n]})});function Fi({label:e,description:t,checked:a,onSave:s,disabled:n=!1,disabledReason:r}){let[i,l]=ea.useState(null),[u,d]=ea.useState(null),o=i??a,c=async b=>{l(b),d(null);try{await s(b)}catch(g){d(Bi(g))}finally{l(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":o,checked:o,disabled:n||i!==null,onChange:b=>void c(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,i!==null&&(0,It.jsx)(Io.Loader2,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&(0,It.jsx)(Da,{children:t})]})]}),(n&&r||u)&&(0,It.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[n&&r&&(0,It.jsx)(Da,{children:r}),u&&(0,It.jsx)(Fr,{children:u})]})]})}var Eo=(e,t)=>JSON.stringify(e)===JSON.stringify(t),To=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function kf(e,t,a,s=[]){if(!To(e)||!To(t)||!To(a))return{draft:Eo(e,t)?a:e,dropped:[]};let n=[],r={...a};for(let i of Object.keys(a))Eo(e[i],t[i])||(s.includes(i)?n.push(i):r[i]=e[i]);return{draft:r,dropped:n}}function Ys(e,t){let a=JSON.stringify(e),[s,n]=ea.useState(e),[r,i]=ea.useState([]),l=ea.useRef(e),u=ea.useRef(e),d=ea.useRef(s);_s(()=>{u.current=e,d.current=s});let o=ea.useRef(t?.when);ea.useEffect(()=>{let b=Object.is(o.current,t?.when)?[]:t?.fields??[];if(o.current=t?.when,Eo(l.current,u.current)&&b.length===0)return;let g=kf(d.current,l.current,u.current,b);l.current=u.current,n(g.draft),g.dropped.length&&i(g.dropped)},[a,t?.when]);let c=ea.useCallback(b=>{n(b??u.current),i([])},[]);return{draft:s,setDraft:n,dirty:JSON.stringify(s)!==a,reset:c,dropped:r}}function Js({dirty:e,saving:t,error:a,onSave:s,onDiscard:n}){return e?(0,It.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,It.jsxs)(y,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&(0,It.jsx)(Io.Loader2,{className:"af-animate-spin"}),"Save"]}),(0,It.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:n,children:"Discard"}),a&&(0,It.jsx)("p",{role:"alert",className:X("af-text-sm af-text-destructive"),children:a})]}):null}function Xs(){let[e,t]=ea.useState(!1),[a,s]=ea.useState(null),n=ea.useCallback(async r=>{t(!0),s(null);try{await r()}catch(i){s(Bi(i))}finally{t(!1)}},[]);return{saving:e,error:a,setError:s,run:n}}function Bc({what:e}){return(0,It.jsxs)(Da,{children:["Only the site owner can change ",e,"."]})}var fn=ce(require("react"),1),Ps=require("lucide-react");var j=require("react/jsx-runtime"),Ao=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function $c({site:e,updateSite:t}){return(0,j.jsxs)("div",{className:"af-space-y-4",children:[(0,j.jsx)(Fi,{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:a=>t({collect_phone_at_checkout:a})}),e.checkout_marketing_consent!==void 0&&(0,j.jsx)(Fi,{label:"Ask buyers for marketing consent at checkout",description:"Adds Stripe's consent checkbox to your checkout. Buyers who tick it join your email list, and buyers who leave without paying can get your abandoned-cart recovery emails.",checked:e.checkout_marketing_consent&&e.stripe_account_country==="US",disabled:e.stripe_account_country!=="US",disabledReason:e.stripe_account_country?'Only available for US stores: Stripe offers its consent checkbox to US businesses only. Your checkout shows an "Email me" box instead.':"Available once your Stripe account is connected and its country has synced.",onSave:a=>t({checkout_marketing_consent:a})})]})}function Fc(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(kt(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(kt(e.free_shipping_over,e.currency))}}function Vc({site:e,updateSite:t,refetch:a,providerSlot:s,currencyChanging:n=!1}){let{draft:r,setDraft:i,dirty:l,reset:u,dropped:d}=Ys(Fc(e),{when:e.currency,fields:["rates","threshold"]}),{saving:o,error:c,setError:b,run:g}=Xs(),m=e.currency.toUpperCase(),p=()=>g(async()=>{let v={},x=[...new Set(r.countries.split(/[\s,]+/).map(N=>N.trim().toUpperCase()).filter(Boolean))],k=x.find(N=>!/^[A-Z]{2}$/.test(N));if(k)throw new Error(`"${k}" isn't a two-letter country code (e.g. US, CA).`);let T=x.length?x:null;Ao(T,e.shipping_countries)||(v.shipping_countries=T);let h=[];for(let N of r.rates){let E=N.label.trim(),A=ia(N.amount,e.currency);if(!E)throw new Error("Every rate needs a name.");if(N.amount.trim()===""||A===null)throw new Error(`Enter a price for "${E}" (0 for free).`);h.push({label:E,amount:A})}let R=h.length?h:null;Ao(R,e.shipping_rates)||(v.shipping_rates=R);let P=null;if(r.threshold.trim()!==""&&(P=ia(r.threshold,e.currency),P===null||P===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(P!==e.free_shipping_over&&(v.free_shipping_over=P),Object.keys(v).length===0){u();return}("shipping_rates"in v||"free_shipping_over"in v)&&(v.expected_currency=e.currency);let D;try{D=await t(v)}catch(N){throw N instanceof jt&&N.details?.code==="currency_changed"&&await a?.(),N}u(Fc(D))}),f=(v,x)=>i({...r,rates:r.rates.map((k,T)=>T===v?{...k,...x}:k)});return(0,j.jsxs)("fieldset",{disabled:o||n,className:"af-space-y-4",children:[(0,j.jsxs)("label",{className:yn,children:["Countries you ship to",(0,j.jsx)(oe,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:v=>i({...r,countries:v.target.value})}),(0,j.jsx)(Da,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsxs)("p",{className:"af-text-sm",children:["Flat shipping rates (",m,")"]}),r.rates.length===0&&(0,j.jsx)(Da,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((v,x)=>(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,j.jsx)(oe,{"aria-label":`Rate ${x+1} name`,value:v.label,placeholder:"Standard",onChange:k=>f(x,{label:k.target.value})}),(0,j.jsx)(oe,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:v.amount,placeholder:"0",className:"af-w-32",onChange:k=>f(x,{amount:k.target.value})}),(0,j.jsx)(y,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${x+1}`,onClick:()=>i({...r,rates:r.rates.filter((k,T)=>T!==x)}),children:(0,j.jsx)(Ps.X,{})})]},x)),(0,j.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[(0,j.jsx)(Ps.Plus,{})," Add rate"]}),(0,j.jsx)(Da,{children:"Buyers pick one at checkout. The first is preselected."})]}),(0,j.jsxs)("label",{className:yn,children:["Free shipping over (",m,")",(0,j.jsx)(oe,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:v=>i({...r,threshold:v.target.value})}),(0,j.jsx)(Da,{children:"Orders at or above this get the cheapest rate free."})]}),d.length>0&&(0,j.jsxs)("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",m,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),(0,j.jsx)(Js,{dirty:l,saving:o,error:c,onSave:()=>void p(),onDiscard:()=>{b(null),u()}}),s]})}var Do="exclusive",Cf=[{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 Tf({href:e,children:t}){return(0,j.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,j.jsx)(Ps.ExternalLink,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function Hc({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=Ys(e.tax_behavior??Do),{saving:i,error:l,setError:u,run:d}=Xs(),[o,c]=fn.useState(!1),b=e.stripe_tax_enabled,g=b||o,m=()=>d(async()=>{let v=a;if(v===e.tax_behavior){r();return}let x={tax_behavior:v};v!=="inclusive"&&e.tax_rate_bps!=null&&(x.tax_rate_bps=null);let k=await t(x);r(k.tax_behavior??Do)}),p=()=>d(async()=>{let v={stripe_tax_enabled:!0,tax_behavior:a};a!=="inclusive"&&e.tax_rate_bps!=null&&(v.tax_rate_bps=null);let x=await t(v);r(x.tax_behavior??Do),c(!1)}),f=(n||o)&&a!=="inclusive"&&e.tax_rate_bps!=null;return(0,j.jsxs)("div",{className:"af-space-y-5",children:[(0,j.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,j.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,j.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,j.jsx)("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:Cf.map(v=>(0,j.jsx)("li",{children:(0,j.jsx)(Tf,{href:v.href,children:v.label})},v.href))})]}),(0,j.jsx)(Fi,{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:g,onSave:async v=>{if(o){c(!1),u(null),r();return}if(v&&!e.tax_behavior){c(!0);return}return t({stripe_tax_enabled:v})}}),g&&(0,j.jsxs)("fieldset",{disabled:i,className:"af-space-y-4 af-pl-6",children:[(0,j.jsxs)("label",{className:yn,children:["Do your prices already include tax?",(0,j.jsxs)("select",{"aria-label":"Your prices",className:Lc,value:a,onChange:v=>s(v.target.value),children:[(0,j.jsx)("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),(0,j.jsx)("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),(0,j.jsx)(Da,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),f&&(0,j.jsxs)(Da,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),o?(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(y,{type:"button",size:"sm",disabled:i,onClick:()=>void p(),children:"Turn on"}),(0,j.jsx)(y,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>{c(!1),u(null),r()},children:"Cancel"})]}),l&&(0,j.jsx)(Fr,{children:l})]}):(0,j.jsx)(Js,{dirty:n,saving:i,error:l,onSave:()=>void m(),onDiscard:()=>{u(null),r()}})]})]})}function Mc(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function zc({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=Ys(Mc(e)),{saving:i,error:l,setError:u,run:d}=Xs(),o=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),c=()=>d(async()=>{let b={},g=null;if(o&&a.rate.trim()!==""){let v=Number(a.rate);if(!Number.isFinite(v)||v<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(v*100)}o&&g!==e.tax_rate_bps&&(b.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let m=a.taxId.trim()||null;m!==e.tax_id&&(b.tax_id=m);let p=a.label.trim()||null;if(p!==e.tax_label&&(b.tax_label=p),Object.keys(b).length===0){r();return}let f=await t(b);r(Mc(f))});return(0,j.jsxs)("fieldset",{disabled:i,className:"af-space-y-4",children:[(0,j.jsxs)("label",{className:yn,children:["Tax rate (%)",(0,j.jsx)(oe,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!o,value:o?a.rate:"",onChange:b=>s({...a,rate:b.target.value})}),(0,j.jsx)(Da,{children:o?"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,j.jsxs)("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[(0,j.jsxs)("label",{className:yn,children:["Tax ID",(0,j.jsx)(oe,{"aria-label":"Tax ID",value:a.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...a,taxId:b.target.value})})]}),(0,j.jsxs)("label",{className:yn,children:["Tax label",(0,j.jsx)(oe,{"aria-label":"Tax label",value:a.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...a,label:b.target.value})})]})]}),(0,j.jsx)(Js,{dirty:n,saving:i,error:l,onSave:()=>void c(),onDiscard:()=>{u(null),r()}})]})}function qc({site:e,updateSite:t,onChangeStart:a}){let[s,n]=fn.useState(e.currency.toUpperCase()),[r,i]=fn.useState(!1),[l,u]=fn.useState(!1),[d,o]=fn.useState(null),c=e.currency.toUpperCase(),b=fn.useRef(c);fn.useEffect(()=>{b.current!==c&&(n(v=>v===b.current?c:v),b.current=c)},[c]);let g=s.trim().toUpperCase(),m=g!==c,p=/^[A-Z]{3}$/.test(g),f=async()=>{u(!0);let v=a?.(),x=!1;o(null);try{let k=await t({currency:g.toLowerCase()});x=!0;let T=k.currency_restatement;T&&!T.applied?o(T.reason?`Not changed: ${T.reason}.`:"The currency was not changed."):(n(k.currency.toUpperCase()),b.current=k.currency.toUpperCase()),i(!1)}catch(k){o(Bi(k))}finally{u(!1),v?.(x)}};return(0,j.jsxs)("div",{className:"af-space-y-3",children:[(0,j.jsxs)("div",{className:"af-flex af-items-end af-gap-2",children:[(0,j.jsxs)("label",{className:yn,children:["Store currency",(0,j.jsx)(oe,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:l||r,onChange:v=>{n(v.target.value),o(null)}})]}),m&&!r&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(y,{type:"button",size:"sm",disabled:!p,onClick:()=>i(!0),children:"Change currency"}),(0,j.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>{n(c),o(null)},children:"Discard"})]})]}),(0,j.jsx)(Da,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&(0,j.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,j.jsxs)("p",{className:"af-text-sm",children:["Change the store currency from ",c," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",ee(2e3,c)," becomes ",ee(2e3,g),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(y,{type:"button",size:"sm",disabled:l,onClick:()=>void f(),children:"Confirm change"}),(0,j.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:l,onClick:()=>i(!1),children:"Cancel"})]})]}),d&&(0,j.jsx)(Fr,{children:d})]})}function Uc(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function Ef(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 jc({site:e,save:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=Ys(Uc(e)),{saving:i,error:l,setError:u,run:d}=Xs();if(!t)return(0,j.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,j.jsxs)("p",{children:["Due ",e.invoice_due_days," days after sending"]}),(0,j.jsxs)("p",{children:["Reminders: ",Ef(e.invoice_reminder_schedule)]}),(0,j.jsxs)("p",{children:["Footer: ",e.invoice_footer||"None"]}),(0,j.jsx)(Bc,{what:"invoice defaults"})]});let o=()=>d(async()=>{let c={},b=Number(a.dueDays);if(a.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&&(c.due_days=b);let m=a.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(m.some(x=>!Number.isInteger(x)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let p=[...new Set(m)].sort((x,k)=>x-k);Ao(p,e.invoice_reminder_schedule)||(c.reminder_schedule=p);let f=a.footer.trim()||null;if(f!==e.invoice_footer&&(c.footer=f),Object.keys(c).length===0){r();return}let v=await t(c);r(v?Uc(v):void 0)});return(0,j.jsxs)("fieldset",{disabled:i,className:"af-space-y-4",children:[(0,j.jsxs)("label",{className:yn,children:["Days until due",(0,j.jsx)(oe,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:a.dueDays,onChange:c=>s({...a,dueDays:c.target.value})})]}),(0,j.jsxs)("label",{className:yn,children:["Reminder schedule",(0,j.jsx)(oe,{"aria-label":"Reminder schedule",value:a.reminders,placeholder:"Off",onChange:c=>s({...a,reminders:c.target.value})}),(0,j.jsx)(Da,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),(0,j.jsxs)("label",{className:yn,children:["Invoice footer",(0,j.jsx)("textarea",{"aria-label":"Invoice footer",className:Oc,maxLength:300,value:a.footer,onChange:c=>s({...a,footer:c.target.value})})]}),(0,j.jsx)(Js,{dirty:n,saving:i,error:l,onSave:()=>void o(),onDiscard:()=>{u(null),r()}})]})}function Wc({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=Ys(e.default_email_recipients),{saving:i,error:l,setError:u,run:d}=Xs(),[o,c]=fn.useState(""),[b,g]=fn.useState(null),m=()=>{let f=o.trim().toLowerCase();if(f){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f)){g("Enter a valid email address.");return}if(a.some(v=>v.toLowerCase()===f)){g("Already added.");return}s([...a,f]),c(""),g(null)}},p=()=>d(async()=>{let f=await t({default_email_recipients:a});r(f.default_email_recipients)});return(0,j.jsxs)("fieldset",{disabled:i,className:"af-space-y-3",children:[(0,j.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[a.map(f=>(0,j.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[f,(0,j.jsx)("button",{type:"button","aria-label":`Remove ${f}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(a.filter(v=>v!==f)),children:(0,j.jsx)(Ps.X,{className:"af-h-3 af-w-3"})})]},f)),a.length===0&&(0,j.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(oe,{"aria-label":"Add notification email",type:"email",value:o,placeholder:"Add email address",onChange:f=>{c(f.target.value),g(null)},onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),m())}}),(0,j.jsx)(y,{type:"button",variant:"outline",disabled:!o.trim(),onClick:m,children:"Add"})]}),b&&(0,j.jsx)(Fr,{children:b}),(0,j.jsx)(Js,{dirty:n,saving:i,error:l,onSave:()=>void p(),onDiscard:()=>{u(null),r()}})]})}var ua=require("react/jsx-runtime");function Lo({siteId:e,refreshKey:t,section:a,shippingProviderSlot:s,onConnectStripe:n,onUpgradePlan:r,className:i}){let{site:l,isLoading:u,error:d,refetch:o,updateSite:c}=Kn({siteId:e,refreshKey:t}),b=Bn.useRef(o),g=Bn.useRef(e);_s(()=>{b.current=o,g.current=e});let m=Bn.useRef({}),[p,f]=Bn.useState([]),v=p.some(R=>R.siteId===e),x=Bn.useCallback(()=>{let R={siteId:e},P=b.current;return f(D=>[...D,R]),D=>{let N=()=>f(A=>A.filter(C=>C!==R));!(g.current===R.siteId)||D&&b.current===P?N():b.current().finally(N)}},[e]),k=R=>P=>{m.current[R]=P},T=l!==null&&l.payments_active;if(Bn.useEffect(()=>{if(!T||!a)return;let R=m.current[a];R&&(R.scrollIntoView?.({behavior:"smooth",block:"start"}),R.focus({preventScroll:!0}))},[T,a]),u)return(0,ua.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ua.jsx)(Gc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!l)return(0,ua.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d?.message??"Could not load store settings."});if(!l.payments_active)return(0,ua.jsx)(xs,{className:i,onConnectStripe:n,onUpgradePlan:r,whenActive:(0,ua.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 h={site:l,updateSite:c,refetch:o};return(0,ua.jsxs)("div",{className:`af-space-y-6 ${i??""}`,children:[d&&(0,ua.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d.message}),(0,ua.jsx)(On,{ref:k("checkout"),id:"checkout",title:"Checkout",children:(0,ua.jsx)($c,{...h})}),(0,ua.jsx)(On,{ref:k("shipping"),id:"shipping",title:"Shipping",children:(0,ua.jsx)(Vc,{...h,providerSlot:s,currencyChanging:v})}),(0,ua.jsx)(On,{ref:k("tax"),id:"tax",title:"Tax",children:(0,ua.jsx)(Hc,{...h})}),(0,ua.jsx)(On,{ref:k("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:(0,ua.jsx)(qc,{...h,onChangeStart:x})})]},e)}var Kc=require("lucide-react");var xn=require("react/jsx-runtime");function Mr({siteId:e,refreshKey:t,onSaveInvoiceSettings:a,className:s}){let{site:n,isLoading:r,error:i,updateSite:l,refetch:u,saveInvoiceSettings:d}=Kn({siteId:e,refreshKey:t,onSaveInvoiceSettings:a});return r?(0,xn.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,xn.jsx)(Kc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):n?(0,xn.jsxs)("div",{className:`af-space-y-6 ${s??""}`,children:[i&&(0,xn.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i.message}),(0,xn.jsx)(On,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:(0,xn.jsx)(jc,{site:n,save:d})}),(0,xn.jsx)(On,{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,xn.jsx)(zc,{site:n,updateSite:l,refetch:u})})]},e):(0,xn.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i?.message??"Could not load invoice settings."})}var Zc=require("lucide-react");var Zn=require("react/jsx-runtime");function Oo({siteId:e,refreshKey:t,className:a}){let{site:s,isLoading:n,error:r,updateSite:i,refetch:l}=Kn({siteId:e,refreshKey:t});return n?(0,Zn.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Zn.jsx)(Zc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?(0,Zn.jsxs)("div",{className:`af-space-y-3 ${a??""}`,children:[r&&(0,Zn.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,Zn.jsx)(On,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:(0,Zn.jsx)(Wc,{site:s,updateSite:i,refetch:l})})]},e):(0,Zn.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 Qs=ce(require("react"),1);var xt=require("react/jsx-runtime");function Bo({refreshKey:e,initialInvoiceId:t,onBackToWebsite:a,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,siteId:i,onSaveInvoiceSettings:l,className:u}){let{aggregates:d,isLoading:o,error:c,refetch:b}=hs({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=Ss({refreshKey:e}),{api:m}=W(),p=g.filters,f=Qs.useCallback(()=>m.exportRetainersCsv(p),[m,p]),[v,x]=Qs.useState(!1),[k,T]=Qs.useState(null),[h,R]=Qs.useState(!1),P=(0,xt.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:c||!o&&!d?(0,xt.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,xt.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):o||!d?(0,xt.jsxs)(xt.Fragment,{children:[(0,xt.jsx)(gt,{label:"Outstanding",children:(0,xt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,xt.jsx)(gt,{label:"Overdue",children:(0,xt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,xt.jsx)(gt,{label:"Paid this month",children:(0,xt.jsx)(ae,{className:"af-h-6 af-w-24"})})]}):(0,xt.jsxs)(xt.Fragment,{children:[(0,xt.jsx)(gt,{label:"Outstanding",detail:`${d.outstanding.count} open`,children:ee(d.outstanding.amount,d.currency)}),(0,xt.jsx)(gt,{label:"Overdue",detail:d.overdue.count===0?"Nothing overdue":`${d.overdue.count} overdue`,valueClassName:d.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:ee(d.overdue.amount,d.currency)}),(0,xt.jsx)(gt,{label:"Paid this month",detail:`${d.paid_this_month.count} paid`,children:ee(d.paid_this_month.amount,d.currency)})]})});return(0,xt.jsxs)(Lt,{title:"Invoices",onBackToWebsite:a,hideBackButton:v,className:u,children:[P,i&&!v&&(0,xt.jsxs)("div",{className:"af-mb-6",children:[(0,xt.jsx)(y,{type:"button",variant:"outline",size:"sm","aria-expanded":h,"aria-controls":"af-invoice-settings",onClick:()=>R(D=>!D),children:"Invoice settings"}),h&&(0,xt.jsx)("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:(0,xt.jsx)(Mr,{siteId:i,refreshKey:e,onSaveInvoiceSettings:l})})]}),!v&&(0,xt.jsx)(ys,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:k?.id??null,onShowCycles:D=>T(N=>N?.id===D.id?null:D),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded,exportCsv:f}),(0,xt.jsx)(Gn,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:x,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,retainerFilter:k?{id:k.id,label:`${k.customer_name??k.customer_email??"Recurring invoices"} \u2014 ${k.description}`}:null,onClearRetainerFilter:()=>T(null)})]})}var ta=ce(require("react"),1);var mn=ce(require("react"),1);function Zt(e,t,a){let[s,n]=mn.useState(null),[r,i]=mn.useState(!0),[l,u]=mn.useState(null),d=mn.useRef(0),o=mn.useRef(e);o.current=e;let c=mn.useRef(a);c.current=a;let b=mn.useCallback(async()=>{let m=++d.current,p=c.current;i(!0),u(null);try{let f=await o.current();m===d.current&&n({scope:p,value:f})}catch(f){m===d.current&&u(f instanceof Error?f:new Error("Request failed"))}finally{m===d.current&&i(!1)}},[]);mn.useEffect(()=>{b()},[b,t]);let g=s!==null&&s.scope===a;return{data:g?s.value:null,isLoading:r||!g&&l===null,error:l,refetch:b}}var Mi={commitBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts"},cancelBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts/{sendId}/cancel",params:["sendId"]},createDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts"},updateDraft:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},deleteDraft:{method:"DELETE",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},testSendDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/test",params:["draftId"]},setDraftTemplate:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}/template",params:["draftId"]},duplicateDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/duplicate",params:["draftId"]},copyEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/copy",params:["templateId"]},publishEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/publish",params:["templateId"]},archiveEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/archive",params:["templateId"]},unarchiveEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/unarchive",params:["templateId"]},deleteEmailTemplate:{method:"DELETE",path:"/sites/{siteId}/marketing/templates/{templateId}",params:["templateId"]},importContacts:{method:"POST",path:"/sites/{siteId}/contacts/import"},exportContacts:{method:"GET",path:"/sites/{siteId}/contacts/export"},createTag:{method:"POST",path:"/sites/{siteId}/contact-tags"},updateTag:{method:"PATCH",path:"/sites/{siteId}/contact-tags/{tagId}",params:["tagId"]},bulkTagContacts:{method:"POST",path:"/sites/{siteId}/contacts/tags"},unsubscribeContact:{method:"POST",path:"/sites/{siteId}/contacts/{contactId}/unsubscribe",params:["contactId"]},updateSettings:{method:"PUT",path:"/sites/{siteId}/marketing"},setFormPurpose:{method:"PATCH",path:"/forms/{formId}",params:["formId"]},createWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps"},updateWelcomeStep:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},deleteWelcomeStep:{method:"DELETE",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},publishWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}/publish",params:["stepId"]},activateWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/activate"},pauseWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/pause"},updateWelcome:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome"},setRecoveryStep:{method:"PUT",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},publishRecoveryStep:{method:"POST",path:"/sites/{siteId}/marketing/recovery/steps/{step}/publish",params:["step"]},deleteRecoveryStep:{method:"DELETE",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},activateRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/activate"},pauseRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/pause"}};function Yc(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Mi,e)}function Jc(e,t,a){let s=Mi[e],n="params"in s?s.params:[],r={...a};delete r.siteId;let i=s.path.replace("{siteId}",encodeURIComponent(t));for(let u of n){let d=r[u];if(typeof d!="string"&&typeof d!="number")throw new Error(`${e} needs ${u}`);i=i.replace(`{${u}}`,encodeURIComponent(String(d))),delete r[u]}let l=s.method==="GET"||s.method==="DELETE"?void 0:r;return{method:s.method,path:i,body:l}}var Fo={marketing_disabled:"Email marketing is not available yet.",site_deleted:"This site has been deleted.",sending_not_enabled:"Email isn't turned on for this site yet.",sending_paused:"Sending is paused while we review this site.",domain_not_verified:"Verify your sending domain before you can send.",dmarc_missing:"Your domain needs a DMARC record before you can send.",postal_address_missing:"Add your business postal address before you can send. Every email has to show it.",allowance_exhausted:"You've used this month's email allowance. Sending resumes next month or when you upgrade.",ramp_limit:"Today's sending limit for a new domain is used up. Sending continues tomorrow.",sample_failed:"Too many emails in the first batch bounced, so the rest of this send was stopped."},Ur=new Set(["sending_not_enabled","domain_not_verified","dmarc_missing","postal_address_missing"]);function ks(e){return e?Fo[e]??"Sending is not available right now.":null}var Fn=ce(require("react"),1);var Cs=50;function $r({siteId:e,q:t="",offset:a=0,refreshKey:s=0}){let{api:n}=W(),r=Zt(()=>n.getMarketingContacts(e,{q:t||void 0,limit:Cs,offset:a}),`${e}|${t}|${a}|${s}`,e),i=Zt(()=>n.getMarketingContactStats(e),`${e}|${s}`,e),l=Zt(()=>n.getMarketingTags(e),`${e}|${s}`,e);return{contacts:r,stats:i,tags:l,refetchAll:async()=>{await Promise.all([r.refetch(),i.refetch(),l.refetch()])}}}var ar=ce(require("react"),1);var wn=ce(require("react"),1);var Sn=require("react/jsx-runtime"),Vr=e=>`af-email-settings-${e}`,Mo=wn.createContext(null);function it(){let e=wn.useContext(Mo);if(!e)throw new Error("Email panels render inside EmailView");return e}function Xc(e){let{setInlineEditOpen:t}=it();wn.useEffect(()=>(t(e),()=>t(!1)),[e,t])}function Uo(e){return e.status==="sending"||e.status==="sent"||(e.status==="cancelled"||e.status==="failed")&&e.recipients.consumed>0}function Ui(e,t){return new Set([...e.filter(a=>a.sent).map(a=>a.id),...t.filter(Uo).flatMap(a=>a.draft_id?[a.draft_id]:[])])}function Ts({onClick:e,children:t}){return(0,Sn.jsx)("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function er({reason:e}){let{openSetup:t,onOpenStoreSettings:a}=it(),s=e&&Ur.has(e)?(0,Sn.jsx)(Ts,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&a?(0,Sn.jsx)(Ts,{onClick:a,children:"Open Store settings"}):null;return s&&(0,Sn.jsxs)(Sn.Fragment,{children:[" ",s]})}function $i(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.code=="string"?t.code:typeof t.details?.code=="string"?t.details.code:null}function Aa(e,t){return $i(e)===t?!0:e instanceof Error&&e.message.includes(t)}function tr(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function Ot(){let{onOrgAction:e}=it(),[t,a]=wn.useState(!1),[s,n]=wn.useState(null),r=wn.useCallback(async(i,l={})=>{a(!0),n(null);try{return{ok:!0,result:await e(i,l)}}catch(u){return n(tr(u)),{ok:!1,error:u}}finally{a(!1)}},[e]);return{busy:t,error:s,setError:n,run:r}}function Ee({tone:e="info",children:t,className:a}){return(0,Sn.jsx)("div",{role:e==="error"?"alert":"status",className:X("af-rounded-md af-border af-px-3 af-py-2 af-text-sm",e==="warning"&&"af-border-yellow-300 af-bg-yellow-50 af-text-yellow-900",e==="error"&&"af-border-destructive af-bg-destructive/10 af-text-destructive",e==="success"&&"af-border-green-300 af-bg-green-50 af-text-green-900",a),children:t})}function Ja({children:e,action:t,id:a}){return(0,Sn.jsxs)("div",{id:a,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[(0,Sn.jsx)("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function qe(e){return e.toLocaleString("en-US")}var Bt=require("react/jsx-runtime"),Vi="I confirm that everyone in this file agreed to receive marketing email from my business.",If={invalid_email:"not a valid email address",duplicate:"listed more than once",inactive_in_source:"inactive or unsubscribed in the file",previously_unsubscribed:"unsubscribed before, so they stay unsubscribed",suppressed:"bounced or marked email as spam before",pending:"still confirming their signup"};function Hr({onImported:e}){let{canWrite:t}=it(),[a,s]=ar.useState(""),[n,r]=ar.useState(null),[i,l]=ar.useState(""),[u,d]=ar.useState(!1),[o,c]=ar.useState(null),b=Ot(),g=async()=>{if(!u||!a.trim())return;let m=i.split(",").map(f=>f.trim()).filter(Boolean),p=await b.run("importContacts",{csv:a,attested:!0,...m.length?{tags:m}:{}});if(p.ok){let f=p.result;c(f),e?.(f)}};if(o){let m=new Map;for(let p of o.skipped_rows)m.set(p.reason,(m.get(p.reason)??0)+1);return(0,Bt.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[(0,Bt.jsx)("div",{className:"af-font-medium",children:"Import finished"}),(0,Bt.jsxs)("p",{className:"af-text-sm",children:[qe(o.rows)," rows: ",qe(o.created)," new, ",qe(o.updated)," updated, ",qe(o.skipped)," skipped."]}),m.size>0&&(0,Bt.jsx)("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...m].map(([p,f])=>(0,Bt.jsxs)("li",{children:[qe(f)," ",If[p]??p]},p))}),(0,Bt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),(0,Bt.jsx)(y,{type:"button",size:"sm",variant:"outline",onClick:()=>{c(null),s(""),r(null),d(!1)},children:"Import another file"})]})}return(0,Bt.jsxs)("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:m=>{m.preventDefault(),g()},children:[(0,Bt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Bt.jsx)("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),(0,Bt.jsx)("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async m=>{let p=m.target.files?.[0];p&&(r(p.name),s(await p.text()))}}),(0,Bt.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:'Needs an "email" column. Tags in a "tags" column are applied too.'}),n&&(0,Bt.jsx)("span",{className:"af-block af-text-xs",children:n})]}),(0,Bt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Bt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),(0,Bt.jsx)(oe,{"aria-label":"Tags for imported contacts",value:i,onChange:m=>l(m.target.value)})]}),(0,Bt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,Bt.jsx)("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:u,onChange:m=>d(m.target.checked)}),(0,Bt.jsxs)("span",{children:[Vi," Importing people who didn't agree can get your sending paused."]})]}),b.error&&(0,Bt.jsx)(Ee,{tone:"error",children:b.error}),(0,Bt.jsx)(y,{type:"submit",size:"sm",disabled:!t||!u||!a.trim()||b.busy,children:b.busy?"Importing\u2026":"Import contacts"})]})}var ve=require("react/jsx-runtime"),Df={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function Qc(){let{siteId:e,canWrite:t,refreshKey:a}=it(),[s,n]=Fn.useState(""),[r,i]=Fn.useState(""),[l,u]=Fn.useState(0),[d,o]=Fn.useState(0),[c,b]=Fn.useState(new Set),[g,m]=Fn.useState(!1),p=$r({siteId:e,q:r,offset:l,refreshKey:d+a}),f=Ot(),v=()=>o(P=>P+1),x=p.stats.data,k=p.contacts.data,T=p.tags.data??[],h=x?x.growth.slice(-4).reduce((P,D)=>P+D.new_subscribers,0):null,R=async()=>{let P=await f.run("exportContacts",{});if(!P.ok||typeof P.result!="string"||typeof document>"u")return;let D=URL.createObjectURL(new Blob([P.result],{type:"text/csv;charset=utf-8"})),N=document.createElement("a");N.href=D,N.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(N),N.click(),document.body.removeChild(N),URL.revokeObjectURL(D)};return(0,ve.jsxs)("div",{children:[(0,ve.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[(0,ve.jsx)(gt,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:x?qe(x.total):(0,ve.jsx)(ae,{className:"af-h-6 af-w-16"})}),(0,ve.jsx)(gt,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:x?qe(x.mailable):(0,ve.jsx)(ae,{className:"af-h-6 af-w-16"})}),(0,ve.jsx)(gt,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:h!==null?qe(h):(0,ve.jsx)(ae,{className:"af-h-6 af-w-16"})})]}),(0,ve.jsxs)("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,ve.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:P=>{P.preventDefault(),u(0),i(s.trim())},children:[(0,ve.jsx)(oe,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:s,onChange:P=>n(P.target.value)}),(0,ve.jsx)(y,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),(0,ve.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>m(P=>!P),children:g?"Close import":"Import"}),(0,ve.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!t||f.busy,onClick:()=>void R(),children:"Export"})]}),g&&(0,ve.jsx)("div",{className:"af-mt-3",children:(0,ve.jsx)(Hr,{onImported:v})}),f.error&&(0,ve.jsx)(Ee,{tone:"error",className:"af-mt-2",children:f.error}),t&&c.size>0&&(0,ve.jsx)(Lf,{tags:T.filter(P=>!P.system),count:c.size,busy:f.busy,onApply:async(P,D)=>{(await f.run("bulkTagContacts",{action:P,tag_id:D,contact_ids:[...c]})).ok&&(b(new Set),v())}}),(0,ve.jsx)("div",{className:"af-mt-3",children:p.contacts.error?(0,ve.jsx)(Et,{message:"Couldn't load contacts.",onRetry:()=>void p.contacts.refetch()}):k?k.contacts.length===0?(0,ve.jsx)(va,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):(0,ve.jsxs)(ve.Fragment,{children:[(0,ve.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:k.contacts.map(P=>(0,ve.jsx)(Af,{contact:P,canWrite:t,busy:f.busy,selected:c.has(P.id),onSelect:D=>b(N=>{let E=new Set(N);return D?E.add(P.id):E.delete(P.id),E}),onUnsubscribe:async()=>{(await f.run("unsubscribeContact",{contactId:P.id})).ok&&v()}},P.id))}),(0,ve.jsxs)("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[(0,ve.jsxs)("span",{children:[qe(l+1),"\u2013",qe(l+k.contacts.length)," of ",qe(k.total)]}),(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:l===0,onClick:()=>u(Math.max(0,l-Cs)),children:"Previous"}),(0,ve.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:l+k.contacts.length>=k.total,onClick:()=>u(l+Cs),children:"Next"})]})]})]}):(0,ve.jsx)(ae,{className:"af-h-24 af-w-full"})}),(0,ve.jsx)(Of,{tags:T,canWrite:t,onChanged:v})]})}function Af({contact:e,canWrite:t,busy:a,selected:s,onSelect:n,onUnsubscribe:r}){return(0,ve.jsxs)("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&(0,ve.jsx)("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:s,onChange:i=>n(i.target.checked)}),(0,ve.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,ve.jsxs)("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?(0,ve.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),(0,ve.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[(0,ve.jsx)(ie,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":Df[e.status]}),e.tags.map(i=>(0,ve.jsx)(ie,{variant:"outline",children:i.label},i.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&(0,ve.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:r,children:"Unsubscribe"})]})}function Lf({tags:e,count:t,busy:a,onApply:s}){let[n,r]=Fn.useState("");return(0,ve.jsxs)("div",{className:"af-mt-3 af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:[(0,ve.jsxs)("span",{children:[qe(t)," selected"]}),(0,ve.jsxs)("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:n,onChange:i=>r(i.target.value),children:[(0,ve.jsx)("option",{value:"",children:"Choose a tag\u2026"}),e.map(i=>(0,ve.jsx)("option",{value:i.id,children:i.label},i.id))]}),(0,ve.jsx)(y,{type:"button",size:"sm",variant:"outline",disabled:!n||a,onClick:()=>s("add",n),children:"Add tag"}),(0,ve.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:!n||a,onClick:()=>s("remove",n),children:"Remove tag"})]})}function Of({tags:e,canWrite:t,onChanged:a}){let[s,n]=Fn.useState(""),[r,i]=Fn.useState(null),l=Ot();return(0,ve.jsxs)("div",{children:[(0,ve.jsx)(Ja,{children:"Tags"}),e.length===0?(0,ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No tags yet. Contacts are tagged automatically with where they signed up and what they bought."}):(0,ve.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(u=>(0,ve.jsx)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:r?.id===u.id?(0,ve.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async d=>{d.preventDefault(),(await l.run("updateTag",{tagId:u.id,label:r.label.trim()})).ok&&(i(null),a())},children:[(0,ve.jsx)(oe,{"aria-label":`New name for ${u.label}`,value:r.label,onChange:d=>i({id:u.id,label:d.target.value})}),(0,ve.jsx)(y,{type:"submit",size:"sm",disabled:!r.label.trim()||l.busy,children:"Save"})]}):(0,ve.jsxs)(ve.Fragment,{children:[(0,ve.jsxs)("span",{children:[u.label," ",(0,ve.jsxs)("span",{className:"af-text-muted-foreground",children:["\xB7 ",qe(u.total)," contacts, ",qe(u.mailable)," can be emailed"]})]}),t&&!u.system&&(0,ve.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>i({id:u.id,label:u.label}),children:"Rename"})]})},u.id))}),t&&(0,ve.jsxs)("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async u=>{u.preventDefault(),(await l.run("createTag",{label:s.trim()})).ok&&(n(""),a())},children:[(0,ve.jsx)(oe,{"aria-label":"New tag",placeholder:"New tag",value:s,maxLength:100,onChange:u=>n(u.target.value)}),(0,ve.jsx)(y,{type:"submit",size:"sm",variant:"outline",disabled:!s.trim()||l.busy,children:"Add tag"})]}),l.error&&(0,ve.jsx)(Ee,{tone:"error",className:"af-mt-2",children:l.error})]})}var _t=ce(require("react"),1),md=require("lucide-react");function Es({siteId:e,refreshKey:t=0}){let{api:a}=W();return Zt(()=>a.getBroadcasts(e),`${e}|${t}`,e)}function Is({siteId:e,kind:t,refreshKey:a=0}){let{api:s}=W();return Zt(()=>s.getEmailDrafts(e,t),`${e}|${t??""}|${a}`,`${e}|${t??""}`)}var Ke=ce(require("react"),1);var zr=e=>typeof e=="number"&&Number.isFinite(e);function $o(e){if(!e||typeof e!="object")return null;let t=e;return zr(t.x)&&zr(t.y)&&zr(t.width)&&zr(t.height)?{x:t.x,y:t.y,width:t.width,height:t.height}:null}var Vo=(e,t)=>Number.isInteger(e)&&e>=0&&e<t;function ed(e,t,a){if(!t||e.source!==t)return null;let s=e.data;if(!s||typeof s!="object"||s.af!=="email-editor")return null;switch(s.type){case"hover":{if(s.section===null)return{type:"hover",section:null,rect:null};let n=$o(s.rect);return Vo(s.section,a)&&n?{type:"hover",section:s.section,rect:n}:null}case"focus":case"open":{let n=$o(s.rect);return Vo(s.section,a)&&n?{type:s.type,section:s.section,rect:n}:null}case"layout":{if(!zr(s.height)||!Array.isArray(s.sections))return null;let n=s.sections.flatMap(r=>{let i=r,l=i?$o(i.rect):null;return i&&Vo(i.section,a)&&l?[{section:i.section,rect:l}]:[]});return{type:"layout",height:s.height,sections:n}}case"template":return s.region==="header"||s.region==="footer"?{type:"template",region:s.region}:null;default:return null}}var qr=(e,t,a)=>Math.min(Math.max(e,t),Math.max(t,a));function Ho(e,t){let a=qr(e.x,0,t.width),s=qr(e.y,0,t.height);return{x:a,y:s,width:qr(e.width,0,t.width-a),height:qr(e.height,0,t.height-s)}}var jr={min:240,max:6e3,initial:480},td=e=>qr(Math.ceil(e),jr.min,jr.max);var Ds=ce(require("react"),1);var ot=require("react/jsx-runtime"),zo={heading:"Heading",text:"Text",button:"Button",image:"Image",cart:"Cart"};function nd(e){switch(e){case"heading":case"text":return{type:e,text:""};case"button":return{type:e,label:"",url:"https://"};case"image":return{type:e,url:"",alt:""};case"cart":return{type:e,label:"Return to your cart"}}}function qo(e){switch(e.type){case"heading":case"text":return e.text;case"button":return`${e.label}
6
+ ${e.url}`;case"image":return[e.url,e.alt].filter(Boolean).join(`
7
+ `);case"cart":return e.label}}function ad(e){switch(e.type){case"heading":case"text":return e.text.trim()!=="";case"button":return e.label.trim()!==""&&e.url.trim()!==""&&e.url.trim()!=="https://";case"image":return e.url.trim()!=="";case"cart":return e.label.trim()!==""}}var Bf={...zo,text:"Markdown: **bold**, *italic*, [link](https://\u2026), blank line = new paragraph"};function sd({block:e,isNew:t,busy:a,error:s,onPickImage:n,onDone:r,onRemove:i,onCancel:l,style:u,className:d}){let[o,c]=Ds.useState(e),[b,g]=Ds.useState(!1),m=v=>c(x=>({...x,...v})),p=Ds.useRef(null);Ds.useEffect(()=>p.current?.focus(),[]);let f=v=>{v&&!p.current&&(p.current=v)};return(0,ot.jsx)("form",{"data-testid":"section-editor",style:u,className:d,onSubmit:v=>{v.preventDefault(),ad(o)&&r(o)},onKeyDown:v=>{v.key==="Escape"&&!a&&l()},children:(0,ot.jsxs)("div",{className:"af-space-y-2",children:[o.type==="heading"&&(0,ot.jsx)(oe,{ref:f,"aria-label":"Heading",value:o.text,maxLength:200,onChange:v=>m({text:v.target.value})}),o.type==="text"&&(0,ot.jsx)("textarea",{ref:f,"aria-label":"Text",className:"af-min-h-[120px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-font-mono af-text-sm",value:o.text,maxLength:5e3,onChange:v=>m({text:v.target.value})}),o.type==="button"&&(0,ot.jsxs)("div",{className:"af-grid af-gap-2 sm:af-grid-cols-2",children:[(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",(0,ot.jsx)(oe,{ref:f,"aria-label":"Button label",value:o.label,maxLength:80,onChange:v=>m({label:v.target.value})})]}),(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Opens",(0,ot.jsx)(oe,{"aria-label":"Button link",type:"url",value:o.url,onChange:v=>m({url:v.target.value})})]})]}),o.type==="image"&&(0,ot.jsxs)("div",{className:"af-space-y-2",children:[n?(0,ot.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[o.url&&(0,ot.jsx)("img",{src:o.url,alt:"",className:"af-h-12 af-w-12 af-rounded af-object-cover"}),(0,ot.jsx)(y,{ref:f,type:"button",variant:"outline",size:"sm",disabled:b,onClick:async()=>{g(!0);try{let v=await n();v&&c(x=>({...x,url:v.url,alt:v.alt??(x.type==="image"?x.alt:"")}))}finally{g(!1)}},children:"Choose from your site's images\u2026"})]}):(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Image address (https://\u2026)",(0,ot.jsx)(oe,{ref:f,"aria-label":"Image URL",type:"url",value:o.url,onChange:v=>m({url:v.target.value})})]}),(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Describe the image (for people who can't see it)",(0,ot.jsx)(oe,{"aria-label":"Image description",value:o.alt??"",maxLength:200,onChange:v=>m({alt:v.target.value})})]})]}),o.type==="cart"&&(0,ot.jsxs)("div",{className:"af-space-y-2",children:[(0,ot.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Each shopper sees their own cart here. There's nothing to write but the button."}),(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",(0,ot.jsx)(oe,{ref:f,"aria-label":"Cart button label",value:o.label,maxLength:80,onChange:v=>m({label:v.target.value})})]})]}),s&&(0,ot.jsx)(Ee,{tone:"error",children:s}),(0,ot.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,ot.jsx)("span",{className:"af-grow af-text-xs af-text-muted-foreground",children:Bf[o.type]}),!t&&(0,ot.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:i,children:"Remove"}),(0,ot.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:l,children:"Cancel"}),(0,ot.jsx)(y,{type:"submit",size:"sm",disabled:a||!ad(o),children:"Done"})]})]})})}var rd=ce(require("react"),1),id=require("lucide-react");var _e=require("react/jsx-runtime"),Mn="standard",Hi={create:"Create an email template that ",copyStandard:"Create an email template based on Standard that ",update:e=>`Update the "${e}" template to be `};function jo({status:e}){return e==="draft"?(0,_e.jsx)(ie,{variant:"warning",children:"Draft"}):e==="published"?(0,_e.jsx)(ie,{variant:"success",children:"Published"}):(0,_e.jsx)(ie,{variant:"secondary",children:e==="archived"?"Archived":"Built in"})}function od(e,t){let{api:a}=W(),{siteId:s,refreshKey:n,settings:r}=it(),i=JSON.stringify([r?.business_name,r?.postal_address,r?.brand]);return Zt(()=>a.previewEmailTemplate(s,e),`${s}|${e}|${t}|${n}|${i}`,`${s}|${e}|${t}`)}function zi({templateId:e,version:t,className:a,frame:s}){let n=od(e,t);return(0,_e.jsx)("div",{"aria-hidden":!0,className:`af-pointer-events-none af-overflow-hidden af-bg-white ${a}`,children:n.data&&(0,_e.jsx)("iframe",{title:"",tabIndex:-1,sandbox:"",srcDoc:n.data.html,style:{width:s.width,height:s.height,border:0,transform:`scale(${s.scale})`,transformOrigin:"top left"}})})}function ld({template:e,onBack:t,onOpenTemplate:a,onOpenDraft:s,onAskAssistant:n,reload:r,refreshKey:i}){let l=od(e?.id??Mn,e?.updated_at??"builtin");return(0,_e.jsxs)("div",{className:"af-space-y-4",children:[(0,_e.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,_e.jsx)(id.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All templates"]}),(0,_e.jsxs)("div",{className:"af-grid af-gap-4 md:af-grid-cols-[minmax(0,1fr)_280px]",children:[(0,_e.jsxs)("div",{children:[l.data?(0,_e.jsx)("iframe",{title:"Template preview",sandbox:"",srcDoc:l.data.html,className:"af-h-[520px] af-w-full af-rounded-md af-border af-bg-white"}):l.error?(0,_e.jsxs)(Ee,{tone:"warning",children:[$i(l.error)==="postal_address_missing"?"Add your business postal address to preview your emails.":"Couldn't load this preview.",(0,_e.jsx)(er,{reason:$i(l.error)})]}):(0,_e.jsx)(ae,{className:"af-h-[520px] af-w-full"}),(0,_e.jsx)("p",{className:"af-mt-2 af-text-center af-text-xs af-text-muted-foreground",children:"Shown with a sample email"})]}),(0,_e.jsxs)("div",{className:"af-space-y-3",children:[(0,_e.jsx)(Ff,{template:e,previewShown:l.data!==null,onOpenTemplate:a,onAskAssistant:n,reload:r}),(0,_e.jsx)(Mf,{templateId:e?.id??null,onOpenDraft:s,refreshKey:i})]})]})]})}function Ff({template:e,previewShown:t,onOpenTemplate:a,onAskAssistant:s,reload:n}){let{canWrite:r}=it(),i=Ot(),[l,u]=rd.useState(null),d=e?.name??"Standard",o=async(g,m)=>{let p=await i.run(g,m);u(null),p.ok&&g==="deleteEmailTemplate"&&a(null),p.ok||(Aa(p.error,"template_changed")?i.setError("The editor changed this template since you opened it. Check the latest version, then publish again."):Aa(p.error,"template_in_use")?i.setError("Emails use this template now."):Aa(p.error,"template_not_draft")&&i.setError("This template is already published.")),n()},c=async g=>{let m=await i.run("copyEmailTemplate",{templateId:g.id});m.ok&&(a(m.result.id),n())},b=null;if(!r)b=null;else if(l&&e){let[g,m,p]=l==="publish"?["Published templates can't be changed.","Publish",()=>o("publishEmailTemplate",{templateId:e.id,updated_at:e.updated_at})]:l==="delete"?["Delete this template?","Delete",()=>o("deleteEmailTemplate",{templateId:e.id})]:["Archive this template?","Archive",()=>o("archiveEmailTemplate",{templateId:e.id})];b=(0,_e.jsxs)(_e.Fragment,{children:[(0,_e.jsx)("p",{className:"af-text-sm",children:g}),(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>u(null),children:"Cancel"}),(0,_e.jsx)(y,{type:"button",size:"sm",variant:l==="delete"?"destructive":"default",className:"af-ml-auto",disabled:i.busy||l==="publish"&&!t,onClick:()=>void p(),children:m})]})]})}else if(!e)b=s&&(0,_e.jsx)(y,{type:"button",size:"sm",onClick:()=>s(Hi.copyStandard),children:"Copy to edit"});else if(e.status==="draft")b=(0,_e.jsxs)(_e.Fragment,{children:[s&&(0,_e.jsx)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>s(Hi.update(e.name)),children:"\u2728 Change this template with the editor"}),(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[e.can_delete&&(0,_e.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:i.busy,onClick:()=>u("delete"),children:"Delete"}),(0,_e.jsx)(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:i.busy||!t,onClick:()=>u("publish"),children:"Publish\u2026"})]})]});else{let g=e.status==="archived";b=(0,_e.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_delete&&!g&&(0,_e.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:i.busy,onClick:()=>u("delete"),children:"Delete"}),e.can_archive&&!g&&(0,_e.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:i.busy,onClick:()=>u("archive"),children:"Archive"}),g&&(0,_e.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:i.busy,onClick:()=>void o("unarchiveEmailTemplate",{templateId:e.id}),children:"Unarchive"}),(0,_e.jsx)(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:i.busy,onClick:()=>void c(e),children:"Copy to edit"})]})}return(0,_e.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_e.jsx)("h3",{"data-testid":"template-title",className:"af-grow af-truncate af-text-sm af-font-semibold",children:d}),(0,_e.jsx)(jo,{status:e?.status??"builtin"})]}),i.error&&(0,_e.jsx)(Ee,{tone:"error",children:i.error}),b]})}function Mf({templateId:e,onOpenDraft:t,refreshKey:a}){let{siteId:s}=it(),n=Is({siteId:s,kind:"broadcast",refreshKey:a}),r=Es({siteId:s,refreshKey:a}),i=n.data?.filter(c=>(c.template?.id??null)===e)??null,l=r.data??[],u=Ui(n.data??[],l),d=new Set(l.flatMap(c=>c.draft_id&&c.status==="scheduled"?[c.draft_id]:[])),o=c=>u.has(c)?"Sent":d.has(c)?"Scheduled":"Draft";return(0,_e.jsxs)("div",{"data-testid":"template-usage",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,_e.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Emails using it"}),n.error||r.error?(0,_e.jsx)(Et,{message:"Couldn't load the emails.",onRetry:()=>{n.refetch(),r.refetch()}}):!i||!r.data?(0,_e.jsx)(ae,{className:"af-h-10 af-w-full"}):i.length===0?(0,_e.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No emails use it."}):(0,_e.jsx)("ul",{className:"af-space-y-1",children:i.map(c=>{let b=o(c.id),g=(0,_e.jsxs)(_e.Fragment,{children:[(0,_e.jsx)("span",{className:"af-block af-truncate af-text-sm",children:c.subject||"(no subject)"}),(0,_e.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["Broadcast \xB7 ",b]})]});return(0,_e.jsx)("li",{children:b==="Sent"?(0,_e.jsx)("div",{className:"af-rounded-md af-px-2 af-py-1",children:g}):(0,_e.jsx)("button",{type:"button",onClick:()=>t(c.id),className:"af-w-full af-rounded-md af-px-2 af-py-1 af-text-left hover:af-bg-muted",children:g})},c.id)})})]})}var Xa=require("react/jsx-runtime");function cd({draft:e,disabled:t,onChanged:a}){let{api:s}=W(),{siteId:n,refreshKey:r}=it(),i=Zt(()=>s.getEmailTemplates(n),`${n}|${r}`,n),l=Ot(),u=e.template?.id??Mn,d=u===Mn,o=(i.data??[]).filter(p=>p.status==="published"),c=o.find(p=>p.id===u),b=d?"Standard":e.template?.name??c?.name??"",g=d?"builtin":c?.updated_at??"current",m=async p=>{if(p===u)return;let f=await l.run("setDraftTemplate",{draftId:e.id,template_id:p===Mn?null:p,expected_version:e.version});f.ok?await a():Aa(f.error,"template_missing_cart")?l.setError("This email shows the shopper's cart, and that template has no cart section. Pick another template, or keep this one."):Aa(f.error,"version_conflict")?(l.setError("This email changed meanwhile. We've loaded the latest version; switch again if you still want to."),await a()):Aa(f.error,"template_not_published")&&(l.setError("That template isn't published any more."),await i.refetch())};return(0,Xa.jsxs)("div",{"data-testid":"template-card",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,Xa.jsx)("div",{className:"af-text-sm af-font-semibold",children:"Template"}),(0,Xa.jsxs)("div",{className:"af-flex af-items-center af-gap-3",children:[(0,Xa.jsx)(zi,{templateId:u,version:g,className:"af-h-20 af-w-[72px] af-shrink-0 af-rounded af-border",frame:{width:600,height:670,scale:.12}}),(0,Xa.jsx)("div",{className:"af-min-w-0 af-grow af-truncate af-text-sm af-font-medium",children:b})]}),(0,Xa.jsxs)("label",{className:"af-grid af-gap-1 af-text-xs af-text-muted-foreground",children:["Switch to",(0,Xa.jsxs)("select",{"aria-label":"Switch to",value:u,disabled:t||l.busy,onChange:p=>void m(p.target.value),className:"af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-text-sm af-text-foreground",children:[(0,Xa.jsx)("option",{value:Mn,children:"Standard"}),o.map(p=>(0,Xa.jsx)("option",{value:p.id,children:p.name},p.id)),!d&&!c&&(0,Xa.jsx)("option",{value:u,disabled:!0,children:b})]})]}),l.error&&(0,Xa.jsx)(Ee,{tone:"error",children:l.error})]})}var Se=require("react/jsx-runtime"),Uf={heading:"Click to edit heading",text:"Click to edit text",button:"Click to edit button",image:"Click to replace image",cart:"The shopper's cart"},$f=320,Vf=600,Hf=e=>({top:Math.max(0,e.y-24),left:e.x});function zf(e,t){let a=Object.keys(e);return a.length!==Object.keys(t).length?!1:a.every(s=>{let n=e[Number(s)],r=t[Number(s)];return r!==void 0&&n.x===r.x&&n.y===r.y&&n.width===r.width&&n.height===r.height})}function ud({draftId:e,renderCommit:t,onSaved:a,scheduled:s,onAskAssistant:n,onPickImage:r}){let{api:i}=W(),{siteId:l,canWrite:u,refreshKey:d,openSettings:o}=it(),c=u&&!s,b=Ke.useRef(c);b.current=c;let[g,m]=Ke.useState(null),[p,f]=Ke.useState(null),[v,x]=Ke.useState(null),[k,T]=Ke.useState(null),[h,R]=Ke.useState(null),[P,D]=Ke.useState(null),[N,E]=Ke.useState(null),[A,C]=Ke.useState(null),[K,Q]=Ke.useState(null),[H,de]=Ke.useState({}),[me,be]=Ke.useState(jr.initial),[V,J]=Ke.useState(!1),F=Ot(),ge=Ot(),pe=Ke.useRef(null),He=Ke.useRef(null),Pe=Ke.useRef(0),Ue=Ke.useRef(!1),ze=Ke.useRef(!1),fe=Ke.useCallback(ke=>{Ue.current=ke!==null,D(ke)},[]);Xc(P!==null);let lt=Ke.useRef(g);lt.current=g;let L=Ke.useRef(0),M=Ke.useCallback(async(ke={})=>{let ut=++L.current,tt=b.current,St=()=>tt?i.previewEmailDraft(l,e,{editable:!0}):i.previewEmailDraft(l,e),[z,Xe]=await Promise.allSettled([i.getEmailDraft(l,e),St()]),ra=Xe,Ms=()=>z.status==="fulfilled"&&ra.status==="fulfilled"&&ra.value.version!==z.value.version;if(Ms()&&ut===L.current&&([ra]=await Promise.allSettled([St()])),ut===L.current){if(ke.background&&Ue.current){ze.current=!0;return}if(T(null),x(null),z.status==="rejected"){T(tr(z.reason));return}m(z.value),ra.status==="fulfilled"?f({...ra.value,editable:tt&&!Ms()}):(f(null),x(Aa(ra.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:tr(ra.reason),code:null}))}},[i,l,e]);Ke.useEffect(()=>{m(null),f(null),M()},[M]);let U=Ke.useRef(c);Ke.useEffect(()=>{U.current!==c&&(U.current=c,c||fe(null),M())},[c,M,fe]);let Te=Ke.useRef(d);Ke.useEffect(()=>{if(d!==Te.current){if(Te.current=d,Ue.current){ze.current=!0;return}M({background:!0})}},[d,M]);let ne=()=>{fe(null),F.setError(null),ze.current&&(ze.current=!1,M())},Re=async(ke,ut,tt)=>{let St=await F.run("updateDraft",{draftId:e,expected_version:ke.version,...ut});St.ok?(E(null),He.current=null,ze.current=!1,fe(null),await M(),a?.()):Aa(St.error,"version_conflict")&&(F.setError(null),E(tt),ze.current=!1,fe(null),await M())},je=Ke.useRef({frame:null,html:null,count:0}),[wt,et]=Ke.useState(null),Dt=(ke,ut)=>{let tt=je.current;tt.frame!==ke.currentTarget||tt.html!==ut?je.current={frame:ke.currentTarget,html:ut,count:1}:++tt.count>1&&et(ut)},Ne=p!==null&&wt===p.html,Le=c&&p?.editable===!0&&!Ne;if(Ke.useEffect(()=>{if(!Le)return;let ke=ut=>{let tt=lt.current;if(!tt)return;let St=ed(ut,pe.current?.contentWindow,tt.blocks.length);if(St)switch(St.type){case"hover":Q(St.section===null?null:{section:St.section,rect:St.rect});return;case"focus":He.current=St.section;return;case"open":if(He.current=St.section,Ue.current)return;C(null),J(!1),fe({kind:"section",base:tt,index:St.section,block:tt.blocks[St.section],isNew:!1,anchor:St.rect,key:++Pe.current});return;case"layout":be(td(St.height));{let z=Object.fromEntries(St.sections.map(Xe=>[Xe.section,Xe.rect]));de(Xe=>zf(Xe,z)?Xe:z)}return;case"template":Ue.current||C(St.region);return}};return window.addEventListener("message",ke),()=>window.removeEventListener("message",ke)},[Le,fe]),k)return(0,Se.jsxs)(Ee,{tone:"error",children:["Couldn't load this email. ",k]});if(!g)return(0,Se.jsx)(ae,{className:"af-h-40 af-w-full"});let ct={width:pe.current?.clientWidth||Vf,height:Le?me:jr.initial},at=P?.kind==="section"?P:null,qt=(()=>{if(!at)return null;if(!at.isNew)return H[at.index]??at.anchor;let ke=H[at.index-1];return ke?{x:ke.x,y:ke.y+ke.height,width:ke.width,height:0}:null})(),Ut=qt?Ho(qt,ct):null,sa=g.kind==="recovery",dt=g.template?.name??"Standard",ht=at&&(0,Se.jsx)(sd,{block:at.block,isNew:at.isNew,busy:F.busy,error:F.error,onPickImage:r,onCancel:ne,onRemove:()=>{let{base:ke}=at;Re(ke,{subject:ke.subject,preheader:ke.preheader,blocks:ke.blocks.filter((ut,tt)=>tt!==at.index)},qo(at.block))},onDone:ke=>{let{base:ut}=at,tt=at.isNew?[...ut.blocks.slice(0,at.index),ke,...ut.blocks.slice(at.index)]:ut.blocks.map((St,z)=>z===at.index?ke:St);Re(ut,{subject:ut.subject,preheader:ut.preheader,blocks:tt},qo(ke))},className:Ut?"af-absolute af-z-10 af-rounded-md af-border af-bg-background af-p-3 af-shadow-lg":"af-rounded-md af-border af-bg-background af-p-3 af-shadow-sm",style:Ut?{top:Ut.y,left:Ut.x,width:Math.min(Math.max(Ut.width,$f),ct.width)}:void 0},at.key);return(0,Se.jsxs)("div",{className:"af-grid af-gap-4 lg:af-grid-cols-[minmax(0,1fr)_300px]",children:[(0,Se.jsxs)("div",{className:"af-min-w-0 af-space-y-3",children:[P?.kind==="subject"?(0,Se.jsx)(qf,{draft:P.base,busy:F.busy,error:F.error,onCancel:ne,onDone:ke=>void Re(P.base,{...ke,blocks:P.base.blocks},[ke.subject,ke.preheader??""].join(`
8
+ `))}):Le?(0,Se.jsx)("button",{type:"button","data-testid":"subject-line",onClick:()=>{Ue.current||(C(null),fe({kind:"subject",base:g}))},className:"af-block af-w-full af-rounded-md af-border af-border-dashed af-px-3 af-py-2 af-text-left hover:af-border-primary",children:(0,Se.jsx)(dd,{draft:g})}):(0,Se.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:(0,Se.jsx)(dd,{draft:g})}),s&&(0,Se.jsxs)(Ee,{tone:"info",children:[(0,Se.jsxs)("p",{children:["This email is scheduled",s.sendsAt?` to send ${new Date(s.sendsAt).toLocaleString()}`:"",", so it can't change. Unschedule it to edit, then schedule it again."]}),(0,Se.jsx)(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:!u||s.busy,onClick:()=>void s.onUnschedule(),children:"Unschedule to edit"}),s.error&&(0,Se.jsx)("p",{className:"af-mt-1 af-text-destructive",children:s.error})]}),N!==null&&(0,Se.jsxs)(Ee,{tone:"warning",children:[(0,Se.jsx)("p",{children:"This email changed while you were editing, so your change wasn't saved. Here is the latest version; your text is below to apply again."}),(0,Se.jsx)("textarea",{readOnly:!0,"aria-label":"Your unsaved text",value:N,className:"af-mt-2 af-min-h-[72px] af-w-full af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-font-mono af-text-xs af-text-foreground"}),(0,Se.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>E(null),children:"Dismiss"})]}),A&&(0,Se.jsx)("div",{"data-testid":"template-hint",children:(0,Se.jsx)(Ee,{children:A==="header"?(0,Se.jsxs)(Se.Fragment,{children:['The header is part of the "',dt,'" template. Switch templates on the right.']}):(0,Se.jsxs)(Se.Fragment,{children:["Every email ends with this footer. Your business name and address come from"," ",(0,Se.jsx)(Ts,{onClick:()=>o("sender"),children:"Settings"}),"."]})})}),Ne&&c&&(0,Se.jsx)(Ee,{tone:"warning",children:"This template tried to open another page in the preview, so the preview can't be edited here."}),p?(0,Se.jsxs)("div",{className:"af-relative",children:[(0,Se.jsx)("iframe",{ref:pe,title:"Email preview",sandbox:Le?"allow-scripts":"",srcDoc:p.html,onLoad:Le?ke=>Dt(ke,p.html):void 0,style:{height:ct.height},className:"af-block af-w-full af-rounded-md af-border af-bg-white"},Le?"editable":"read-only"),Le&&K&&!P&&(0,Se.jsx)("div",{"aria-hidden":!0,className:"af-pointer-events-none af-absolute af-rounded af-bg-primary af-px-2 af-py-0.5 af-text-xs af-text-primary-foreground",style:Hf(Ho(K.rect,ct)),children:Uf[g.blocks[K.section]?.type??"text"]}),Ut&&ht]}):v?(0,Se.jsxs)(Ee,{tone:"warning",children:[v.text,(0,Se.jsx)(er,{reason:v.code})]}):(0,Se.jsx)(ae,{className:"af-h-40 af-w-full"}),!Ut&&ht,Le&&!P&&(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>J(ke=>!ke),"aria-expanded":V,children:"+ Add a section"}),V&&(0,Se.jsx)("div",{"data-testid":"add-section-menu",className:"af-flex af-flex-wrap af-gap-2",children:["text","heading","button","image",...sa?["cart"]:[]].map(ke=>(0,Se.jsx)(y,{type:"button",size:"sm",variant:"secondary",onClick:()=>{let ut=He.current!==null?He.current+1:g.blocks.length;J(!1),C(null),fe({kind:"section",base:g,index:ut,block:nd(ke),isNew:!0,anchor:null,key:++Pe.current})},children:zo[ke]},ke))})]}),(0,Se.jsx)("p",{className:"af-text-center af-text-xs af-text-muted-foreground",children:"Header and footer come from your template."})]}),(0,Se.jsxs)("div",{className:"af-space-y-3",children:[(0,Se.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[(0,Se.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!u||ge.busy,onClick:async()=>{R(null);let ke=await ge.run("testSendDraft",{draftId:e});ke.ok&&R(ke.result?.sent_to??"your email")},children:"Send a test to me"}),h&&(0,Se.jsxs)(Ee,{tone:"success",children:["Test sent to ",h,"."]}),ge.error&&(0,Se.jsx)(Ee,{tone:"error",children:ge.error}),p&&!s&&t?.({draft:g,preview:p,reload:()=>M()})]}),(0,Se.jsx)(cd,{draft:g,disabled:!c||P!==null,onChanged:async()=>{await M(),a?.()}}),n&&u&&(0,Se.jsx)(y,{type:"button",variant:"outline",className:"af-w-full",onClick:()=>n(`Update the "${g.subject}" email to `),children:"\u2728 Change this email with the editor"})]})]})}function dd({draft:e}){return(0,Se.jsxs)(Se.Fragment,{children:[(0,Se.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Subject "}),(0,Se.jsx)("span",{className:"af-font-medium",children:e.subject||"(no subject)"}),e.preheader&&(0,Se.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:[" \u2014 ",e.preheader]})]})}function qf({draft:e,busy:t,error:a,onDone:s,onCancel:n}){let[r,i]=Ke.useState(e.subject),[l,u]=Ke.useState(e.preheader??"");return(0,Se.jsxs)("form",{className:"af-space-y-2 af-rounded-md af-border af-p-3",onSubmit:d=>{d.preventDefault(),s({subject:r,preheader:l.trim()||null})},children:[(0,Se.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Subject",(0,Se.jsx)(oe,{"aria-label":"Subject",value:r,maxLength:200,autoFocus:!0,onChange:d=>i(d.target.value)})]}),(0,Se.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Preview text (the grey line after the subject in the inbox)",(0,Se.jsx)(oe,{"aria-label":"Preview text",value:l,maxLength:200,onChange:d=>u(d.target.value)})]}),a&&(0,Se.jsx)(Ee,{tone:"error",children:a}),(0,Se.jsxs)("div",{className:"af-flex af-justify-end af-gap-2",children:[(0,Se.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:t,onClick:n,children:"Cancel"}),(0,Se.jsx)(y,{type:"submit",size:"sm",disabled:t,children:"Done"})]})]})}var ue=require("react/jsx-runtime"),jf={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function pd({openDraftId:e,onOpenDraft:t,onAskAssistant:a,onPickImage:s}){let{siteId:n,canWrite:r,refreshKey:i}=it(),[l,u]=_t.useState(0),d=l+i,o=Is({siteId:n,kind:"broadcast",refreshKey:d}),c=Es({siteId:n,refreshKey:d}),b=Ot(),g=Ot(),m=Ui(o.data??[],c.data??[]),p=o.data?.filter(f=>!m.has(f.id))??null;if(e){let f=c.data?.find(v=>v.draft_id===e&&v.status==="scheduled");return(0,ue.jsxs)("div",{className:"af-space-y-4",children:[(0,ue.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>t(null),children:[(0,ue.jsx)(md.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),!c.data&&!c.error||!o.data&&!o.error?(0,ue.jsx)(ae,{className:"af-h-40 af-w-full"}):m.has(e)?(0,ue.jsx)(Ee,{children:"This email has been sent, so it can't change. Duplicate it from the list to send it again."}):(0,ue.jsx)(ud,{draftId:e,onSaved:()=>u(v=>v+1),renderCommit:v=>(0,ue.jsx)(Zf,{...v,onCommitted:()=>u(x=>x+1)}),scheduled:f?{sendsAt:f.scheduled_at,busy:b.busy,error:b.error,onUnschedule:async()=>{(await b.run("cancelBroadcast",{sendId:f.id})).ok&&u(x=>x+1)}}:void 0,onAskAssistant:a,onPickImage:s})]})}return(0,ue.jsxs)("div",{children:[(0,ue.jsx)(Ja,{children:"Drafts"}),o.error?(0,ue.jsx)(Et,{message:"Couldn't load drafts.",onRetry:()=>void o.refetch()}):p?p.length===0?(0,ue.jsx)(va,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):(0,ue.jsx)("ul",{"data-testid":"drafts",className:"af-divide-y af-rounded-md af-border",children:p.map(f=>(0,ue.jsxs)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[(0,ue.jsx)("span",{className:"af-truncate af-text-sm",children:f.subject||"(no subject)"}),(0,ue.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(f.id),children:"Review"})]},f.id))}):(0,ue.jsx)(ae,{className:"af-h-10 af-w-full"}),(0,ue.jsx)(Ja,{children:"Sent and scheduled"}),b.error&&(0,ue.jsx)(Ee,{tone:"error",children:b.error}),g.error&&(0,ue.jsx)(Ee,{tone:"error",children:g.error}),c.error?(0,ue.jsx)(Et,{message:"Couldn't load broadcasts.",onRetry:()=>void c.refetch()}):c.data?c.data.length===0?(0,ue.jsx)(va,{children:"Nothing sent yet."}):(0,ue.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:c.data.map(f=>(0,ue.jsx)(Wf,{broadcast:f,canCancel:r&&(f.status==="scheduled"||f.status==="unscheduled"||f.status==="sending"),busy:b.busy||g.busy,onCancel:async()=>{(await b.run("cancelBroadcast",{sendId:f.id})).ok&&u(x=>x+1)},onDuplicate:r&&f.draft_id&&Uo(f)?async()=>{let v=await g.run("duplicateDraft",{draftId:f.draft_id});v.ok&&(u(x=>x+1),t(v.result.id))}:void 0},f.id))}):(0,ue.jsx)(ae,{className:"af-h-10 af-w-full"})]})}function Wf({broadcast:e,canCancel:t,busy:a,onCancel:s,onDuplicate:n}){return(0,ue.jsxs)("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[(0,ue.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,ue.jsx)("span",{className:"af-truncate af-text-sm af-font-medium",children:e.subject}),(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ue.jsx)(ie,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:jf[e.status]}),t&&(0,ue.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:s,children:"Cancel"}),n&&(0,ue.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:n,children:"Duplicate"})]})]}),(0,ue.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",qe(e.recipients.planned)," recipients \xB7 ",qe(e.stats.delivered)," delivered \xB7 ",qe(e.stats.opened)," opened \xB7"," ",qe(e.stats.clicked)," clicked \xB7 ",qe(e.stats.bounced)," bounced \xB7 ",qe(e.stats.complained)," complaints \xB7"," ",qe(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&(0,ue.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:ks(e.status_reason)})]})}var gd=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function fd(e){let t=e.targeting??null,a=e.proposed_send_at?new Date(e.proposed_send_at):null,s=a!==null&&a.getTime()>Date.now();return{key:gd(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:s?Gf(a):"",suggested:t!==null||a!==null,timePassed:a!==null&&!s}}function Gf(e){let t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}var Kf=(e,t)=>e.match===t.match&&e.scheduleAt===t.scheduleAt&&e.tagIds.length===t.tagIds.length&&e.tagIds.every(a=>t.tagIds.includes(a));function Zf({draft:e,preview:t,reload:a,onCommitted:s}){let{api:n}=W(),{siteId:r,canWrite:i,settings:l,refreshKey:u}=it(),[d,o]=_t.useState(null),[c,b]=_t.useState(!1),[g,m]=_t.useState(null),[p,f]=_t.useState(()=>fd(e)),[v,x]=_t.useState(p.tagIds),[k,T]=_t.useState(p.match),[h,R]=_t.useState(p.scheduleAt),[P,D]=_t.useState(0),N=!Kf({tagIds:v,match:k,scheduleAt:h},p),E=gd(e);_t.useEffect(()=>{if(E===p.key||e.id===p.draftId&&N)return;let ne=fd(e);f(ne),x(ne.tagIds),T(ne.match),R(ne.scheduleAt),D(0)},[E,e,p,N]);let A=_t.useMemo(()=>d?new Set(d.map(ne=>ne.id)):null,[d]),C=A!==null&&v.every(ne=>A.has(ne));_t.useEffect(()=>{if(!A||v.every(Re=>A.has(Re)))return;let ne=Re=>Re.filter(je=>A.has(je));D(Re=>Re+v.length-ne(v).length),x(ne(v)),f(Re=>({...Re,tagIds:ne(Re.tagIds)}))},[A,v]);let[K,Q]=_t.useState(null),[H,de]=_t.useState(null),[me,be]=_t.useState(null),V=Ot();_t.useEffect(()=>{n.getMarketingTags(r).then(ne=>{o(ne),b(!1)},()=>{o(null),b(!0)}),n.getMarketingContactStats(r).then(m,()=>m(null))},[n,r,u]);let J=h?new Date(h).toISOString():null,F=JSON.stringify([v,k,J]),ge=K?.plan??null,pe=K!==null&&K.key===F,He=_t.useRef(0),Pe=_t.useCallback(async()=>{let ne=++He.current;de(null);try{let Re=await n.estimateBroadcast(r,{targeting:{tag_ids:v,match:k},scheduled_at:J});ne===He.current&&Q({key:F,plan:Re})}catch(Re){if(ne!==He.current)return;Q(null),de(tr(Re))}},[n,r,v,k,J,F,u]),Ue=_t.useRef(!1);_t.useEffect(()=>{if(!C&&v.length>0)return;if(!Ue.current){Ue.current=!0,Pe();return}let ne=setTimeout(()=>void Pe(),300);return()=>clearTimeout(ne)},[Pe,C,v.length]);let ze=l&&!l.readiness.can_send?ks(l.readiness.reason):null,fe=ge!==null&&!ge.fits,lt=g?Math.max(0,g.by_status.subscribed-g.mailable):null,L=g&&ge&&lt!==null?Math.max(0,g.total-ge.recipients-lt):null,M=!i||V.busy||!ge||!pe||fe||ge.recipients===0||ze!==null||c&&v.length>0,U=async()=>{be(null);let ne=await V.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:v,match:k},scheduled_at:J});if(ne.ok){be({tone:"success",text:J?"Scheduled.":"Sending now."}),s();return}Aa(ne.error,"version_conflict")?(V.setError(null),await a(),be({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):Aa(ne.error,"over_allowance")&&await Pe()},Te=ne=>x(Re=>Re.includes(ne)?Re.filter(je=>je!==ne):[...Re,ne]);return(0,ue.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[p.suggested&&!N&&(0,ue.jsx)(Ee,{children:"Suggested by your assistant \u2014 review before sending."}),(0,ue.jsx)(Ja,{children:"Who gets it"}),c&&(0,ue.jsx)(Ee,{tone:"warning",children:v.length>0?"Couldn't load your tags, so this targeted send can't go out yet. Refresh to try again.":"Couldn't load your tags. Refresh to target by tag."}),P>0&&(0,ue.jsx)(Ee,{tone:"warning",children:P===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),d&&d.length>0?(0,ue.jsxs)("div",{className:"af-space-y-2",children:[(0,ue.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:d.map(ne=>(0,ue.jsxs)("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[(0,ue.jsx)("input",{type:"checkbox",checked:v.includes(ne.id),onChange:()=>Te(ne.id)}),ne.label]},ne.id))}),v.length>1&&(0,ue.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",(0,ue.jsxs)("select",{"aria-label":"Tag match",value:k,onChange:ne=>T(ne.target.value),className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,ue.jsx)("option",{value:"any",children:"any of these tags"}),(0,ue.jsx)("option",{value:"all",children:"all of these tags"})]})]}),v.length===0&&(0,ue.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):(0,ue.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Everyone who can be emailed."}),(0,ue.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,ue.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),(0,ue.jsx)(oe,{"aria-label":"Schedule time",type:"datetime-local",value:h,onChange:ne=>R(ne.target.value)})]}),p.timePassed&&!h&&(0,ue.jsx)(Ee,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),H?(0,ue.jsxs)(Ee,{tone:"error",children:["Couldn't work out the audience. ",H]}):ge?(0,ue.jsxs)("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[(0,ue.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,ue.jsx)(Wo,{label:"Will receive it",value:ge.recipients}),(0,ue.jsx)(Wo,{label:"Suppressed (bounced or complained)",value:lt}),(0,ue.jsx)(Wo,{label:"Not included",value:L})]}),(0,ue.jsxs)("p",{className:"af-text-muted-foreground",children:[qe(ge.allowance.remaining)," of ",qe(ge.allowance.monthly)," emails left this month."]}),ge.sample_size!==null&&(0,ue.jsxs)(Ee,{children:["We'll send to ",qe(ge.sample_size)," people first and check for bounces before sending the rest."]}),ge.ramp_days.length>1&&(0,ue.jsxs)(Ee,{children:["Your domain is new, so this goes out over ",ge.ramp_days.length," days:"," ",ge.ramp_days.map(ne=>`${qe(ne.recipients)} on ${ne.date}`).join(", "),"."]})]}):(0,ue.jsx)(ae,{className:"af-h-12 af-w-full"}),fe&&ge&&(0,ue.jsxs)(Ee,{tone:"warning",children:["This send needs ",qe(ge.recipients)," emails, but only ",qe(ge.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),ze&&(0,ue.jsxs)(Ee,{tone:"warning",children:[ze,(0,ue.jsx)(er,{reason:l?.readiness.reason})]}),me&&(0,ue.jsx)(Ee,{tone:me.tone,children:me.text}),V.error&&(0,ue.jsx)(Ee,{tone:"error",children:V.error}),(0,ue.jsx)(y,{type:"button",disabled:M,onClick:()=>void U(),children:J?"Schedule":"Send now"})]})}function Wo({label:e,value:t}){return(0,ue.jsxs)("div",{className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,ue.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,ue.jsx)("div",{className:"af-font-semibold",children:t===null?"\u2014":qe(t)})]})}var Na=ce(require("react"),1);var Ls=require("lucide-react");var As=ce(require("react"),1),Yt=require("lucide-react");var I=require("react/jsx-runtime"),Yf=[{title:"Own your audience",body:"Your list is yours. Reaching it doesn't depend on a social feed or an ad budget."},{title:"Bring people back",body:"Most visitors leave and never return. Email gets them back when you have news, a sale or something new."},{title:"Look like you",body:"Emails come from your own domain, with your logo and colors."}],Jf="hello";function Ko(e){return`${Jf}@${e}`}function vd({onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,onTurnOn:s,siteDomain:n,businessName:r}){let{api:i}=W(),{siteId:l,settings:u,canWrite:d,refreshKey:o,refetchSettings:c}=it(),b=Zt(()=>i.getMarketingContactStats(l),`${l}|${o}`,l),[g,m]=As.useState(!1),[p,f]=As.useState(null);if(!u)return null;let v=b.data?.by_status.subscribed??0,x={siteDomain:n,businessName:r};return Xf(u)?(0,I.jsx)(Zo,{settings:u,site:x,waiting:v,children:d?s&&(0,I.jsxs)("div",{className:"af-space-y-2",children:[(0,I.jsxs)(y,{disabled:g,onClick:async()=>{m(!0),f(null);try{await s(),await c()}catch(k){f(k instanceof Error?k.message:"Couldn't turn on email. Try again.")}finally{m(!1)}},children:["Get started ",(0,I.jsx)(Yt.ArrowRight,{className:"af-ml-2 af-h-4 af-w-4","aria-hidden":!0})]}),p&&(0,I.jsx)(Ee,{tone:"error",children:p})]}):(0,I.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Only the site owner can set up email."})}):(0,I.jsx)(Qf,{settings:u,site:x,waiting:v,onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a})}function Xf(e){return e.readiness.reason==="sending_not_enabled"}function Zo({settings:e,site:t,waiting:a=0,children:s}){return(0,I.jsx)("div",{className:"af-mx-auto af-max-w-3xl af-px-2 af-py-8",children:(0,I.jsxs)("div",{className:"af-grid af-items-center af-gap-10 md:af-grid-cols-[1fr_18rem]",children:[(0,I.jsxs)("div",{children:[(0,I.jsxs)("div",{className:"af-mb-3 af-inline-flex af-items-center af-gap-1.5 af-rounded-full af-bg-muted af-px-2.5 af-py-1 af-text-xs af-font-medium",children:[(0,I.jsx)(Yt.Mail,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0})," Email marketing"]}),(0,I.jsx)("h3",{className:"af-text-2xl af-font-semibold af-tracking-tight",children:"Turn visitors into regulars"}),(0,I.jsx)("p",{className:"af-mt-2 af-text-muted-foreground",children:"Build an email list from your website and reach those people directly, whenever you have something worth telling them."}),(0,I.jsx)("ol",{className:"af-mt-6 af-space-y-3",children:Yf.map((n,r)=>(0,I.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,I.jsx)("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-border af-text-xs af-font-semibold",children:r+1}),(0,I.jsxs)("p",{className:"af-text-sm",children:[(0,I.jsxs)("span",{className:"af-font-medium",children:[n.title,"."]})," ",(0,I.jsx)("span",{className:"af-text-muted-foreground",children:n.body})]})]},n.title))}),a>0&&(0,I.jsxs)("p",{className:"af-mt-5 af-rounded-md af-bg-amber-50 af-px-3 af-py-2 af-text-sm af-text-amber-900",children:[(0,I.jsxs)("span",{className:"af-font-semibold",children:[qe(a)," ",a===1?"person has":"people have"]})," ","already signed up and ",a===1?"is":"are"," waiting for your first email."]}),(0,I.jsx)("div",{className:"af-mt-6",children:s})]}),(0,I.jsx)(qi,{settings:e,site:t,className:"af-rotate-1"})]})})}function bd({onUpgradePlan:e}){return(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-border-violet-200 af-bg-gradient-to-r af-from-violet-50 af-to-white af-p-4",children:[(0,I.jsx)(Yt.Lock,{className:"af-h-5 af-w-5 af-shrink-0 af-text-violet-700","aria-hidden":!0}),(0,I.jsxs)("div",{className:"af-flex-1",children:[(0,I.jsx)("div",{className:"af-text-sm af-font-semibold af-text-violet-900",children:"Email marketing is part of Pro"}),(0,I.jsx)("div",{className:"af-text-sm af-text-violet-900/80",children:"Collect subscribers and send newsletters from your own domain."})]}),e&&(0,I.jsx)(y,{size:"sm",onClick:e,children:"Upgrade to Pro"})]})}function Qf({settings:e,site:t,waiting:a,onStartDomainSetup:s,onConnectDomain:n,onAskAssistant:r}){let{refetchSettings:i,canWrite:l}=it(),[u,d]=As.useState(null),o=p=>d(f=>f===p?null:p),{siteDomain:c}=t,b=Wr(e),g=c===null&&!e.domain.sending_domain,m=!!e.postal_address;return(0,I.jsxs)("div",{className:"af-mx-auto af-max-w-4xl af-py-4",children:[(0,I.jsxs)("div",{className:"af-mb-6 af-flex af-items-start af-justify-between af-gap-6",children:[(0,I.jsxs)("div",{children:[(0,I.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Set up email"}),(0,I.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Newsletters to your subscribers, sent from ",c??"your own domain","."]})]}),a>0&&(0,I.jsxs)("div",{className:"af-text-right",children:[(0,I.jsx)("div",{className:"af-text-2xl af-font-semibold",children:qe(a)}),(0,I.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[a===1?"subscriber":"subscribers"," waiting"]})]})]}),!l&&(0,I.jsx)(Ee,{className:"af-mb-4",children:"Only the site owner can finish setup."}),(0,I.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_16rem]",children:[(0,I.jsxs)("div",{className:"af-space-y-4",children:[(0,I.jsxs)(Go,{title:c??"Your domain",sub:"One domain for your website and your email.",children:[c&&(0,I.jsx)(Rn,{icon:Yt.Globe,label:"Website",value:c,status:(0,I.jsx)(Nn,{tone:"green",children:"Live"})}),g?(0,I.jsx)(Rn,{icon:Yt.Mail,label:"Email sending",value:"Needs a custom domain",status:(0,I.jsx)(Nn,{tone:"gray",children:"Not available"}),action:n&&l?{label:"Connect domain",onClick:n}:void 0}):(0,I.jsxs)(Rn,{icon:Yt.Mail,label:"Email sending",value:e.domain.sending_domain??(c?`news.${c}`:"news.yourdomain.com"),status:Yo(e),action:!b&&l?{label:e.domain.sending_domain?"Details":"Set up",onClick:()=>o("sending")}:void 0,expanded:u==="sending",children:[!e.domain.sending_domain&&(0,I.jsx)("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:"Emails go out from a subdomain of your site's domain, so they reach inboxes and are clearly from you. If we manage your domain's DNS we add the records; otherwise you'll get a few to copy into your DNS provider."}),(0,I.jsx)(Jo,{settings:e,canWrite:l,onStartDomainSetup:s,onChanged:i})]})]}),(0,I.jsx)(Go,{title:"Sender",sub:"Who your emails are from. The mailing address is legally required in every email.",children:(0,I.jsx)(Rn,{icon:Yt.PenLine,label:m?e.business_name??"Sender":"Not set",value:e.postal_address??"Name, mailing address and reply-to",status:m?(0,I.jsx)(Nn,{tone:"green",children:"Done"}):(0,I.jsx)(Nn,{tone:"gray",children:"Needed"}),action:l?{label:m?"Edit":"Add",onClick:()=>o("sender")}:void 0,expanded:u==="sender",children:(0,I.jsx)(em,{settings:e,businessName:t.businessName,onSaved:async()=>{await i(),d(null)}})})}),(0,I.jsx)(Go,{title:"How people join your list",sub:"Only people who asked to hear from you get your emails.",children:(0,I.jsx)(sm,{onAskAssistant:l?r:void 0})})]}),(0,I.jsxs)("aside",{className:"af-space-y-3",children:[(0,I.jsx)("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails will look like"}),(0,I.jsx)(qi,{settings:e,site:t})]})]})]})}function Go({title:e,sub:t,children:a}){return(0,I.jsxs)("section",{className:"af-rounded-xl af-border af-bg-background",children:[(0,I.jsxs)("div",{className:"af-px-5 af-pb-3 af-pt-4",children:[(0,I.jsx)("h4",{className:"af-text-sm af-font-semibold",children:e}),(0,I.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:t})]}),(0,I.jsx)("div",{className:"af-space-y-2 af-px-3 af-pb-3",children:a})]})}function Rn({icon:e,marker:t,label:a,value:s,mono:n=!0,hint:r,status:i,action:l,expanded:u=!1,children:d}){return(0,I.jsxs)("div",{className:"af-rounded-lg af-border af-bg-muted/30",children:[(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-p-3",children:[t?(0,I.jsxs)("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-xs af-font-semibold af-text-background",children:[(0,I.jsx)("span",{"aria-hidden":!0,children:t}),(0,I.jsxs)("span",{className:"af-sr-only",children:["Shown at ",t," in the preview"]})]}):e&&(0,I.jsx)("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-background",children:(0,I.jsx)(e,{className:"af-h-4 af-w-4","aria-hidden":!0})}),(0,I.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,I.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:a}),(0,I.jsx)("div",{className:X("af-truncate af-text-sm",n&&"af-font-mono"),children:s}),r&&(0,I.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:r})]}),i,l&&(0,I.jsxs)(y,{size:"sm",variant:u?"secondary":"outline","aria-expanded":d?u:void 0,onClick:l.onClick,children:[l.label,d&&(0,I.jsx)(Yt.ChevronDown,{className:X("af-ml-1 af-h-3.5 af-w-3.5 af-transition-transform",u&&"af-rotate-180"),"aria-hidden":!0})]})]}),u&&d&&(0,I.jsx)("div",{className:"af-border-t af-bg-background af-p-4",children:d})]})}function Nn({tone:e,children:t}){return(0,I.jsx)("span",{className:X("af-inline-flex af-shrink-0 af-items-center af-rounded-full af-px-2 af-py-0.5 af-text-xs af-font-medium",e==="green"&&"af-bg-green-100 af-text-green-800",e==="amber"&&"af-bg-amber-100 af-text-amber-900",e==="gray"&&"af-bg-muted af-text-muted-foreground",e==="red"&&"af-bg-red-100 af-text-red-800"),children:t})}function Wr(e){return e.domain.status==="verified"&&e.domain.dmarc_status==="ok"}function Yo(e){let{sending_domain:t,status:a}=e.domain;return!t||a==="none"?(0,I.jsx)(Nn,{tone:"gray",children:"Not set up"}):a==="verified"?Wr(e)?(0,I.jsx)(Nn,{tone:"green",children:"Live"}):(0,I.jsx)(Nn,{tone:"amber",children:"DMARC record missing"}):a==="failed"?(0,I.jsx)(Nn,{tone:"red",children:"Records not found"}):(0,I.jsx)(Nn,{tone:"amber",children:"Waiting for DNS"})}function em({settings:e,businessName:t,onSaved:a}){let{canWrite:s}=it(),[n,r]=As.useState(e.business_name??t??""),[i,l]=As.useState(e.postal_address??""),[u,d]=As.useState(e.reply_to??""),o=Ot();return(0,I.jsxs)("form",{className:"af-space-y-3",onSubmit:async c=>{c.preventDefault(),(await o.run("updateSettings",{business_name:n.trim()||null,postal_address:i.trim()||null,reply_to:u.trim()||null,double_opt_in:e.double_opt_in})).ok&&await a()},children:[(0,I.jsx)(tm,{name:n,address:i}),(0,I.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,I.jsx)("span",{className:"af-text-sm af-font-medium",children:"Sender name"}),(0,I.jsx)(oe,{"aria-label":"Business name",value:n,disabled:!s,onChange:c=>r(c.target.value)})]}),(0,I.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,I.jsx)("span",{className:"af-text-sm af-font-medium",children:"Mailing address"}),(0,I.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:i,disabled:!s,onChange:c=>l(c.target.value)}),(0,I.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Anti-spam law requires it at the bottom of every email. A PO box works."})]}),(0,I.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,I.jsx)("span",{className:"af-text-sm af-font-medium",children:"Replies go to (optional)"}),(0,I.jsx)(oe,{"aria-label":"Reply-to email",type:"email",value:u,disabled:!s,onChange:c=>d(c.target.value)}),(0,I.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Your account email or an address on your domain."})]}),o.error&&(0,I.jsx)(Ee,{tone:"error",children:o.error}),s&&(0,I.jsx)(y,{type:"submit",size:"sm",disabled:o.busy||!i.trim(),children:"Save sender details"})]})}function tm({name:e,address:t}){return(0,I.jsxs)("div",{className:"af-rounded-lg af-bg-muted/50 af-px-4 af-py-4 af-text-center af-text-xs af-leading-relaxed af-text-muted-foreground",children:[(0,I.jsx)("div",{className:"af-mb-1 af-text-[10px] af-uppercase af-tracking-wide",children:"Footer of every email"}),(0,I.jsxs)("div",{children:["\xA9 ",new Date().getFullYear()," ",(0,I.jsx)("span",{className:"af-font-medium af-text-foreground",children:e.trim()||"Your business"})]}),(0,I.jsx)("div",{className:X(!t.trim()&&"af-italic af-text-amber-700"),children:t.trim()||"No mailing address yet"}),(0,I.jsxs)("div",{children:[(0,I.jsx)("span",{className:"af-underline",children:"Manage preferences"})," | ",(0,I.jsx)("span",{className:"af-underline",children:"Unsubscribe"})]})]})}var am={1:"From",2:"Subject and body",3:"Footer"};function qi({settings:e,site:t,className:a,numbered:s=!1,highlight:n=null,postalAddress:r}){let i=e?.business_name||t.businessName||"Your business",l=e?.domain.sending_domain??(t.siteDomain?`news.${t.siteDomain}`:"news.yourdomain.com"),u={backgroundColor:e?.brand.color??"hsl(var(--primary))"},d=r!==void 0?r.trim()||null:e?.postal_address,o=(c,b,g)=>s?(0,I.jsxs)("div",{"data-preview-region":c,"data-highlighted":n===c,className:X("af-relative af-rounded-md af-transition-shadow",n===c&&"af-ring-2 af-ring-primary af-ring-offset-2",b),children:[(0,I.jsxs)("span",{className:"af-absolute -af-left-3 -af-top-2 af-flex af-h-5 af-w-5 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-[10px] af-font-semibold af-text-background",children:[(0,I.jsx)("span",{"aria-hidden":!0,children:c}),(0,I.jsxs)("span",{className:"af-sr-only",children:[c,". ",am[c],":"]})]}),g]}):(0,I.jsx)("div",{className:b,children:g});return(0,I.jsxs)("div",{className:X("af-rounded-lg af-border af-bg-background af-p-4 af-shadow-sm",a),"aria-hidden":s?void 0:!0,"aria-label":s?"Email preview":void 0,role:s?"group":void 0,children:[o(1,"af-flex af-items-start af-gap-3",(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-sm af-font-semibold af-text-white",style:u,children:i.slice(0,1).toUpperCase()}),(0,I.jsxs)("div",{className:"af-min-w-0",children:[(0,I.jsx)("div",{className:"af-truncate af-text-sm af-font-semibold",children:i}),(0,I.jsxs)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:["<",Ko(l),">"]}),(0,I.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:"to me"})]})]})),o(2,"af-mt-4 af-space-y-2",(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)("div",{className:"af-text-sm af-font-medium",children:"What's new this month"}),(0,I.jsx)("div",{className:"af-h-2 af-w-full af-rounded af-bg-muted"}),(0,I.jsx)("div",{className:"af-h-2 af-w-5/6 af-rounded af-bg-muted"}),(0,I.jsx)("div",{className:"af-h-2 af-w-2/3 af-rounded af-bg-muted"})]})),o(3,"af-mt-4 af-border-t af-pt-2 af-text-center af-text-[10px] af-leading-snug af-text-muted-foreground",(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)("div",{children:d??(0,I.jsx)("span",{className:"af-italic af-text-amber-700",children:"Mailing address goes here"})}),(0,I.jsx)("div",{className:"af-underline",children:"Unsubscribe"})]}))]})}var nm="Add a newsletter signup to my footer";function sm({onAskAssistant:e}){let t=Xo();if(!t.data)return null;let{signups:a,optIns:s,others:n}=Qo(t.data);return(0,I.jsxs)("div",{className:"af-space-y-3",children:[a.length===0?(0,I.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-gap-2 af-rounded-lg af-border af-border-dashed af-px-6 af-py-6 af-text-center",children:[(0,I.jsx)("div",{className:"af-flex af-h-10 af-w-10 af-items-center af-justify-center af-rounded-full af-bg-muted",children:(0,I.jsx)(Yt.Mail,{className:"af-h-5 af-w-5","aria-hidden":!0})}),(0,I.jsx)("div",{className:"af-text-sm af-font-medium",children:"Add a signup form to your site"}),(0,I.jsx)("p",{className:"af-max-w-sm af-text-xs af-text-muted-foreground",children:`A short "Get our news" form, usually in the footer. It's how most of your list will find you.`}),e&&(0,I.jsxs)(y,{type:"button",size:"sm",className:"af-mt-1",onClick:()=>e(nm),children:[(0,I.jsx)(Yt.Sparkles,{className:"af-mr-1.5 af-h-3.5 af-w-3.5","aria-hidden":!0}),"Add signup form"]})]}):(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[(0,I.jsx)(Yt.Check,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),(0,I.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,I.jsx)("span",{className:"af-font-medium",children:"Signup form is live"}),(0,I.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",a.map(r=>r.name).join(", ")]})]})]}),s.length>0&&(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[(0,I.jsx)(Yt.Check,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),(0,I.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,I.jsx)("span",{className:"af-font-medium",children:"Opt-in checkbox"}),(0,I.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",s.map(r=>r.name).join(", ")]})]})]}),a.length===0&&n.length>0&&(0,I.jsxs)("p",{className:"af-px-2 af-text-xs af-text-muted-foreground",children:["Your ",n.length===1?"form":"forms"," ",n.map(r=>`"${r.name}"`).join(", "),' can also add people, with a "Send me news" checkbox.',e&&(0,I.jsxs)(I.Fragment,{children:[" ",(0,I.jsx)("button",{type:"button",className:"af-font-medium af-text-foreground af-underline af-underline-offset-2",onClick:()=>e(el(n)),children:"Add the checkbox"})]})]})]})}var te=require("react/jsx-runtime"),Gr="Subscribers confirm by email before they receive anything. Useful if many subscribers are in the EU (especially Germany), or if your forms attract fake or mistyped signups. Some signups need confirming even with this off: bursts of signups, and people re-subscribing after they unsubscribed.";function rm(e){let{status:t,dmarc_status:a,sending_domain:s}=e.domain;return!s||t==="none"?"No sending domain yet.":t==="verified"?a==="ok"?`Verified. Emails send from ${s}.`:`${s} is verified, but your domain still needs a DMARC record.`:t==="failed"?`${s} couldn't be verified. Check the DNS records below.`:`Waiting for the DNS records on ${s} to take effect. This can take a few hours.`}function tl({onStartDomainSetup:e,onAskAssistant:t}){let{settings:a,refetchSettings:s,canWrite:n,settingsSection:r}=it(),[i,l]=Na.useState(null),[u,d]=Na.useState(null),[o,c]=Na.useState(""),b=a!==null;if(Na.useEffect(()=>{b&&r&&document.getElementById(Vr(r))?.scrollIntoView?.({block:"start"})},[b,r]),!a)return(0,te.jsx)(ae,{className:"af-h-40 af-w-full"});let g=h=>d(R=>R===h?null:h),m=()=>d(null),p=async()=>{await s(),m()},f=(h,R,P)=>({id:P,"data-settings-row":h,onMouseEnter:()=>l(R),onMouseLeave:()=>l(null),onFocus:()=>l(R),onBlur:()=>l(null)}),v=Wr(a),{sending_domain:x,status:k}=a.domain,T=h=>n?{expanded:u===h}:{};return(0,te.jsx)("div",{className:"af-@container",children:(0,te.jsxs)("div",{className:"af-grid af-items-start af-gap-6 @2xl:af-grid-cols-[minmax(0,17rem)_minmax(0,1fr)]",children:[(0,te.jsxs)("aside",{className:"af-space-y-3 af-pl-3",children:[(0,te.jsx)("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails look like this"}),(0,te.jsx)(qi,{settings:a,site:{},numbered:!0,highlight:i,postalAddress:u==="address"?o:void 0}),(0,te.jsx)(um,{settings:a})]}),(0,te.jsxs)("div",{children:[(0,te.jsx)(Ja,{children:"From"}),(0,te.jsxs)("div",{className:"af-space-y-2",children:[(0,te.jsx)("div",{...f("Sending domain",1,Vr("domain")),children:(0,te.jsx)(Rn,{marker:1,label:"Sending from",value:x?Ko(x):"No sending domain yet",status:Yo(a),action:!v&&n?{label:x?k==="verified"||k==="failed"?"Fix":"Details":"Set up",onClick:()=>g("domain")}:void 0,...T("domain"),children:(0,te.jsx)(Jo,{settings:a,canWrite:n,onStartDomainSetup:e,onChanged:s})})}),(0,te.jsx)("div",{...f("Sender name and replies",1),children:(0,te.jsx)(Rn,{marker:1,label:"Sender name and replies",mono:!1,value:`${a.business_name??"No sender name"} \xB7 replies to ${a.reply_to??"your account email"}`,action:n?{label:"Edit",onClick:()=>g("sender")}:void 0,...T("sender"),children:(0,te.jsx)(im,{settings:a,onSaved:p,onCancel:m})})})]}),(0,te.jsx)(Ja,{children:"Brand"}),(0,te.jsx)("div",{...f("Brand color and logo",2),children:(0,te.jsx)(Rn,{marker:2,label:"Brand color and logo",value:`${a.brand.color}, ${a.brand.logo_url?"with your logo":"no logo"}`,action:n?{label:"Edit",onClick:()=>g("brand")}:void 0,...T("brand"),children:(0,te.jsx)(om,{settings:a,onSaved:p,onCancel:m})})}),(0,te.jsx)(Ja,{children:"Footer"}),(0,te.jsx)("div",{...f("Mailing address",3,Vr("sender")),children:(0,te.jsx)(Rn,{marker:3,label:"Mailing address",mono:!1,value:a.postal_address??"Not set",hint:"Anti-spam law requires it at the bottom of every email. A PO box works.",status:a.postal_address?void 0:(0,te.jsx)(Nn,{tone:"amber",children:"Needed"}),action:n?{label:a.postal_address?"Edit":"Add",onClick:()=>{c(a.postal_address??""),g("address")}}:void 0,...T("address"),children:(0,te.jsx)(lm,{settings:a,draft:o,onDraft:c,onSaved:p,onCancel:m})})}),(0,te.jsxs)("div",{id:Vr("signups"),children:[(0,te.jsx)(Ja,{children:"Who gets it"}),(0,te.jsxs)("div",{className:"af-space-y-2",children:[(0,te.jsx)("div",{...f("Double opt-in",null),children:(0,te.jsx)(cm,{settings:a,canWrite:n,onSaved:s})}),(0,te.jsx)(fm,{onAskAssistant:n?t:void 0})]})]})]})]})})}function Wi(e,t){return{business_name:e.business_name,postal_address:e.postal_address,reply_to:e.reply_to,double_opt_in:e.double_opt_in,...t}}function al({busy:e,error:t,canSave:a=!0,onSave:s,onCancel:n,children:r}){return(0,te.jsxs)("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),await s()},children:[r,t&&(0,te.jsx)(Ee,{tone:"error",children:t}),(0,te.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,te.jsx)(y,{type:"submit",size:"sm",disabled:e||!a,children:"Save"}),(0,te.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Cancel"})]})]})}function im({settings:e,onSaved:t,onCancel:a}){let[s,n]=Na.useState(e.business_name??""),[r,i]=Na.useState(e.reply_to??""),l=Ot();return(0,te.jsxs)(al,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",Wi(e,{business_name:s.trim()||null,reply_to:r.trim()||null}))).ok&&await t()},children:[(0,te.jsx)(ji,{label:"Sender name",children:(0,te.jsx)(oe,{"aria-label":"Business name",value:s,onChange:u=>n(u.target.value)})}),(0,te.jsx)(ji,{label:"Replies go to (your account email or an address on your domain)",children:(0,te.jsx)(oe,{"aria-label":"Reply-to email",type:"email",value:r,onChange:u=>i(u.target.value)})})]})}function om({settings:e,onSaved:t,onCancel:a}){let[s,n]=Na.useState(e.brand.color),[r,i]=Na.useState(e.brand.logo_url??""),l=Ot();return(0,te.jsx)(al,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",Wi(e,{brand:{color:s,logo_url:r.trim()||null}}))).ok&&await t()},children:(0,te.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-3",children:[(0,te.jsx)(ji,{label:"Brand color",children:(0,te.jsx)(oe,{"aria-label":"Brand color",type:"color",className:"af-h-9 af-w-16 af-p-1",value:s,onChange:u=>n(u.target.value)})}),(0,te.jsx)(ji,{label:"Logo URL (https)",children:(0,te.jsx)(oe,{"aria-label":"Logo URL",value:r,onChange:u=>i(u.target.value)})})]})})}function lm({settings:e,draft:t,onDraft:a,onSaved:s,onCancel:n}){let r=Ot();return(0,te.jsx)(al,{busy:r.busy,error:r.error,canSave:!!t.trim(),onCancel:n,onSave:async()=>{(await r.run("updateSettings",Wi(e,{postal_address:t.trim()}))).ok&&await s()},children:(0,te.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:t,onChange:i=>a(i.target.value)})})}function cm({settings:e,canWrite:t,onSaved:a}){let[s,n]=Na.useState(null),[r,i]=Na.useState(!1),l=Ot(),u=s??e.double_opt_in;return(0,te.jsxs)("div",{className:"af-space-y-2",children:[(0,te.jsx)(Rn,{icon:Ls.ShieldCheck,label:"Double opt-in",mono:!1,value:u?"New subscribers confirm by email first":"New subscribers join straight away",status:(0,te.jsxs)("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[(0,te.jsx)("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:Gr,className:"af-inline-flex af-h-4 af-w-4 af-cursor-help af-items-center af-justify-center af-rounded-full af-border af-text-[10px]",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:"?"}),(0,te.jsx)("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!r,className:"af-absolute af-right-0 af-top-6 af-z-10 af-w-72 af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:Gr}),(0,te.jsx)("input",{"aria-label":"Double opt-in",type:"checkbox",role:"switch",checked:u,disabled:!t||l.busy,onChange:async d=>{let o=d.target.checked;n(o),(await l.run("updateSettings",Wi(e,{double_opt_in:o}))).ok&&await a(),n(null)}})]})}),l.error&&(0,te.jsx)(Ee,{tone:"error",children:l.error})]})}function Jo({settings:e,canWrite:t,onStartDomainSetup:a,onChanged:s}){let[n,r]=Na.useState(null),[i,l]=Na.useState(!1),[u,d]=Na.useState(null),o=Wr(e);return(0,te.jsxs)("div",{children:[(0,te.jsx)("p",{className:"af-text-sm",children:rm(e)}),!o&&a&&(0,te.jsx)(y,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||i,onClick:async()=>{l(!0),d(null);try{r(await a()),await s()}catch(c){d(c instanceof Error?c.message:"Couldn't start domain setup.")}finally{l(!1)}},children:e.domain.sending_domain?"Check domain setup":"Set up sending domain"}),u&&(0,te.jsx)(Ee,{tone:"error",className:"af-mt-2",children:u}),n?.records&&n.records.length>0&&(0,te.jsxs)("div",{className:"af-mt-3 af-space-y-1",children:[(0,te.jsx)("p",{className:"af-text-sm",children:"Add these records at your domain provider:"}),(0,te.jsxs)("table",{className:"af-w-full af-text-left af-text-xs",children:[(0,te.jsx)("thead",{children:(0,te.jsxs)("tr",{children:[(0,te.jsx)("th",{className:"af-py-1 af-pr-2",children:"Type"}),(0,te.jsx)("th",{className:"af-py-1 af-pr-2",children:"Name"}),(0,te.jsx)("th",{className:"af-py-1 af-pr-2",children:"Value"}),(0,te.jsx)("th",{className:"af-py-1",children:"Priority"})]})}),(0,te.jsx)("tbody",{children:n.records.map((c,b)=>(0,te.jsxs)("tr",{className:"af-border-t af-align-top",children:[(0,te.jsx)("td",{className:"af-py-1 af-pr-2",children:c.type}),(0,te.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:c.name}),(0,te.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:c.value}),(0,te.jsx)("td",{className:"af-py-1",children:c.priority??""})]},b))})]})]}),n&&(0,te.jsx)(dm,{result:n})]})}function dm({result:e}){return e.status==="no_domain"?(0,te.jsx)(Ee,{tone:"warning",className:"af-mt-2",children:"Emails send from your own domain, so this site needs a custom domain first. Connect one, then come back to finish here."}):e.status==="not_available"?(0,te.jsx)(Ee,{tone:"warning",className:"af-mt-2",children:"Email sending isn't available for this site. It needs the Pro plan."}):e.records&&e.records.length>0?null:(0,te.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",children:"We added the DNS records for you. Verification usually finishes within a few hours."})}function um({settings:e}){let{monthly:t,sent:a,reserved:s}=e.allowance,n=a+s;return(0,te.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[qe(n)," of ",qe(t)," emails used this month (",qe(Math.max(0,t-n))," left). Receipts and form notifications don't count."]})}function Xo(){let{api:e}=W(),{siteId:t,refreshKey:a}=it();return Zt(async()=>Promise.all((await e.getForms()).map(s=>e.getForm(s.id))),`${t}|${a}`,t)}function Qo(e){return{signups:e.filter(t=>t.purpose==="newsletter"),optIns:e.filter(t=>t.purpose==="opt_in"),others:e.filter(t=>t.purpose!=="newsletter"&&t.purpose!=="opt_in")}}function el(e){let t=e.length===1;return`Add a "Send me news" opt-in checkbox to ${t?"the":"these"} ${e.map(a=>a.name).join(" and ")} form${t?"":"s"}`}function fm({onAskAssistant:e}){let t=Xo();if(!t.data||t.data.length===0)return null;let{signups:a,optIns:s,others:n}=Qo(t.data),r=[{id:"signup",label:"Signup forms",note:"Submitting one subscribes the visitor.",forms:a,icon:Ls.Check},{id:"opt_in",label:'Forms with a "Send me news" checkbox',note:"Visitors who tick the box join your list.",forms:s,icon:Ls.Check},{id:"other",label:"Other forms",note:"These don't add anyone to your list.",forms:n,icon:Ls.FileText,action:a.length===0&&e?{label:"Add the checkbox",onClick:()=>e(el(n))}:void 0}];return(0,te.jsx)(te.Fragment,{children:r.filter(i=>i.forms.length>0).map(i=>(0,te.jsx)("div",{"data-form-group":i.id,children:(0,te.jsx)(Rn,{icon:i.icon,label:i.label,mono:!1,value:i.forms.map(l=>l.name).join(", "),hint:i.note,action:i.action})},i.id))})}function ji({label:e,children:t}){return(0,te.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,te.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}var Gi=ce(require("react"),1);var bt=require("react/jsx-runtime");function yd({templateId:e,onOpenTemplate:t,onOpenDraft:a,onAskAssistant:s}){let{api:n}=W(),{siteId:r,canWrite:i,refreshKey:l}=it(),[u,d]=Gi.useState(0),o=u+l,c=Zt(()=>n.getEmailTemplates(r),`${r}|${o}`,r),b=Gi.useCallback(()=>d(f=>f+1),[]),g=i?s:void 0;if(e){let f=e===Mn?null:c.data?.find(v=>v.id===e);if(f!==void 0)return(0,bt.jsx)(ld,{template:f,onBack:()=>t(null),onOpenTemplate:t,onOpenDraft:a,onAskAssistant:g,reload:b,refreshKey:o},e);if(c.isLoading)return(0,bt.jsx)(ae,{className:"af-h-96 af-w-full"})}let m=c.data?.filter(f=>f.status!=="archived")??[],p=c.data?.filter(f=>f.status==="archived")??[];return(0,bt.jsxs)("div",{children:[(0,bt.jsxs)("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[(0,bt.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Templates"}),g&&(0,bt.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(Hi.create),children:"\u2728 New template with the editor"})]}),(0,bt.jsxs)(hd,{children:[(0,bt.jsx)(nl,{template:null,onOpen:()=>t(Mn)}),m.map(f=>(0,bt.jsx)(nl,{template:f,onOpen:()=>t(f.id)},f.id))]}),c.error&&!c.data?(0,bt.jsx)("div",{className:"af-mt-3",children:(0,bt.jsx)(Et,{message:"Couldn't load your templates.",onRetry:()=>void c.refetch()})}):!c.data&&(0,bt.jsx)(ae,{className:"af-mt-3 af-h-10 af-w-full"}),p.length>0&&(0,bt.jsxs)("div",{"data-testid":"archived-templates",children:[(0,bt.jsx)(Ja,{children:"Archived"}),(0,bt.jsx)(hd,{children:p.map(f=>(0,bt.jsx)(nl,{template:f,onOpen:()=>t(f.id)},f.id))})]})]})}function hd({children:e}){return(0,bt.jsx)("ul",{className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:e})}function mm(e){if(e.status==="draft")return null;let t=e.usage.drafts+e.usage.scheduled,a=[t>0&&`${t} email${t===1?"":"s"}`,e.usage.sent>0&&`${e.usage.sent} sent`].filter(Boolean);return a.length>0?a.join(" \xB7 "):"Not used yet"}function nl({template:e,onOpen:t}){let a=e?.name??"Standard",s=e&&mm(e);return(0,bt.jsxs)("li",{"data-testid":"template-card",className:"af-relative af-overflow-hidden af-rounded-md af-border hover:af-border-primary",children:[(0,bt.jsx)(zi,{templateId:e?.id??Mn,version:e?.updated_at??"builtin",className:"af-h-40 af-border-b",frame:{width:600,height:400,scale:.4}}),(0,bt.jsxs)("div",{className:"af-space-y-1 af-p-2",children:[(0,bt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,bt.jsx)("span",{"data-testid":"template-name",className:"af-grow af-truncate af-text-sm af-font-medium",children:a}),(0,bt.jsx)(jo,{status:e?.status??"builtin"})]}),s&&(0,bt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:s})]}),(0,bt.jsx)("button",{type:"button","aria-label":`Open ${a}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}var Ze=require("react/jsx-runtime"),pm=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"templates",label:"Templates"},{id:"settings",label:"Settings"}];function os(e,t={}){return{tab:e,draftId:null,templateId:null,...t}}var xd=e=>!!(e.tab||e.draftId||e.templateId);function wd(e){return e.draftId?os("broadcasts"):e.templateId?os("templates",{templateId:e.templateId}):os(e.tab==="template"?"templates":e.tab==="automations"||!e.tab?"audience":e.tab)}var gm={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function sl(e){return(0,Ze.jsx)(vm,{...e},e.siteId)}function vm({siteId:e,isOwnerSide:t,needsPaidPlan:a,initialDraftId:s,initialTab:n,templateId:r,showViewNonce:i,onOrgAction:l,onRequestReview:u,onStartDomainSetup:d,onBackToWebsite:o,onUpgradePlan:c,onConnectDomain:b,onAskAssistant:g,onPickImage:m,onTurnOn:p,siteDomain:f,businessName:v,onOpenStoreSettings:x,refreshKey:k=0,className:T}){let{api:h}=W(),R=Zt(()=>h.getMarketingSettings(e),`${e}|${k}`,e),P={tab:n,draftId:s,templateId:r},[D,N]=ta.useState(()=>wd(P)),[E,A]=ta.useState(s??null),[C,K]=ta.useState(xd(P)),[Q,H]=ta.useState(null),[de,me]=ta.useState(!1),be=ta.useCallback(()=>K(!1),[]),V=ta.useCallback(fe=>{N(os("settings")),H(fe??null)},[]),J=fe=>{N(os(fe)),H(null)},F=ta.useCallback(fe=>N(os("broadcasts",{draftId:fe})),[]),ge=ta.useCallback(fe=>N(os("templates",{templateId:fe})),[]),pe=!C&&R.data!==null&&bm(R.data),He=R.data&&!R.error?hm(R.data):null,Pe=JSON.stringify([i??null,n??null,s??null,r??null]),Ue=ta.useRef(Pe);ta.useEffect(()=>{if(Pe===Ue.current||de)return;Ue.current=Pe;let fe={tab:n,draftId:s,templateId:r};xd(fe)&&(N(wd(fe)),A(fe.draftId??null),H(null),K(!0))},[Pe,de,n,s,r]),ta.useEffect(()=>{if(!E||a)return;let fe=!0,lt=L=>{fe&&(N(os("broadcasts",{draftId:L})),A(null))};return h.getEmailDraft(e,E).then(L=>lt(L.kind==="broadcast"?L.id:null),()=>lt(null)),()=>{fe=!1}},[h,e,E,a]);let ze=ta.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:l,settings:R.data,refetchSettings:R.refetch,refreshKey:k,openSetup:be,openSettings:V,settingsSection:Q,onOpenStoreSettings:x,setInlineEditOpen:me}),[e,t,l,R.data,R.refetch,k,be,V,Q,x]);return a?(0,Ze.jsx)(Lt,{title:"Email Marketing",onBackToWebsite:o,className:T,children:(0,Ze.jsx)(Zo,{settings:R.data,site:{siteDomain:f,businessName:v},children:(0,Ze.jsx)(bd,{onUpgradePlan:c})})}):(0,Ze.jsx)(Lt,{title:"Email Marketing",onBackToWebsite:o,className:T,children:(0,Ze.jsx)(Mo.Provider,{value:ze,children:pe?(0,Ze.jsx)(vd,{onStartDomainSetup:d,onConnectDomain:b,onAskAssistant:g,onTurnOn:p,siteDomain:f,businessName:v}):(0,Ze.jsxs)(Ze.Fragment,{children:[R.error&&!R.data&&(0,Ze.jsx)(Et,{message:"Couldn't load email settings.",onRetry:()=>void R.refetch()}),He&&(0,Ze.jsx)(xm,{reason:He,pauseReason:R.data?.paused.reason??null,onRequestReview:u}),!t&&(0,Ze.jsx)(Ee,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),(0,Ze.jsx)("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:pm.map(fe=>(0,Ze.jsxs)("button",{type:"button",role:"tab","aria-selected":D.tab===fe.id,onClick:()=>J(fe.id),className:X("af-border-b-2 af-px-3 af-py-2 af-text-sm",D.tab===fe.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:[fe.label,fe.id==="settings"&&He&&(0,Ze.jsx)("span",{"data-testid":"settings-dot",role:"img","aria-label":"Sending is on hold",className:"af-ml-1.5 af-inline-block af-h-1.5 af-w-1.5 af-rounded-full af-bg-amber-600 af-align-middle"})]},fe.id))}),(0,Ze.jsx)("div",{role:"tabpanel",children:E?(0,Ze.jsx)(ae,{className:"af-h-24 af-w-full"}):D.tab==="audience"?(0,Ze.jsx)(Qc,{}):D.tab==="broadcasts"?(0,Ze.jsx)(pd,{openDraftId:D.draftId,onOpenDraft:F,onAskAssistant:g,onPickImage:m}):D.tab==="templates"?(0,Ze.jsx)(yd,{templateId:D.templateId,onOpenTemplate:ge,onOpenDraft:F,onAskAssistant:g}):(0,Ze.jsx)(tl,{onStartDomainSetup:d,onAskAssistant:g})})]})})})}function bm(e){return!e.paused.paused_at&&!e.readiness.can_send&&Ur.has(e.readiness.reason??"")}function hm(e){if(e.paused.paused_at)return"paused";let t=e.readiness.reason;return!e.readiness.can_send&&t&&Ur.has(t)?t:null}var ym={domain_not_verified:"domain",dmarc_missing:"domain",postal_address_missing:"sender"};function xm({reason:e,pauseReason:t,onRequestReview:a}){let{openSetup:s,openSettings:n}=it(),[r,i]=ta.useState("idle");if(e==="paused")return(0,Ze.jsx)("div",{"data-testid":"email-hold",className:"af-mb-3",children:(0,Ze.jsxs)(Ee,{tone:"warning",children:[(0,Ze.jsx)("div",{className:"af-font-medium",children:"Sending is paused."}),(0,Ze.jsxs)("p",{children:[gm[t??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),a&&(r==="sent"?(0,Ze.jsx)("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):(0,Ze.jsx)(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{i("sending");try{await a(),i("sent")}catch{i("failed")}},children:"Request review"})),r==="failed"&&(0,Ze.jsx)("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]})});let l=ym[e];return(0,Ze.jsx)("div",{"data-testid":"email-hold",className:"af-mb-3",children:(0,Ze.jsxs)(Ee,{tone:"warning",children:["Sending is on hold. ",ks(e)," ",l?(0,Ze.jsx)(Ts,{onClick:()=>n(l),children:"Fix in Settings"}):(0,Ze.jsx)(Ts,{onClick:s,children:"Finish setup"})]})})}var aa=ce(require("react"),1);var wm=2e3,fa=()=>({data:null,error:null,isLoading:!0});function Os(e,{refreshKey:t,breakdowns:a=[],filters:s=[]}={}){let{api:n}=W(),[r,i]=aa.useState(fa),[l,u]=aa.useState(fa),[d,o]=aa.useState(fa),[c,b]=aa.useState(fa),[g,m]=aa.useState(fa),p=V=>Object.fromEntries(V.map(J=>[J,fa()])),[f,v]=aa.useState(()=>p(a)),x=aa.useRef(0),k=aa.useRef(0),T=aa.useRef("idle"),h=a.join(","),R=Xn()??"",P=JSON.stringify(s),D=`${e}:${h}:${P}:${R}`,[N,E]=aa.useState({api:n,fetchIdentity:D});(N.api!==n||N.fetchIdentity!==D)&&(E({api:n,fetchIdentity:D}),x.current+=1,i(fa),u(fa),o(fa),b(fa),v(p(h?h.split(","):[])));let A=`${e}:${String(t??"")}:${R}`,[C,K]=aa.useState({api:n,conversionsIdentity:A});(C.api!==n||C.conversionsIdentity!==A)&&(K({api:n,conversionsIdentity:A}),k.current+=1,T.current="idle",m(fa));let Q=aa.useCallback(async V=>{let J=++x.current,F=h?h.split(","):[];i(fa),u(fa),o(fa),b(fa),v(Object.fromEntries(F.map(L=>[L,fa()])));let ge=T.current!=="pending"&&(V?.force===!0||T.current==="idle"),pe=(L,M)=>M.then(U=>{J===x.current&&L({data:U,error:null,isLoading:!1})},U=>{J===x.current&&L({data:null,error:U instanceof Error?U:new Error("Failed to fetch report"),isLoading:!1})}),He=n.getAnalyticsStatus(),Pe=pe(i,He),Ue=Symbol("status-timeout"),ze,fe=await Promise.race([He.then(L=>L,()=>null),new Promise(L=>{ze=setTimeout(()=>L(Ue),wm)})]);if(clearTimeout(ze),J!==x.current)return;if(fe===Ue&&i({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),fe!==null&&fe!==Ue&&(fe.collecting!==!0||fe.first_seen===null&&!fe.first_seen_unavailable||fe.first_seen!==null&&fe.first_seen_in_reports===!1)){let L={data:null,error:null,isLoading:!1};u(L),o(L),b(L),v(Object.fromEntries(F.map(M=>[M,{...L}]))),ge&&(m(L),T.current="done"),await Pe;return}await Promise.all([fe===Ue?Promise.resolve():Pe,pe(u,n.getAnalyticsSummary(e,s)),pe(o,n.getAnalyticsTimeseries(e,s)),pe(b,n.getAnalyticsChannels(e,s)),ge?(()=>{T.current="pending";let L=++k.current;return m(fa),n.getAnalyticsConversions(e).then(M=>{L===k.current&&(m({data:M,error:null,isLoading:!1}),T.current="done")},M=>{L===k.current&&(m({data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}),T.current="done")})})():Promise.resolve(),...F.map(L=>n.getAnalyticsBreakdown(L,e,s).then(M=>{J===x.current&&v(U=>({...U,[L]:{data:M,error:null,isLoading:!1}}))},M=>{J===x.current&&v(U=>({...U,[L]:{data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,P,A,R]),H=aa.useCallback(async()=>{let V=x.current;try{let J=await n.getAnalyticsStatus();if(V!==x.current)return;i({data:J,error:null,isLoading:!1})}catch(J){if(V!==x.current)return;i(F=>({data:F.data,error:J instanceof Error?J:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),de=aa.useCallback(()=>Q({force:!0}),[Q]);aa.useEffect(()=>{Q()},[Q,t]);let me=r.isLoading||l.isLoading||d.isLoading||c.isLoading||g.isLoading||Object.values(f).some(V=>V.isLoading),be=[d,l,c,g,...Object.values(f)].map(V=>V.data?.status==="ok"?V.data.timezone:void 0).find(V=>V!==void 0);return{status:r,summary:l,timeseries:d,channels:c,conversions:g,breakdowns:f,reportedZone:be,isLoading:me,refetch:de,refetchStatus:H}}var na=ce(require("react"),1);var Ki=3e4,Zi=3;function Kr(e={}){let t="collecting"in e,{collecting:a,statusFailed:s=!1,identity:n}=e,{api:r}=W(),[i,l]=na.useState(null),[u,d]=na.useState(null),[o,c]=na.useState(!1),[b,g]=na.useState(null),[m,p]=na.useState(!1),[f,v]=na.useState(!0),[x,k]=na.useState(0),T=na.useRef(0),h=na.useRef(0),R=na.useRef(void 0);a!==void 0&&(R.current=a);let P=t?R.current===!0||R.current===void 0&&s:!0,[D,N]=na.useState({api:r,identity:n}),E=n!==void 0&&n!==D.identity;(D.api!==r||E)&&(R.current=void 0,N({api:r,identity:n}),h.current+=1,T.current=0,l(null),d(null),c(!1),g(null),p(!1),v(!0),k(0));let A=na.useRef(()=>{}),C=na.useRef(null),K=na.useCallback(async()=>{if(C.current!==null&&C.current===h.current)return;let Q=++h.current;C.current=Q;try{let H=await r.getAnalyticsRealtime();if(Q!==h.current)return;if(H.status==="unreachable"){p(!0),c(!0),v(!1),k(de=>de+1);return}T.current=0,p(!1),l(H.data.current_visitors),d(H.as_of),c(!1),g(null),v(!1),k(de=>de+1)}catch(H){if(Q!==h.current)return;T.current+=1,v(!1),k(de=>de+1),c(!0),T.current>=Zi&&g(H instanceof Error?H:new Error("Realtime unavailable"))}finally{C.current===Q&&(C.current=null)}},[r]);return A.current=()=>void K(),na.useEffect(()=>{let Q,H=()=>{Q===void 0&&(Q=setInterval(()=>A.current(),Ki))},de=()=>{Q!==void 0&&(clearInterval(Q),Q=void 0)},me=()=>{typeof document<"u"&&document.hidden?de():(A.current(),H())};return P?((typeof document>"u"||!document.hidden)&&(A.current(),H()),document?.addEventListener("visibilitychange",me),()=>{de(),document?.removeEventListener("visibilitychange",me),h.current+=1}):()=>{document?.removeEventListener("visibilitychange",me)}},[D.api,D.identity,P]),{currentVisitors:i,asOf:u,isStale:o,error:b,isUnreachable:m,isInitialLoad:f,polls:x}}var Mt=ce(require("react"),1);var Sd=ce(require("react"),1);var Bs=require("react/jsx-runtime");function Sm(){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 rl({value:e,chosen:t,onChange:a}){let s=rr(),n=t===null&&s!==null&&e===s,r=Sd.useMemo(()=>{let i=Sm();return i.includes(e)?i:[e,...i]},[e]);return(0,Bs.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,Bs.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,Bs.jsxs)("select",{value:n?"":e,onChange:i=>a(i.target.value===""?null:i.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,Bs.jsx)("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(i=>(0,Bs.jsx)("option",{value:i,children:i.replace(/_/g," ")},i))]})]})}var Yi=(e,{published:t}={})=>{let a=t===!1,s=e!=null&&(!e.collecting||a&&e.first_seen===null&&!e.first_seen_unavailable),n=!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,i=n||r;return{notCollecting:s,awaitingFirstVisit:n,firstVisitTooRecent:r,holdingForFirstData:i,nothingToReport:s||i}};var Zr=ce(require("react"),1),Nm=3e4;function Ji({status:e,holdingForFirstData:t,refetchStatus:a,refetch:s}){Zr.useEffect(()=>{if(!t)return;let r,i=()=>{r===void 0&&(r=setInterval(()=>void a(),Nm))},l=()=>{r!==void 0&&(clearInterval(r),r=void 0)},u=()=>{typeof document<"u"&&document.hidden?l():(a(),i())};return(typeof document>"u"||!document.hidden)&&i(),document?.addEventListener("visibilitychange",u),()=>{l(),document?.removeEventListener("visibilitychange",u)}},[t,a]);let n=Zr.useRef(void 0);Zr.useEffect(()=>{if(!e){n.current=void 0;return}let r=n.current;n.current=t,r===!0&&!t&&s()},[e,t,s])}var Fs=ce(require("react"),1);var Rm=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ra(e){let t=Math.abs(e);if(t<1e3)return String(e);let a=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[s,n]of a)if(t>=s){let r=e/s,i=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(i)>=1e3&&s!==1e9?Ra(i*s):`${i}${n}`}return String(e)}function nr(e){return`${(e*100).toFixed(1)}%`}function Yr(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let a=Math.floor(t/60);return a<60?`${a}m ${t%60}s`:`${Math.floor(a/60)}h ${a%60}m`}function Rd(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`:Yr(t)}function _d(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Pd(e,t){if(!(!Number.isFinite(e)||e<=0))for(let a of t){let s=Math.ceil(e/a);if(s<=5)return Array.from({length:s+1},(n,r)=>Number((r*a).toPrecision(12)))}}function Jr(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function kd(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 il(e){let t=Number(e.slice(5,7)),a=Number(e.slice(8,10));return`${Rm[t-1]} ${a}`}function Nd(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function _m(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Cd(e,t,a="UTC"){let s=new Map(t.map(i=>[i.date,i])),n=[],r=Nd(e.to,a);for(let i=Nd(e.from,a);i<r;i=_m(i))n.push(s.get(i)??{date:i,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function Td(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=["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 n=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${n} ${a[s.getUTCMonth()]}`}var Qa=require("react/jsx-runtime");function Ed({what:e="This report",onRetry:t,collecting:a}){return(0,Qa.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,Qa.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,Qa.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:a===!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,Qa.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 Xi({what:e="No data"}){return(0,Qa.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 Yn({sourced:e,error:t,isLoading:a,what:s,onRetry:n,collecting:r,children:i}){return a?(0,Qa.jsx)("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,Qa.jsx)(Ed,{what:s,onRetry:n,collecting:r}):!e||e.status==="unreachable"?(0,Qa.jsx)(Ed,{what:s,onRetry:n,collecting:r}):(0,Qa.jsx)(Qa.Fragment,{children:i(e.data)})}var Pt=require("react/jsx-runtime");function ol({rows:e,dimension:t,metric:a,metricLabel:s,secondary:n,emptyCopy:r="No data for this period",onFilter:i,canFilter:l,maxRows:u=9}){let[d,o]=Fs.useState(!1);if(e.length===0)return(0,Pt.jsx)(Xi,{what:r});let c=e.reduce((m,p)=>Math.max(m,Number(p[a]??0)),0)||1,b=Math.max(0,e.length-u),g=d?e:e.slice(0,u);return(0,Pt.jsxs)(Pt.Fragment,{children:[(0,Pt.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Pt.jsx)("thead",{children:(0,Pt.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Pt.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,Pt.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),(0,Pt.jsx)("tbody",{children:g.map((m,p)=>{let f=Number(m[a]??0),v=m[t]??null,x=Jr(v),k=n?m[n]:null,T=v!==null&&(l?l(v,k):!0);return(0,Pt.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,Pt.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,Pt.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,f/c*100)}%`}}),v!==null&&i&&T?(0,Pt.jsx)("button",{type:"button",onClick:()=>i(v,k),title:`Filter by ${x}`,"aria-label":`Filter by ${x}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:x}):(0,Pt.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:x}),k?(0,Pt.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:k}):null]}),(0,Pt.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Ra(f)})]},`${x}-${k??""}-${p}`)})})]}),b>0?(0,Pt.jsx)("button",{type:"button",onClick:()=>o(m=>!m),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:d?"Show fewer":`Show all ${e.length}`}):null]})}function Xr({title:e,tabs:t,defaultTabId:a,headerRight:s}){let[n,r]=Fs.useState(a),i=t.find(g=>g.id===n)??t[0],l=Fs.useId(),u=g=>`${l}-tab-${g}`,d=g=>`${l}-panel-${g}`,o=Fs.useRef(null),c=(g,m)=>{g.preventDefault();let p=(m+t.length)%t.length;r(t[p].id),o.current?.querySelectorAll('[role="tab"]')?.[p]?.focus()};return(0,Pt.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,Pt.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,Pt.jsx)("div",{ref:o,role:"tablist","aria-label":e,onKeyDown:g=>{let m=t.findIndex(p=>p.id===n);g.key==="ArrowRight"&&c(g,m+1),g.key==="ArrowLeft"&&c(g,m-1),g.key==="Home"&&c(g,0),g.key==="End"&&c(g,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(g=>(0,Pt.jsx)("button",{id:u(g.id),role:"tab",type:"button","aria-selected":g.id===n,"aria-controls":d(g.id),tabIndex:g.id===n?0:-1,onClick:()=>r(g.id),className:g.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:g.label},g.id))}),s]}),i?(0,Pt.jsx)("div",{id:d(i.id),role:"tabpanel","aria-labelledby":u(i.id),tabIndex:0,className:"af-px-3 af-py-2",children:i.render()},i.id):null]})}var La=ce(require("react"),1),ds=ce(require("@radix-ui/react-popover"),1);var ls=3,cs=100;var Qe=require("react/jsx-runtime"),Qr={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"},Pm=Object.keys(Qr);function Id(e){let t=Qr[e.dimension],a=e.operator==="is_not"?"is not":"is",s=e.values.map(n=>Jr(n)).join(" or ");return`${t} ${a} ${s}`}function ll(e,t){let a=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));if(a>=0){let s=[...new Set([...e[a].values,...t.values])];return s.length>cs||s.length===e[a].values.length?e:e.map((n,r)=>r===a?{...n,values:s}:n)}return t.values.length>cs||e.length>=ls?e:[...e,t]}function km(e,t){let a={};for(let[s,n]of Object.entries(t)){let r=e.get(s)??new Set;for(let i of n)r.add(i);e.set(s,r),a[s]=[...r]}return a}function Dd(e,t){let a=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));return a>=0?e.map((s,n)=>n===a?t:s):t.values.length>cs||e.length>=ls?e:[...e,t]}function Cm(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Ad(e,t,a,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 n=km(e.byDimension,a);for(let[r,i]of Object.entries(s)){let l=e.foldsByLabel.get(r)??new Set;for(let u of i)l.add(u);e.foldsByLabel.set(r,l)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([r,i])=>[r,[...i]]))}}function Ld(e){let{filters:t,onChange:a}=e,s=t.length>=ls;return La.useEffect(()=>{if(t.length===0)return;let n=r=>{let i=r.target;i&&(i.tagName==="INPUT"||i.closest('[role="dialog"]'))||r.key==="Escape"&&a([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[t.length,a]),(0,Qe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,r)=>(0,Qe.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,Qe.jsx)("span",{className:"af-text-foreground",children:Id(n)}),(0,Qe.jsx)("button",{type:"button","aria-label":`Remove filter ${Id(n)}`,onClick:()=>a(t.filter((i,l)=>l!==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"})]},`${n.dimension}-${n.operator??"is"}`)),(0,Qe.jsx)(Tm,{...e,disabled:s}),t.length>0?(0,Qe.jsx)("button",{type:"button",onClick:()=>a([]),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 Tm({filters:e,onChange:t,suggestions:a,resetKey:s,disabled:n,expandValues:r}){let[i,l]=La.useState(!1),u=La.useRef(null),[d,o]=La.useState(null);La.useEffect(()=>{o(u.current?.closest(".aifeatures-admin")??null)},[]);let[c,b]=La.useState(null),[g,m]=La.useState("is"),[p,f]=La.useState(""),[v,x]=La.useState([]);La.useEffect(()=>{i||(b(null),m("is"),f(""),x([]))},[i]);let k=La.useRef(s);k.current!==s&&(k.current=s,i&&l(!1),c!==null&&b(null),v.length>0&&x([]),p!==""&&f(""),g!=="is"&&m("is"));let T=E=>{let A=Cm(E);b(A.dimension),x(A.picked),f(A.search),m(A.operator)},R=(c?a[c]??[]:[]).filter(E=>E.toLowerCase().includes(p.trim().toLowerCase())),P=c===null||v.length===0?null:ll(e,{dimension:c,operator:g,values:r?r(c,v):v}),D=P!==null&&P!==e,N=()=>{let E=P;!E||E===e||(t(E),l(!1))};return(0,Qe.jsxs)(ds.Root,{open:i,onOpenChange:l,children:[(0,Qe.jsx)(ds.Trigger,{asChild:!0,children:(0,Qe.jsx)("button",{ref:u,type:"button",disabled:!1,title:n?`At most ${ls} 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,Qe.jsx)(ds.Portal,{container:d,children:(0,Qe.jsx)(ds.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:c===null?(0,Qe.jsxs)("div",{children:[(0,Qe.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Qe.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:Pm.filter(E=>a[E]!==void 0).map(E=>{let A=a[E]?.length??0,C=!e.some(K=>K.dimension===E)&&e.length>=ls;return(0,Qe.jsxs)("button",{type:"button",onClick:()=>T(E),disabled:A===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,Qe.jsx)("span",{children:Qr[E]}),(0,Qe.jsx)("span",{className:"af-text-muted-foreground",children:A===0?"no data":C?"no room":A})]},E)})})]}):(0,Qe.jsxs)("div",{children:[(0,Qe.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Qe.jsx)("button",{type:"button",onClick:()=>T(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Qe.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Qr[c]}),(0,Qe.jsxs)("select",{"aria-label":"Operator",value:g,onChange:E=>m(E.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,Qe.jsx)("option",{value:"is",children:"is"}),(0,Qe.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Qe.jsx)("input",{type:"text",value:p,onChange:E=>f(E.target.value),placeholder:"Search\u2026","aria-label":`Search ${Qr[c]}`,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,Qe.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:R.length===0?(0,Qe.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",p,"\u201D."]}):R.map(E=>(0,Qe.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,Qe.jsx)("input",{type:"checkbox",checked:v.includes(E),disabled:!v.includes(E)&&v.length>=cs,onChange:A=>x(C=>A.target.checked?[...C,E]:C.filter(K=>K!==E))}),(0,Qe.jsx)("span",{className:"af-break-all",children:Jr(E)})]},E))}),(0,Qe.jsx)("button",{type:"button",onClick:N,disabled:!D,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:v.length<=1?"Apply filter":v.length>=cs?`Apply filter (${v.length} values \u2014 the maximum)`:`Apply filter (${v.length} values)`})]})})})]})}var Ft=require("react/jsx-runtime"),Em=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Ra,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Ra,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Ra,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:nr,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Yr,chart:"visit_duration_seconds"}];function Im({current:e,previous:t,downIsGood:a}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let n=s>0,r=a?!n:n,i=`${n?"+":""}${(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:i})}function Od({summary:e,selected:t,onSelect:a}){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:Em.map(s=>{let n=s.chart===t,r=a!==void 0,i=(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)(Im,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?(0,Ft.jsx)("button",{type:"button","aria-pressed":n,onClick:()=>a(s.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:i},s.key):(0,Ft.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:i},s.key)})})})}function cl({currentVisitors:e,asOf:t,isStale:a,isUnreachable:s,isInitialLoad:n=!1,scopeIsSiteWide:r=!1}){if(n&&!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 i=t?kd(t):"freshness unknown",l=r?" across the whole site, not the current filter,":"",u=a?`${e} current visitors${l} ${i} (not updating)`:`${e} current visitors${l} ${i}`;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:u,children:[(0,Ft.jsx)("span",{"aria-hidden":"true",className:a?"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:u})]})}var Bd=ce(require("react"),1),Fd=require("lucide-react");var st=require("react/jsx-runtime");function Qi(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function eo({rows:e,denominator:t,windowPrecedesCollection:a=!1,coverageUnknown:s=!1,emptyCopy:n="No conversions in this period",maxRows:r=9,primaryConversion:i}){let[l,u]=Bd.useState(!1),d=e.filter(f=>!f.implicit||f.visitors>0||f.events>0||Qi(f,i)),o=a?(0,st.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,st.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(d.length===0)return(0,st.jsxs)(st.Fragment,{children:[(0,st.jsx)(Xi,{what:n}),o]});let c=d.slice(0,r),b=i?d.find(f=>Qi(f,i)):void 0,g=b&&!c.includes(b)?d.filter(f=>c.includes(f)||f===b).slice(0,Math.max(0,r-1)).concat(b):c,m=l?e:g,p=Math.max(0,e.length-g.length);return(0,st.jsxs)(st.Fragment,{children:[(0,st.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,st.jsx)("thead",{children:(0,st.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,st.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,st.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,st.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,st.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,st.jsx)("tbody",{children:m.map((f,v)=>(0,st.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":Qi(f,i)?"true":void 0,children:[(0,st.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Qi(f,i)?(0,st.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,st.jsx)(Fd.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,st.jsx)("span",{className:"af-font-medium af-text-foreground",children:f.goal}),(0,st.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):f.goal}),(0,st.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ra(f.visitors)}),(0,st.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ra(f.events)}),(0,st.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:f.conversion_rate===null?(0,st.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):nr(f.conversion_rate)})]},`${f.goal}-${v}`))})]}),p>0?(0,st.jsx)("button",{type:"button",onClick:()=>u(f=>!f),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length} goals`}):null,(0,st.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Ra(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),o]})}var Oa=require("recharts");var $t=require("react/jsx-runtime"),to={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},ul={visitors:Ra,visits:Ra,pageviews:Ra,views_per_visit:e=>e.toFixed(2),bounce_rate:nr,visit_duration_seconds:Yr},Dm=31,Am=new Set(["visitors","visits","pageviews"]),Lm={...ul,bounce_rate:_d,visit_duration_seconds:Rd},dl=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Om=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Bm=[.01,.02,.05,.1,.2,.25,.5,1],Fm=[.25,.5,1,2,5,10,25,50],Mm={visitors:dl,visits:dl,pageviews:dl,views_per_visit:Fm,bounce_rate:Bm,visit_duration_seconds:Om};function Um({active:e,payload:t,label:a,metric:s}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return(0,$t.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,$t.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:to[s]}),(0,$t.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,$t.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,$t.jsx)("span",{className:"af-text-muted-foreground",children:Td(String(a))}),(0,$t.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:ul[s](Number(n[s]??0))})]})]})}function ao({rows:e,window:t,metric:a,timeZone:s="UTC",height:n=260}){let r=Cd(t,e,s),i=ul[a],l=Lm[a],u=Pd(r.reduce((o,c)=>Math.max(o,Number(c[a]??0)),0),Mm[a]),d=`${to[a]} by day: ${r.map(o=>`${il(o.date)}: ${i(Number(o[a]??0))}`).join("; ")}.`;return(0,$t.jsxs)("figure",{"aria-label":`${to[a]} over time`,className:"af-m-0",children:[(0,$t.jsx)(Oa.ResponsiveContainer,{width:"100%",height:n,children:(0,$t.jsxs)(Oa.AreaChart,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,$t.jsx)("defs",{children:(0,$t.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,$t.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,$t.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,$t.jsx)(Oa.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,$t.jsx)(Oa.XAxis,{dataKey:"date",tickFormatter:il,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,$t.jsx)(Oa.YAxis,{allowDecimals:!Am.has(a),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...u?{ticks:u,domain:[0,u[u.length-1]]}:{},tickFormatter:o=>l(o),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,$t.jsx)(Oa.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,$t.jsx)(Um,{metric:a})}),(0,$t.jsx)(Oa.Area,{type:"linear",dataKey:a,name:to[a],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=Dm?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,$t.jsx)("figcaption",{className:"af-sr-only",children:d})]})}var he=require("react/jsx-runtime"),$m="2026-08-13",Vm=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Hm=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Md({filters:e,onFiltersChange:t,refreshKey:a,onBackToWebsite:s,primaryConversion:n,className:r,published:i,lastPublishedAt:l}){let[u,d]=Mt.useState(30),[o,c]=Mt.useState(()=>io()),b=e!==void 0&&t!==void 0,[g,m]=Mt.useState(e??[]),{api:p}=W(),[f,v]=Mt.useState(p);f!==p&&(v(p),!b&&g.length>0&&m([]));let x=b?e:g,k=Mt.useCallback(U=>{t&&t(U),b||m(U)},[t,b]),T=Mt.useCallback((U,Te,ne)=>{let Re=Array.isArray(Te)?Te:[Te];if(Re.length===0)return null;let je=ll(x,{dimension:U,operator:"is",values:Re});if(ne&&(!ne.value||(je=Dd(je,{dimension:ne.dimension,operator:"is",values:[ne.value]}),!je.find(Dt=>Dt.dimension===ne.dimension&&Dt.operator!=="is_not")?.values.includes(ne.value))))return null;let wt=je.find(et=>et.dimension===U&&et.operator!=="is_not");return Re.every(et=>wt?.values.includes(et))?JSON.stringify(je)===JSON.stringify(x)?null:je:null},[x]),h=Mt.useCallback((U,Te,ne)=>T(U,Te,ne)!==null,[T]),R=Mt.useCallback((U,Te,ne)=>{let Re=T(U,Te,ne);Re&&k(Re)},[T,k]),[P,D]=Mt.useState("visitors"),N=Os(u,{refreshKey:a,breakdowns:Hm,filters:x}),E=N.status.data,A=N.reportedZone??E?.timezone,C=A??o??rr()??"UTC",{notCollecting:K,awaitingFirstVisit:Q,firstVisitTooRecent:H,holdingForFirstData:de}=Yi(E,{published:i}),me=i===!1,be=Kr({collecting:Q||K?!1:E?.collecting,statusFailed:N.status.error!=null,identity:E?.analytics_id}),V=Mt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),J=Mt.useMemo(()=>{let U=N.breakdowns.sources?.data,Te={};if(!U||U.status!=="ok")return Te;for(let ne of U.data){let Re=ne.source,je=ne.sources;typeof Re=="string"&&Array.isArray(je)&&je.length>0&&(Te[Re]=je)}return Te},[N.breakdowns.sources?.data]),F=Mt.useMemo(()=>{let U=(Re,je)=>{let wt=N.breakdowns[Re]?.data;return!wt||wt.status!=="ok"?[]:[...new Set(wt.data.map(et=>et[je]).filter(et=>typeof et=="string"&&et!==""))]};return{channel:N.channels.data?.status==="ok"?[...new Set(N.channels.data.data.map(Re=>Re.channel))]:[],source:U("sources","source"),campaign:U("utm/campaign","campaign"),page:U("pages","pathname"),entry_page:U("entry-pages","pathname"),exit_page:U("exit-pages","pathname"),country:U("countries","country"),browser:U("browsers","browser"),os:U("operating-systems","os"),device:U("devices","device")}},[N.breakdowns,N.channels.data]),[ge,pe]=Mt.useState({}),He=JSON.stringify(F),[Pe,Ue]=Mt.useState(new Map),ze=JSON.stringify(J);Mt.useEffect(()=>{let{suggestions:U,folds:Te}=Ad(V.current,{api:p,period:u},JSON.parse(He),JSON.parse(ze));pe(U),Ue(Te)},[He,ze,p,u]);let fe=Mt.useCallback((U,Te)=>U!=="source"?Te:[...new Set(Te.flatMap(ne=>{let Re=[...Pe.get(ne)??[],...J[ne]??[]];return Re.length>0?Re:[ne]}))],[Pe,J]),lt=Mt.useMemo(()=>{let U=N.conversions.error;return U instanceof jt&&U.details?.code==="goals_exceed_report_budget"?U.message:null},[N.conversions.error]),L=Mt.useMemo(()=>{let U=[N.summary,N.timeseries,N.channels,...Object.values(N.breakdowns)];for(let Te of U){let ne=Te?.error;if(ne instanceof jt&&ne.details?.code==="filter_unsupported")return ne.message}return null},[N.summary,N.timeseries,N.channels,N.breakdowns]),M=(U,Te,ne,Re,je,wt,et,Dt,Ne)=>()=>{let Le=N.breakdowns[U];return(0,he.jsx)(Yn,{sourced:Le?.data??null,error:Le?.error,isLoading:Le?.isLoading,what:Te,collecting:E?.collecting,onRetry:N.refetch,children:ct=>{let at=qt=>Dt?fe(Dt,[qt]):qt;return(0,he.jsx)(ol,{rows:ct,dimension:ne,metric:Re,metricLabel:je,secondary:wt,emptyCopy:x.length>0?"No data for this filter":et,canFilter:Dt?(qt,Ut)=>h(Dt,at(qt),Ne?{dimension:Ne,value:Ut}:void 0):()=>!1,onFilter:Dt?(qt,Ut)=>R(Dt,at(qt),Ne?{dimension:Ne,value:Ut}:void 0):void 0})}})};if(Ji({status:E,holdingForFirstData:de,refetchStatus:N.refetchStatus,refetch:N.refetch}),K){let U=!!l&&String(l).slice(0,10)<$m;return(0,he.jsx)(Lt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,he.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,he.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:me?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":U?"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 Q?(0,he.jsx)(Lt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,he.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,he.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."})]})}):H?(0,he.jsxs)(Lt,{title:"Analytics",onBackToWebsite:s,className:r,children:[(0,he.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,he.jsx)(rl,{value:C,chosen:o,onChange:U=>{oo(U),c(U)}})}),(0,he.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,he.jsxs)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",E?.timezone?` ${E.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,he.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,he.jsx)(cl,{currentVisitors:be.currentVisitors,asOf:be.asOf,isStale:be.isStale,isUnreachable:be.isUnreachable||be.error!==null,isInitialLoad:be.isInitialLoad})})]})]}):(0,he.jsx)(Lt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,he.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,he.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,he.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Vm.map(U=>(0,he.jsx)("button",{type:"button","aria-pressed":U.value===u,onClick:()=>d(U.value),className:U.value===u?"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:U.label},U.value))}),(0,he.jsx)(rl,{value:C,chosen:o,onChange:U=>{oo(U),c(U)}}),(0,he.jsx)(cl,{currentVisitors:be.currentVisitors,asOf:be.asOf,isStale:be.isStale,isUnreachable:be.isUnreachable||be.error!==null,isInitialLoad:be.isInitialLoad,scopeIsSiteWide:x.length>0})]}),(0,he.jsx)(Ld,{filters:x,onChange:k,suggestions:ge,expandValues:fe,resetKey:p}),L?(0,he.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,he.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:L}),(0,he.jsx)("button",{type:"button",onClick:()=>k([]),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,!L&&E?.timezone_defaulted?(0,he.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,L?null:(0,he.jsxs)(he.Fragment,{children:[(0,he.jsx)(Yn,{sourced:N.summary.data,error:N.summary.error,isLoading:N.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:N.refetch,children:U=>(0,he.jsxs)(he.Fragment,{children:[(0,he.jsx)(Od,{summary:U,selected:P,onSelect:D}),U.previous_unavailable?(0,he.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[U.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,he.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,he.jsx)(Yn,{sourced:N.timeseries.data,error:N.timeseries.error,isLoading:N.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:N.refetch,children:U=>{let Te=N.timeseries.data?.status==="ok"?N.timeseries.data.window:{from:"",to:""};return(0,he.jsx)(ao,{rows:U,window:Te,metric:P,timeZone:A??"UTC"})}})}),(0,he.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,he.jsx)(Xr,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,he.jsx)(Yn,{sourced:N.channels.data,error:N.channels.error,isLoading:N.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:N.refetch,children:U=>(0,he.jsx)(ol,{rows:U,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:Te=>h("channel",Te),onFilter:Te=>R("channel",Te)})})},{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,he.jsx)(Xr,{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,he.jsx)(Xr,{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,he.jsx)(Xr,{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,he.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,he.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,he.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,he.jsxs)("div",{className:"af-px-3 af-py-2",children:[x.length>0?(0,he.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",x.length===1?"filter":"filters"," above."]}):null,lt!==null?(0,he.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,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,he.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:lt})]}):(0,he.jsx)(Yn,{sourced:N.conversions.data,error:N.conversions.error,isLoading:N.conversions.isLoading,what:"Conversions",collecting:E?.collecting,onRetry:N.refetch,children:U=>{let Te=N.conversions.data?.status==="ok"?N.conversions.data:null;return(0,he.jsx)(he.Fragment,{children:(0,he.jsx)(eo,{rows:U,primaryConversion:n,denominator:Te?.denominator??0,windowPrecedesCollection:Te?.window_precedes_collection??!1,coverageUnknown:Te?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var qd=ce(require("react"),1),la=require("lucide-react");var pn=ce(require("react"),1),Jn=require("lucide-react");var Ae=require("react/jsx-runtime"),Ud=90,$d=100;function zm(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Vd(e){return!!e.label&&e.label!==e.target}function qm(e,t,a){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:n}=t;return s===0?e===0?"Nothing specific has converted here yet.":null:n===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":n<s?a?`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function ei(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Hd({current:e,onChange:t,onClose:a}){let{api:s}=W(),[n,r]=pn.useState(null),[i,l]=pn.useState(!1),[u,d]=pn.useState({at:"goals"}),[o,c]=pn.useState(null),[b,g]=pn.useState(null),[m,p]=pn.useState(!1),[f,v]=pn.useState(null),x=pn.useRef(0);pn.useEffect(()=>{let R=!0;return r(null),l(!1),d({at:"goals"}),c(null),g(null),p(!1),v(null),x.current+=1,s.getAnalyticsConversions(Ud).then(P=>{if(R){if(P.status!=="ok"){l(!0);return}r(P.data)}}).catch(()=>{R&&l(!0)}),()=>{R=!1}},[s]);let k=R=>{d({at:"targets",row:R}),c(null),g(null),p(!1),v(null);let P=++x.current;s.getAnalyticsGoalTargets(R.goal,Ud,$d).then(D=>{if(P===x.current){if(D.status!=="ok"){g("failed");return}c(D.data),p(D.truncated===!0),v(D.coverage??null)}}).catch(D=>{if(P!==x.current)return;let N=D instanceof jt?D.details?.code:void 0;g(N==="goal_has_no_targets"?"no-values":"failed")})},T=R=>{t(R),a()};if(i)return(0,Ae.jsx)("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return(0,Ae.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,Ae.jsx)(Jn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Ae.jsx)("span",{children:"Loading your conversions\u2026"})]});if(u.at==="targets"){let R=u.row,P=new Map;for(let D of o??[])P.set(D.label,(P.get(D.label)??0)+1);return(0,Ae.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,Ae.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,Ae.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>d({at:"goals"}),children:[(0,Ae.jsx)(Jn.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,Ae.jsx)("span",{children:"All conversions"})]})}),(0,Ae.jsxs)("button",{type:"button","aria-current":e&&ei(R,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:R.goal,implicit:R.implicit}),children:[e&&ei(R,e)&&!e.target&&(0,Ae.jsx)(Jn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ae.jsxs)("span",{children:["Any ",R.goal.toLowerCase()]})]}),b==="no-values"&&(0,Ae.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,Ae.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,Ae.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,Ae.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>k(R),children:"Try again"})]}),!o&&b===null&&(0,Ae.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,Ae.jsx)(Jn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Ae.jsx)("span",{children:"Loading\u2026"})]}),o&&(0,Ae.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:qm(o.length,f,m)}),m&&(0,Ae.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",$d,". If what you want isn\u2019t here, pick the conversion itself instead."]}),o?.some(Vd)&&(0,Ae.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."}),o?.map(D=>{let N=!!(e&&ei(R,e)&&e.target===D.target),E=P.get(D.label)>1;return Vd(D)?(0,Ae.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,Ae.jsxs)("span",{className:"af-min-w-0",children:[(0,Ae.jsx)("span",{className:"af-block af-truncate",children:D.label}),E&&(0,Ae.jsx)("span",{className:"af-block af-truncate af-text-xs",children:D.target})]}),(0,Ae.jsx)("span",{className:"af-shrink-0 af-text-xs",children:D.visitors.toLocaleString()})]},D.target):(0,Ae.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:()=>T({goal:R.goal,implicit:R.implicit,target:D.target,...D.label&&D.label!==D.target?{label:D.label}:{}}),children:[(0,Ae.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[N&&(0,Ae.jsx)(Jn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ae.jsxs)("span",{className:"af-min-w-0",children:[(0,Ae.jsx)("span",{className:"af-block af-truncate",children:D.label}),E&&(0,Ae.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:D.target})]})]}),(0,Ae.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:D.visitors.toLocaleString()})]},D.target)})]})}let h=e?.goal&&!n.some(R=>ei(R,e));return(0,Ae.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:[h&&(0,Ae.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&(0,Ae.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(R=>{let P=e?ei(R,e):!1;return(0,Ae.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,Ae.jsxs)("button",{type:"button","aria-current":P?"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:()=>T({goal:R.goal,implicit:R.implicit}),children:[(0,Ae.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[P&&(0,Ae.jsx)(Jn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ae.jsx)("span",{className:"af-truncate",children:R.goal})]}),(0,Ae.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:R.visitors.toLocaleString()})]}),zm(R)&&(0,Ae.jsx)(y,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${R.goal}`,onClick:()=>k(R),children:"Narrow"})]},R.goal)}),e?.goal&&(0,Ae.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:()=>T(null),children:"No main conversion"})]})}var en=require("react/jsx-runtime");function jm(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let a of t)try{let{hostname:s}=new URL(a);if(s)return s.toLowerCase().replace(/^www\./,"")}catch{}return null}function Wm(e){if(fl(e,"whatsapp"))return!0;let t=jm(e);return t===null?!1:["wa.me","whatsapp.com"].some(a=>t===a||t.endsWith(`.${a}`))}function fl(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var zd=[{goal:"Contact",target:e=>fl(e,"tel"),icon:la.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>fl(e,"mailto"),icon:la.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:la.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Wm(e),icon:la.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:la.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:la.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:la.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:la.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:la.Download,line:"This site is set up to get your file downloaded."}];function jd(e){let{goal:t,target:a}=e;return e.implicit!==!0?null:(a?zd.find(n=>n.goal===t&&n.target?.(a)):void 0)??zd.find(n=>n.goal===t&&!n.target)??null}function Gm(e){return jd(e)?.icon??la.Target}function Wd({primaryConversion:e,onChange:t}){let[a,s]=qd.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?jd(e):null,i=e?.label?.trim(),l=e?Gm(e):la.Target,u=e?.goal?i?`Your main conversion is ${i}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",d=(0,en.jsxs)(en.Fragment,{children:[(0,en.jsx)(l,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,en.jsx)("span",{children:u})]});return t?(0,en.jsxs)(gi,{open:a,onOpenChange:s,children:[(0,en.jsx)(vi,{asChild:!0,children:(0,en.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:d})}),(0,en.jsx)(Pr,{align:"start",className:"af-w-80 af-p-1",children:a&&(0,en.jsx)(Hd,{current:e,onChange:t,onClose:()=>s(!1)})})]}):(0,en.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:d})}var ha=require("react/jsx-runtime");function Gd({refreshKey:e,onViewAll:t,primaryConversion:a}){let s=Os(7,{refreshKey:e,breakdowns:[]}),n=s.status.data??void 0,{nothingToReport:r,notCollecting:i,holdingForFirstData:l}=Yi(n);return Ji({status:n,holdingForFirstData:l,refetchStatus:s.refetchStatus,refetch:s.refetch}),(0,ha.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ha.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,ha.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,ha.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?(0,ha.jsx)("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:i?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):(0,ha.jsxs)(ha.Fragment,{children:[(0,ha.jsx)(Yn,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let d=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return(0,ha.jsx)(ao,{rows:u,window:d?.window??{from:"",to:""},metric:"visitors",timeZone:d?.timezone,height:140})}}),(0,ha.jsxs)("div",{className:"af-mt-3",children:[(0,ha.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,ha.jsx)(Yn,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let d=s.conversions.data?.status==="ok"?s.conversions.data:null;return(0,ha.jsx)(eo,{rows:u,primaryConversion:a,denominator:d?.denominator??0,windowPrecedesCollection:d?.window_precedes_collection??!1,coverageUnknown:d?.first_seen_unavailable??!1})}})]})]})]})}var ca=require("react/jsx-runtime"),ml=5;function pl({title:e,viewAllLabel:t,onViewAll:a}){return(0,ca.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,ca.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),a&&(0,ca.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:a,children:t})]})}function Kd({refreshKey:e,onBackToWebsite:t,primaryConversion:a,onChangePrimaryConversion:s,onOpenSurface:n,needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l}){let u=Ns({refreshKey:e}),d=(u.summary?.products.count??0)>0||(u.summary?.commerce?.storefront_orders??!1),o=d||(u.summary?.commerce?.invoicing??!1);return(0,ca.jsx)(Lt,{title:"Dashboard",onBackToWebsite:t,children:(0,ca.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,ca.jsx)(Wd,{primaryConversion:a,onChange:s}),(0,ca.jsx)(Gd,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:a}),(0,ca.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ca.jsx)(pl,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),(0,ca.jsx)(Or,{refreshKey:e,maxRows:ml,onViewAll:n&&(()=>n("leads"))})]}),d&&(0,ca.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ca.jsx)(pl,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),(0,ca.jsx)(jn,{refreshKey:e,maxRows:ml,onViewAll:n&&(()=>n("orders"))})]}),o&&(0,ca.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ca.jsx)(pl,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),(0,ca.jsx)(Gn,{refreshKey:e,maxRows:ml,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l})]})]})})}0&&(module.exports={AUDIENCE_PAGE_SIZE,AifeaturesApiError,AifeaturesProvider,AnalyticsView,ContactImport,CustomerDetail,CustomersList,DOUBLE_OPT_IN_HELP,DashboardView,EMAIL_ORG_ACTIONS,EMAIL_READINESS_TEXT,EmailView,ExportCsvButton,FormSettings,FormSubmissions,FormsDashboard,FormsList,IMPORT_ATTESTATION,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,buildEmailOrgRequest,chargedTotal,createApiClient,emailReadinessText,formatPrice,isEmailOrgAction,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useAudience,useBroadcasts,useBusinessSummary,useCsvExport,useCustomers,useEmailDrafts,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSiteSettings,useSubmissions,useSubscriptions});