@aifeatures/admin-react 0.22.0 → 0.23.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 +4 -4
- package/dist/index.d.cts +506 -1
- package/dist/index.d.ts +506 -1
- package/dist/index.js +4 -4
- package/dist/styles.css +1 -1
- package/package.json +14 -13
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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&>>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&>.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 tu=Object.create;var Fr=Object.defineProperty;var au=Object.getOwnPropertyDescriptor;var su=Object.getOwnPropertyNames;var nu=Object.getPrototypeOf,ru=Object.prototype.hasOwnProperty;var iu=(e,t)=>{for(var s in t)Fr(e,s,{get:t[s],enumerable:!0})},$o=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of su(t))!ru.call(e,a)&&a!==s&&Fr(e,a,{get:()=>t[a],enumerable:!(n=au(t,a))||n.enumerable});return e};var ie=(e,t,s)=>(s=e!=null?tu(nu(e)):{},$o(t||!e||!e.__esModule?Fr(s,"default",{value:e,enumerable:!0}):s,e)),ou=e=>$o(Fr({},"__esModule",{value:!0}),e);var Af={};iu(Af,{AUDIENCE_PAGE_SIZE:()=>hn,AifeaturesApiError:()=>Dt,AifeaturesProvider:()=>Wo,AnalyticsView:()=>zc,ContactImport:()=>Rr,CustomerDetail:()=>mr,CustomersList:()=>pr,DOUBLE_OPT_IN_HELP:()=>kr,DashboardView:()=>Qc,EMAIL_ORG_ACTIONS:()=>xi,EMAIL_READINESS_TEXT:()=>bo,EmailView:()=>Ro,ExportCsvButton:()=>Zt,FormSettings:()=>sr,FormSubmissions:()=>Xn,FormsDashboard:()=>zi,FormsList:()=>jn,IMPORT_ATTESTATION:()=>Ri,InvoiceDetail:()=>oi,InvoiceLabelBadge:()=>Tn,InvoiceSettingsPanel:()=>Sr,InvoicesList:()=>Ls,InvoicesView:()=>vo,LeadsView:()=>yr,MAX_ANALYTICS_FILTERS:()=>Js,MAX_ANALYTICS_FILTER_VALUES:()=>Xs,NotificationRecipientsSettings:()=>go,OrderDetail:()=>dr,OrderStatusBadge:()=>Gs,OrdersList:()=>Ds,OrdersView:()=>so,PaymentsDashboard:()=>ao,PaymentsSetup:()=>dn,ProductSettings:()=>or,ProductsList:()=>rr,ProductsView:()=>no,PromosPanel:()=>nn,REALTIME_FAILURES_BEFORE_ERROR:()=>Ci,REALTIME_POLL_MS:()=>Pi,RetainerStatusBadge:()=>ci,RetainersPanel:()=>un,StoreSettings:()=>po,SubmissionDetail:()=>Yn,SubscriptionsView:()=>oo,VariantsEditor:()=>ir,ViewShell:()=>St,WebhookDeliveries:()=>tr,WebhookSettings:()=>ar,buildEmailOrgRequest:()=>bc,chargedTotal:()=>vs,createApiClient:()=>$r,emailReadinessText:()=>yn,formatPrice:()=>Z,isEmailOrgAction:()=>vc,isZeroDecimalCurrency:()=>Fa,toMajorUnits:()=>mt,toMinorUnits:()=>zt,useAifeatures:()=>W,useAifeaturesContext:()=>W,useAnalytics:()=>xn,useAudience:()=>wr,useBroadcasts:()=>_r,useBusinessSummary:()=>pn,useCsvExport:()=>Jn,useCustomers:()=>fr,useEmailDrafts:()=>Pr,useEventDestinations:()=>Qn,useForms:()=>tn,useInvoices:()=>cn,useOrders:()=>lr,usePaymentsStatus:()=>Ts,usePeople:()=>vr,usePerson:()=>br,useProducts:()=>fn,useRealtimeVisitors:()=>Er,useRetainers:()=>mn,useSiteSettings:()=>Os,useSubmissions:()=>Kn,useSubscriptions:()=>hr});module.exports=ou(Af);var zs=ie(require("react"),1);var Ui="aifeatures:analytics:timezone",Mi;function Hn(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function Vo(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function Vs(){return $i()??Hn()}function $i(){if(Mi!==void 0)return Mi;try{let e=window.localStorage.getItem(Ui);return Vo(e)?e:null}catch{return null}}function Vi(e){if(!(e!==null&&!Vo(e))){Mi=e;try{e===null?window.localStorage.removeItem(Ui):window.localStorage.setItem(Ui,e)}catch{}}}function Ur(e,t){let s=new URLSearchParams({period:String(e)}),n=Vs();return n&&s.set("timezone",n),t&&t.length>0&&s.set("filters",JSON.stringify(t)),s.toString()}var Dt=class extends Error{constructor(s,n,a){super(s);this.status=n;this.details=a;this.name="AifeaturesApiError"}};function Mr(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 zn(e,t){let s=t.toString();return s?`${e}?${s}`:e}function Ho(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 zo(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 $r(e,t="https://aifeatures.dev"){async function s(a,r={}){let o=`${t}${a}`,c=await fetch(o,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!c.ok){let d;try{d=await c.json()}catch{}throw new Dt(Mr(d?.error,c.status),c.status,d)}if(c.status!==204)return c.json()}async function n(a){let r=await fetch(`${t}${a}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let o;try{o=await r.json()}catch{}throw new Dt(Mr(o?.error,r.status),r.status,o)}return r.blob()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(a){return s(`/api/v1/forms/${a}`)},async createForm(a){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,r){return s(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(a){await s(`/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 c=o.toString(),d=`/api/v1/forms/${a}/submissions${c?`?${c}`:""}`;return s(d)},async getSubmission(a){return s(`/api/v1/submissions/${a}`)},async exportSubmissionsCsv(a,r={}){let o=new URLSearchParams;return r.includeSpam&&o.set("include_spam","true"),n(zn(`/api/v1/forms/${encodeURIComponent(a)}/submissions/export`,o))},async deleteSubmission(a){await s(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,r){let o=typeof r=="string"?{name:r}:r,c=o.name,d=o.id??o.name,l=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(d)}`,i=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){let u;try{u=await i.json()}catch{}throw new Dt(Mr(u?.error,i.status),i.status,u)}let m=await i.blob(),v=URL.createObjectURL(m),g=document.createElement("a");g.href=v,g.download=c,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(v)},async getSite(a){return s(`/api/v1/sites/${encodeURIComponent(a)}`)},async updateSite(a,r){return s(`/api/v1/sites/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return s("/api/v1/payments/status")},getPromos(a){let r=new URLSearchParams({limit:"10"});return a&&r.set("cursor",a),s(`/api/v1/promos?${r}`)},getPromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return s("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,r){return s(`/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 s(`/api/v1/products${o?`?${o}`:""}`)).products},async getProduct(a){return s(`/api/v1/products/${a}`)},async createProduct(a){return s("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,r){return s(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(a){await s(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,r){let o=new FormData;o.append("file",r);let c=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:o});if(!c.ok){let d;try{d=await c.json()}catch{}throw new Dt(Mr(d?.error,c.status),c.status,d)}return c.json()},async attachProductFileFromUrl(a,r){return s(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(a,r){return s(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(a,r){return s(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(a){await s(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,r){return s(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(a,r){return s(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(a){await s(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,r){return s(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(a,r){return s(`/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 s(`/api/v1/customers${o?`?${o}`:""}`)},async getCustomer(a){return s(`/api/v1/customers/${a}`)},async exportProductsCsv(){return n("/api/v1/products/export")},async exportCustomersCsv(){return n("/api/v1/customers/export")},async getOrders(a={}){let r=Ho(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 s(`/api/v1/orders${o?`?${o}`:""}`)},async exportOrdersCsv(a={}){return n(zn("/api/v1/orders/export",Ho(a)))},async getOrder(a){return s(`/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 s(`/api/v1/invoices${o?`?${o}`:""}`)},async getInvoice(a){return s(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return s(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(a={}){let r=zo(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 s(`/api/v1/retainers${o?`?${o}`:""}`)},async exportRetainersCsv(a={}){return n(zn("/api/v1/retainers/export",zo(a)))},async getRetainer(a){return s(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await s(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return s(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,r){return s(`/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 s(`/api/v1/subscriptions${o?`?${o}`:""}`)},async exportSubscriptionsCsv(a={}){let r=new URLSearchParams;return a.status&&r.set("status",a.status),n(zn("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let a=new URLSearchParams,r=Vs();r&&a.set("timezone",r);let o=a.toString();return s(`/api/v1/analytics/status${o?`?${o}`:""}`)},async getAnalyticsSummary(a,r){return s(`/api/v1/analytics/summary?${Ur(a,r)}`)},async getAnalyticsTimeseries(a,r){return s(`/api/v1/analytics/timeseries?${Ur(a,r)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,r){return s(`/api/v1/analytics/channels?${Ur(a,r)}`)},async getAnalyticsConversions(a){return s((()=>{let r=new URLSearchParams({period:String(a)}),o=Vs();return o&&r.set("timezone",o),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(a,r,o){let c=new URLSearchParams({goal:a,period:String(r)}),d=Vs();return d&&c.set("timezone",d),o!==void 0&&c.set("limit",String(o)),s(`/api/v1/analytics/conversions/targets?${c.toString()}`)},async getAnalyticsBreakdown(a,r,o){let c=a.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${c}?${Ur(r,o)}`)},async getBusinessSummary(a){let r=new URLSearchParams;r.set("tz_offset_minutes",String(a.tzOffsetMinutes));let o=Vs();return o&&r.set("timezone",o),s(`/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 s(`/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),n(zn("/api/v1/people/export",r))},async getPerson(a){return s(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(a){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,r){return s(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(a){await s(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return s(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await s(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,r){let o=r===void 0?"":`?limit=${r}`;return(await s(`/api/v1/event-destinations/${a}/deliveries${o}`)).deliveries},async retryEventDelivery(a,r){return s(`/api/v1/event-destinations/${a}/deliveries/${r}/retry`,{method:"POST"})},async getMarketingSettings(a){return s(`${ns(a)}/marketing`)},async getMarketingContacts(a,r={}){let o=new URLSearchParams;r.q&&o.set("q",r.q),r.limit&&o.set("limit",String(r.limit)),r.offset&&o.set("offset",String(r.offset));let c=o.toString();return s(`${ns(a)}/contacts${c?`?${c}`:""}`)},async getMarketingContactStats(a){return s(`${ns(a)}/contacts/stats`)},async getMarketingTags(a){return(await s(`${ns(a)}/contact-tags`)).tags},async getEmailDrafts(a,r){let o=r?`?kind=${r}`:"";return(await s(`${ns(a)}/marketing/drafts${o}`)).drafts},async getEmailDraft(a,r){return s(`${ns(a)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(a,r){return s(`${ns(a)}/marketing/drafts/${encodeURIComponent(r)}/preview`)},async getBroadcasts(a){return(await s(`${ns(a)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(a,r){return s(`${ns(a)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getWelcomeSequence(a){return s(`${ns(a)}/marketing/welcome`)},async getRecoveryFlow(a){return s(`${ns(a)}/marketing/recovery`)}}}function ns(e){return`/api/v1/sites/${encodeURIComponent(e)}`}var Hs=require("react/jsx-runtime"),qo=zs.createContext(null);function lu(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 Wo({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:s=!1,className:n,children:a}){let r=zs.useMemo(()=>lu(e),[e]),o=zs.useMemo(()=>$r(e,t),[e,t]),c=zs.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return r?(0,Hs.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${n||""}`,children:(0,Hs.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Hs.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Hs.jsx)("p",{className:"af-text-sm af-text-destructive",children:r})]})}):(0,Hs.jsx)(qo.Provider,{value:c,children:(0,Hs.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${n||""}`,children:a})})}function W(){let e=zs.useContext(qo);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var ks=ie(require("react"),1),_n=require("lucide-react");var Vr=ie(require("react"),1),rs=ie(require("@radix-ui/react-tabs"),1);var jo=require("clsx"),Go=require("tailwind-merge"),cu=(0,Go.extendTailwindMerge)({prefix:"af-"});function J(...e){return cu((0,jo.clsx)(e))}var zr=require("react/jsx-runtime"),Hr=rs.Root,qn=Vr.forwardRef(({className:e,...t},s)=>(0,zr.jsx)(rs.List,{ref:s,className:J("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}));qn.displayName=rs.List.displayName;var is=Vr.forwardRef(({className:e,...t},s)=>(0,zr.jsx)(rs.Trigger,{ref:s,className:J("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}));is.displayName=rs.Trigger.displayName;var os=Vr.forwardRef(({className:e,...t},s)=>(0,zr.jsx)(rs.Content,{ref:s,className:J("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}));os.displayName=rs.Content.displayName;var Ko=ie(require("react"),1),Zo=require("@radix-ui/react-slot"),Yo=require("class-variance-authority");var Jo=require("react/jsx-runtime"),uu=(0,Yo.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"}}),x=Ko.forwardRef(({className:e,variant:t,size:s,asChild:n=!1,...a},r)=>(0,Jo.jsx)(n?Zo.Slot:"button",{className:J(uu({variant:t,size:s,className:e})),ref:r,...a}));x.displayName="Button";var Wn=require("lucide-react");var Ps=ie(require("react"),1);var ms=require("react/jsx-runtime"),et=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,ms.jsx)("table",{ref:s,className:J("af-w-full af-caption-bottom af-text-sm",e),...t})}));et.displayName="Table";var tt=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("thead",{ref:s,className:J("[&_tr]:af-border-b",e),...t}));tt.displayName="TableHeader";var at=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("tbody",{ref:s,className:J("[&_tr:last-child]:af-border-0",e),...t}));at.displayName="TableBody";var du=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("tfoot",{ref:s,className:J("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));du.displayName="TableFooter";var Ie=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("tr",{ref:s,className:J("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Ie.displayName="TableRow";var j=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("th",{ref:s,className:J("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=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("td",{ref:s,className:J("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));G.displayName="TableCell";var fu=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("caption",{ref:s,className:J("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));fu.displayName="TableCaption";var ls=ie(require("react"),1);function tn(){let{api:e}=W(),[t,s]=ls.useState([]),[n,a]=ls.useState(!0),[r,o]=ls.useState(null),c=ls.useCallback(async()=>{try{a(!0),o(null);let m=await e.getForms();s(m)}catch(m){o(m instanceof Error?m:new Error("Failed to fetch forms"))}finally{a(!1)}},[e]);ls.useEffect(()=>{c()},[c]);let d=ls.useCallback(async m=>{let v=await e.createForm(m);return s(g=>[...g,v]),v},[e]),l=ls.useCallback(async(m,v)=>{let g=await e.updateForm(m,v);return s(u=>u.map(f=>f.id===m?g:f)),g},[e]),i=ls.useCallback(async m=>{await e.deleteForm(m),s(v=>v.filter(g=>g.id!==m))},[e]);return{forms:t,isLoading:n,error:r,refetch:c,createForm:d,updateForm:l,deleteForm:i}}var ut=require("react/jsx-runtime");function jn({onSelectForm:e,className:t}){let{forms:s,isLoading:n,error:a}=tn();return n?(0,ut.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ut.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):a?(0,ut.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ut.jsxs)("div",{className:"af-text-destructive",children:["Error: ",a.message]})}):s.length===0?(0,ut.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,ut.jsx)(Wn.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ut.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,ut.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,ut.jsx)("div",{className:t,children:(0,ut.jsxs)(et,{children:[(0,ut.jsx)(tt,{children:(0,ut.jsxs)(Ie,{children:[(0,ut.jsx)(j,{children:"Name"}),(0,ut.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,ut.jsx)(at,{children:s.map(r=>(0,ut.jsxs)(Ie,{children:[(0,ut.jsx)(G,{className:"af-font-medium",children:r.name}),(0,ut.jsx)(G,{className:"af-text-right",children:(0,ut.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,ut.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[(0,ut.jsx)(Wn.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,ut.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[(0,ut.jsx)(Wn.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}var el=require("lucide-react");var Xo=require("class-variance-authority");var Qo=require("react/jsx-runtime"),mu=(0,Xo.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 oe({className:e,variant:t,...s}){return(0,Qo.jsx)("div",{className:J(mu({variant:t}),e),...s})}var Ca=require("react/jsx-runtime"),pu={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 qr(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 Hi(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function gu(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 Gn({deliveries:e,label:t="Email needs attention"}){return Hi(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)(el.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function ps({deliveries:e,problemsOnly:t=!1,className:s=""}){let n=(e??[]).filter(a=>!t||Hi([a]));return n.length?(0,Ca.jsx)("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:n.map(a=>{let r=qr(a),o=gu(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:pu[a.kind]??"Email notification"}),(0,Ca.jsx)(oe,{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&&Hi([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 Ws=ie(require("react"),1),Ga=require("lucide-react");var qs=ie(require("react"),1),$e=ie(require("@radix-ui/react-select"),1),an=require("lucide-react");var kt=require("react/jsx-runtime"),qa=$e.Root;var Wa=$e.Value,ka=qs.forwardRef(({className:e,children:t,...s},n)=>(0,kt.jsxs)($e.Trigger,{ref:n,className:J("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[t,(0,kt.jsx)($e.Icon,{asChild:!0,children:(0,kt.jsx)(an.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));ka.displayName=$e.Trigger.displayName;var tl=qs.forwardRef(({className:e,...t},s)=>(0,kt.jsx)($e.ScrollUpButton,{ref:s,className:J("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,kt.jsx)(an.ChevronUp,{className:"af-h-4 af-w-4"})}));tl.displayName=$e.ScrollUpButton.displayName;var al=qs.forwardRef(({className:e,...t},s)=>(0,kt.jsx)($e.ScrollDownButton,{ref:s,className:J("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,kt.jsx)(an.ChevronDown,{className:"af-h-4 af-w-4"})}));al.displayName=$e.ScrollDownButton.displayName;var Ta=qs.forwardRef(({className:e,children:t,position:s="popper",...n},a)=>(0,kt.jsx)($e.Portal,{children:(0,kt.jsxs)($e.Content,{ref:a,className:J("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...n,children:[(0,kt.jsx)(tl,{}),(0,kt.jsx)($e.Viewport,{className:J("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,kt.jsx)(al,{})]})}));Ta.displayName=$e.Content.displayName;var vu=qs.forwardRef(({className:e,...t},s)=>(0,kt.jsx)($e.Label,{ref:s,className:J("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));vu.displayName=$e.Label.displayName;var dt=qs.forwardRef(({className:e,children:t,...s},n)=>(0,kt.jsxs)($e.Item,{ref:n,className:J("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...s,children:[(0,kt.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,kt.jsx)($e.ItemIndicator,{children:(0,kt.jsx)(an.Check,{className:"af-h-4 af-w-4"})})}),(0,kt.jsx)($e.ItemText,{children:t})]}));dt.displayName=$e.Item.displayName;var bu=qs.forwardRef(({className:e,...t},s)=>(0,kt.jsx)($e.Separator,{ref:s,className:J("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));bu.displayName=$e.Separator.displayName;var oa=ie(require("react"),1);function Kn({formId:e,initialPageSize:t=25}){let{api:s}=W(),[n,a]=oa.useState([]),[r,o]=oa.useState(0),[c,d]=oa.useState(!0),[l,i]=oa.useState(null),[m,v]=oa.useState(0),[g,u]=oa.useState(t),f=oa.useRef(0),p=oa.useCallback(async()=>{if(!e)return;let T=++f.current;try{d(!0),i(null);let y={limit:g,offset:m*g},C=await s.getSubmissions(e,y);if(T!==f.current)return;if(C.submissions.length===0&&m>0){v(Math.max(0,Math.ceil(C.total/g)-1));return}a(C.submissions),o(C.total)}catch(y){if(T!==f.current)return;i(y instanceof Error?y:new Error("Failed to fetch submissions"))}finally{T===f.current&&d(!1)}},[s,e,m,g]);oa.useEffect(()=>{p()},[p]);let b=oa.useRef(p);b.current=p;let w=oa.useCallback(async T=>{await s.deleteSubmission(T),b.current()},[s]),P=Math.ceil(r/g);return{submissions:n,total:r,isLoading:c,error:l,page:m,pageSize:g,hasNextPage:m<P-1,hasPreviousPage:m>0,setPage:v,setPageSize:T=>{u(T),v(0)},refetch:p,deleteSubmission:w}}var Wr=ie(require("react"),1),rl=require("lucide-react");var Zn=ie(require("react"),1),Ft=ie(require("@radix-ui/react-dialog"),1),sl=require("lucide-react");var ga=require("react/jsx-runtime"),ja=Ft.Root;var yu=Ft.Portal;var nl=Zn.forwardRef(({className:e,...t},s)=>(0,ga.jsx)(Ft.Overlay,{ref:s,className:J("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));nl.displayName=Ft.Overlay.displayName;var Ea=Zn.forwardRef(({className:e,children:t,...s},n)=>(0,ga.jsx)(yu,{children:(0,ga.jsxs)("div",{className:"aifeatures-admin",children:[(0,ga.jsx)(nl,{}),(0,ga.jsxs)(Ft.Content,{ref:n,className:J("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[t,(0,ga.jsxs)(Ft.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[(0,ga.jsx)(sl.X,{className:"af-h-4 af-w-4"}),(0,ga.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Ea.displayName=Ft.Content.displayName;var Ia=({className:e,...t})=>(0,ga.jsx)("div",{className:J("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Ia.displayName="DialogHeader";var Da=({className:e,...t})=>(0,ga.jsx)("div",{className:J("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Da.displayName="DialogFooter";var Aa=Zn.forwardRef(({className:e,...t},s)=>(0,ga.jsx)(Ft.Title,{ref:s,className:J("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Aa.displayName=Ft.Title.displayName;var La=Zn.forwardRef(({className:e,...t},s)=>(0,ga.jsx)(Ft.Description,{ref:s,className:J("af-text-sm af-text-muted-foreground",e),...t}));La.displayName=Ft.Description.displayName;var Qt=require("react/jsx-runtime");function Nn({onDelete:e,iconOnly:t}){let[s,n]=Wr.useState(!1),[a,r]=Wr.useState(!1),[o,c]=Wr.useState(null);return(0,Qt.jsxs)(Qt.Fragment,{children:[(0,Qt.jsxs)(x,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{c(null),n(!0)},children:[(0,Qt.jsx)(rl.Trash2,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),(0,Qt.jsx)(ja,{open:s,onOpenChange:l=>{!l&&!a&&n(!1)},children:(0,Qt.jsxs)(Ea,{children:[(0,Qt.jsxs)(Ia,{children:[(0,Qt.jsx)(Aa,{children:"Delete this submission?"}),(0,Qt.jsx)(La,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),o&&(0,Qt.jsx)("p",{className:"af-text-sm af-text-destructive",children:o}),(0,Qt.jsxs)(Da,{children:[(0,Qt.jsx)(x,{variant:"outline",onClick:()=>n(!1),disabled:a,children:"Cancel"}),(0,Qt.jsx)(x,{variant:"destructive",onClick:async()=>{r(!0),c(null);try{await e(),n(!1)}catch(l){c(l instanceof Error?l.message:"Failed to delete submission")}finally{r(!1)}},disabled:a,children:a?"Deleting...":"Delete"})]})]})})]})}var ol=ie(require("react"),1),ea=require("lucide-react");var Pe=require("react/jsx-runtime");function il(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function hu(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,n)).toFixed(1))} ${s[n]}`}function Yn({submission:e,onBack:t,onDelete:s}){let{api:n}=W(),[a,r]=ol.useState(null),o=l=>l.id??l.name,c=async l=>{r(o(l));try{await n.downloadAttachment(e.id,l)}catch(i){console.error("Download failed:",i)}finally{r(null)}},d=Object.entries(e.data).filter(([l])=>!l.startsWith("_"));return(0,Pe.jsxs)("div",{children:[(0,Pe.jsxs)("div",{className:"af-mb-6",children:[(0,Pe.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,Pe.jsx)(ea.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,Pe.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Pe.jsxs)("div",{children:[(0,Pe.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,Pe.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",il(e.metadata.submitted_at)]})]}),s&&(0,Pe.jsx)(Nn,{onDelete:s})]})]}),(0,Pe.jsxs)("div",{className:"af-space-y-6",children:[(0,Pe.jsx)(ps,{deliveries:e.email_deliveries}),(0,Pe.jsxs)("div",{children:[(0,Pe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,Pe.jsxs)("div",{className:"af-space-y-3",children:[d.map(([l,i])=>(0,Pe.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,Pe.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:l.replace(/_/g," ")}),(0,Pe.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof i=="string"&&i.includes(`
|
|
3
|
+
`)?(0,Pe.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)),d.length===0&&(0,Pe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,Pe.jsxs)("div",{children:[(0,Pe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,Pe.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((l,i)=>(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Pe.jsx)(ea.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,Pe.jsx)("span",{className:"af-text-sm",children:l.name}),(0,Pe.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",hu(l.size),")"]})]}),(0,Pe.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>c(l),disabled:a===o(l),children:[a===o(l)?(0,Pe.jsx)(ea.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Pe.jsx)(ea.Download,{className:"af-h-4 af-w-4 af-mr-1"}),a===o(l)?"Downloading...":"Download"]})]},i))})]}),(0,Pe.jsxs)("div",{children:[(0,Pe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,Pe.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Pe.jsx)(ea.Clock,{className:"af-h-4 af-w-4"}),(0,Pe.jsx)("span",{children:il(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Pe.jsx)(ea.Globe,{className:"af-h-4 af-w-4"}),(0,Pe.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,Pe.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,Pe.jsx)(ea.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,Pe.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Pe.jsx)(ea.Mail,{className:"af-h-4 af-w-4"}),(0,Pe.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var cl=require("lucide-react");var sn=ie(require("react"),1);var xu=/^\+[1-9]\d{1,14}$/;function ll(e){let t=e==null?"":String(e),s=!xu.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),n=s?`'${t}`:t;return s||/[",;\r\n]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function jr(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function Gr(e,t){if(typeof document>"u")return;let s=URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}function Jn({fetchCsv:e,filename:t}){let[s,n]=sn.useState(!1),[a,r]=sn.useState(null),o=sn.useRef(!1);return{exportCsv:sn.useCallback(async()=>{if(!o.current){o.current=!0,n(!0),r(null);try{let d=await e();Gr(d,jr(t))}catch(d){r(d instanceof Error?d:new Error("Export failed"))}finally{o.current=!1,n(!1)}}},[e,t]),exporting:s,error:a}}var Rn=require("react/jsx-runtime");function Zt({fetchCsv:e,filename:t,label:s="Export CSV",disabled:n,className:a}){let{exportCsv:r,exporting:o,error:c}=Jn({fetchCsv:e,filename:t});return(0,Rn.jsxs)("span",{className:a,children:[(0,Rn.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:n||o,"aria-busy":o,children:[(0,Rn.jsx)(cl.Download,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Exporting\u2026":s]}),c&&(0,Rn.jsx)("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}var be=require("react/jsx-runtime");function Su(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function wu(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let s of t)if(typeof e[s]=="string")return e[s];return null}var Nu=["message","comments","comment","inquiry","question","details","body","notes"];function Ru(e){let t=Object.entries(e).filter(([r,o])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),s=new Map(t.map(([r,o])=>[r.toLowerCase(),o])),a=(Nu.map(r=>s.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 Xn({formId:e,className:t,defaultSubmissionId:s,submissionId:n,onSelectSubmission:a}){let{api:r}=W(),{submissions:o,total:c,isLoading:d,error:l,page:i,pageSize:m,hasNextPage:v,hasPreviousPage:g,setPage:u,setPageSize:f,deleteSubmission:p}=Kn({formId:e}),b=Ws.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[w,P]=Ws.useState(s??null),T=a?n??null:w,y=a??P,C=z=>!!z&&z.id===T&&z.form_id===e,k=o.find(C),[I,N]=Ws.useState(null),E=C(I)?I:null,[D,_]=Ws.useState(null);if(Ws.useEffect(()=>{if(_(null),!T||k||E)return;let z=!1;return r.getSubmission(T).then(le=>{if(!z){if(le.form_id!==e){_("This submission could not be found.");return}N(le)}}).catch(()=>{z||_("This submission could not be found.")}),()=>{z=!0}},[r,e,T,k,E]),T){let z=k??E;return z?(0,be.jsx)("div",{className:t,children:(0,be.jsx)(Yn,{submission:z,onBack:()=>y(null),onDelete:async()=>{await p(z.id),y(null)}})}):D?(0,be.jsxs)("div",{className:t,children:[(0,be.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>y(null),className:"af-mb-2 af--ml-2",children:[(0,be.jsx)(Ga.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,be.jsx)("p",{className:"af-text-sm af-text-destructive",children:D})]}):(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(d)return(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(l)return(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,be.jsxs)("div",{className:"af-text-destructive",children:["Error: ",l.message]})});if(o.length===0&&i===0)return(0,be.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,be.jsx)(Ga.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,be.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,be.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let Y=i*m+1,Q=Math.min((i+1)*m,c);return(0,be.jsxs)("div",{className:t,children:[(0,be.jsx)("div",{className:"af-mb-2 af-flex af-justify-end",children:(0,be.jsx)(Zt,{fetchCsv:b,filename:"submissions"})}),(0,be.jsxs)(et,{children:[(0,be.jsx)(tt,{children:(0,be.jsxs)(Ie,{children:[(0,be.jsx)(j,{children:"Email"}),(0,be.jsx)(j,{children:"Preview"}),(0,be.jsx)(j,{children:"Date"}),(0,be.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,be.jsx)(at,{children:o.map(z=>{let le=wu(z.data),fe=Ru(z.data);return(0,be.jsxs)(Ie,{children:[(0,be.jsxs)(G,{className:"af-font-medium",children:[(0,be.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[le||(0,be.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),z.attachments.length>0&&(0,be.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${z.attachments.length} attachment(s)`,children:[(0,be.jsx)(Ga.Paperclip,{className:"af-h-3 af-w-3"}),(0,be.jsx)("span",{className:"af-text-xs",children:z.attachments.length})]})]}),(0,be.jsx)(Gn,{deliveries:z.email_deliveries,label:"Notification email needs attention"})]}),(0,be.jsx)(G,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:fe||(0,be.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,be.jsx)(G,{className:"af-text-muted-foreground",children:Su(z.metadata.submitted_at)}),(0,be.jsxs)(G,{className:"af-text-right",children:[(0,be.jsx)(x,{variant:"ghost",size:"icon",onClick:()=>y(z.id),title:"View details",children:(0,be.jsx)(Ga.Eye,{className:"af-h-4 af-w-4"})}),(0,be.jsx)(Nn,{iconOnly:!0,onDelete:()=>p(z.id)})]})]},z.id)})})]}),(0,be.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,be.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,be.jsxs)("span",{children:["Showing ",Y,"-",Q," of ",c]}),(0,be.jsxs)(qa,{value:String(m),onValueChange:z=>f(Number(z)),children:[(0,be.jsx)(ka,{className:"af-w-[70px] af-h-8",children:(0,be.jsx)(Wa,{})}),(0,be.jsxs)(Ta,{children:[(0,be.jsx)(dt,{value:"10",children:"10"}),(0,be.jsx)(dt,{value:"25",children:"25"}),(0,be.jsx)(dt,{value:"50",children:"50"}),(0,be.jsx)(dt,{value:"100",children:"100"})]})]}),(0,be.jsx)("span",{children:"per page"})]}),(0,be.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,be.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>u(i-1),disabled:!g,children:[(0,be.jsx)(Ga.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,be.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>u(i+1),disabled:!v,children:["Next",(0,be.jsx)(Ga.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ba=ie(require("react"),1),js=require("lucide-react");var ul=ie(require("react"),1);var dl=require("react/jsx-runtime"),re=ul.forwardRef(({className:e,type:t,...s},n)=>(0,dl.jsx)("input",{type:t,className:J("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:n,...s}));re.displayName="Input";var fl=ie(require("react"),1),ml=require("class-variance-authority");var pl=require("react/jsx-runtime"),_u=(0,ml.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Oe=fl.forwardRef(({className:e,...t},s)=>(0,pl.jsx)("label",{ref:s,className:J(_u(),e),...t}));Oe.displayName="Label";var Ka=ie(require("react"),1),ta=require("lucide-react");var Oa=ie(require("react"),1);function Qn(){let{api:e}=W(),[t,s]=Oa.useState([]),[n,a]=Oa.useState(!0),[r,o]=Oa.useState(null),c=Oa.useCallback(async()=>{try{a(!0),o(null),s(await e.getEventDestinations())}catch(g){o(g instanceof Error?g:new Error("Failed to fetch webhooks"))}finally{a(!1)}},[e]);Oa.useEffect(()=>{c()},[c]);let d=Oa.useCallback(async g=>{let u=await e.createEventDestination(g);return s(f=>[u,...f]),u},[e]),l=Oa.useCallback(async(g,u)=>{let f=await e.updateEventDestination(g,u);return s(p=>p.map(b=>b.id===g?f:b)),f},[e]),i=Oa.useCallback(async g=>{await e.deleteEventDestination(g),s(u=>u.filter(f=>f.id!==g))},[e]),m=Oa.useCallback(async g=>{let u=await e.rotateEventDestinationSecret(g);return s(f=>f.map(p=>p.id===g?u:p)),u},[e]),v=Oa.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:n,error:r,refetch:c,createDestination:d,updateDestination:l,deleteDestination:i,rotateSecret:m,getSecret:v}}var Cs=ie(require("react"),1),er=require("lucide-react");var Ut=require("react/jsx-runtime");function tr({destinationId:e,limit:t=25,className:s}){let{api:n}=W(),[a,r]=Cs.useState([]),[o,c]=Cs.useState(!0),[d,l]=Cs.useState(null),[i,m]=Cs.useState(null),v=Cs.useCallback(async()=>{try{c(!0),l(null),r(await n.getEventDeliveries(e,t))}catch(u){l(u instanceof Error?u.message:"Failed to load deliveries")}finally{c(!1)}},[n,e,t]);Cs.useEffect(()=>{v()},[v]);let g=async u=>{try{m(u.id),l(null);let f=await n.retryEventDelivery(e,u.id);r(p=>p.map(b=>b.id===u.id?f:b))}catch(f){l(f instanceof Error?f.message:"Retry failed")}finally{m(null)}};return o?(0,Ut.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,Ut.jsx)(er.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):d?(0,Ut.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:d}):a.length===0?(0,Ut.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,Ut.jsx)("div",{className:s,children:(0,Ut.jsx)("div",{className:"af-divide-y af-border af-rounded",children:a.map(u=>{let f=u.delivered_at!==null;return(0,Ut.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,Ut.jsxs)("div",{className:"af-min-w-0",children:[(0,Ut.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[f?(0,Ut.jsx)(oe,{variant:"secondary",children:u.last_status??200}):(0,Ut.jsx)(oe,{variant:"destructive",children:u.last_status??"failed"}),(0,Ut.jsx)("span",{className:"af-text-sm af-truncate",children:u.type})]}),(0,Ut.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[u.event_id," \xB7 ",u.created_at,u.attempts>0&&` \xB7 ${u.attempts} failed ${u.attempts===1?"attempt":"attempts"}`]}),!f&&u.last_error&&(0,Ut.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),(0,Ut.jsx)(x,{variant:"ghost",size:"sm",title:"Send this event again",disabled:i===u.id,onClick:()=>g(u),children:i===u.id?(0,Ut.jsx)(er.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ut.jsx)(er.RotateCw,{className:"af-h-4 af-w-4"})})]},u.id)})})})}var Se=require("react/jsx-runtime");function ar({formId:e,topics:t,description:s,className:n}){let{destinations:a,isLoading:r,error:o,createDestination:c,updateDestination:d,deleteDestination:l,rotateSecret:i,getSecret:m}=Qn(),[v,g]=Ka.useState(""),[u,f]=Ka.useState(!1),[p,b]=Ka.useState(null),[w,P]=Ka.useState(null),[T,y]=Ka.useState(null),[C,k]=Ka.useState(!1),[I,N]=Ka.useState(null),[E,D]=Ka.useState(null),[_,Y]=Ka.useState(null),Q=Ka.useMemo(()=>a.filter(U=>U.form_id===e),[a,e]),z=async()=>{let U=v.trim();if(U){if(!U.startsWith("https://")){b("Webhook URLs must start with https://");return}try{f(!0),b(null),await c({url:U,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(ve){b(ve instanceof Error?ve.message:"Failed to add webhook")}finally{f(!1)}}},le=async U=>{try{D(U.id),b(null),await i(U.id),k(!1),y(await m(U.id))}catch(ve){b(ve instanceof Error?ve.message:"Failed to rotate secret")}finally{D(null)}},fe=async U=>{try{D(U.id),b(null),await d(U.id,{status:"active"})}catch(ve){b(ve instanceof Error?ve.message:"Failed to re-enable")}finally{D(null)}},he=async()=>{if(I)try{D(I.id),await l(I.id),N(null)}catch(U){b(U instanceof Error?U.message:"Failed to delete")}finally{D(null)}},M=async U=>{if(w===U.id){P(null),y(null);return}try{D(U.id),b(null),k(!1),P(U.id),y(await m(U.id))}catch(ve){P(null),b(ve instanceof Error?ve.message:"Failed to read secret")}finally{D(null)}},ee=async()=>{if(T)try{await navigator.clipboard.writeText(T),k(!0)}catch{}};return(0,Se.jsxs)("div",{className:n,children:[(0,Se.jsxs)("div",{className:"af-space-y-1",children:[(0,Se.jsx)(Oe,{children:"Webhooks"}),(0,Se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:s??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),(0,Se.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,Se.jsx)(re,{value:v,placeholder:"https://hooks.zapier.com/...",onChange:U=>g(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),z())},disabled:u}),(0,Se.jsxs)(x,{onClick:z,disabled:u||!v.trim(),children:[u?(0,Se.jsx)(ta.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Se.jsx)(ta.Plus,{className:"af-h-4 af-w-4"}),(0,Se.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(p||o)&&(0,Se.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:p||o?.message}),(0,Se.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[r&&(0,Se.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Se.jsx)(ta.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&Q.length===0&&(0,Se.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(U=>(0,Se.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,Se.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Se.jsxs)("div",{className:"af-min-w-0",children:[(0,Se.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Se.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:U.url}),U.status==="disabled"?(0,Se.jsx)(oe,{variant:"destructive",children:"Disabled"}):(0,Se.jsx)(oe,{variant:"secondary",children:"Active"})]}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:U.topics.includes("*")?"All events":U.topics.join(", ")})]}),(0,Se.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,Se.jsx)(x,{variant:"ghost",size:"sm",onClick:()=>Y(_===U.id?null:U.id),children:_===U.id?"Hide log":"Deliveries"}),(0,Se.jsx)(x,{variant:"ghost",size:"sm",onClick:()=>M(U),disabled:E===U.id,children:w===U.id?"Hide secret":"Show secret"}),(0,Se.jsx)(x,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:E===U.id,onClick:()=>N(U),children:(0,Se.jsx)(ta.Trash2,{className:"af-h-4 af-w-4"})})]})]}),U.status==="disabled"&&(0,Se.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,Se.jsx)(ta.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,Se.jsxs)("div",{className:"af-text-sm",children:[(0,Se.jsxs)("p",{children:["We stopped sending after repeated failures."," ",U.disabled_reason]}),(0,Se.jsx)(x,{variant:"outline",size:"sm",className:"af-mt-2",disabled:E===U.id,onClick:()=>fe(U),children:"Re-enable"})]})]}),w===U.id&&T&&(0,Se.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,Se.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,Se.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Se.jsx)(re,{readOnly:!0,value:T,className:"af-font-mono"}),(0,Se.jsx)(x,{variant:"outline",title:"Copy signing secret",onClick:ee,children:C?(0,Se.jsx)(ta.Check,{className:"af-h-4 af-w-4"}):(0,Se.jsx)(ta.Copy,{className:"af-h-4 af-w-4"})}),(0,Se.jsx)(x,{variant:"outline",title:"Rotate signing secret",disabled:E===U.id,onClick:()=>le(U),children:E===U.id?(0,Se.jsx)(ta.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Se.jsx)(ta.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),_===U.id&&(0,Se.jsx)(tr,{destinationId:U.id})]},U.id))]}),(0,Se.jsx)(ja,{open:!!I,onOpenChange:U=>{!U&&!E&&N(null)},children:(0,Se.jsxs)(Ea,{children:[(0,Se.jsxs)(Ia,{children:[(0,Se.jsx)(Aa,{children:"Delete this webhook?"}),(0,Se.jsxs)(La,{children:["New submissions will stop being sent to ",I?.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,Se.jsxs)(Da,{children:[(0,Se.jsx)(x,{variant:"outline",onClick:()=>N(null),disabled:!!E,children:"Cancel"}),(0,Se.jsx)(x,{variant:"destructive",onClick:he,disabled:!!E,children:E?"Deleting...":"Delete"})]})]})})]})}var Le=require("react/jsx-runtime");function sr({form:e,onSaved:t,className:s}){let{updateForm:n}=tn(),[a,r]=Ba.useState(!1),[o,c]=Ba.useState(null),[d,l]=Ba.useState(null),[i,m]=Ba.useState(e.name),[v,g]=Ba.useState(e.redirect_url||""),[u,f]=Ba.useState(e.email_recipients),[p,b]=Ba.useState("");Ba.useEffect(()=>{m(e.name),g(e.redirect_url||""),f(e.email_recipients),l(null)},[e]);let w=Ba.useCallback(async k=>{try{r(!0),l(null);let I=await n(e.id,k);c(new Date),t?.(I)}catch(I){l(I instanceof Error?I.message:"Failed to save")}finally{r(!1)}},[e.id,n,t]);Ba.useEffect(()=>{if(o){let k=setTimeout(()=>c(null),2e3);return()=>clearTimeout(k)}},[o]);let P=async()=>{let k=p.trim().toLowerCase();if(!k)return;if(!k.includes("@")){l("Please enter a valid email address");return}if(u.includes(k)){l("This email is already added");return}let I=[...u,k];f(I),b(""),l(null),await w({email_recipients:I})},T=async k=>{let I=u.filter(N=>N!==k);f(I),await w({email_recipients:I})},y=async()=>{i!==e.name&&await w({name:i})},C=async()=>{let k=v||null;k!==e.redirect_url&&await w({redirect_url:k})};return(0,Le.jsxs)("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(a||o)&&(0,Le.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:a?(0,Le.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,Le.jsx)(js.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,Le.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,Le.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,Le.jsx)(js.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,Le.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{htmlFor:"form-name",children:"Form Name"}),(0,Le.jsx)(re,{id:"form-name",value:i,onChange:k=>m(k.target.value),onBlur:y,placeholder:"Contact Form"}),(0,Le.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{children:"Email Recipients"}),(0,Le.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,Le.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(k=>(0,Le.jsxs)(oe,{variant:"secondary",className:"af-gap-1",children:[k,(0,Le.jsx)("button",{type:"button",onClick:()=>T(k),className:"af-ml-1 hover:af-text-destructive",disabled:a,children:(0,Le.jsx)(js.X,{className:"af-h-3 af-w-3"})})]},k)),u.length===0&&(0,Le.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,Le.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Le.jsx)(re,{type:"email",value:p,onChange:k=>b(k.target.value),placeholder:"Add email address",onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),P())},disabled:a}),(0,Le.jsx)(x,{type:"button",variant:"outline",onClick:P,disabled:!p.trim()||a,children:(0,Le.jsx)(js.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,Le.jsx)(re,{id:"redirect-url",value:v,onChange:k=>g(k.target.value),onBlur:C,placeholder:"/thank-you"}),(0,Le.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,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{children:"Form Endpoint"}),(0,Le.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Le.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,Le.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{children:"Captcha Protection"}),(0,Le.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Le.jsx)(oe,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,Le.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,Le.jsx)(ar,{formId:e.id}),d&&(0,Le.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})]})}var it=require("react/jsx-runtime");function zi({className:e,location:t,onNavigate:s,submissionId:n}){let{api:a}=W(),[r,o]=ks.useState({submissionId:n});ks.useEffect(()=>{n&&o({submissionId:n})},[n]);let c=s?t??{}:r,d=s??o,[l,i]=ks.useState(null),m=`${c.formId??""}|${c.submissionId??""}`,[v,g]=ks.useState(null),u=v?.key===m?v.message:null,f=c.formId??(l&&l.submissionId===c.submissionId?l.formId:void 0);ks.useEffect(()=>{let k=c.submissionId;if(!k||c.formId)return;let I=!1;return a.getSubmission(k).then(N=>{I||(g(null),i({submissionId:k,formId:N.form_id}))}).catch(()=>{I||g({key:m,message:"This submission could not be found."})}),()=>{I=!0}},[a,c.submissionId,c.formId,m]);let[p,b]=ks.useState(null);ks.useEffect(()=>{if(!f||p?.id===f)return;let k=!1;return a.getForm(f).then(I=>{k||(g(null),b(I))}).catch(()=>{k||g({key:m,message:"This form could not be found."})}),()=>{k=!0}},[a,f,p?.id,m]);let w=(k,I)=>{b(k),d({formId:k.id,tab:I})},P=()=>d({});if(!c.formId&&!c.submissionId)return(0,it.jsxs)("div",{className:e,children:[(0,it.jsxs)("div",{className:"af-mb-6",children:[(0,it.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,it.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,it.jsx)(jn,{onSelectForm:w})]});let y=(0,it.jsxs)(x,{variant:"ghost",size:"sm",onClick:P,className:"af-mb-2 af--ml-2",children:[(0,it.jsx)(_n.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(u)return(0,it.jsxs)("div",{className:e,children:[y,(0,it.jsx)("p",{className:"af-text-sm af-text-destructive",children:u})]});if(!f||p?.id!==f)return(0,it.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,it.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let C=c.submissionId?"submissions":c.tab??"submissions";return(0,it.jsxs)("div",{className:e,children:[(0,it.jsxs)("div",{className:"af-mb-6",children:[y,(0,it.jsx)("h2",{className:"af-text-lg af-font-semibold",children:p.name})]}),(0,it.jsxs)(Hr,{value:C,onValueChange:k=>d({formId:f,tab:k}),children:[(0,it.jsxs)(qn,{className:"af-mb-4",children:[(0,it.jsxs)(is,{value:"submissions",className:"af-gap-2",children:[(0,it.jsx)(_n.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,it.jsxs)(is,{value:"settings",className:"af-gap-2",children:[(0,it.jsx)(_n.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,it.jsx)(os,{value:"submissions",children:(0,it.jsx)(Xn,{formId:f,submissionId:c.submissionId,onSelectSubmission:k=>d({formId:f,tab:"submissions",submissionId:k??void 0})})}),(0,it.jsx)(os,{value:"settings",children:(0,it.jsx)(sr,{form:p,onSaved:b})})]})]})}var Xe=ie(require("react"),1);var gs=ie(require("react"),1);function Ts(){let{api:e}=W(),[t,s]=gs.useState(null),[n,a]=gs.useState(!0),[r,o]=gs.useState(null),c=gs.useRef(0),d=gs.useCallback(async()=>{let l=++c.current;try{a(!0),o(null);let i=await e.getPaymentsStatus();if(l!==c.current)return;s(i)}catch(i){if(l!==c.current)return;o(i instanceof Error?i:new Error("Failed to fetch payments status"))}finally{l===c.current&&a(!1)}},[e]);return gs.useEffect(()=>{d()},[d]),{status:t,isLoading:n,error:r,refetch:d}}var Pu=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Fa(e){return Pu.has(e.toLowerCase())}function Z(e,t,s){let n=Fa(t)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:t.toUpperCase()}).format(n)}catch{return`${n} ${t.toUpperCase()}`}}function vs(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 zt(e,t){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let n=Fa(t)?s:s*100;return Math.round(n)}function mt(e,t){return Fa(t)?e:e/100}function Kr(e){return e.amount_paid??Math.max(0,vs(e)-(e.credit_applied??0))}var ge=require("react/jsx-runtime");function nr(e){return e instanceof Dt&&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 gl(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${Z(e.amount_off,e.currency)} off`:"Discount unavailable"}function nn(){let{api:e,siteToken:t}=W();return(0,ge.jsx)(Cu,{api:e},t)}function Cu({api:e}){let{status:t,error:s}=Ts(),[n,a]=Xe.useState([]),[r,o]=Xe.useState(null),[c,d]=Xe.useState(null),[l,i]=Xe.useState(!1),[m,v]=Xe.useState(!1),[g,u]=Xe.useState(""),[f,p]=Xe.useState(null),[b,w]=Xe.useState(null),[P,T]=Xe.useState(!1),y=Xe.useRef(0),C=Xe.useCallback(async N=>{let E=++y.current;i(!0),u("");try{let D=await e.getPromos(N);if(E!==y.current)return;a(_=>N?[..._,...D.promos.filter(Y=>!_.some(Q=>Q.id===Y.id))]:D.promos),o(D.next_cursor),d(D.checkout_enabled)}catch(D){E===y.current&&u(nr(D))}finally{E===y.current&&i(!1)}},[e]);Xe.useEffect(()=>(C(),()=>{y.current++}),[C]);async function k(N){let E=++y.current;i(!0),u(""),T(!1);try{let D=await e.getPromo(N);E===y.current&&p(D)}catch(D){E===y.current&&u(nr(D))}finally{E===y.current&&i(!1)}}async function I(){if(f){v(!0),i(!0),u("");try{let N=await e.disablePromo(f.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.");T(!1),await C()}catch(N){u(nr(N))}finally{v(!1),i(!1)}}}return b?(0,ge.jsx)(ku,{currency:t?.currency??void 0,replaces:b.replaces,onCancel:()=>w(null),onSave:async N=>{let E=b.replaces?await e.replacePromo(b.replaces.id,N):await e.createPromo(N),D=await e.getPromo(E.id);if(D.status==="pending"||D.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(D),w(null),await C()}}):(0,ge.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,ge.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,ge.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,ge.jsx)(x,{disabled:l||!t?.currency,onClick:()=>{u(""),w({})},children:"Create promo code"})]}),(0,ge.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."}),c===!1&&(0,ge.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,ge.jsx)("p",{className:"af-text-sm",children:s?nr(s):"Connect Stripe and set the payment currency before creating codes."}),g&&(0,ge.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",(0,ge.jsx)(x,{variant:"outline",disabled:l,onClick:()=>f?void k(f.id):void C(),children:"Refresh"})]}),f?(0,ge.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,ge.jsx)(x,{variant:"ghost",disabled:m,onClick:()=>{p(null),T(!1),C()},children:"Back to codes"}),(0,ge.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[f.code," \xB7 ",f.name]}),(0,ge.jsxs)("p",{children:[gl(f)," \xB7 ",f.status]}),(0,ge.jsxs)("p",{className:"af-text-sm",children:[f.times_redeemed==null?"Usage unavailable":`${f.times_redeemed} redemptions`,f.max_redemptions!=null?` / ${f.max_redemptions} maximum`:""]}),(0,ge.jsxs)("p",{className:"af-text-sm",children:[f.minimum_amount!=null&&f.currency?`Minimum order: ${Z(f.minimum_amount,f.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,ge.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",f.duration==="repeating"?`${f.duration_in_months} months`:f.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,ge.jsx)("p",{className:"af-text-sm",children:f.expires_at?`Expires ${new Date(f.expires_at).toLocaleString()}`:"No expiry"}),(0,ge.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ge.jsx)(x,{variant:"outline",disabled:l,onClick:()=>void k(f.id),children:"Refresh details"}),(0,ge.jsx)(x,{variant:"outline",disabled:l||f.status==="pending"||f.status==="unavailable"||!t?.currency,onClick:()=>w({replaces:f}),children:"Replace with new code"}),(0,ge.jsx)(x,{variant:"outline",disabled:l||!["active","pending","unavailable"].includes(f.status),onClick:()=>T(!0),children:f.status==="pending"?"Cancel pending offer":"Disable code"})]}),P&&(0,ge.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,ge.jsxs)("p",{className:"af-text-sm",children:[f.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${f.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,ge.jsx)(x,{disabled:l,onClick:()=>void I(),children:f.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,ge.jsx)(x,{variant:"ghost",disabled:l,onClick:()=>T(!1),children:"Cancel"})]})]}):(0,ge.jsxs)(ge.Fragment,{children:[n.map(N=>(0,ge.jsxs)("button",{type:"button",disabled:l,onClick:()=>void k(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,ge.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,ge.jsx)("span",{className:"af-font-semibold af-break-all",children:N.code}),(0,ge.jsx)("span",{className:"af-text-sm",children:N.status})]}),(0,ge.jsxs)("div",{className:"af-text-sm",children:[gl(N)," \xB7"," ",N.times_redeemed==null?"Usage unavailable":`${N.times_redeemed} redemptions`]})]},N.id)),!l&&!g&&n.length===0&&(0,ge.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,ge.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),r&&(0,ge.jsx)(x,{variant:"outline",disabled:l,onClick:()=>void C(r),children:"Load more"})]})]})}function ku({currency:e,replaces:t,onCancel:s,onSave:n}){let[a,r]=Xe.useState(""),[o,c]=Xe.useState(t?.name??""),[d,l]=Xe.useState(t?.amount_off!=null?"fixed":"percent"),[i,m]=Xe.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(mt(t.amount_off,e)):"")),[v,g]=Xe.useState(t?.minimum_amount!=null&&e?String(mt(t.minimum_amount,e)):""),[u,f]=Xe.useState(()=>{if(!t?.expires_at)return"";let fe=new Date(t.expires_at);return Number.isFinite(fe.getTime())?new Date(fe.getTime()-fe.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,b]=Xe.useState(t?.max_redemptions?.toString()??""),[w,P]=Xe.useState(t?.duration??"once"),[T,y]=Xe.useState(t?.duration_in_months?.toString()??"3"),[C,k]=Xe.useState(null),[I,N]=Xe.useState(!1),[E,D]=Xe.useState(""),_=Xe.useRef(!1),Y=e&&Fa(e)?"1":"0.01";async function Q(fe){if(fe.preventDefault(),_.current)return;D("");let he=C;if(!he){if(!e){D("Payment currency is not available.");return}if(t&&a.trim().toUpperCase()===t.code.toUpperCase()){D("Choose a different code for the replacement.");return}let M=zt(i,e),ee=v?zt(v,e):null;if(d==="fixed"&&(!M||M>999999999999)||v&&(!ee||ee>999999999999)){D("Enter a positive amount within the supported range.");return}if(u&&new Date(u).getTime()<=Date.now()){D("Choose a future expiry.");return}he={request_id:crypto.randomUUID(),code:a.trim().toUpperCase(),name:o.trim(),duration:w,...d==="percent"?{percent_off:Number(i)}:{amount_off:M,currency:e},...v?{minimum_amount:ee,currency:e}:{},...u?{expires_at:new Date(u).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...w==="repeating"?{duration_in_months:Number(T)}:{}},k(he)}_.current=!0,N(!0);try{await n(he)}catch(M){D(nr(M)),M instanceof Dt&&M.status>=400&&M.status<500&&M.details?.retryable!==!0&&k(null)}finally{_.current=!1,N(!1)}}let z=(fe,he,M,ee={})=>(0,ge.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[fe,(0,ge.jsx)(re,{"aria-label":fe,value:he,onChange:U=>M(U.target.value),...ee})]}),le="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,ge.jsxs)("form",{onSubmit:Q,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,ge.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,ge.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,ge.jsxs)("fieldset",{disabled:I||!!C,className:"af-grid af-gap-4",children:[z("Code",a,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),z("Name",o,c,{required:!0,maxLength:40}),(0,ge.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,ge.jsxs)("select",{"aria-label":"Discount type",className:le,value:d,onChange:fe=>l(fe.target.value),children:[(0,ge.jsx)("option",{value:"percent",children:"Percentage"}),(0,ge.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),z("Discount",i,m,{type:"number",required:!0,min:d==="percent"?"0.01":Y,max:d==="percent"?"100":void 0,step:d==="percent"?"0.01":Y}),z("Minimum order amount",v,g,{type:"number",min:Y,step:Y,placeholder:e?.toUpperCase()}),(0,ge.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."]}),z("Expires at (local time)",u,f,{type:"datetime-local",step:1}),z("Maximum redemptions",p,b,{type:"number",min:1,max:1e6,step:1}),(0,ge.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,ge.jsxs)("select",{"aria-label":"Subscription duration",className:le,value:w,onChange:fe=>P(fe.target.value),children:[(0,ge.jsx)("option",{value:"once",children:"First invoice only"}),(0,ge.jsx)("option",{value:"forever",children:"Every invoice"}),(0,ge.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),w==="repeating"&&z("Months",T,y,{type:"number",required:!0,min:1,max:36,step:1})]}),E&&(0,ge.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:E}),C&&!I&&(0,ge.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,ge.jsx)("span",{className:"af-break-all",children:C.request_id})]}),(0,ge.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ge.jsx)(x,{type:"submit",disabled:I,children:I?"Saving\u2026":C?"Retry same request":t?"Create replacement":"Create code"}),(0,ge.jsx)(x,{type:"button",variant:"ghost",disabled:I||!!C,onClick:s,children:"Cancel"})]})]})}var En=ie(require("react"),1),Xa=require("lucide-react");var Zr=ie(require("react"),1),Es=require("lucide-react");var Te=require("react/jsx-runtime");function Tu(e){if(e.allow_custom_amount){let t=e.min_amount!==null?Z(e.min_amount,e.currency):"?",s=e.max_amount!==null?Z(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${s})`}return e.unit_amount===null?"Varies by variant":Z(e.unit_amount,e.currency)}function Eu(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function rr({productsState:e,onSelectProduct:t,onCreateProduct:s,className:n}){let{products:a,isLoading:r,error:o,deleteProduct:c}=e,[d,l]=Zr.useState(null),[i,m]=Zr.useState(!1),[v,g]=Zr.useState(null),u=async()=>{if(d)try{m(!0),g(null),await c(d.id),l(null)}catch(f){g(f instanceof Error?f.message:"Failed to delete product")}finally{m(!1)}};return r?(0,Te.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:(0,Te.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,Te.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:(0,Te.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):a.length===0?(0,Te.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${n||""}`,children:[(0,Te.jsx)(Es.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Te.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,Te.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,Te.jsxs)(x,{variant:"outline",onClick:()=>s?.(),children:[(0,Te.jsx)(Es.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,Te.jsxs)("div",{className:n,children:[(0,Te.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,Te.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[(0,Te.jsx)(Es.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,Te.jsxs)(et,{children:[(0,Te.jsx)(tt,{children:(0,Te.jsxs)(Ie,{children:[(0,Te.jsx)(j,{children:"Name"}),(0,Te.jsx)(j,{children:"Price"}),(0,Te.jsx)(j,{children:"Fulfillment"}),(0,Te.jsx)(j,{children:"Status"}),(0,Te.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,Te.jsx)(at,{children:a.map(f=>(0,Te.jsxs)(Ie,{children:[(0,Te.jsx)(G,{className:"af-font-medium",children:f.name}),(0,Te.jsx)(G,{children:Tu(f)}),(0,Te.jsx)(G,{className:"af-text-muted-foreground",children:Eu(f)}),(0,Te.jsx)(G,{children:(0,Te.jsx)(oe,{variant:f.active?"success":"secondary",children:f.active?"Active":"Inactive"})}),(0,Te.jsx)(G,{className:"af-text-right",children:(0,Te.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Te.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>t?.(f),children:[(0,Te.jsx)(Es.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,Te.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>{g(null),l(f)},children:[(0,Te.jsx)(Es.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},f.id))})]}),(0,Te.jsx)(ja,{open:!!d,onOpenChange:f=>{!f&&!i&&l(null)},children:(0,Te.jsxs)(Ea,{children:[(0,Te.jsxs)(Ia,{children:[(0,Te.jsx)(Aa,{children:"Delete product?"}),(0,Te.jsxs)(La,{children:['"',d?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),v&&(0,Te.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),(0,Te.jsxs)(Da,{children:[(0,Te.jsx)(x,{variant:"outline",onClick:()=>l(null),disabled:i,children:"Cancel"}),(0,Te.jsx)(x,{variant:"destructive",onClick:u,disabled:i,children:i?"Deleting...":"Delete"})]})]})})]})}var pt=ie(require("react"),1),Ua=require("lucide-react");var At=ie(require("react"),1),Za=require("lucide-react");var O=require("react/jsx-runtime");function qi(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function ir({productId:e,currency:t,className:s}){let{api:n}=W(),a=Fa(t)?"1":"0.01",[r,o]=At.useState(null),[c,d]=At.useState(!0),[l,i]=At.useState(null),[m,v]=At.useState(null),[g,u]=At.useState(!1),f=At.useRef(!0);At.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]);let p=At.useCallback(async()=>{try{let L=await n.getProduct(e);if(!f.current)return;o(L)}catch(L){if(!f.current)return;i(L instanceof Error?L.message:"Failed to load product")}finally{f.current&&d(!1)}},[n,e]);At.useEffect(()=>{p()},[p]);let b=async L=>{v(null),u(!0);try{await L(),await p()}catch($){f.current&&v($ instanceof Error?$.message:"Something went wrong")}finally{f.current&&u(!1)}},[w,P]=At.useState(""),[T,y]=At.useState(""),[C,k]=At.useState({}),I=()=>b(async()=>{let L=w.trim(),$=T.split(",").map(F=>F.trim()).filter(Boolean);if(!L)throw new Error("Option name is required");if($.length===0)throw new Error("Add at least one value");await n.createOption(e,{title:L,values:$}),f.current&&(P(""),y(""))}),N=L=>b(async()=>{let $=(C[L.id]??"").trim();if(!$)throw new Error("Enter a value");await n.updateOption(L.id,{add_values:[$]}),f.current&&k(F=>({...F,[L.id]:""}))}),E=(L,$)=>b(()=>n.updateOption(L.id,{remove_values:[$]})),D=L=>b(()=>n.deleteOption(L.id)),[_,Y]=At.useState(null),[Q,z]=At.useState(null),[le,fe]=At.useState(!1),[he,M]=At.useState(null),ee=r?.options??[],U=r?.variants??[],ve=()=>{z(null),Y({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(ee.map(L=>[L.id,L.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},me=L=>{z(null);let $=L.inventory?.on_hand??0,F=$<0?"":String($);Y({variant:L,title:L.title??"",sku:L.sku??"",unitAmount:L.unit_amount!=null?String(mt(L.unit_amount,t)):"",compareAt:L.compare_at_amount!=null?String(mt(L.compare_at_amount,t)):"",active:L.active,optionValues:{},tracked:L.inventory?.tracked??!1,onHand:F,initialOnHand:F,allowBackorder:L.inventory?.allow_backorder??!1})},Qe=async()=>{if(!_)return;z(null);let L=_.variant?.allow_custom_amount??!1,$=null,F=null;if(!L){if($=zt(_.unitAmount,t),$===null||$<=0){z("Enter a valid price");return}if(_.compareAt.trim()&&(F=zt(_.compareAt,t),F===null||F<=$)){z("Compare-at price must be greater than the price");return}}let Re=_.onHand.trim()!==_.initialOnHand.trim(),te=parseInt(_.onHand,10);if(_.tracked&&Re&&(!Number.isFinite(te)||te<0)){z("On-hand quantity must be zero or more");return}try{if(fe(!0),_.variant)await n.updateVariant(_.variant.id,{title:_.title.trim()||null,sku:_.sku.trim()||null,...L?{}:{unit_amount:$,compare_at_amount:F},active:_.active}),await n.setVariantInventory(_.variant.id,{tracked:_.tracked,on_hand:_.tracked&&Re?te:void 0,allow_backorder:_.allowBackorder});else{let we={};for(let He of ee){let bt=_.optionValues[He.id];if(!bt){z(`Choose a ${He.title}`),fe(!1);return}we[He.title]=bt}await n.createVariant(e,{title:_.title.trim()||null,sku:_.sku.trim()||null,unit_amount:$,compare_at_amount:F,active:_.active,option_values:ee.length>0?we:void 0,inventory:_.tracked?{tracked:!0,on_hand:te,allow_backorder:_.allowBackorder}:{tracked:!1,allow_backorder:_.allowBackorder}})}await p(),f.current&&Y(null)}catch(we){if(f.current&&z(we instanceof Error?we.message:"Failed to save variant"),_.variant)try{let He=await n.getProduct(e);f.current&&o(He)}catch{}}finally{f.current&&fe(!1)}},ke=()=>b(async()=>{he&&(await n.deleteVariant(he.id),f.current&&M(null))}),Ge=_?.variant?.allow_custom_amount??!1,Je=_?.variant!=null&&_.variant.option_values.length===0&&ee.length>0&&!_.variant.active,Fe=_?.variant?.inventory!=null&&_.variant.inventory.on_hand<0?-_.variant.inventory.on_hand:null;function _t(L){let $=L.inventory;if(!$||!$.tracked)return(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let F=$.available??$.on_hand;return F<0?(0,O.jsxs)("span",{children:[-F," backordered"]}):(0,O.jsxs)("span",{children:[F," in stock",$.allow_backorder&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return c?(0,O.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:(0,O.jsx)(Za.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):l?(0,O.jsx)("div",{className:s,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 ${s||""}`,children:[(0,O.jsxs)("div",{className:"af-space-y-3",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)(Oe,{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."})]}),ee.length>0&&(0,O.jsx)("div",{className:"af-space-y-3",children:ee.map(L=>(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:L.title}),(0,O.jsx)(x,{variant:"ghost",size:"sm",onClick:()=>D(L),disabled:g,children:(0,O.jsx)(Za.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,O.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:L.values.map($=>(0,O.jsxs)(oe,{variant:"secondary",className:"af-gap-1",children:[$.value,(0,O.jsx)("button",{type:"button",onClick:()=>E(L,$.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:(0,O.jsx)(Za.X,{className:"af-h-3 af-w-3"})})]},$.id))}),(0,O.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,O.jsx)(re,{value:C[L.id]??"",onChange:$=>k(F=>({...F,[L.id]:$.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),N(L))},disabled:g}),(0,O.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>N(L),disabled:g||!(C[L.id]??"").trim(),children:(0,O.jsx)(Za.Plus,{className:"af-h-4 af-w-4"})})]})]},L.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)(Oe,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,O.jsx)(re,{id:"new-option-title",value:w,onChange:L=>P(L.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),(0,O.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,O.jsx)(Oe,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,O.jsx)(re,{id:"new-option-values",value:T,onChange:L=>y(L.target.value),placeholder:"S, M, L",disabled:g})]}),(0,O.jsxs)(x,{type:"button",variant:"outline",onClick:I,disabled:g||!w.trim()||!T.trim(),children:[(0,O.jsx)(Za.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)(Oe,{children:"Variants"}),(0,O.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:ve,disabled:g||ee.length===0,children:[(0,O.jsx)(Za.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ee.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)(et,{children:[(0,O.jsx)(tt,{children:(0,O.jsxs)(Ie,{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)(at,{children:U.map(L=>(0,O.jsxs)(Ie,{children:[(0,O.jsx)(G,{className:"af-font-medium",children:qi(L)}),(0,O.jsx)(G,{className:"af-text-muted-foreground",children:L.sku||"-"}),(0,O.jsx)(G,{children:L.unit_amount!=null?(0,O.jsxs)("span",{children:[L.compare_at_amount!=null&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:Z(L.compare_at_amount,L.currency)}),Z(L.unit_amount,L.currency)]}):L.allow_custom_amount?(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,O.jsx)(G,{children:_t(L)}),(0,O.jsx)(G,{children:(0,O.jsx)(oe,{variant:L.active?"success":"secondary",children:L.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)(x,{variant:"ghost",size:"sm",onClick:()=>me(L),disabled:g,children:"Edit"}),(0,O.jsx)(x,{variant:"ghost",size:"icon",onClick:()=>M(L),disabled:g,title:"Delete variant",children:(0,O.jsx)(Za.Trash2,{className:"af-h-4 af-w-4"})})]})})]},L.id))})]})]}),m&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m}),(0,O.jsx)(ja,{open:_!==null,onOpenChange:L=>{!L&&!le&&Y(null)},children:(0,O.jsxs)(Ea,{children:[(0,O.jsxs)(Ia,{children:[(0,O.jsx)(Aa,{children:_?.variant?"Edit variant":"Add variant"}),(0,O.jsx)(La,{children:"Price, markdown, and stock live on the variant."})]}),_&&(0,O.jsxs)("div",{className:"af-space-y-3",children:[_.variant?_.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"}),qi(_.variant)]}):ee.map(L=>(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{className:"af-text-xs af-text-muted-foreground",children:L.title}),(0,O.jsxs)(qa,{value:_.optionValues[L.id]??"",onValueChange:$=>Y(F=>F&&{...F,optionValues:{...F.optionValues,[L.id]:$}}),children:[(0,O.jsx)(ka,{children:(0,O.jsx)(Wa,{placeholder:`Choose ${L.title}`})}),(0,O.jsx)(Ta,{children:L.values.map($=>(0,O.jsx)(dt,{value:$.value,children:$.value},$.id))})]})]},L.id)),Ge?(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{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)(Oe,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,O.jsx)(re,{id:"variant-price",type:"number",min:"0",step:a,value:_.unitAmount,onChange:L=>Y($=>$&&{...$,unitAmount:L.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,O.jsx)(re,{id:"variant-compare",type:"number",min:"0",step:a,value:_.compareAt,onChange:L=>Y($=>$&&{...$,compareAt:L.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,O.jsx)(re,{id:"variant-sku",value:_.sku,onChange:L=>Y($=>$&&{...$,sku:L.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:_.tracked,onChange:L=>Y($=>$&&{...$,tracked:L.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),_.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)(Oe,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,O.jsx)(re,{id:"variant-onhand",type:"number",min:"0",step:"1",value:_.onHand,onChange:L=>Y($=>$&&{...$,onHand:L.target.value}),placeholder:Fe!=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:_.allowBackorder,onChange:L=>Y($=>$&&{...$,allowBackorder:L.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Fe!=null&&(0,O.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,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:_.active,onChange:L=>Y($=>$&&{...$,active:L.target.checked}),className:"af-h-4 af-w-4",disabled:Je}),"Active (buyers can purchase this variant)"]}),Je&&(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."})]}),Q&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Q})]}),(0,O.jsxs)(Da,{children:[(0,O.jsx)(x,{variant:"outline",onClick:()=>Y(null),disabled:le,children:"Cancel"}),(0,O.jsxs)(x,{onClick:Qe,disabled:le,children:[le?(0,O.jsx)(Za.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,_?.variant?"Save":"Add variant"]})]})]})}),(0,O.jsx)(ja,{open:he!==null,onOpenChange:L=>{!L&&!g&&M(null)},children:(0,O.jsxs)(Ea,{children:[(0,O.jsxs)(Ia,{children:[(0,O.jsx)(Aa,{children:"Delete variant?"}),(0,O.jsx)(La,{children:he&&`"${qi(he)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,O.jsxs)(Da,{children:[(0,O.jsx)(x,{variant:"outline",onClick:()=>M(null),disabled:g,children:"Cancel"}),(0,O.jsx)(x,{variant:"destructive",onClick:ke,disabled:g,children:"Delete"})]})]})})]})}var X=require("react/jsx-runtime");function Iu(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,n)).toFixed(1))} ${s[n]}`}function or({productsState:e,product:t,currency:s,onSaved:n,className:a}){let{createProduct:r,updateProduct:o,attachProductFile:c,attachProductFileFromUrl:d}=e,l=!!t,i=t?.currency??s,m=Fa(i)?"1":"0.01",v=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,u]=pt.useState(!1),[f,p]=pt.useState(null),b=pt.useRef(!0);pt.useEffect(()=>(b.current=!0,()=>{b.current=!1}),[]);let[w,P]=pt.useState(t?.name??""),[T,y]=pt.useState(t?.description??""),[C,k]=pt.useState(t?.allow_custom_amount?"custom":"fixed"),[I,N]=pt.useState(t?.unit_amount!=null?String(mt(t.unit_amount,i)):""),[E,D]=pt.useState(t?.min_amount!=null?String(mt(t.min_amount,i)):""),[_,Y]=pt.useState(t?.max_amount!=null?String(mt(t.max_amount,i)):""),[Q,z]=pt.useState(String(t?.max_quantity??10)),le=pt.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(mt(t.unit_amount,i)):"",minAmount:t?.min_amount!=null?String(mt(t.min_amount,i)):"",maxAmount:t?.max_amount!=null?String(mt(t.max_amount,i)):"",maxQuantity:String(t?.max_quantity??10)}).current,[fe,he]=pt.useState(t?.collect_shipping_address??!1),[M,ee]=pt.useState(t?.active??!0),[U,ve]=pt.useState(t?.images??[]),[me,Qe]=pt.useState(""),[ke,Ge]=pt.useState(t?.fulfillment??null),[Je,Fe]=pt.useState(!1),[_t,L]=pt.useState(""),[$,F]=pt.useState(null),Re=pt.useRef(null),te=g||Je,we=()=>{let xe=me.trim();if(xe){if(U.includes(xe)){p("This image URL is already added");return}ve(Me=>[...Me,xe]),Qe(""),p(null)}},He=xe=>{ve(Me=>Me.filter(yt=>yt!==xe))},bt=async()=>{if(p(null),!w.trim()){p("Product name is required");return}let xe=null,Me=null,yt=null,Pa=!l||C!==le.pricingMode||(C==="fixed"?I!==le.unitAmount:E!==le.minAmount||_!==le.maxAmount),Kt=!l||Q!==le.maxQuantity,fa=v||C==="fixed";if(!(v||!Pa))if(C==="fixed"){if(xe=zt(I,i),xe===null||xe<=0){p("Enter a valid price");return}}else{if(Me=zt(E,i),yt=zt(_,i),Me===null||yt===null){p("Enter valid minimum and maximum amounts");return}if(yt<Me){p("Maximum amount must be at least the minimum amount");return}}let Xt=parseInt(Q,10);if(fa&&Kt&&(!Number.isFinite(Xt)||Xt<1)){p("Max quantity must be at least 1");return}try{u(!0);let rt;if(l&&t){let ht={name:w.trim(),description:T.trim()||null,images:U,collect_shipping_address:fe,active:M};!v&&Pa&&(ht.allow_custom_amount=C==="custom",C==="fixed"?ht.unit_amount=xe:(ht.min_amount=Me,ht.max_amount=yt)),fa&&Kt&&(ht.max_quantity=Xt),rt=await o(t.id,ht),le.pricingMode=rt.allow_custom_amount?"custom":"fixed",le.unitAmount=rt.unit_amount!=null?String(mt(rt.unit_amount,i)):"",le.minAmount=rt.min_amount!=null?String(mt(rt.min_amount,i)):"",le.maxAmount=rt.max_amount!=null?String(mt(rt.max_amount,i)):"",le.maxQuantity=String(rt.max_quantity)}else{let ht={name:w.trim(),allow_custom_amount:C==="custom",collect_shipping_address:fe,active:M};T.trim()&&(ht.description=T.trim()),U.length>0&&(ht.images=U),C==="fixed"?(ht.unit_amount=xe,ht.max_quantity=Xt):(ht.min_amount=Me,ht.max_amount=yt),rt=await r(ht)}if(!b.current)return;Ge(rt.fulfillment),n?.(rt)}catch(rt){if(!b.current)return;p(rt instanceof Error?rt.message:"Failed to save product")}finally{b.current&&u(!1)}},Ze=async xe=>{let Me=xe.target.files?.[0];if(!(!Me||!t))try{Fe(!0),F(null);let yt=await c(t.id,Me);if(!b.current)return;Ge(yt.fulfillment),n?.(yt)}catch(yt){if(!b.current)return;F(yt instanceof Error?yt.message:"Failed to upload file")}finally{b.current&&(Fe(!1),Re.current&&(Re.current.value=""))}},Ct=async()=>{let xe=_t.trim();if(!(!xe||!t))try{Fe(!0),F(null);let Me=await d(t.id,xe);if(!b.current)return;Ge(Me.fulfillment),L(""),n?.(Me)}catch(Me){if(!b.current)return;F(Me instanceof Error?Me.message:"Failed to fetch file")}finally{b.current&&Fe(!1)}};return(0,X.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{htmlFor:"product-name",children:"Name"}),(0,X.jsx)(re,{id:"product-name",value:w,onChange:xe=>P(xe.target.value),placeholder:"My product"})]}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{htmlFor:"product-description",children:"Description"}),(0,X.jsx)("textarea",{id:"product-description",value:T,onChange:xe=>y(xe.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,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{children:"Pricing"}),v?(0,X.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,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(qa,{value:C,onValueChange:xe=>k(xe),children:[(0,X.jsx)(ka,{className:"af-w-[260px]",children:(0,X.jsx)(Wa,{})}),(0,X.jsxs)(Ta,{children:[(0,X.jsx)(dt,{value:"fixed",children:"Fixed price"}),(0,X.jsx)(dt,{value:"custom",children:"Buyer chooses the amount"})]})]}),C==="fixed"?(0,X.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsxs)(Oe,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",i.toUpperCase(),")"]}),(0,X.jsx)(re,{id:"product-price",type:"number",min:"0",step:m,value:I,onChange:xe=>N(xe.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsxs)(Oe,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",i.toUpperCase(),")"]}),(0,X.jsx)(re,{id:"product-min-amount",type:"number",min:"0",step:m,value:E,onChange:xe=>D(xe.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsxs)(Oe,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",i.toUpperCase(),")"]}),(0,X.jsx)(re,{id:"product-max-amount",type:"number",min:"0",step:m,value:_,onChange:xe=>Y(xe.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,X.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,X.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",i.toUpperCase(),"), which follows the country of your payment account."]})]}),(v||C==="fixed")&&(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsx)(Oe,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,X.jsx)(re,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:Q,onChange:xe=>z(xe.target.value),className:"af-w-[140px]"})]})]}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{children:"Images"}),(0,X.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,X.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[U.map(xe=>(0,X.jsxs)(oe,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,X.jsx)("span",{className:"af-truncate",children:xe}),(0,X.jsx)("button",{type:"button",onClick:()=>He(xe),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:(0,X.jsx)(Ua.X,{className:"af-h-3 af-w-3"})})]},xe)),U.length===0&&(0,X.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,X.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,X.jsx)(re,{type:"url",value:me,onChange:xe=>Qe(xe.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:xe=>{xe.key==="Enter"&&(xe.preventDefault(),we())},disabled:g}),(0,X.jsx)(x,{type:"button",variant:"outline",onClick:we,disabled:!me.trim()||g,children:(0,X.jsx)(Ua.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{children:"Digital File"}),(0,X.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,X.jsxs)("div",{className:"af-space-y-3",children:[ke?.type==="download"&&(0,X.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,X.jsx)(Ua.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,X.jsx)("span",{className:"af-text-sm",children:ke.filename}),ke.size!=null&&(0,X.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Iu(ke.size),")"]})]}),ke?.type==="redirect"&&ke.url&&(0,X.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,X.jsx)(Ua.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,X.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",ke.url]})]}),(0,X.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,X.jsx)("input",{ref:Re,type:"file",onChange:Ze,className:"af-hidden",disabled:te}),(0,X.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>Re.current?.click(),disabled:te,children:[Je?(0,X.jsx)(Ua.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,X.jsx)(Ua.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),ke?.type==="download"?"Replace file":"Upload file"]}),(0,X.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,X.jsx)(re,{type:"url",value:_t,onChange:xe=>L(xe.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Je}),(0,X.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:Ct,disabled:!_t.trim()||te,children:"Fetch from URL"})]}),$&&(0,X.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:$})]}):(0,X.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{children:"Settings"}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,X.jsx)("input",{type:"checkbox",checked:fe,onChange:xe=>he(xe.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,X.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,X.jsx)("input",{type:"checkbox",checked:M,onChange:xe=>ee(xe.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),l&&t&&(0,X.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,X.jsx)(Oe,{children:"Options & Variants"}),(0,X.jsx)(ir,{productId:t.id,currency:i})]}),f&&(0,X.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f}),(0,X.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,X.jsxs)(x,{type:"button",onClick:bt,disabled:te,children:[g?(0,X.jsx)(Ua.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,l?"Save changes":"Create product"]})})]})}var Mt=ie(require("react"),1),Ma=require("lucide-react");var xt=ie(require("react"),1);var Du=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function lr({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=W(),[n,a]=xt.useState([]),[r,o]=xt.useState(0),[c,d]=xt.useState(!0),[l,i]=xt.useState(null),[m,v]=xt.useState(0),[g,u]=xt.useState(e),[f,p]=xt.useState(void 0),[b,w]=xt.useState(""),[P,T]=xt.useState(""),[y,C]=xt.useState(""),[k,I]=xt.useState(!1),[N,E]=xt.useState(!1),[D,_]=xt.useState(void 0),Y=D?D.join(","):"",Q=xt.useMemo(()=>{if(!Y)return;let M=new Set(Y.split(","));return Du.filter(ee=>!M.has(ee))},[Y]),z=xt.useMemo(()=>{let M={};return f?M.status=f:Q?M.excludeStatus=Q:k||(M.excludeStatus=["pending","expired"]),b.trim()&&(M.customerEmail=b.trim()),P.trim()&&(M.from=P.trim()),y.trim()&&(M.to=y.trim()),N&&(M.unfulfilledOnly=!0),M},[f,Q,k,b,P,y,N]),le=xt.useRef(0),fe=xt.useCallback(async()=>{let M=++le.current;try{d(!0),i(null);let ee={...z,limit:g,offset:m*g},U=await s.getOrders(ee);if(M!==le.current)return;a(U.orders),o(U.total)}catch(ee){if(M!==le.current)return;i(ee instanceof Error?ee:new Error("Failed to fetch orders"))}finally{M===le.current&&d(!1)}},[s,m,g,z,t]);xt.useEffect(()=>{fe()},[fe]);let he=Math.ceil(r/g);return{orders:n,total:r,isLoading:c,error:l,page:m,pageSize:g,hasNextPage:m<he-1,hasPreviousPage:m>0,setPage:v,setPageSize:M=>{u(M),v(0)},status:f,setStatus:M=>{p(M),v(0)},statusIn:D,setStatusIn:M=>{_(M&&M.length>0?M:void 0),v(0)},customerEmail:b,setCustomerEmail:M=>{w(M),v(0)},from:P,setFrom:M=>{T(M),v(0)},to:y,setTo:M=>{C(M),v(0)},showAbandoned:k,setShowAbandoned:M=>{I(M),v(0)},unfulfilledOnly:N,setUnfulfilledOnly:M=>{E(M),v(0)},clearFilters:()=>{p(void 0),_(void 0),I(!1),E(!1),w(""),T(""),C(""),v(0)},filters:z,refetch:fe}}var Tt=ie(require("react"),1),ze=require("lucide-react");var vl=ie(require("react"),1),bs=ie(require("@radix-ui/react-popover"),1);var Yr=require("react/jsx-runtime"),Jr=bs.Root,Xr=bs.Trigger;var cr=vl.forwardRef(({className:e,align:t="end",sideOffset:s=4,...n},a)=>(0,Yr.jsx)(bs.Portal,{children:(0,Yr.jsx)("div",{className:"aifeatures-admin",children:(0,Yr.jsx)(bs.Content,{ref:a,align:t,sideOffset:s,className:J("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),...n})})}));cr.displayName=bs.Content.displayName;var ur=require("react/jsx-runtime"),Au={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Lu(e){return Au[e]??e}function bl(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 rn({status:e,className:t}){return(0,ur.jsx)(oe,{variant:bl(e),className:t,children:Lu(e)})}function Gs({status:e}){return(0,ur.jsx)(rn,{status:e})}function Pn({order:e,className:t}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,ur.jsx)(oe,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,ur.jsx)(oe,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Is(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var h=require("react/jsx-runtime"),Sl="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",on="af-text-xs af-text-muted-foreground";function Wi(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 Ou(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wl(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 Qr=24,Bu=["paid","partially_refunded"],Fu=["paid","partially_refunded","disputed"],Uu=/^[A-Za-z0-9 _-]*$/,yl=100;function Ki(e,t,s,n,a){let r=Bu.includes(n);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 ${s} of ${Qr} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${Qr} tries used). Nothing is being retried while the order is ${n.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?s<Qr&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:s<Qr&&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 ${s} attempt${s===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${n==="refunded"?"because the order was refunded":n==="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 hl({title:e,recipient:t,status:s,attempts:n,side:a,orderStatus:r,action:o,delivery:c}){if(c)return(0,h.jsxs)("div",{children:[(0,h.jsx)(ps,{deliveries:[c]}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]});let d=Ki(a,s,n,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)(oe,{variant:d.variant,className:"af-shrink-0",children:d.label})]}),d.detail&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:d.detail}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]})}function xl(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let s=Ou(e.address)?e.address:null;if(s){for(let a of["line1","line2"]){let r=s[a];typeof r=="string"&&r&&t.push(r)}let n=["city","state","postal_code"].map(a=>s[a]).filter(a=>typeof a=="string"&&!!a).join(", ");n&&t.push(n),typeof s.country=="string"&&s.country&&t.push(s.country)}return t.length>0?t:Object.entries(e).map(([n,a])=>`${n}: ${wl(a)}`)}function Mu(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Zi({value:e,label:t,children:s,className:n,size:a="icon"}){let[r,o]=Tt.useState(!1);if(!Mu())return null;let c=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},d=r?(0,h.jsx)(ze.Check,{className:"af-h-3 af-w-3"}):(0,h.jsx)(ze.Copy,{className:"af-h-3 af-w-3"});return a==="icon"?(0,h.jsx)(x,{variant:"ghost",size:"icon",className:J("af-h-6 af-w-6 af-shrink-0",n),onClick:c,title:t,"aria-label":t,children:d}):(0,h.jsxs)(x,{variant:"outline",size:"sm",className:n,onClick:c,"aria-label":t,children:[r?(0,h.jsx)(ze.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,h.jsx)(ze.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":s]})}function ji({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)(Zi,{value:t,label:`Copy ${e}`})]})]})}function $u({src:e}){let[t,s]=Tt.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)(ze.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,h.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>s(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function ys({title:e,action:t,children:s,className:n}){return(0,h.jsxs)("section",{className:J("af-rounded-lg af-border af-p-4",n),children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,h.jsx)("h4",{className:Sl,children:e}),t]}),(0,h.jsx)("div",{className:"af-mt-3",children:s})]})}function va({label:e,emphasis:t,divider:s,children:n}){return(0,h.jsxs)("div",{className:J("af-flex af-items-baseline af-justify-between af-gap-6",s&&"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:J("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:n})]})}function Gi({onSelect:e,disabled:t,icon:s,children:n}){return(0,h.jsxs)(x,{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:s}),n]})}function Vu(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?t.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${Z(Kr(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(a=>a.kind==="purchase_receipt"),n=s?qr(s):Ki("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 ${n.label.toLowerCase()}`,at:null,tone:n.variant==="destructive"?"destructive":n.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(a=>a.kind==="merchant_sale"),n=s?qr(s):Ki("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 ${n.label.toLowerCase()}`,at:null,tone:n.variant==="destructive"?"destructive":n.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${Z(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function dr({order:e,onBack:t,onRefund:s,onOrderUpdated:n,allowFulfillment:a=!1,onPrevOrder:r,onNextOrder:o,hasPrevOrder:c=!1,hasNextOrder:d=!1}){let{api:l}=W(),[i,m]=Tt.useState(e),[v,g]=Tt.useState(null),[u,f]=Tt.useState(null),[p,b]=Tt.useState(!1),[w,P]=Tt.useState(!1),[T,y]=Tt.useState(!1),[C,k]=Tt.useState(!1),[I,N]=Tt.useState(""),[E,D]=Tt.useState(!1),[_,Y]=Tt.useState(null),[Q,z]=Tt.useState(!1),[le,fe]=Tt.useState(""),[he,M]=Tt.useState([]),[ee,U]=Tt.useState(!1),[ve,me]=Tt.useState(!1),[Qe,ke]=Tt.useState(null);Tt.useEffect(()=>{m(e)},[e]);let Ge=B=>{let Ke=B.id===i.id&&B.email_deliveries===void 0?{...B,email_deliveries:i.email_deliveries}:B;m(Ke),n?.(Ke)},Je=Object.entries(i.metadata??{}),Fe=Math.max(0,Kr(i)-i.amount_refunded),_t=(i.status==="paid"||i.status==="partially_refunded")&&Fe>0,L=i.exclusive_tax_total!=null,$=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)),Re=he.reduce((B,Ke)=>B+$(i.line_items[Ke]??{}),0)+(ee?F:0),te=i.tax_total??0,we=Math.max(0,(i.exclusive_tax_total??0)-i.line_items.reduce((B,Ke)=>B+(Ke.exclusiveTax??0),0)),He=L?ee&&F>0?we:0:i.automatic_tax&&i.tax_behavior==="exclusive"&&te>0&&i.amount_total+(i.shipping_total??0)>0?Math.min(Math.max(0,te-(i.tax_refunded??0)),Math.round(te*Re/(i.amount_total+(i.shipping_total??0)))):0,bt=i.source==="subscription"&&(i.credit_applied??0)>0&&i.line_items.length===1?Math.min(Re+He,Fe):Re+He,Ze=he.length>0||ee,Ct=Ze?bt:zt(le,i.currency),xe=Fa(i.currency)?"1":"0.01",Me=async()=>{try{b(!0),g(null),f(null),await l.resendOrderReceipt(i.id);let B=await l.getOrder(i.id);Ge(B),f("Receipt email queued.")}catch(B){g(B instanceof Error?B.message:"Failed to resend receipt")}finally{b(!1)}},yt=async()=>{try{P(!0),g(null),f(null);let B=await l.resetOrderDownloads(i.id);Ge(B),y(!1),f("Download count reset.")}catch(B){g(B instanceof Error?B.message:"Failed to reset downloads")}finally{P(!1)}},Pa=i.line_items.some(B=>B.collectShippingAddress===!0&&!B.refunded&&!B.unavailableReason),Kt=typeof i.merchant_fulfilled_at=="string",fa=Fu.includes(i.status)||i.status==="refunded"&&i.line_items.some(B=>B.collectShippingAddress===!0&&B.amountNet===0&&!B.refunded&&!B.unavailableReason),Xt=I.trim(),rt=Uu.test(Xt)&&Xt.length<=yl,ht=async B=>{try{D(!0),Y(null),f(null);let Ke=await l.setOrderFulfillment(i.id,{fulfilled:B,...B&&Xt?{trackingNumber:Xt}:{}});Ge(Ke),N(""),f(B?"Marked as shipped.":"Marked as not shipped.")}catch(Ke){Ke instanceof Dt&&Ke.status===409?Y(`This order is ${i.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Y(Ke instanceof Error?Ke.message:"Failed to update the order")}finally{D(!1)}},ss=()=>{ke(null),fe(String(mt(Fe,i.currency))),M([]),U(!1),z(!0)},en=B=>M(Ke=>Ke.includes(B)?Ke.filter(pa=>pa!==B):[...Ke,B]),ma=async(B,Ke)=>{if(s)try{me(!0),ke(null),await s(i,B,Ke);let pa=await l.getOrder(i.id);Ge(pa),z(!1),f("Refund issued.")}catch(pa){ke(pa instanceof Error?pa.message:"Refund failed")}finally{me(!1)}},Oi=async()=>{if(Ze){if(bt<=0){ke("The lines you picked were charged nothing");return}if(bt>Fe){ke(`That selection exceeds the refundable remainder (${Z(Fe,i.currency)})`);return}await ma(bt,{...he.length>0?{line_items:[...he].sort((Ke,pa)=>Ke-pa)}:{},...ee?{shipping:!0}:{}});return}let B=zt(le,i.currency);if(B===null||B<=0){ke("Enter a valid refund amount");return}if(B>Fe){ke(`Amount exceeds the refundable remainder (${Z(Fe,i.currency)})`);return}await ma(B,{amount:B})},K=()=>ma(Fe,{full:!0}),ct=!i.subscription_history_only&&i.fulfillment_type==="download",fs=!i.subscription_history_only&&a&&Pa,Bi=Vu(i),se=i.shipping_address?xl(i.shipping_address).join(`
|
|
4
|
+
`):"",ia=i.shipping_total!=null,Fi=i.exclusive_tax_total??(i.automatic_tax&&i.tax_behavior==="exclusive"?i.tax_total??0:0),Oo=i.exclusive_tax_total!=null?Math.max(0,(i.tax_total??0)-Fi):i.automatic_tax&&i.tax_behavior==="exclusive"?0:i.tax_total??0,Bo=Fi>0,eu=Oo>0,Fo=i.amount_subtotal!=null||ia||Bo||(i.discount_total??0)>0,Vn=[];return i.subscription_history_only||Vn.push((0,h.jsx)(Gi,{icon:p?(0,h.jsx)(ze.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,h.jsx)(ze.Mail,{className:"af-h-4 af-w-4"}),disabled:p||i.fulfillment_status!=="fulfilled",onSelect:()=>{k(!1),Me()},children:"Resend receipt"},"resend")),ct&&Vn.push((0,h.jsx)(Gi,{icon:(0,h.jsx)(ze.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:w,onSelect:()=>{k(!1),y(!0)},children:"Reset download count"},"reset")),_t&&Vn.push((0,h.jsxs)("div",{children:[(0,h.jsx)(Gi,{icon:(0,h.jsx)(ze.Undo2,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{k(!1),ss()},children:"Refund\u2026"}),!s&&(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)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,h.jsx)(ze.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:Is(i)}),(0,h.jsx)(rn,{status:i.status}),a&&!i.subscription_history_only&&(0,h.jsx)(Pn,{order:i}),i.is_test&&(0,h.jsx)(oe,{variant:"outline",children:"Test"})]}),(0,h.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Wi(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)(x,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!c,"aria-label":"Previous order",children:(0,h.jsx)(ze.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,h.jsx)(x,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!d,"aria-label":"Next order",children:(0,h.jsx)(ze.ChevronRight,{className:"af-h-4 af-w-4"})})]}),fs&&(Kt?(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 ${Wi(i.merchant_fulfilled_at)}`:""]}),fa&&(0,h.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>ht(!1),disabled:E,children:[E?(0,h.jsx)(ze.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(ze.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):fa?(0,h.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,h.jsx)(re,{value:I,onChange:B=>N(B.target.value),placeholder:"Tracking number (optional)",maxLength:yl,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:E}),(0,h.jsxs)(x,{variant:"default",className:"af-shrink-0",onClick:()=>ht(!0),disabled:E||!rt,children:[E?(0,h.jsx)(ze.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(ze.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Vn.length>0&&(0,h.jsxs)(Jr,{open:C,onOpenChange:k,children:[(0,h.jsx)(Xr,{asChild:!0,children:(0,h.jsx)(x,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,h.jsx)(ze.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,h.jsx)(cr,{children:(0,h.jsx)("div",{className:"af-space-y-0.5",children:Vn})})]})]})]}),fs&&!Kt&&!rt&&(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."}),_&&(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:_}),u&&(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:u}),v&&(0,h.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:v})]}),(0,h.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,h.jsxs)("div",{className:"af-space-y-6",children:[i.line_items.length>0&&(0,h.jsx)(ys,{title:"Items",children:(0,h.jsx)("ul",{className:"af-space-y-3",children:i.line_items.map((B,Ke)=>{let pa=typeof B.name=="string"&&B.name?B.name:"Item",Uo=typeof B.quantity=="number"&&B.quantity>0?B.quantity:1,Mo=typeof B.unitAmount=="number";return(0,h.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,h.jsx)($u,{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:[pa,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:[Uo," \xD7"," ",Mo?Z(B.unitAmount,i.currency):"\u2014"]}),B.unavailableReason==="oversold"&&!B.refunded&&(0,h.jsx)(oe,{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)(oe,{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"||Mo?Z(B.amountNet??B.unitAmount*Uo,i.currency):"\u2014"})]},Ke)})})}),Je.length>0&&(0,h.jsx)(ys,{title:"Order details",children:(0,h.jsx)("dl",{className:"af-space-y-2",children:Je.map(([B,Ke])=>(0,h.jsxs)("div",{children:[(0,h.jsx)("dt",{className:J(on,"af-capitalize"),children:B.replace(/_/g," ")}),(0,h.jsx)("dd",{className:"af-text-sm af-break-words",children:wl(Ke)})]},B))})}),(0,h.jsx)(ys,{title:"Totals",children:(0,h.jsxs)("div",{className:"af-w-full",children:[Fo&&(0,h.jsx)(va,{label:"Subtotal",children:Z(i.amount_subtotal??i.amount_total+(i.discount_total??0),i.currency)}),(i.discount_total??0)>0&&(0,h.jsxs)(va,{label:"Discount",children:["\u2212",Z(i.discount_total,i.currency)]}),ia&&(0,h.jsx)(va,{label:"Shipping",children:i.shipping_total===0?"Free":Z(i.shipping_total??0,i.currency)}),Bo&&(0,h.jsx)(va,{label:"Tax",children:Z(Fi,i.currency)}),(0,h.jsx)(va,{label:"Total",emphasis:!0,divider:Fo,children:Z(vs(i),i.currency)}),(i.credit_applied??0)>0&&(0,h.jsxs)(va,{label:"Credit applied",children:["\u2212",Z(i.credit_applied,i.currency)]}),i.amount_paid!=null&&(0,h.jsx)(va,{label:"Amount paid",children:Z(i.amount_paid,i.currency)}),eu&&(0,h.jsx)(va,{label:"incl. tax",children:Z(Oo,i.currency)}),i.base_currency!=null&&i.base_amount_total!=null&&(0,h.jsxs)(va,{label:"Your price",children:[Z(i.base_amount_total,i.base_currency),(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",i.currency.toUpperCase()]})]}),i.amount_refunded>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(va,{label:"Refunded",children:["\u2212",Z(i.amount_refunded,i.currency),(i.shipping_refunded??0)>0&&(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",Z(i.shipping_refunded??0,i.currency)," ","shipping"]})]}),(0,h.jsx)(va,{label:"Net",children:(0,h.jsx)("span",{className:"af-font-medium",children:Z(Math.max(0,Kr(i)-i.amount_refunded),i.currency)})})]})]})}),i.application_fee_state&&(0,h.jsxs)(ys,{title:"Platform fee",children:[i.application_fee_original!=null&&(0,h.jsx)(va,{label:"Collected",children:Z(i.application_fee_original,i.application_fee_currency??i.currency)}),i.application_fee_returned!=null&&(0,h.jsx)(va,{label:"Returned",children:Z(i.application_fee_returned,i.application_fee_currency??i.currency)}),i.application_fee_retained!=null&&(0,h.jsx)(va,{label:"Retained",children:Z(i.application_fee_retained,i.application_fee_currency??i.currency)}),i.application_fee_state!=="complete"&&(0,h.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:i.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,h.jsx)(ys,{title:"Timeline",children:(0,h.jsx)("ol",{className:"af-space-y-3",children:Bi.map(B=>(0,h.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,h.jsx)("span",{"aria-hidden":"true",className:J("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:Wi(B.at)})]})]},B.key))})})]}),(0,h.jsxs)("div",{className:"af-space-y-6",children:[(0,h.jsx)(ys,{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)(Zi,{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)(oe,{variant:"secondary",children:"Linked"})]})]})]})}),i.shipping_address&&(0,h.jsx)(ys,{title:"Ship to",action:(0,h.jsx)(Zi,{value:se,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:xl(i.shipping_address).map((B,Ke)=>(0,h.jsx)("div",{children:B},Ke))})}),i.subscription_history_only?(0,h.jsx)(ys,{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)(ys,{title:"Emails",children:[(0,h.jsx)(ps,{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)(hl,{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)(x,{variant:"outline",size:"sm",onClick:Me,disabled:p||i.fulfillment_status!=="fulfilled",children:[p?(0,h.jsx)(ze.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(ze.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,h.jsx)(hl,{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})]})]}),ct&&(0,h.jsx)(ys,{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)(ze.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:J(Sl,"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)(ji,{label:"Order ID",value:i.id}),i.stripe_checkout_session_id&&(0,h.jsx)(ji,{label:"Checkout session",value:i.stripe_checkout_session_id}),i.stripe_payment_intent_id&&(0,h.jsx)(ji,{label:"Payment",value:i.stripe_payment_intent_id})]})]})]})]}),(0,h.jsx)(ja,{open:T,onOpenChange:B=>{!B&&!w&&y(!1)},children:(0,h.jsxs)(Ea,{children:[(0,h.jsxs)(Ia,{children:[(0,h.jsx)(Aa,{children:"Reset download count?"}),(0,h.jsx)(La,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,h.jsxs)(Da,{children:[(0,h.jsx)(x,{variant:"outline",onClick:()=>y(!1),disabled:w,children:"Cancel"}),(0,h.jsx)(x,{onClick:yt,disabled:w,children:w?"Resetting...":"Reset"})]})]})}),(0,h.jsx)(ja,{open:Q,onOpenChange:B=>{!B&&!ve&&z(!1)},children:(0,h.jsxs)(Ea,{children:[(0,h.jsxs)(Ia,{children:[(0,h.jsx)(Aa,{children:"Refund order"}),(0,h.jsxs)(La,{children:["Refund up to ",Z(Fe,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)(Oe,{children:"Items"}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[i.line_items.map((B,Ke)=>{let pa=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:he.includes(Ke),onChange:()=>en(Ke),disabled:ve||pa||!!B.unavailableReason||$(B)<=0,className:"af-h-4 af-w-4"}),(0,h.jsxs)("span",{className:pa?"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:pa?"Refunded":Z($(B),i.currency)})]},Ke)}),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:ee,onChange:B=>U(B.target.checked),disabled:ve,className:"af-h-4 af-w-4"}),(0,h.jsx)("span",{children:"Shipping"}),(0,h.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Z(F,i.currency)})]})]})]}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)(Oe,{htmlFor:"refund-amount",children:["Amount (",i.currency.toUpperCase(),")"]}),(0,h.jsx)(re,{id:"refund-amount",type:"number",min:"0",step:xe,value:Ze?String(mt(bt,i.currency)):le,onChange:B=>fe(B.target.value),disabled:ve||Ze}),Ze&&(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."})]})]}),Qe&&(0,h.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Qe}),(0,h.jsxs)(Da,{children:[(0,h.jsx)(x,{variant:"outline",onClick:()=>z(!1),disabled:ve,children:"Cancel"}),(0,h.jsx)(x,{variant:"outline",onClick:K,disabled:ve,children:"Refund everything"}),(0,h.jsx)(x,{variant:"destructive",onClick:Oi,disabled:ve,children:ve?"Refunding...":Ct!==null&&Ct>0?`Refund ${Z(Ct,i.currency)}`:"Refund"})]})]})})]})}var ei=ie(require("react"),1),ti=require("lucide-react");var gt=require("react/jsx-runtime");function St({title:e,onBackToWebsite:t,hideBackButton:s=!1,children:n,className:a}){let r=ei.useRef(null);return ei.useEffect(()=>{r.current?.focus()},[]),(0,gt.jsxs)("div",{className:J("af-bg-background",a),children:[(0,gt.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,gt.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&&!s&&(0,gt.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,gt.jsx)(ti.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,gt.jsx)("div",{className:"af-p-4",children:n})]})}function ae({className:e}){return(0,gt.jsx)("div",{"aria-hidden":"true",className:J("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function st({label:e,children:t,detail:s,valueClassName:n}){return(0,gt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,gt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,gt.jsx)("div",{className:J("af-mt-1 af-text-lg af-font-semibold",n),children:t}),s&&(0,gt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function Lt({message:e,onRetry:t}){return(0,gt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,gt.jsx)("span",{children:e}),(0,gt.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,gt.jsx)(ti.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function aa({icon:e,children:t}){return(0,gt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,gt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function Ks({icon:e,heading:t,body:s,action:n,className:a,children:r}){return(0,gt.jsxs)("div",{className:J("af-px-6 af-py-10 af-text-center",a),children:[(0,gt.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,gt.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,gt.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:s}),n&&(0,gt.jsx)(x,{type:"button",className:"af-mt-4",onClick:n.onClick,children:n.label}),r]})}var A=require("react/jsx-runtime"),Hu={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Nl={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Rl(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 _l(e){let t=Array.isArray(e.line_items)?e.line_items:[],s=t[0];if(!s)return"\u2014";let n=typeof s.name=="string"&&s.name?s.name:"Item",a=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,r=a>1?`${n} \xD7${a}`:n;return t.length>1?`${r} +${t.length-1} more`:r}function ai(e){return e.customer?.name||e.customer_name||null}function zu({onRefund:e,className:t,refreshKey:s,initialOrderId:n,showFulfillment:a=!1,emptyMessage:r,onDetailOpenChange:o,maxRows:c,onViewAll:d}){let l=typeof c=="number",{api:i}=W(),m=lr({refreshKey:s}),{orders:v,total:g,isLoading:u,error:f,page:p,pageSize:b,hasNextPage:w,hasPreviousPage:P,setPage:T,setPageSize:y,customerEmail:C,setCustomerEmail:k,setStatusIn:I,from:N,setFrom:E,to:D,setTo:_,showAbandoned:Y,setShowAbandoned:Q,setUnfulfilledOnly:z,filters:le,refetch:fe}=m,he=Mt.useCallback(()=>i.exportOrdersCsv(le),[i,le]),[M,ee]=Mt.useState("list"),[U,ve]=Mt.useState(null),[me,Qe]=Mt.useState(""),[ke,Ge]=Mt.useState(""),[Je,Fe]=Mt.useState(!l&&a?"needs_shipping":"all"),[_t,L]=Mt.useState(!1),[$,F]=Mt.useState(!!n&&!l),[Re,te]=Mt.useState(null);Mt.useEffect(()=>{if(!n||l)return;let se=!1;return F(!0),te(null),i.getOrder(n).then(ia=>{se||(ve(ia),ee("detail"))}).catch(()=>{se||te("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{se||F(!1)}),()=>{se=!0}},[i,n,l]);let we=Mt.useCallback(se=>{Fe(se);let ia=Nl[se];I(ia.statusIn),z(ia.unfulfilledOnly)},[I,z]);Mt.useEffect(()=>{a&&!l&&z(!0)},[]);let He=Mt.useRef(!a);Mt.useEffect(()=>{He.current||u||(He.current=!0,v.length===0&&we("all"))},[u,v.length,we]);let bt=M==="detail"&&!!U;Mt.useEffect(()=>{o?.(bt)},[bt,o]);let Ze=(N?1:0)+(D?1:0)+(Y?1:0),Ct=Ze>0||!!C||!!ke,xe=!!N&&!!D&&N>D,Me=!l||!!d,yt=se=>{if(l){d?.();return}ve(se),ee("detail")},Pa=()=>{ee("list"),ve(null),fe()},Kt=se=>{let ia=se.trim();if(!ia){Ge(""),C&&k("");return}if(ia.startsWith("#")||/^\d+$/.test(ia)){Ge(ia),C&&k("");return}Ge(""),k(ia)},fa=()=>{Qe(""),Ge(""),k(""),E(""),_(""),Q(!1),L(!1)},Xt=ke.replace(/^#/,"").toLowerCase(),rt=Xt?v.filter(se=>String(se.order_number??"")===Xt||se.id.toLowerCase().startsWith(Xt)):v,ht=l?rt.slice(0,c):rt,ss=U?v.findIndex(se=>se.id===U.id):-1,en=ss>0,ma=ss>=0&&ss<v.length-1;if($)return(0,A.jsx)("div",{className:t,children:(0,A.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,A.jsx)(Ma.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(M==="detail"&&U)return(0,A.jsx)("div",{className:t,children:(0,A.jsx)(dr,{order:U,onBack:Pa,onRefund:e,onOrderUpdated:se=>ve(se),allowFulfillment:a,onPrevOrder:en?()=>ve(v[ss-1]):void 0,onNextOrder:ma?()=>ve(v[ss+1]):void 0,hasPrevOrder:en,hasNextOrder:ma},U.id)});let K=(0,A.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[Re&&(0,A.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:Re}),(0,A.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,A.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(se=>(0,A.jsx)("button",{type:"button","aria-pressed":Je===se,onClick:()=>we(se),className:J("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",Je===se?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Hu[se]},se))}),(0,A.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,A.jsx)(Ma.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,A.jsx)(re,{type:"text",value:me,onChange:se=>Qe(se.target.value),onBlur:()=>Kt(me),onKeyDown:se=>{se.key==="Enter"&&(se.preventDefault(),Kt(me))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,A.jsxs)(x,{type:"button",variant:Ze>0?"secondary":"ghost",size:"sm",onClick:()=>L(se=>!se),"aria-expanded":_t,children:[(0,A.jsx)(Ma.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ze>0&&(0,A.jsx)(oe,{variant:"secondary",className:"af-ml-2",children:Ze})]}),Ct&&(0,A.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:fa,children:"Clear filters"}),(0,A.jsx)(Zt,{fetchCsv:he,filename:"orders",disabled:!!ke,className:"af-ml-auto"})]}),(_t||!!N||!!D)&&(0,A.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,A.jsx)(Oe,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,A.jsx)(re,{id:"orders-from",type:"date",value:N,max:D||void 0,onChange:se=>E(se.target.value),className:"af-w-[170px]"}),(0,A.jsx)(Oe,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,A.jsx)(re,{id:"orders-to",type:"date",value:D,min:N||void 0,onChange:se=>_(se.target.value),className:"af-w-[170px]"}),!Nl[Je].statusIn&&(0,A.jsx)(x,{type:"button",variant:Y?"secondary":"ghost",size:"sm",onClick:()=>Q(!Y),"aria-pressed":Y,children:Y?"Hide abandoned":"Show abandoned"})]}),xe&&(0,A.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(u)return(0,A.jsxs)("div",{className:t,children:[l?null:K,(0,A.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(se=>(0,A.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,A.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,A.jsx)(ae,{className:"af-h-4 af-w-16"}),(0,A.jsx)(ae,{className:"af-h-4 af-w-14"})]}),(0,A.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-40"}),(0,A.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-24"})]},se))}),(0,A.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,A.jsxs)(et,{children:[(0,A.jsx)(tt,{children:(0,A.jsxs)(Ie,{children:[(0,A.jsx)(j,{children:"Order"}),(0,A.jsx)(j,{children:"Date"}),(0,A.jsx)(j,{children:"Customer"}),(0,A.jsx)(j,{children:"Items"}),(0,A.jsx)(j,{className:"af-text-right",children:"Total"}),(0,A.jsx)(j,{children:"Status"}),(0,A.jsx)(j,{className:"af-w-8"})]})}),(0,A.jsx)(at,{"aria-hidden":"true",children:[0,1,2,3,4].map(se=>(0,A.jsxs)(Ie,{children:[(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-4 af-w-14"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-4 af-w-40"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-4 af-w-32"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-5 af-w-16"})}),(0,A.jsx)(G,{})]},se))})]})}),(0,A.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(f)return(0,A.jsxs)("div",{className:t,children:[l?null:K,(0,A.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,A.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,A.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>fe(),children:"Try again"})]})]});let ct=Je!=="all";if(rt.length===0&&p===0)return Ct||ct?(0,A.jsxs)("div",{className:t,children:[!l&&K,(0,A.jsx)(aa,{children:"No orders match these filters."})]}):(0,A.jsx)("div",{className:t,children:(0,A.jsx)(Ks,{icon:Ma.Receipt,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!l&&(0,A.jsx)(x,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>Q(!0),children:"Show abandoned checkouts"})})});let fs=p*b+1,Bi=Math.min((p+1)*b,g);return(0,A.jsxs)("div",{className:t,children:[l?null:K,(0,A.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ht.map(se=>(0,A.jsxs)("button",{type:"button",onClick:()=>yt(se),disabled:!Me,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Me?" hover:af-bg-muted/50":""}`,children:[(0,A.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,A.jsx)("span",{className:"af-font-medium",children:Is(se)}),(0,A.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:Z(vs(se),se.currency)})]}),(0,A.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,A.jsxs)("div",{className:"af-truncate af-text-sm",children:[se.customer_email||(0,A.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),ai(se)&&(0,A.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",ai(se)]})]}),(0,A.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:_l(se)}),se.amount_refunded>0&&(0,A.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Z(se.amount_refunded,se.currency)," refunded"]})]}),(0,A.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,A.jsx)(rn,{status:se.status}),(0,A.jsx)(Gn,{deliveries:se.email_deliveries}),se.is_test&&(0,A.jsx)(oe,{variant:"outline",children:"Test"}),a&&(0,A.jsx)(Pn,{order:se}),(0,A.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Rl(se.created_at)})]})]},se.id))}),(0,A.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,A.jsxs)(et,{children:[(0,A.jsx)(tt,{children:(0,A.jsxs)(Ie,{children:[(0,A.jsx)(j,{children:"Order"}),(0,A.jsx)(j,{children:"Date"}),(0,A.jsx)(j,{children:"Customer"}),(0,A.jsx)(j,{children:"Items"}),(0,A.jsx)(j,{className:"af-text-right",children:"Total"}),(0,A.jsx)(j,{children:"Status"}),(0,A.jsx)(j,{className:"af-w-8"})]})}),(0,A.jsx)(at,{children:ht.map(se=>(0,A.jsxs)(Ie,{onClick:Me?()=>yt(se):void 0,className:Me?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,A.jsxs)(G,{className:"af-whitespace-nowrap af-font-medium",children:[(0,A.jsx)("button",{type:"button",onClick:ia=>{ia.stopPropagation(),yt(se)},disabled:!Me,"aria-label":`Open order ${Is(se)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Me?" hover:af-underline":""}`,children:Is(se)}),se.is_test&&(0,A.jsx)(oe,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,A.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Rl(se.created_at)}),(0,A.jsxs)(G,{className:"af-max-w-[220px]",children:[(0,A.jsx)("div",{className:"af-truncate",children:se.customer_email||(0,A.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),ai(se)&&(0,A.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ai(se)})]}),(0,A.jsx)(G,{className:"af-max-w-[220px]",children:(0,A.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:_l(se)})}),(0,A.jsxs)(G,{className:"af-whitespace-nowrap af-text-right",children:[(0,A.jsx)("div",{className:"af-font-medium af-tabular-nums",children:Z(vs(se),se.currency)}),se.amount_refunded>0&&(0,A.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Z(se.amount_refunded,se.currency)," ","refunded"]})]}),(0,A.jsx)(G,{children:(0,A.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,A.jsx)(rn,{status:se.status}),(0,A.jsx)(Gn,{deliveries:se.email_deliveries}),a&&(0,A.jsx)(Pn,{order:se})]})}),(0,A.jsx)(G,{className:"af-w-8 af-text-right",children:(0,A.jsx)(Ma.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},se.id))})]})}),l?null:(0,A.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,A.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,A.jsx)("span",{children:Xt?`${rt.length} matching this page`:`Showing ${fs}-${Bi} of ${g}`}),(0,A.jsxs)(qa,{value:String(b),onValueChange:se=>y(Number(se)),children:[(0,A.jsx)(ka,{className:"af-w-[70px] af-h-8",children:(0,A.jsx)(Wa,{})}),(0,A.jsxs)(Ta,{children:[(0,A.jsx)(dt,{value:"10",children:"10"}),(0,A.jsx)(dt,{value:"25",children:"25"}),(0,A.jsx)(dt,{value:"50",children:"50"}),(0,A.jsx)(dt,{value:"100",children:"100"})]})]}),(0,A.jsx)("span",{children:"per page"})]}),(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,A.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>T(p-1),disabled:!P,children:[(0,A.jsx)(Ma.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,A.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>T(p+1),disabled:!w,children:["Next",(0,A.jsx)(Ma.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function Ds(e){return(0,A.jsx)(zu,{...e},e.maxRows==null?"full":"compact")}var Cn=ie(require("react"),1),hs=require("lucide-react");var ba=ie(require("react"),1);function fr({initialPageSize:e=25}={}){let{api:t}=W(),[s,n]=ba.useState([]),[a,r]=ba.useState(0),[o,c]=ba.useState(!0),[d,l]=ba.useState(null),[i,m]=ba.useState(0),[v,g]=ba.useState(e),[u,f]=ba.useState(""),p=ba.useRef(0),b=ba.useCallback(async()=>{let P=++p.current;try{c(!0),l(null);let T={limit:v,offset:i*v};u.trim()&&(T.email=u.trim());let y=await t.getCustomers(T);if(P!==p.current)return;n(y.customers),r(y.total)}catch(T){if(P!==p.current)return;l(T instanceof Error?T:new Error("Failed to fetch customers"))}finally{P===p.current&&c(!1)}},[t,i,v,u]);ba.useEffect(()=>{b()},[b]);let w=Math.ceil(a/v);return{customers:s,total:a,isLoading:o,error:d,page:i,pageSize:v,hasNextPage:i<w-1,hasPreviousPage:i>0,setPage:m,setPageSize:P=>{g(P),m(0)},email:u,setEmail:P=>{f(P),m(0)},refetch:b}}var ln=ie(require("react"),1),si=require("lucide-react");var _e=require("react/jsx-runtime");function Pl(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function qu(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&t.push(s),e.country&&t.push(e.country),t}function mr({customer:e,onBack:t,className:s}){let{api:n}=W(),[a,r]=ln.useState(null),[o,c]=ln.useState([]),[d,l]=ln.useState(!0),[i,m]=ln.useState(null);ln.useEffect(()=>{let u=!1;return l(!0),m(null),Promise.all([n.getCustomer(e.id),n.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([f,p])=>{u||(r(f),c(p.orders))}).catch(f=>{u||m(f instanceof Error?f.message:"Failed to load customer")}).finally(()=>{u||l(!1)}),()=>{u=!0}},[n,e.id,e.email]);let v=a?.addresses??[],g=a?.order_count??o.length;return(0,_e.jsxs)("div",{className:s,children:[(0,_e.jsxs)("div",{className:"af-mb-6",children:[(0,_e.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,_e.jsx)(si.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,_e.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,_e.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Pl(e.created_at)]})]}),d?(0,_e.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,_e.jsx)(si.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):i?(0,_e.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i}):(0,_e.jsxs)("div",{className:"af-space-y-6",children:[(0,_e.jsx)(ps,{deliveries:a?.email_deliveries}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,_e.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,_e.jsx)("span",{children:e.email})]}),e.name&&(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,_e.jsx)("span",{children:e.name})]}),e.phone&&(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,_e.jsx)("span",{children:e.phone})]}),(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,_e.jsx)("span",{children:g})]})]})]}),v.length>0&&(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,_e.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:v.map(u=>(0,_e.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&(0,_e.jsx)(oe,{variant:"secondary",className:"af-mb-1",children:"Default"}),qu(u).map((f,p)=>(0,_e.jsx)("div",{children:f},p))]},u.id))})]}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,_e.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,_e.jsxs)(et,{children:[(0,_e.jsx)(tt,{children:(0,_e.jsxs)(Ie,{children:[(0,_e.jsx)(j,{children:"Date"}),(0,_e.jsx)(j,{children:"Amount"}),(0,_e.jsx)(j,{children:"Status"})]})}),(0,_e.jsx)(at,{children:o.map(u=>(0,_e.jsxs)(Ie,{children:[(0,_e.jsx)(G,{className:"af-text-muted-foreground",children:Pl(u.created_at)}),(0,_e.jsx)(G,{children:Z(vs(u),u.currency)}),(0,_e.jsx)(G,{children:(0,_e.jsx)(Gs,{status:u.status})})]},u.id))})]})]})]})]})}var ye=require("react/jsx-runtime");function Wu(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 pr({className:e}){let{customers:t,total:s,isLoading:n,error:a,page:r,pageSize:o,hasNextPage:c,hasPreviousPage:d,setPage:l,setPageSize:i,email:m,setEmail:v,refetch:g}=fr(),{api:u}=W(),f=Cn.useCallback(()=>u.exportCustomersCsv(),[u]),[p,b]=Cn.useState("list"),[w,P]=Cn.useState(null),[T,y]=Cn.useState(""),C=D=>{P(D),b("detail")},k=()=>{b("list"),P(null),g()};if(p==="detail"&&w)return(0,ye.jsx)("div",{className:e,children:(0,ye.jsx)(mr,{customer:w,onBack:k})});let I=(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,ye.jsx)(re,{type:"email",value:T,onChange:D=>y(D.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),v(T.trim()))}}),(0,ye.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>v(T.trim()),children:[(0,ye.jsx)(hs.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),m&&(0,ye.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>{y(""),v("")},children:"Clear"}),(0,ye.jsx)(Zt,{fetchCsv:f,filename:"customers",className:"af-ml-auto"})]});if(n)return(0,ye.jsxs)("div",{className:e,children:[I,(0,ye.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ye.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(a)return(0,ye.jsxs)("div",{className:e,children:[I,(0,ye.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ye.jsxs)("div",{className:"af-text-destructive",children:["Error: ",a.message]})})]});if(t.length===0&&r===0)return(0,ye.jsxs)("div",{className:e,children:[m&&I,(0,ye.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,ye.jsx)(hs.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ye.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:m?"No customers match that email.":(0,ye.jsxs)(ye.Fragment,{children:["No customers yet.",(0,ye.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let N=r*o+1,E=Math.min((r+1)*o,s);return(0,ye.jsxs)("div",{className:e,children:[I,(0,ye.jsxs)(et,{children:[(0,ye.jsx)(tt,{children:(0,ye.jsxs)(Ie,{children:[(0,ye.jsx)(j,{children:"Email"}),(0,ye.jsx)(j,{children:"Name"}),(0,ye.jsx)(j,{children:"Phone"}),(0,ye.jsx)(j,{children:"Customer since"}),(0,ye.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,ye.jsx)(at,{children:t.map(D=>(0,ye.jsxs)(Ie,{children:[(0,ye.jsx)(G,{className:"af-font-medium",children:D.email}),(0,ye.jsx)(G,{children:D.name||(0,ye.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ye.jsx)(G,{children:D.phone||(0,ye.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ye.jsx)(G,{className:"af-text-muted-foreground",children:Wu(D.created_at)}),(0,ye.jsx)(G,{className:"af-text-right",children:(0,ye.jsx)(x,{variant:"ghost",size:"icon",onClick:()=>C(D),title:"View customer",children:(0,ye.jsx)(hs.Eye,{className:"af-h-4 af-w-4"})})})]},D.id))})]}),(0,ye.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ye.jsxs)("span",{children:["Showing ",N,"-",E," of ",s]}),(0,ye.jsxs)(qa,{value:String(o),onValueChange:D=>i(Number(D)),children:[(0,ye.jsx)(ka,{className:"af-w-[70px] af-h-8",children:(0,ye.jsx)(Wa,{})}),(0,ye.jsxs)(Ta,{children:[(0,ye.jsx)(dt,{value:"10",children:"10"}),(0,ye.jsx)(dt,{value:"25",children:"25"}),(0,ye.jsx)(dt,{value:"50",children:"50"}),(0,ye.jsx)(dt,{value:"100",children:"100"})]})]}),(0,ye.jsx)("span",{children:"per page"})]}),(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ye.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>l(r-1),disabled:!d,children:[(0,ye.jsx)(hs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ye.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>l(r+1),disabled:!c,children:["Next",(0,ye.jsx)(hs.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ve=ie(require("react"),1),Bt=require("lucide-react");var Ot=ie(require("react"),1);function cn({initialPageSize:e=25,refreshKey:t,includeAggregates:s=!1}={}){let{api:n}=W(),[a,r]=Ot.useState([]),[o,c]=Ot.useState(0),[d,l]=Ot.useState(null),[i,m]=Ot.useState(!0),[v,g]=Ot.useState(null),[u,f]=Ot.useState(0),[p,b]=Ot.useState(e),[w,P]=Ot.useState(void 0),[T,y]=Ot.useState(""),[C,k]=Ot.useState(""),[I,N]=Ot.useState(""),[E,D]=Ot.useState(""),[_,Y]=Ot.useState(""),Q=w?w.join(","):"",z=Ot.useRef(0),le=Ot.useCallback(async()=>{let he=++z.current;m(!0),g(null);try{let M={labels:Q?Q.split(","):void 0,customerEmail:T||void 0,q:C||void 0,from:I||void 0,to:E||void 0,retainerId:_||void 0,includeAggregates:s,limit:p,offset:u*p},ee=await n.getInvoices(M);if(he!==z.current)return;if(u>0&&u*p>=ee.total){f(Math.max(0,Math.ceil(ee.total/p)-1));return}r(ee.invoices),c(ee.total),s&&l(ee.aggregates??null)}catch(M){if(he!==z.current)return;g(M instanceof Error?M:new Error("Failed to fetch invoices"))}finally{he===z.current&&m(!1)}},[n,Q,T,C,I,E,_,u,p,s]);Ot.useEffect(()=>{le()},[le,t]);let fe=he=>M=>{f(0),he(M)};return{invoices:a,total:o,aggregates:d,isLoading:i,error:v,page:u,pageSize:p,hasNextPage:(u+1)*p<o,hasPreviousPage:u>0,setPage:f,setPageSize:fe(b),labels:w,setLabels:fe(P),customerEmail:T,setCustomerEmail:fe(y),q:C,setQ:fe(k),from:I,setFrom:fe(N),to:E,setTo:fe(D),retainerId:_,setRetainerId:fe(Y),clearFilters:()=>{f(0),P(void 0),y(""),k(""),N(""),D(""),Y("")},refetch:le}}var S=require("react/jsx-runtime"),ju={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 Qi(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:ju[e.label]??e.label}function Gu(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 Xi={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Ku={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Tn({invoice:e,className:t}){return(0,S.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,S.jsx)(oe,{variant:Gu(e.label),className:t,children:Qi(e)}),e.collection_method==="charge_automatically"&&(0,S.jsx)(oe,{variant:"secondary",children:"Managed in Stripe"})]})}function ii({delivery:e,className:t}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,S.jsx)(oe,{variant:s,className:t,children:Xi[e.state]??e.state})}function kn(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function Ja(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Cl={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},ni={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},Yi=100,Ji=5e3;async function Zu(e,t){let s=[],n=0;for(let a=0;a<Ji;a+=Yi){let r=await e.getInvoices({...t,limit:Yi,offset:a});if(n=r.total,s.push(...r.invoices),r.invoices.length<Yi||s.length>=n)break}return{invoices:s.slice(0,Ji),total:n,truncated:n>s.length||n>Ji}}function Tl(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],s=e.map(n=>[n.id,kn(n),Qi(n),n.customer_name??"",n.customer_email??"",n.created_at,n.due_at??"",n.paid_at??"",n.currency.toUpperCase(),Z(n.amount_subtotal,n.currency),Z(n.tax_total,n.currency),Z(n.amount_total,n.currency),n.amount_due===null?"":Z(n.amount_due,n.currency),n.amount_paid===null?"":Z(n.amount_paid,n.currency),Z(n.amount_refunded,n.currency),n.payment_method??"",n.pay_url??"",n.retainer_id??"",n.replaces_order_id??"",n.replaced_by_order_id??"",n.tax_behavior??"",n.discount_total===void 0?"":Z(n.discount_total,n.currency),n.collection_method??""]);return[t,...s].map(n=>n.map(ll).join(",")).join(`
|
|
5
|
+
`)}function Yu(e){Gr(new Blob([Tl(e)],{type:"text/csv;charset=utf-8"}),jr("invoices"))}function Ju({className:e,refreshKey:t,initialInvoiceId:s,onDetailOpenChange:n,onConnectStripe:a,onUpgradePlan:r,needsPaidPlan:o=!1,retainerFilter:c=null,onClearRetainerFilter:d,maxRows:l,onViewAll:i}){let m=typeof l=="number",{api:v}=W(),{invoices:g,total:u,isLoading:f,error:p,page:b,pageSize:w,hasNextPage:P,hasPreviousPage:T,setPage:y,labels:C,setLabels:k,customerEmail:I,setCustomerEmail:N,q:E,setQ:D,from:_,setFrom:Y,to:Q,setTo:z,retainerId:le,setRetainerId:fe,refetch:he}=cn({refreshKey:t}),[M,ee]=Ve.useState(typeof l=="number"?"all":"open"),[U,ve]=Ve.useState(""),[me,Qe]=Ve.useState(null),ke=Ve.useRef(0),Ge=!m||!!i,Je=Ve.useCallback(K=>{if(m){i?.();return}ke.current++,_t(!1),Qe(K)},[m,i]),[Fe,_t]=Ve.useState(!1),[L,$]=Ve.useState(0),[F,Re]=Ve.useState(null),[te,we]=Ve.useState(!1),[He,bt]=Ve.useState(0);Ve.useEffect(()=>{Qe(K=>{if(!K)return K;let ct=g.find(fs=>fs.id===K.id);return ct&&ct!==K?ct:K})},[g]);let[Ze,Ct]=Ve.useState(!1),[xe,Me]=Ve.useState(null),yt=async()=>{if(!Ze){Ct(!0),Me(null);try{let{invoices:K,total:ct,truncated:fs}=await Zu(v,{labels:C,customerEmail:I,q:E,from:_,to:Q,retainerId:le});Yu(K),Me(fs?`Exported the first ${K.length.toLocaleString()} of ${ct.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Me("Couldn't export \u2014 try again.")}finally{Ct(!1)}}},Pa=!I&&!E&&!_&&!Q&&!le,[Kt,fa]=Ve.useState(null);Ve.useEffect(()=>{if(f||u>0||!Pa||M!=="open")return;let K=!1;return v.getInvoices({limit:1}).then(ct=>{K||fa(ct.total>0)}).catch(()=>{K||fa(!0)}),()=>{K=!0}},[v,f,u,Pa,M,t]),Ve.useEffect(()=>{k(m?ni.all:ni.open)},[]),Ve.useEffect(()=>{let K=c?.id??"";K!==le&&(fe(K),K&&(ee("all"),k(ni.all),N(""),D(""),ve(""),Y(""),z("")))},[c?.id]),Ve.useEffect(()=>{let K=!1;return we(!1),v.getInvoiceSettings().then(ct=>{K||Re({payments_active:ct.payments_active,blocked:ct.blocked})}).catch(()=>{K||we(!0)}),()=>{K=!0}},[v,t,He]),Ve.useEffect(()=>{if(!s||m)return;let K=!1,ct=ke.current;return _t(!1),v.getInvoice(s).then(fs=>{!K&&ct===ke.current&&Qe(fs)}).catch(()=>{!K&&ct===ke.current&&_t(!0)}),()=>{K=!0}},[v,s,L,m]),Ve.useEffect(()=>{n?.(me!==null)},[me,n]);let Xt=K=>{ee(K),k(ni[K])},rt=K=>{let ct=K.trim();if(!ct){E&&D(""),I&&N("");return}if(ct.includes("@")){E&&D(""),N(ct);return}I&&N(""),D(ct.replace(/^#/,""))},ht=g,ss=m?ht.slice(0,l):ht,en=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)(x,{type:"button",variant:"link",size:"sm",onClick:()=>$(K=>K+1),children:"Retry opening invoice"})]});if(me)return(0,S.jsxs)("div",{className:e,children:[en,(0,S.jsx)(oi,{invoice:me,refreshKey:t,onBack:()=>{Je(null),he()}},me.id)]});let ma=(0,S.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[te&&(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)(x,{type:"button",variant:"link",size:"sm",onClick:()=>bt(K=>K+1),children:"Retry setup check"})]}),en,F?.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",F.blocked.reason?`: ${F.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),c&&(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,S.jsxs)(oe,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",c.label]}),d&&(0,S.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:d,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(Cl).map(K=>(0,S.jsx)("button",{type:"button","aria-pressed":M===K,onClick:()=>Xt(K),className:J("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",M===K?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Cl[K]},K))}),(0,S.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,S.jsx)(Bt.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,S.jsx)(re,{type:"text",value:U,onChange:K=>ve(K.target.value),onBlur:()=>rt(U),onKeyDown:K=>{K.key==="Enter"&&(K.preventDefault(),rt(U))},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)(Oe,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,S.jsx)(re,{id:"invoices-from",type:"date",value:_,max:Q||void 0,onChange:K=>Y(K.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)(Oe,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,S.jsx)(re,{id:"invoices-to",type:"date",value:Q,min:_||void 0,onChange:K=>z(K.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,S.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>void yt(),disabled:Ze||f||!!p||u===0,"aria-busy":Ze,children:[(0,S.jsx)(Bt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),Ze?"Exporting\u2026":"Export CSV (all matching)"]})]}),xe&&(0,S.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:xe})]});return f?(0,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(K=>(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"})]},K))})]}):p?(0,S.jsxs)("div",{className:e,children:[m?null:ma,(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)(x,{type:"button",variant:"link",size:"sm",onClick:()=>void he(),children:"Retry"})]})]}):u===0&&Pa&&(M==="all"||Kt===!1)&&(M==="open"||M==="all")?F?.blocked?(0,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)(ri,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)(ri,{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,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)(ri,{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,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)(ri,{heading:"No invoices yet",body:!F||te?"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:[m?null:ma,ss.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:ss.map(K=>(0,S.jsxs)("button",{type:"button",onClick:()=>Je(K),disabled:!Ge,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ge?" hover:af-bg-muted/50":""}`,children:[(0,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:kn(K)}),(0,S.jsx)(Tn,{invoice:K})]}),(0,S.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:K.customer_name??K.customer_email??"\u2014"}),K.delivery&&(0,S.jsx)("div",{className:"af-mt-1",children:(0,S.jsx)(ii,{delivery:K.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:K.collection_method==="charge_automatically"?"Automatic collection":K.due_at?`Due ${Ja(K.due_at)}`:"Due on receipt"}),(0,S.jsx)("span",{className:"af-font-medium af-tabular-nums",children:Z(K.amount_due??K.amount_total,K.currency)})]})]},K.id))}),(0,S.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,S.jsxs)(et,{children:[(0,S.jsx)(tt,{children:(0,S.jsxs)(Ie,{children:[(0,S.jsx)(j,{children:"Invoice"}),(0,S.jsx)(j,{children:"Created"}),(0,S.jsx)(j,{children:"Customer"}),(0,S.jsx)(j,{children:"Due"}),(0,S.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,S.jsx)(j,{children:"Status"}),(0,S.jsx)(j,{children:"Delivery"}),(0,S.jsx)(j,{className:"af-w-8"})]})}),(0,S.jsx)(at,{children:ss.map(K=>(0,S.jsxs)(Ie,{className:Ge?"af-cursor-pointer":void 0,onClick:Ge?()=>Je(K):void 0,children:[(0,S.jsx)(G,{className:"af-font-medium",children:(0,S.jsx)("button",{type:"button",disabled:!Ge,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ge?" hover:af-underline":""}`,onClick:ct=>{ct.stopPropagation(),Je(K)},"aria-label":`Open invoice ${kn(K)}`,children:kn(K)})}),(0,S.jsx)(G,{children:Ja(K.created_at)}),(0,S.jsxs)(G,{children:[(0,S.jsx)("div",{children:K.customer_name??"\u2014"}),(0,S.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:K.customer_email})]}),(0,S.jsx)(G,{children:K.collection_method==="charge_automatically"?"Automatic":K.due_at?Ja(K.due_at):"On receipt"}),(0,S.jsx)(G,{className:"af-text-right af-tabular-nums",children:Z(K.amount_due??K.amount_total,K.currency)}),(0,S.jsx)(G,{children:(0,S.jsx)(Tn,{invoice:K})}),(0,S.jsx)(G,{children:(0,S.jsx)(ii,{delivery:K.delivery})}),(0,S.jsx)(G,{children:(0,S.jsx)(Bt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},K.id))})]})}),m?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:[u," invoice",u===1?"":"s"]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b-1),disabled:!T,"aria-label":"Previous page",children:(0,S.jsx)(Bt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,S.jsxs)("span",{className:"af-tabular-nums",children:[b*w+1,"\u2013",Math.min((b+1)*w,u)]}),(0,S.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b+1),disabled:!P,"aria-label":"Next page",children:(0,S.jsx)(Bt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function ri({heading:e,body:t,action:s}){return(0,S.jsx)(Ks,{icon:Bt.FileText,heading:e,body:t,action:s})}function Ls(e){return(0,S.jsx)(Ju,{...e},e.maxRows==null?"full":"compact")}var As="af-text-xs af-text-muted-foreground";function kl(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function oi({invoice:e,onBack:t,refreshKey:s,className:n}){let{api:a}=W(),r=Ve.useRef(null);Ve.useEffect(()=>{r.current?.focus()},[e.id]);let[o,c]=Ve.useState(!1),[d,l]=Ve.useState(null),[i,m]=Ve.useState(!1),[v,g]=Ve.useState(!1),u=Ve.useRef(0),[f,p]=Ve.useState(null),[b,w]=Ve.useState(!1),[P,T]=Ve.useState(0);Ve.useEffect(()=>{let _=!1;return w(!1),a.getInvoice(e.id).then(Y=>{_||p({source:e,value:Y})}).catch(()=>{_||w(!0)}),()=>{_=!0}},[a,e,s,P]);let y=f?.source===e?f.value:e,C=y.collection_method==="charge_automatically";Ve.useEffect(()=>(u.current++,l(null),m(!1),g(!1),c(!1),()=>{u.current++}),[a,y,s]);let k=_=>_==null?"\u2014":Z(_,y.currency),I=async()=>{if(!(!y.pay_url||!kl()))try{await navigator.clipboard.writeText(y.pay_url),c(!0),setTimeout(()=>c(!1),1500)}catch{}},N=async()=>{if(d){l(null);return}let _=++u.current;g(!1),m(!0);try{let Y=await a.getInvoicePreview(y.id);_===u.current&&l(Y)}catch{_===u.current&&g(!0)}finally{_===u.current&&m(!1)}},E=y.bill_to,D=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(_=>!!_&&_.length>0):[];return(0,S.jsxs)("div",{className:n,children:[(0,S.jsxs)("div",{className:"af-mb-4",children:[(0,S.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,S.jsx)(Bt.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 ",kn(y)]}),(0,S.jsx)(Tn,{invoice:y}),(0,S.jsx)(ii,{delivery:y.delivery})]}),(0,S.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[y.customer_name??y.customer_email,y.customer_name&&y.customer_email?` \xB7 ${y.customer_email}`:""]})]}),b&&(0,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)(x,{type:"button",variant:"link",size:"sm",onClick:()=>T(_=>_+1),children:"Retry details"})]}),y.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."}),y.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)(et,{children:[(0,S.jsx)(tt,{children:(0,S.jsxs)(Ie,{children:[(0,S.jsx)(j,{children:"Description"}),(0,S.jsx)(j,{className:"af-text-right",children:"Qty"}),(0,S.jsx)(j,{className:"af-text-right",children:"Amount"})]})}),(0,S.jsx)(at,{children:y.line_items.map((_,Y)=>(0,S.jsxs)(Ie,{children:[(0,S.jsx)(G,{style:{overflowWrap:"anywhere"},children:_.description}),(0,S.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_.quantity}),(0,S.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:k(_.amount)})]},Y))})]}),(0,S.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,S.jsx)(Zs,{label:"Subtotal",value:k(y.amount_subtotal)}),(y.discount_total??0)>0&&(0,S.jsx)(Zs,{label:"Discount",value:`-${k(y.discount_total)}`}),y.tax_total>0&&(0,S.jsx)(Zs,{label:y.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:k(y.tax_total)}),(0,S.jsx)(Zs,{label:"Total",value:k(y.amount_total),strong:!0}),y.credit_applied>0&&(0,S.jsx)(Zs,{label:"Credit applied",value:`-${k(y.credit_applied)}`}),y.amount_due!==null&&y.amount_due!==y.amount_total&&(0,S.jsx)(Zs,{label:"Amount due",value:k(y.amount_due),strong:!0}),y.amount_paid!==null&&y.amount_paid>0&&(0,S.jsx)(Zs,{label:"Amount paid",value:k(y.amount_paid)}),y.amount_refunded>0&&(0,S.jsx)(Zs,{label:"Refunded",value:k(y.amount_refunded)})]}),y.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:As,children:"Credit notes"}),y.credit_notes.map(_=>(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:[Ja(_.created_at)," \xB7 ",_.origin==="dashboard"?"issued in Stripe":"refund",_.stripe_credit_note_id?"":" \xB7 being created"]}),(0,S.jsxs)("span",{className:"af-tabular-nums",children:["-",Z(_.amount,_.currency)]})]},_.id))]})]}),(y.note||y.footer)&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[y.note&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:As,children:"Note"}),(0,S.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:y.note})]}),y.footer&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:As,children:"Footer"}),(0,S.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:y.footer})]})]}),d&&!C&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,S.jsxs)("div",{className:J(As,"af-break-words"),children:["Email preview \u2014 ",d.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:d.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)(Ya,{label:"Created",value:Ja(y.created_at)}),(0,S.jsx)(Ya,{label:"Due",value:y.collection_method==="charge_automatically"?"Managed in Stripe":y.due_at?Ja(y.due_at):"On receipt"}),y.paid_at&&(0,S.jsx)(Ya,{label:"Paid",value:Ja(y.paid_at)}),y.payment_method&&(0,S.jsx)(Ya,{label:"Paid by",value:y.paid_out_of_band?`${y.payment_method} (recorded outside Stripe)`:y.payment_method}),y.payment_state!=="none"&&(0,S.jsx)(Ya,{label:"Payment",value:y.payment_state==="processing"?"Processing":y.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),y.delivery&&(0,S.jsx)(Ya,{label:"Delivery",value:`${Xi[y.delivery.state]} \xB7 ${y.delivery.recipient}`}),y.marked_uncollectible_at&&(0,S.jsx)(Ya,{label:"Written off",value:Ja(y.marked_uncollectible_at)}),y.correction_reason&&(0,S.jsx)(Ya,{label:"Correction",value:y.correction_reason}),y.replaced_by_order_id&&(0,S.jsx)(Ya,{label:"Replaced by",value:y.replaced_by_order_id}),y.collection_method==="charge_automatically"?(0,S.jsx)(Ya,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):y.retainer_id&&(0,S.jsx)(Ya,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),y.replaces_order_id&&(0,S.jsx)(Ya,{label:"Replaces",value:y.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:As,children:"Reminders"}),C?(0,S.jsx)("div",{children:"View automatic payment reminders in Stripe."}):y.reminders.disabled?(0,S.jsx)("div",{children:"Off for this invoice."}):y.reminders.paused_until?(0,S.jsxs)("div",{children:["Paused until ",Ja(y.reminders.paused_until),"."]}):y.reminders.next_at?(0,S.jsxs)("div",{children:["Next on ",Ja(y.reminders.next_at),"."]}):y.reminders.final_sent_at?(0,S.jsxs)("div",{children:["Final reminder sent ",Ja(y.reminders.final_sent_at),"."]}):(0,S.jsx)("div",{children:"None scheduled."}),!C&&(0,S.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",y.reminders.schedule.length===0?"none":y.reminders.schedule.map(_=>_<0?`${-_}d before`:_===0?"due day":`${_}d after`).join(", ")]})]}),y.communications&&y.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:As,children:"Email delivery history"}),y.communications.map(_=>(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:[Ku[_.kind]??_.kind,_.kind==="reminder"&&_.slot!==null?` #${_.slot}`:"",(0,S.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",_.recipient]})]}),(0,S.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Xi[_.state]??_.state," \xB7 ",Ja(_.state_at??_.created_at)]})]},_.id))]}),D.length>0&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,S.jsx)("div",{className:As,children:"Bill to"}),D.map((_,Y)=>(0,S.jsx)("div",{className:"af-break-words",children:_},Y))]}),(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[y.pay_url&&(0,S.jsxs)(x,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void I(),disabled:!kl(),children:[(0,S.jsx)(Bt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":C?"Copy invoice link":"Copy pay link"]}),y.pdf_url&&(0,S.jsx)(x,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,S.jsxs)("a",{href:y.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,S.jsx)(Bt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!C&&(0,S.jsxs)(x,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void N(),disabled:i,children:[i?(0,S.jsx)(Bt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(Bt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),d?"Hide email preview":v?"Retry email preview":"Show email preview"]}),v&&!C&&(0,S.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),y.pay_url&&(0,S.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:y.pay_url}),(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:C?"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 Ya({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:J(As,"af-shrink-0"),children:e}),(0,S.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function Zs({label:e,value:t,strong:s}){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:J(As,s&&"af-font-medium af-text-foreground"),children:e}),(0,S.jsx)("dd",{className:J("af-tabular-nums",s&&"af-font-semibold"),children:t})]})}var Il=require("lucide-react");var qe=require("react/jsx-runtime"),Xu={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},El={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Qu(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 Dl(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>El[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>El[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Xu[e.status]}function Al(e){let t=e.interval==="year"?"every year":"every month";return`${Z(e.amount,e.currency)} ${t}`}function ed(e){return e.status==="canceled"?`Ended ${li(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${li(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 ${li(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${li(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function li(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(t);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ci({retainer:e,className:t}){return(0,qe.jsx)(oe,{variant:Qu(e.status),className:J("af-max-w-full af-whitespace-normal af-break-words",t),children:Dl(e)})}function un({retainers:e,isLoading:t,error:s,onRetry:n,onShowCycles:a,activeRetainerId:r,total:o,endedTotal:c=0,isLoadingMore:d=!1,onLoadMore:l,includeEnded:i=!1,onIncludeEndedChange:m,exportCsv:v,className:g}){let u=!!m;if(!t&&!s&&e.length===0&&!(u&&(i||c>0)))return null;let f=o!==void 0?Math.max(0,o-e.length):0;return(0,qe.jsxs)("section",{className:J("af-mb-6",g),"aria-label":"Recurring invoices",children:[(0,qe.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,qe.jsx)(Il.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,qe.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,qe.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."}),u&&(0,qe.jsx)(x,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":i,onClick:()=>m?.(!i),children:i?"Hide ended recurring invoices":c>0&&e.length===0?`Show ended recurring invoices (${c})`:"Show ended recurring invoices"}),v&&(0,qe.jsx)(Zt,{fetchCsv:v,filename:"retainers",className:u?void 0:"af-ml-auto"})]}),s?(0,qe.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,qe.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:n,children:"Retry"})]}):t?(0,qe.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(p=>(0,qe.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,qe.jsx)(ae,{className:"af-h-4 af-w-48"}),(0,qe.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-32"})]},p))}):e.length===0?(0,qe.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,qe.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(p=>{let b=r===p.id;return(0,qe.jsxs)("li",{className:J("af-rounded-md af-border af-p-3",b&&"af-border-primary af-bg-muted/40"),children:[(0,qe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,qe.jsxs)("div",{className:"af-min-w-0",children:[(0,qe.jsx)("div",{className:"af-truncate af-font-medium",children:p.customer_name??p.customer_email??"\u2014"}),(0,qe.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:p.description})]}),(0,qe.jsx)(ci,{retainer:p})]}),p.collection_method==="charge_automatically"?(0,qe.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,qe.jsx)(oe,{variant:"secondary",children:"Managed in Stripe"}),(0,qe.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,qe.jsx)("div",{className:"af-mt-2 af-text-sm",children:Al(p)}),(0,qe.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,qe.jsxs)("span",{children:[ed(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,qe.jsx)(x,{type:"button",variant:b?"secondary":"ghost",size:"sm",onClick:()=>a(p),"aria-pressed":b,children:b?"Showing invoices":"View invoices"})]}),p.status==="failed"&&p.operation?.last_error&&(0,qe.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&&!s&&f>0&&l&&(0,qe.jsx)("div",{className:"af-mt-2",children:(0,qe.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:d,children:d?"Loading\u2026":`Load more (${f} more)`})})]})}var Ll=ie(require("react"),1),$a=require("lucide-react");var De=require("react/jsx-runtime");function dn({onConnectStripe:e,onUpgradePlan:t,whenActive:s,className:n}){let{status:a,isLoading:r,error:o,refetch:c}=Ts(),[d,l]=Ll.useState(!1),i=async()=>{l(!0);try{await c()}finally{l(!1)}};return r&&!a?(0,De.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:(0,De.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):o||!a?(0,De.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:(0,De.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o?.message||"Failed to load payment status"]})}):a.status==="active"?s!==void 0?(0,De.jsx)("div",{className:n,children:s}):(0,De.jsx)("div",{className:n,children:(0,De.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,De.jsx)($a.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,De.jsxs)("div",{children:[(0,De.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,De.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,De.jsxs)("div",{className:`af-space-y-4 ${n||""}`,children:[a.reason==="needs_stripe"&&(0,De.jsxs)("div",{className:"af-space-y-3",children:[(0,De.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,De.jsx)($a.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,De.jsxs)("div",{children:[(0,De.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,De.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,De.jsxs)(x,{onClick:e,children:[(0,De.jsx)($a.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,De.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,De.jsxs)("div",{className:"af-space-y-3",children:[(0,De.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,De.jsx)($a.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,De.jsxs)("div",{children:[(0,De.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,De.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,De.jsx)(x,{onClick:t,children:"Upgrade plan"}):(0,De.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,De.jsxs)("div",{className:"af-space-y-3",children:[(0,De.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,De.jsx)($a.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,De.jsxs)("div",{children:[(0,De.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?(0,De.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,De.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,De.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&(0,De.jsxs)(x,{onClick:e,children:[(0,De.jsx)($a.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,De.jsxs)(x,{variant:"outline",onClick:i,disabled:d,children:[d?(0,De.jsx)($a.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,De.jsx)($a.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var la=ie(require("react"),1);function eo(e,t,s){return e.map(n=>n.id===t?{...n,...s}:n)}function fn({includeStats:e=!1,refreshKey:t}={}){let{api:s}=W(),[n,a]=la.useState([]),[r,o]=la.useState(!0),[c,d]=la.useState(null),l=la.useRef(0),i=la.useCallback(async()=>{let p=++l.current;try{o(!0),d(null);let b=await s.getProducts(e?{include:"stats"}:{});if(p!==l.current)return;a(b)}catch(b){if(p!==l.current)return;d(b instanceof Error?b:new Error("Failed to fetch products"))}finally{p===l.current&&o(!1)}},[s,e,t]);la.useEffect(()=>{i()},[i]);let m=la.useCallback(async p=>{let b=await s.createProduct(p);return a(w=>[b,...w]),b},[s]),v=la.useCallback(async(p,b)=>{let w=await s.updateProduct(p,b);return a(P=>eo(P,p,w)),w},[s]),g=la.useCallback(async p=>{await s.deleteProduct(p),a(b=>b.filter(w=>w.id!==p))},[s]),u=la.useCallback(async(p,b)=>{let w=await s.attachProductFile(p,b);return a(P=>eo(P,p,w)),w},[s]),f=la.useCallback(async(p,b)=>{let w=await s.attachProductFileFromUrl(p,b);return a(P=>eo(P,p,w)),w},[s]);return{products:n,isLoading:r,error:c,refetch:i,createProduct:m,updateProduct:v,deleteProduct:g,attachProductFile:u,attachProductFileFromUrl:f}}var ca=ie(require("react"),1);var to=["creating","active","paused","canceling"],td=["canceled","failed"],ad={statuses:to},sd={};function mn({refreshKey:e,includeEnded:t=!1,limit:s=50}={}){let{api:n}=W(),[a,r]=ca.useState([]),[o,c]=ca.useState(0),[d,l]=ca.useState(0),[i,m]=ca.useState(!0),[v,g]=ca.useState(!1),[u,f]=ca.useState(null),[p,b]=ca.useState(t),w=ca.useRef(0),P=ca.useCallback(async()=>{let y=++w.current;m(!0),g(!1),f(null);try{let C=await n.getRetainers({statuses:p?void 0:to,limit:s,offset:0});if(y!==w.current)return;if(r(C.retainers),c(C.total),!p&&C.total===0){let k=await n.getRetainers({statuses:td,limit:1,offset:0});if(y!==w.current)return;l(k.total)}else l(0)}catch(C){if(y!==w.current)return;f(C instanceof Error?C:new Error("Failed to fetch retainers"))}finally{y===w.current&&m(!1)}},[n,p,s]);ca.useEffect(()=>{P()},[P,e]);let T=ca.useCallback(async()=>{if(i||v||a.length>=o)return;let y=w.current;g(!0);try{let C=await n.getRetainers({statuses:p?void 0:to,limit:s,offset:a.length});if(y!==w.current)return;r(k=>{let I=new Set(k.map(N=>N.id));return[...k,...C.retainers.filter(N=>!I.has(N.id))]}),c(C.total)}catch(C){if(y!==w.current)return;f(C instanceof Error?C:new Error("Failed to fetch retainers"))}finally{y===w.current&&g(!1)}},[n,p,s,i,v,a.length,o]);return{retainers:a,total:o,endedTotal:d,hasMore:a.length<o,isLoading:i,isLoadingMore:v,error:u,includeEnded:p,setIncludeEnded:b,loadMore:T,refetch:P,filters:p?sd:ad}}var Ee=require("react/jsx-runtime");function ao({className:e,defaultTab:t="products",onConnectStripe:s,onRefund:n,onUpgradePlan:a}){let[r,o]=En.useState(t),[c,d]=En.useState("list"),[l,i]=En.useState(null),m=fn(),{status:v,error:g}=Ts(),u=v?.currency,f=P=>{i(P),d("edit")},p=()=>{i(null),d("create")},b=()=>{d("list"),i(null)},w=P=>{i(P),d("edit")};return(0,Ee.jsxs)("div",{className:e,children:[(0,Ee.jsxs)("div",{className:"af-mb-6",children:[(0,Ee.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Ee.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Ee.jsxs)(Hr,{value:r,onValueChange:P=>o(P),children:[(0,Ee.jsxs)(qn,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Ee.jsxs)(is,{value:"products",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Ee.jsxs)(is,{value:"orders",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Ee.jsxs)(is,{value:"invoices",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Ee.jsxs)(is,{value:"customers",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Ee.jsx)(is,{value:"promos",children:"Promo codes"}),(0,Ee.jsxs)(is,{value:"setup",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Ee.jsx)(os,{value:"products",children:c==="list"?(0,Ee.jsx)(rr,{productsState:m,onSelectProduct:f,onCreateProduct:p}):(0,Ee.jsxs)("div",{children:[(0,Ee.jsxs)("div",{className:"af-mb-6",children:[(0,Ee.jsxs)(x,{variant:"ghost",size:"sm",onClick:b,className:"af-mb-2 af--ml-2",children:[(0,Ee.jsx)(Xa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Ee.jsx)("h3",{className:"af-text-lg af-font-semibold",children:c==="create"?"New Product":l?.name})]}),c==="create"&&!u?(0,Ee.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?(0,Ee.jsxs)("div",{className:"af-text-destructive",children:["Error: ",g.message]}):(0,Ee.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Ee.jsx)(or,{productsState:m,product:c==="edit"?l:null,currency:u??"usd",onSaved:w},c==="edit"?l?.id??"edit":"new")]})}),(0,Ee.jsx)(os,{value:"orders",children:(0,Ee.jsx)(Ds,{onRefund:n})}),(0,Ee.jsx)(os,{value:"invoices",children:(0,Ee.jsx)(nd,{onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:v?.reason==="needs_paid_plan"})}),(0,Ee.jsx)(os,{value:"customers",children:(0,Ee.jsx)(pr,{})}),(0,Ee.jsx)(os,{value:"promos",children:(0,Ee.jsx)(nn,{})}),(0,Ee.jsx)(os,{value:"setup",children:(0,Ee.jsx)(dn,{onConnectStripe:s,onUpgradePlan:a})})]})]})}function nd({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s}){let n=mn(),[a,r]=En.useState(null),[o,c]=En.useState(!1);return(0,Ee.jsxs)(Ee.Fragment,{children:[!o&&(0,Ee.jsx)(un,{retainers:n.retainers,isLoading:n.isLoading,error:n.error,onRetry:()=>void n.refetch(),activeRetainerId:a?.id??null,onShowCycles:d=>r(l=>l?.id===d.id?null:d),total:n.total,endedTotal:n.endedTotal,isLoadingMore:n.isLoadingMore,onLoadMore:()=>void n.loadMore(),includeEnded:n.includeEnded,onIncludeEndedChange:n.setIncludeEnded}),(0,Ee.jsx)(Ls,{onDetailOpenChange:c,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s,retainerFilter:a?{id:a.id,label:`${a.customer_name??a.customer_email??"Recurring invoices"} \u2014 ${a.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}var Bl=ie(require("react"),1);var xs=ie(require("react"),1);function pn({refreshKey:e}={}){let{api:t}=W(),[s,n]=xs.useState(null),[a,r]=xs.useState(!0),[o,c]=xs.useState(null),d=xs.useRef(0),l=xs.useCallback(async()=>{let i=++d.current;try{r(!0),c(null);let m=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(i!==d.current)return;n(m)}catch(m){if(i!==d.current)return;c(m instanceof Error?m:new Error("Failed to fetch summary"))}finally{i===d.current&&r(!1)}},[t,e]);return xs.useEffect(()=>{l()},[l]),{summary:s,isLoading:a,error:o,refetch:l}}var nt=require("react/jsx-runtime");function Ol(e,t){if(e.settled.complete)return{headline:Z(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:Z(s.gross,s.currency),extra:e.totals.slice(1).map(n=>`+ ${Z(n.gross,n.currency)} in ${n.currency.toUpperCase()}`)}:{headline:Z(0,t),extra:[]}}function so({refreshKey:e,initialOrderId:t,isOwner:s=!1,onRefund:n,onBackToWebsite:a,className:r}){let{summary:o,isLoading:c,error:d,refetch:l}=pn({refreshKey:e}),[i,m]=Bl.useState(!1),v=(0,nt.jsx)("div",{className:"af-mb-6",children:d&&!o?(0,nt.jsx)(Lt,{message:"Couldn't load your revenue summary.",onRetry:()=>l()}):(0,nt.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:c||!o?(0,nt.jsxs)(nt.Fragment,{children:[(0,nt.jsx)(st,{label:"This week",children:(0,nt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,nt.jsx)(st,{label:"Today",children:(0,nt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,nt.jsx)(st,{label:"Needs attention",children:(0,nt.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,nt.jsx)(nt.Fragment,{children:(()=>{let g=Ol(o.revenue.d7,o.currency),u=Ol(o.revenue.today,o.currency);return(0,nt.jsxs)(nt.Fragment,{children:[(0,nt.jsx)(st,{label:"This week",detail:g.extra.length>0?(0,nt.jsx)("div",{children:g.extra.map(f=>(0,nt.jsx)("div",{children:f},f))}):void 0,children:g.headline}),(0,nt.jsx)(st,{label:"Today",detail:u.extra.length>0?(0,nt.jsx)("div",{children:u.extra.map(f=>(0,nt.jsx)("div",{children:f},f))}):void 0,children:u.headline}),(0,nt.jsx)(st,{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,nt.jsxs)(St,{title:"Orders",onBackToWebsite:a,hideBackButton:i,className:r,children:[v,(0,nt.jsx)(Ds,{refreshKey:e,initialOrderId:t,onDetailOpenChange:m,showFulfillment:!0,onRefund:s?n:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Qa=ie(require("react"),1),In=require("lucide-react");var Ss=ie(require("react"),1),gi=require("lucide-react");var qt=require("react/jsx-runtime"),Fl="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ys="af-text-xs af-text-muted-foreground",ui="af-text-sm af-font-medium af-tabular-nums",rd=3;function id(e){let t=e.pricing,s=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let d=e.min_amount??t?.min_amount??null,l=e.max_amount??t?.max_amount??null;return d!==null&&l!==null?{text:`Buyer chooses (${Z(d,s)} \u2013 ${Z(l,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let a=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(a===null||r===null)return{text:"Varies by variant",compareAt:null};let o=a===r?Z(a,s):`${Z(a,s)} \u2013 ${Z(r,s)}`,c=t?.compare_at_amount??null;return{text:o,compareAt:c!==null&&c>r?Z(c,s):null}}function di({product:e,className:t}){let s=id(e);return(0,qt.jsxs)("div",{className:t,children:[(0,qt.jsx)("span",{className:ui,children:s.text}),s.compareAt&&(0,qt.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function fi({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,qt.jsx)(oe,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,qt.jsxs)(oe,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,qt.jsx)(oe,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,qt.jsxs)(oe,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,qt.jsx)(oe,{variant:"warning",children:"Low stock"}):null}function mi(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function pi(e){return e.map(t=>Z(t.amount,t.currency)).join(" + ")}function Ul(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${Z(e.min_amount,e.currency)} \u2013 ${Z(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":Z(e.unit_amount,e.currency)}function Ml({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,qt.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=t.available??0;return t.allow_backorder?(0,qt.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,qt.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,s)}),(0,qt.jsx)(oe,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?(0,qt.jsx)(oe,{variant:"destructive",children:"Out of stock"}):(0,qt.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,qt.jsx)("span",{className:"af-tabular-nums",children:s}),s<=rd&&(0,qt.jsx)(oe,{variant:"warning",children:"Low"})]})}var ne=require("react/jsx-runtime");function gr({title:e,children:t,className:s}){return(0,ne.jsxs)("section",{className:J("af-rounded-lg af-border af-p-4",s),children:[(0,ne.jsx)("h4",{className:Fl,children:e}),(0,ne.jsx)("div",{className:"af-mt-3",children:t})]})}function $l({src:e,className:t}){let[s,n]=Ss.useState(!1);return Ss.useEffect(()=>n(!1),[e]),!e||s?(0,ne.jsx)("div",{"aria-hidden":"true",className:J("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,ne.jsx)(gi.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,ne.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>n(!0),className:J("af-object-cover",t)})}function Vl({product:e,showStats:t=!1,onBack:s}){let{api:n}=W(),[a,r]=Ss.useState(null),[o,c]=Ss.useState(!0),[d,l]=Ss.useState(null),[i,m]=Ss.useState(0),[v,g]=Ss.useState(0);Ss.useEffect(()=>{let y=!1;return c(!0),l(null),n.getProduct(e.id).then(C=>{y||r(C)}).catch(C=>{y||l(C instanceof Error?C:new Error("Failed to load product"))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[n,e.id,i]);let u=a?{...e,...a}:e,f=u.images.length>0?u.images:e.images,p=f[v]??f[0],b=mi(u),w=t?u.stats:void 0,P=a?.variants??[],T=P.length>1;return(0,ne.jsxs)("div",{children:[(0,ne.jsxs)("div",{className:"af-mb-6",children:[(0,ne.jsxs)(x,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,ne.jsx)(gi.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,ne.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,ne.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),(0,ne.jsx)(oe,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),(0,ne.jsx)(fi,{product:u})]}),(0,ne.jsx)(di,{product:u,className:"af-mt-1"}),!u.active&&(0,ne.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,ne.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,ne.jsxs)("div",{className:"af-space-y-2",children:[(0,ne.jsx)($l,{src:p,className:"af-h-48 af-w-full af-rounded-md af-border"}),f.length>1&&(0,ne.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:f.map((y,C)=>(0,ne.jsx)("button",{type:"button",onClick:()=>g(C),"aria-label":`Show photo ${C+1} of ${f.length}`,"aria-pressed":C===v,className:J("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",C===v?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,ne.jsx)($l,{src:y,className:"af-h-12 af-w-12 af-rounded-md"})},`${y}-${C}`))})]}),(0,ne.jsxs)("div",{className:"af-space-y-6",children:[u.description&&(0,ne.jsx)(gr,{title:"Description",children:(0,ne.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?(0,ne.jsxs)(gr,{title:"Variants",children:[(0,ne.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(y=>(0,ne.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,ne.jsx)(ae,{className:"af-h-4 af-w-28"}),(0,ne.jsx)(ae,{className:"af-h-4 af-w-20"}),(0,ne.jsx)(ae,{className:"af-h-4 af-w-16"})]},y))}),(0,ne.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):d?(0,ne.jsx)(Lt,{message:"Couldn't load this product's variants.",onRetry:()=>m(y=>y+1)}):T?(0,ne.jsx)(gr,{title:`Variants \xB7 ${P.length}`,children:(0,ne.jsx)("div",{className:"af-overflow-x-auto",children:(0,ne.jsxs)(et,{children:[(0,ne.jsx)(tt,{children:(0,ne.jsxs)(Ie,{children:[(0,ne.jsx)(j,{children:"Variant"}),(0,ne.jsx)(j,{children:"SKU"}),(0,ne.jsx)(j,{className:"af-text-right",children:"Price"}),(0,ne.jsx)(j,{children:"Stock"})]})}),(0,ne.jsx)(at,{children:P.map(y=>(0,ne.jsxs)(Ie,{children:[(0,ne.jsxs)(G,{className:"af-font-medium",children:[y.title||y.option_values.map(C=>C.value).join(" / ")||"\u2014",!y.active&&(0,ne.jsx)(oe,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,ne.jsx)(G,{className:"af-text-muted-foreground",children:y.sku?(0,ne.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:y.sku}):"\u2014"}),(0,ne.jsxs)(G,{className:"af-whitespace-nowrap af-text-right",children:[(0,ne.jsx)("div",{className:ui,children:Ul(y)}),y.compare_at_amount!==null&&y.unit_amount!==null&&y.compare_at_amount>y.unit_amount&&(0,ne.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:Z(y.compare_at_amount,y.currency)})]}),(0,ne.jsx)(G,{className:"af-text-sm",children:(0,ne.jsx)(Ml,{variant:y})})]},y.id))})]})})}):null,(0,ne.jsx)(gr,{title:"Details",children:(0,ne.jsxs)("dl",{className:"af-space-y-2",children:[(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Delivery"}),(0,ne.jsx)("dd",{className:"af-text-sm",children:b==="Digital download"?u.fulfillment.filename??"Digital download":b??"Nothing to deliver"})]}),u.fulfillment.type==="redirect"&&u.fulfillment.url&&(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Sends buyers to"}),(0,ne.jsx)("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Shipping address"}),(0,ne.jsx)("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Most one buyer can order"}),(0,ne.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),w&&(0,ne.jsx)(gr,{title:"Last 30 days",children:(0,ne.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Units sold"}),(0,ne.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:w.units_sold})]}),(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Orders"}),(0,ne.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:w.orders})]}),(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Gross"}),(0,ne.jsx)("dd",{className:ui,children:w.gross.length>0?pi(w.gross):"\u2014"})]})]})}),(0,ne.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var q=require("react/jsx-runtime"),od={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},ld=["all","active","draft","low_stock","out_of_stock"];function Hl(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t).getTime();return Number.isNaN(s)?0:s}function zl(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function cd(e){return e.inventory?.out_of_stock??!1}function ud(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return zl(e);case"out_of_stock":return cd(e);default:return!0}}function dd({product:e,showStats:t,onOpen:s}){let n=e.images[0],a=t?e.stats:void 0,r=mi(e),o=e.variant_count??0;return(0,q.jsxs)("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[n?(0,q.jsx)("img",{src:n,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,q.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,q.jsx)(In.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,q.jsxs)("div",{className:"af-space-y-2 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 af-text-foreground",children:e.name}),(0,q.jsx)(di,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,q.jsx)(oe,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,q.jsx)(fi,{product:e}),o>1&&(0,q.jsxs)(oe,{variant:"outline",children:[o," variants"]}),r&&(0,q.jsx)(oe,{variant:"outline",children:r})]}),a&&(0,q.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[a.units_sold," sold",a.gross.length>0?` \xB7 ${pi(a.gross)}`:""," ",(0,q.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function fd(){return(0,q.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,q.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,q.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,q.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,q.jsx)(ae,{className:"af-w-32"}),(0,q.jsx)(ae,{className:"af-w-16"}),(0,q.jsx)(ae,{className:"af-h-5 af-w-24"})]})]},e))})}function no({refreshKey:e,showStats:t=!1,onBackToWebsite:s,className:n}){let{products:a,isLoading:r,error:o,refetch:c}=fn({includeStats:t,refreshKey:e}),[d,l]=Qa.useState(!1),[i,m]=Qa.useState(null),[v,g]=Qa.useState("all"),{api:u}=W(),f=Qa.useCallback(()=>u.exportProductsCsv(),[u]),[p,b]=Qa.useState(""),[w,P]=Qa.useState("newest"),T=Qa.useMemo(()=>{if(!t)return null;let Q=null;for(let z of a)!z.stats||z.stats.units_sold===0||(!Q||z.stats.units_sold>(Q.stats?.units_sold??0))&&(Q=z);return Q},[a,t]),y=Qa.useMemo(()=>a.filter(zl).length,[a]),C=p.trim().toLowerCase(),k=Qa.useMemo(()=>{let z=[...a.filter(le=>ud(le,v)&&(!C||le.name.toLowerCase().includes(C)))];return w==="name"?z.sort((le,fe)=>le.name.localeCompare(fe.name)):w==="best_selling"?z.sort((le,fe)=>(fe.stats?.units_sold??0)-(le.stats?.units_sold??0)):z.sort((le,fe)=>Hl(fe.created_at)-Hl(le.created_at)),z},[a,v,C,w]),I=v!=="all"||!!C,N=()=>{g("all"),b("")},E=r||o!==null&&a.length===0,D=(0,q.jsx)("div",{className:"af-mb-6",children:(0,q.jsx)("div",{className:J("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:E?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(st,{label:"Products",children:(0,q.jsx)(ae,{className:"af-h-6 af-w-10"})}),t?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(st,{label:"Best seller",children:(0,q.jsx)(ae,{className:"af-h-6 af-w-28"})}),(0,q.jsx)(st,{label:"Low stock",children:(0,q.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,q.jsx)(st,{label:"Active",children:(0,q.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(st,{label:"Products",children:a.length}),t?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(st,{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,q.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:T.name}):(0,q.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,q.jsx)(st,{label:"Low stock",children:y})]}):(0,q.jsx)(st,{label:"Active",children:a.filter(Q=>Q.active).length})]})})}),_=(0,q.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,q.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:ld.map(Q=>(0,q.jsx)("button",{type:"button","aria-pressed":v===Q,onClick:()=>g(Q),className:J("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===Q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:od[Q]},Q))}),(0,q.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,q.jsx)(In.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,q.jsx)(re,{type:"text",value:p,onChange:Q=>b(Q.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,q.jsxs)(qa,{value:w,onValueChange:Q=>P(Q),children:[(0,q.jsx)(ka,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,q.jsx)(Wa,{})}),(0,q.jsxs)(Ta,{children:[(0,q.jsx)(dt,{value:"newest",children:"Newest"}),(0,q.jsx)(dt,{value:"name",children:"Name A\u2013Z"}),t&&(0,q.jsx)(dt,{value:"best_selling",children:"Best selling"})]})]}),I&&(0,q.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:N,children:"Clear filters"}),(0,q.jsx)(Zt,{fetchCsv:f,filename:"products",label:I?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&a.length===0?(0,q.jsx)(ae,{className:"af-h-4 af-w-28"}):(0,q.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:I?`${k.length} of ${a.length} products`:`${a.length} ${a.length===1?"product":"products"}${y>0?` \xB7 ${y} low stock`:""}`})]}),Y;return i?Y=(0,q.jsx)(Vl,{product:i,showStats:t,onBack:()=>{m(null),c()}},i.id):r&&a.length===0?Y=(0,q.jsxs)(q.Fragment,{children:[_,(0,q.jsx)(fd,{}),(0,q.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&a.length===0?Y=(0,q.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,q.jsx)(Lt,{message:"Couldn't load your products.",onRetry:()=>c()})}):a.length===0?Y=(0,q.jsxs)(aa,{icon:(0,q.jsx)(In.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,q.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):Y=(0,q.jsxs)(q.Fragment,{children:[_,o&&(0,q.jsx)("div",{className:"af-mb-4",children:(0,q.jsx)(Lt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>c()})}),k.length===0?(0,q.jsxs)(aa,{children:["No products match these filters.",(0,q.jsx)("br",{}),(0,q.jsx)(x,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:N,children:"Show all products"})]}):(0,q.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:k.map(Q=>(0,q.jsx)(dd,{product:Q,showStats:t,onOpen:()=>m(Q)},Q.id))})]}),(0,q.jsx)(St,{title:"Products",onBackToWebsite:s,hideBackButton:!!i,className:n,children:d?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(x,{variant:"ghost",onClick:()=>l(!1),children:"Back to products"}),(0,q.jsx)(nn,{})]}):(0,q.jsxs)(q.Fragment,{children:[!i&&(0,q.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,q.jsx)(x,{variant:"outline",onClick:()=>l(!0),children:"Promo codes"})}),!i&&D,Y]})})}var ha=ie(require("react"),1),Et=require("lucide-react");var ya=ie(require("react"),1);function vr({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=W(),[n,a]=ya.useState([]),[r,o]=ya.useState(!0),[c,d]=ya.useState(null),[l,i]=ya.useState(0),[m]=ya.useState(e),[v,g]=ya.useState(""),[u,f]=ya.useState(void 0),p=ya.useRef(0),b=ya.useCallback(async({afterRemoval:w=!1}={})=>{let P=++p.current;try{o(!0),d(null);let T={limit:m,offset:l*m};v.trim()&&(T.q=v.trim()),u&&(T.source=u);let y=await s.getPeople(T);if(P!==p.current)return;if(w&&y.people.length===0&&l>0){i(l-1);return}a(y.people)}catch(T){if(P!==p.current)return;d(T instanceof Error?T:new Error("Failed to fetch people"))}finally{P===p.current&&o(!1)}},[s,l,m,v,u,t]);return ya.useEffect(()=>{b()},[b]),{people:n,isLoading:r,error:c,page:l,pageSize:m,hasNextPage:n.length===m,hasPreviousPage:l>0,setPage:i,q:v,setQ:w=>{g(w),i(0)},source:u,setSource:w=>{f(w),i(0)},refetch:()=>b(),refetchAfterRemoval:()=>b({afterRemoval:!0})}}var ws=ie(require("react"),1);function br(e,{refreshKey:t}={}){let{api:s}=W(),[n,a]=ws.useState(null),[r,o]=ws.useState(e!==null),[c,d]=ws.useState(null),l=ws.useRef(0),i=ws.useCallback(async()=>{if(e===null){a(null),o(!1),d(null);return}let m=++l.current;try{o(!0),d(null);let v=await s.getPerson(e);if(m!==l.current)return;a(v)}catch(v){if(m!==l.current)return;d(v instanceof Error?v:new Error("Failed to fetch person"))}finally{m===l.current&&o(!1)}},[s,e,t]);return ws.useEffect(()=>{i()},[i]),{person:n,isLoading:r,error:c,refetch:i}}var R=require("react/jsx-runtime"),ro="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",md="af-text-xs af-text-muted-foreground";function Dn(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 io(e,t){let s=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function pd(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function gd({value:e,label:t}){let[s,n]=ha.useState(!1);return pd()?(0,R.jsxs)(x,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[s?(0,R.jsx)(Et.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,R.jsx)(Et.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function ql(e){return(0,R.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,R.jsxs)(oe,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,R.jsx)(oe,{variant:"secondary",children:"Contact form"})]})}function Wl(e){return e.name?e.name:e.email?e.email:(0,R.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var vd=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,bd=40;function yd(e){let t=Object.entries(e).filter(([a])=>!a.startsWith("_")),n=t.find(([a,r])=>vd.test(a)&&typeof r=="string"&&r.trim())??t.filter(([,a])=>typeof a=="string"&&a.trim().length>=bd).sort((a,r)=>String(r[1]).trim().length-String(a[1]).trim().length)[0];return n?{message:String(n[1]),rest:t.filter(([a])=>a!==n[0])}:{message:null,rest:t}}function hd(e){return e.replace(/_/g," ")}function xd(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Sd({data:e}){let{message:t,rest:s}=yd(e);return t===null&&s.length===0?(0,R.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,R.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,R.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),s.length>0&&(0,R.jsx)("dl",{className:"af-space-y-1",children:s.map(([n,a])=>(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,R.jsx)("dt",{className:J(md,"af-w-28 af-shrink-0 af-capitalize"),children:hd(n)}),(0,R.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:xd(a)})]},n))})]})}function Gl({formName:e,createdAt:t,data:s,onDelete:n}){return(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)(oe,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,R.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,R.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Dn(t)}),(0,R.jsx)(Nn,{iconOnly:!0,onDelete:n})]}),(0,R.jsx)(Sd,{data:s})]})}function wd(e){return e.charged_total??e.amount_total}function Nd({email:e,refreshKey:t,onBack:s,onRemoved:n}){let{api:a}=W(),{person:r,isLoading:o,error:c,refetch:d}=br(e,{refreshKey:t}),l=async m=>{await a.deleteSubmission(m),n(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?d():s()},i=io(e,r?.submissions[0]?.form_name);return(0,R.jsxs)("div",{children:[(0,R.jsxs)("div",{className:"af-mb-6",children:[(0,R.jsxs)(x,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,R.jsx)(Et.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,R.jsxs)("div",{className:"af-min-w-0",children:[o?(0,R.jsx)(ae,{className:"af-h-7 af-w-48"}):(0,R.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),(0,R.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,R.jsx)(gd,{value:e,label:"Copy email address"})]})]}),(0,R.jsx)(x,{asChild:!0,children:(0,R.jsxs)("a",{href:i,children:[(0,R.jsx)(Et.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),o?(0,R.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(m=>(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsx)(ae,{className:"af-w-40"}),(0,R.jsx)(ae,{className:"af-mt-2 af-w-64"})]},m)),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):c||!r?(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(Lt,{message:"Couldn't load this person.",onRetry:()=>d()})}):(0,R.jsxs)("div",{className:"af-space-y-6",children:[r.customer&&(0,R.jsxs)("div",{children:[(0,R.jsx)("h4",{className:J(ro,"af-mb-3"),children:"Customer"}),(0,R.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&(0,R.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,R.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,R.jsx)("dd",{children:r.customer.name})]}),r.customer.phone&&(0,R.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,R.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,R.jsx)("dd",{children:r.customer.phone})]}),(0,R.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,R.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,R.jsx)("dd",{children:Dn(r.customer.created_at)})]})]})]}),r.orders.length>0&&(0,R.jsxs)("div",{children:[(0,R.jsx)("h4",{className:J(ro,"af-mb-3"),children:"Purchases"}),(0,R.jsx)("div",{className:"af-overflow-x-auto",children:(0,R.jsxs)(et,{children:[(0,R.jsx)(tt,{children:(0,R.jsxs)(Ie,{children:[(0,R.jsx)(j,{children:"Order"}),(0,R.jsx)(j,{children:"Date"}),(0,R.jsx)(j,{className:"af-text-right",children:"Total"}),(0,R.jsx)(j,{children:"Status"})]})}),(0,R.jsx)(at,{children:r.orders.map(m=>(0,R.jsxs)(Ie,{children:[(0,R.jsx)(G,{className:"af-whitespace-nowrap af-font-medium",children:Is(m)}),(0,R.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Dn(m.created_at)}),(0,R.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:Z(wd(m),m.currency)}),(0,R.jsx)(G,{children:(0,R.jsx)(Gs,{status:m.status})})]},m.id))})]})}),(0,R.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,R.jsxs)("div",{children:[(0,R.jsx)("h4",{className:J(ro,"af-mb-3"),children:"Messages"}),(0,R.jsx)("div",{className:"af-space-y-3",children:r.submissions.map(m=>(0,R.jsx)(Gl,{formName:m.form_name,createdAt:m.created_at,data:m.data,onDelete:()=>l(m.id)},m.id))})]})]})]})}function Rd({submissionId:e,onBack:t,onRemoved:s}){let{api:n}=W(),[a,r]=ha.useState(null),[o,c]=ha.useState(!0),[d,l]=ha.useState(null),[i,m]=ha.useState(0);return ha.useEffect(()=>{let v=!1;return c(!0),l(null),n.getSubmission(e).then(g=>{v||r(g)}).catch(g=>{v||l(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{v||c(!1)}),()=>{v=!0}},[n,e,i]),(0,R.jsxs)("div",{children:[(0,R.jsxs)("div",{className:"af-mb-6",children:[(0,R.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,R.jsx)(Et.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,R.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),o?(0,R.jsx)(ae,{className:"af-mt-1 af-h-4 af-w-32"}):a&&(0,R.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Dn(a.metadata.submitted_at)})]}),o?(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,R.jsx)(ae,{className:"af-w-40"}),(0,R.jsx)(ae,{className:"af-mt-2 af-w-64"}),(0,R.jsx)(ae,{className:"af-mt-2 af-w-52"}),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):d||!a?(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(Lt,{message:"Couldn't load this submission.",onRetry:()=>m(v=>v+1)})}):(0,R.jsxs)("div",{className:"af-space-y-3",children:[(0,R.jsx)(Gl,{formName:null,createdAt:a.metadata.submitted_at,data:a.data,onDelete:async()=>{await n.deleteSubmission(e),s(),t()}}),(0,R.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 _d={all:"All",customers:"Customers",leads:"Leads"},Pd=["all","customers","leads"],jl={all:void 0,customers:"customer",leads:"lead"};function Cd({refreshKey:e,onBackToWebsite:t,className:s,maxRows:n,onViewAll:a}){let r=typeof n=="number",{people:o,isLoading:c,error:d,page:l,pageSize:i,hasNextPage:m,hasPreviousPage:v,setPage:g,q:u,setQ:f,source:p,setSource:b,refetch:w,refetchAfterRemoval:P}=vr({refreshKey:e}),[T,y]=ha.useState({kind:"list"}),[C,k]=ha.useState(""),I=p==="customer"?"customers":p==="lead"?"leads":"all",N=ee=>{jl[ee]!==p&&b(jl[ee])},{api:E}=W(),D=ha.useCallback(()=>E.exportPeopleCsv({...u?{q:u}:{},...p?{source:p}:{}}),[E,u,p]),_=!r||!!a,Y=ee=>{if(r){a?.();return}ee.email?y({kind:"person",email:ee.email}):ee.submission_id&&y({kind:"submission",submissionId:ee.submission_id})},Q=ha.useRef(!1),z=()=>{Q.current=!0},le=()=>{y({kind:"list"}),Q.current?(Q.current=!1,P()):w()},fe=ee=>{let U=ee.trim();U!==u&&f(U)},he=r?o.slice(0,n):o,M;if(T.kind==="person")M=(0,R.jsx)(Nd,{email:T.email,refreshKey:e,onBack:le,onRemoved:z});else if(T.kind==="submission")M=(0,R.jsx)(Rd,{submissionId:T.submissionId,onBack:le,onRemoved:z});else{let ee=(0,R.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.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:Pd.map(U=>(0,R.jsx)("button",{type:"button","aria-pressed":I===U,onClick:()=>N(U),className:J("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",I===U?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:_d[U]},U))}),(0,R.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,R.jsx)(Et.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,R.jsx)(re,{type:"text",value:C,onChange:U=>k(U.target.value),onBlur:()=>fe(C),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),fe(C))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),u&&(0,R.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>{k(""),f("")},children:"Clear search"}),(0,R.jsx)(Zt,{fetchCsv:D,filename:"people",className:"af-ml-auto"})]});if(c)M=(0,R.jsxs)("div",{children:[r?null:ee,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,R.jsx)(ae,{className:"af-h-4 af-w-32"}),(0,R.jsx)(ae,{className:"af-h-4 af-w-16"})]}),(0,R.jsx)(ae,{className:"af-mt-2 af-h-5 af-w-28"}),(0,R.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-56"})]},U))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(et,{children:[(0,R.jsx)(tt,{children:(0,R.jsxs)(Ie,{children:[(0,R.jsx)(j,{children:"Person"}),(0,R.jsx)(j,{children:"Came from"}),(0,R.jsx)(j,{children:"Latest message"}),(0,R.jsx)(j,{children:"Last activity"}),(0,R.jsx)(j,{className:"af-w-8"}),(0,R.jsx)(j,{className:"af-w-8"})]})}),(0,R.jsx)(at,{"aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,R.jsxs)(Ie,{children:[(0,R.jsx)(G,{children:(0,R.jsx)(ae,{className:"af-h-4 af-w-40"})}),(0,R.jsx)(G,{children:(0,R.jsx)(ae,{className:"af-h-5 af-w-24"})}),(0,R.jsx)(G,{children:(0,R.jsx)(ae,{className:"af-h-4 af-w-56"})}),(0,R.jsx)(G,{children:(0,R.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,R.jsx)(G,{}),(0,R.jsx)(G,{})]},U))})]})}),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(d)M=(0,R.jsxs)("div",{children:[r?null:ee,(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(Lt,{message:"Couldn't load your leads.",onRetry:()=>w()})})]});else if(he.length===0&&l===0){let U=!!u||I!=="all";M=(0,R.jsxs)("div",{children:[U&&ee,U?(0,R.jsx)(aa,{children:u?"Nobody matches that search.":I==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,R.jsx)(Ks,{icon:Et.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)M=(0,R.jsxs)("div",{children:[r?null:ee,(0,R.jsx)(aa,{children:"No more results."}),(0,R.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,R.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>g(l-1),children:[(0,R.jsx)(Et.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let U=l*i+1,ve=l*i+o.length;M=(0,R.jsxs)("div",{children:[r?null:ee,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:he.map((me,Qe)=>(0,R.jsxs)("div",{onClick:_?()=>Y(me):void 0,className:`af-rounded-md af-border af-p-3${_?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,R.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,R.jsxs)("div",{className:"af-min-w-0",children:[(0,R.jsx)("button",{type:"button",onClick:ke=>{ke.stopPropagation(),Y(me)},disabled:!_,"aria-label":`Open ${me.name||me.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${_?" hover:af-underline":""}`,children:Wl(me)}),me.name&&me.email&&(0,R.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:me.email})]}),(0,R.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,R.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:Dn(me.last_activity_at)}),me.email&&(0,R.jsx)(x,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,R.jsx)("a",{href:io(me.email),onClick:ke=>ke.stopPropagation(),"aria-label":`Email ${me.email}`,children:(0,R.jsx)(Et.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,R.jsx)("div",{className:"af-mt-2",children:ql(me)}),me.latest_message_excerpt&&(0,R.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:me.latest_message_excerpt})]},me.email??me.submission_id??Qe))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(et,{children:[(0,R.jsx)(tt,{children:(0,R.jsxs)(Ie,{children:[(0,R.jsx)(j,{children:"Person"}),(0,R.jsx)(j,{children:"Came from"}),(0,R.jsx)(j,{children:"Latest message"}),(0,R.jsx)(j,{children:"Last activity"}),(0,R.jsx)(j,{className:"af-w-8",children:(0,R.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,R.jsx)(j,{className:"af-w-8"})]})}),(0,R.jsx)(at,{children:he.map((me,Qe)=>(0,R.jsxs)(Ie,{onClick:_?()=>Y(me):void 0,className:_?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,R.jsxs)(G,{className:"af-max-w-[260px] af-font-medium",children:[(0,R.jsx)("button",{type:"button",onClick:ke=>{ke.stopPropagation(),Y(me)},disabled:!_,"aria-label":`Open ${me.name||me.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${_?" hover:af-underline":""}`,children:Wl(me)}),me.name&&me.email&&(0,R.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:me.email})]}),(0,R.jsx)(G,{children:ql(me)}),(0,R.jsx)(G,{className:"af-max-w-[320px]",children:me.latest_message_excerpt?(0,R.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:me.latest_message_excerpt}):(0,R.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,R.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Dn(me.last_activity_at)}),(0,R.jsx)(G,{className:"af-w-8",children:me.email&&(0,R.jsx)(x,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,R.jsx)("a",{href:io(me.email),onClick:ke=>ke.stopPropagation(),"aria-label":`Email ${me.email}`,children:(0,R.jsx)(Et.Mail,{className:"af-h-4 af-w-4"})})})}),(0,R.jsx)(G,{className:"af-w-8 af-text-right",children:(0,R.jsx)(Et.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},me.email??me.submission_id??Qe))})]})}),!r&&(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,R.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${U}-${ve}`}),(0,R.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,R.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>g(l-1),disabled:!v,children:[(0,R.jsx)(Et.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,R.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>g(l+1),disabled:!m,children:["Next",(0,R.jsx)(Et.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?(0,R.jsx)("div",{className:s,children:M}):(0,R.jsx)(St,{title:"Leads",onBackToWebsite:t,hideBackButton:T.kind!=="list",className:s,children:M})}function yr(e){return(0,R.jsx)(Cd,{...e},e.maxRows==null?"full":"compact")}var Xl=ie(require("react"),1),gn=require("lucide-react");var xa=ie(require("react"),1);function hr({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=W(),[n,a]=xa.useState([]),[r,o]=xa.useState(0),[c,d]=xa.useState(!0),[l,i]=xa.useState(null),[m,v]=xa.useState(0),[g,u]=xa.useState(e),[f,p]=xa.useState(void 0),b=xa.useRef(0),w=xa.useCallback(async()=>{let T=++b.current;try{d(!0),i(null);let y={limit:g,offset:m*g};f&&(y.status=f);let C=await s.getSubscriptions(y);if(T!==b.current)return;a(C.subscriptions),o(C.total)}catch(y){if(T!==b.current)return;i(y instanceof Error?y:new Error("Failed to fetch subscriptions"))}finally{T===b.current&&d(!1)}},[s,m,g,f,t]);xa.useEffect(()=>{w()},[w]);let P=Math.ceil(r/g);return{subscriptions:n,total:r,isLoading:c,error:l,page:m,pageSize:g,hasNextPage:m<P-1,hasPreviousPage:m>0,setPage:v,setPageSize:T=>{u(T),v(0)},status:f,setStatus:T=>{p(T),v(0)},refetch:w}}var V=require("react/jsx-runtime");function Kl(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 Zl({sub:e}){return e.status==="canceled"?(0,V.jsx)(oe,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,V.jsx)(oe,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,V.jsx)(oe,{variant:"warning",children:"Scheduled to cancel"}):(0,V.jsx)(oe,{variant:"success",children:"Active"}):(0,V.jsx)(oe,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function kd(e,t){let s=Z(t,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function Yl({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:kd(e,e.current_amount)}),t&&(0,V.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",Z(e.plan_amount,e.currency)]})]})}function Jl(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Kl(e.current_period_end)}`:"Ends at period end":e.current_period_end?Kl(e.current_period_end):"\u2014"}function oo({refreshKey:e,onBackToWebsite:t,className:s}){let{subscriptions:n,total:a,isLoading:r,error:o,page:c,pageSize:d,hasNextPage:l,hasPreviousPage:i,setPage:m,status:v,refetch:g}=hr({refreshKey:e}),{api:u}=W(),f=Xl.useCallback(()=>u.exportSubscriptionsCsv(v?{status:v}:{}),[u,v]),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(b=>(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)(ae,{className:"af-h-4 af-w-40"}),(0,V.jsx)(ae,{className:"af-h-4 af-w-20"})]}),(0,V.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-32"}),(0,V.jsx)(ae,{className:"af-mt-2 af-h-5 af-w-24"})]},b))}),(0,V.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,V.jsxs)(et,{children:[(0,V.jsx)(tt,{children:(0,V.jsxs)(Ie,{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)(at,{"aria-hidden":"true",children:[0,1,2,3,4].map(b=>(0,V.jsxs)(Ie,{children:[(0,V.jsx)(G,{children:(0,V.jsx)(ae,{className:"af-h-4 af-w-44"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ae,{className:"af-h-4 af-w-32"})}),(0,V.jsx)(G,{className:"af-text-right",children:(0,V.jsx)(ae,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ae,{className:"af-h-5 af-w-20"})})]},b))})]})}),(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)(Lt,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(n.length===0&&c===0)p=(0,V.jsx)(aa,{icon:(0,V.jsx)(gn.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(n.length===0)p=(0,V.jsxs)("div",{children:[(0,V.jsx)(aa,{children:"No more results."}),(0,V.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,V.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>m(c-1),children:[(0,V.jsx)(gn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let b=c*d+1,w=c*d+n.length;p=(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,V.jsx)(Zt,{fetchCsv:f,filename:"subscriptions"})}),(0,V.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:n.map(P=>(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:P.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:P.plan_title||"Untitled plan"})]}),(0,V.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,V.jsx)(Yl,{sub:P})})]}),(0,V.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Zl,{sub:P}),P.is_test&&(0,V.jsx)(oe,{variant:"outline",children:"Test"}),(0,V.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Jl(P)})]}),(0,V.jsx)(ps,{deliveries:P.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},P.id))}),(0,V.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,V.jsxs)(et,{children:[(0,V.jsx)(tt,{children:(0,V.jsxs)(Ie,{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)(at,{children:n.map(P=>(0,V.jsxs)(Ie,{children:[(0,V.jsx)(G,{className:"af-max-w-[240px]",children:(0,V.jsx)("div",{className:"af-truncate af-font-medium",children:P.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:P.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)(Yl,{sub:P})}),(0,V.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Jl(P)}),(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)(Zl,{sub:P}),P.is_test&&(0,V.jsx)(oe,{variant:"outline",children:"Test"})]}),(0,V.jsx)(ps,{deliveries:P.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},P.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 ${b}-${w} of ${a}`}),(0,V.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,V.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>m(c-1),disabled:!i,children:[(0,V.jsx)(gn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,V.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>m(c+1),disabled:!l,children:["Next",(0,V.jsx)(gn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,V.jsx)(St,{title:"Subscriptions",onBackToWebsite:t,className:s,children:p})}var Rs=ie(require("react"),1),mc=require("lucide-react");var sa=ie(require("react"),1);var vi=ie(require("react"),1),vn=typeof window>"u"?vi.useEffect:vi.useLayoutEffect;var bi=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},Td=(e,t)=>e instanceof Error?e:new Error(t);function Ed(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 Ql(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function Os({siteId:e,refreshKey:t,onSaveInvoiceSettings:s}){let{api:n}=W(),[a,r]=sa.useState(null),[o,c]=sa.useState(!0),[d,l]=sa.useState(null),i=sa.useRef(null),[m,v]=sa.useState(()=>Ql(n,e)),g=m.api!==n||m.siteId!==e,u=m;g&&(u=Ql(n,e),v(u),r(null),c(!0),l(null));let f=sa.useRef(u);vn(()=>{f.current!==u&&(f.current=u,i.current=null)},[u]);let p=(N,E)=>f.current===N&&E>N.applied,b=(N,E,D)=>p(N,E)?(N.applied=E,i.current=D,r(D),c(!1),!0):!1,w=async N=>{for(;N.writing;)await N.idle;let E=++N.seq;try{let D=await N.api.getSite(N.siteId);return b(N,E,D)&&l(null),{seq:E,error:null}}catch(D){return{seq:E,error:Td(D,"Failed to load store settings")}}},P=(N,E)=>{let D=async()=>{if(f.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 E(++N.seq)}finally{N.writing=!1,N.markIdle()}},_=N.queue.then(D,D);return N.queue=_.catch(()=>{}),_},T=sa.useCallback(async()=>{let N=await w(u);N.error&&p(u,N.seq)&&(l(N.error),c(!1))},[u]);sa.useEffect(()=>{T()},[T,t]);let y=sa.useCallback(N=>P(u,async E=>{let D=await u.api.updateSite(u.siteId,N),{currency_restatement:_,...Y}=D;return b(u,E,Y)&&l(Q=>Q instanceof bi?Q:null),D}),[u]),C=sa.useRef(s);vn(()=>{C.current=s});let k=sa.useCallback(async(N,E)=>{await P(u,()=>N());let D=await w(u);return D.error&&p(u,D.seq)&&i.current&&(b(u,D.seq,{...i.current,...E}),l(new bi(`Saved, but couldn't refresh settings: ${D.error.message}`))),f.current===u?i.current:null},[u]),I=sa.useCallback(N=>{let E=C.current;return k(()=>E(N),Ed(N))},[k]);return{site:g?null:a,isLoading:g||o,error:g?null:d,refetch:T,updateSite:y,saveInvoiceSettings:s?I:null}}var $t=ie(require("react"),1),uo=require("lucide-react");var vt=require("react/jsx-runtime");function yi(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var cs="af-grid af-gap-1 af-text-sm",ec="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",tc="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 Sa({children:e}){return(0,vt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function xr({children:e}){return(0,vt.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var Ns=$t.forwardRef(function({id:t,title:s,description:n,children:a},r){let o=`af-store-${t}-title`;return(0,vt.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,vt.jsxs)("div",{className:"af-space-y-1",children:[(0,vt.jsx)("h3",{id:o,className:"af-text-sm af-font-semibold",children:s}),n&&(0,vt.jsx)(Sa,{children:n})]}),a]})});function hi({label:e,description:t,checked:s,onSave:n,disabled:a=!1,disabledReason:r}){let[o,c]=$t.useState(null),[d,l]=$t.useState(null),i=o??s,m=async v=>{c(v),l(null);try{await n(v)}catch(g){l(yi(g))}finally{c(null)}};return(0,vt.jsxs)("div",{className:"af-space-y-1",children:[(0,vt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,vt.jsx)("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":i,checked:i,disabled:a||o!==null,onChange:v=>void m(v.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),(0,vt.jsxs)("span",{className:"af-space-y-0.5",children:[(0,vt.jsxs)("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,o!==null&&(0,vt.jsx)(uo.Loader2,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&(0,vt.jsx)(Sa,{children:t})]})]}),(a&&r||d)&&(0,vt.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[a&&r&&(0,vt.jsx)(Sa,{children:r}),d&&(0,vt.jsx)(xr,{children:d})]})]})}var co=(e,t)=>JSON.stringify(e)===JSON.stringify(t),lo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Id(e,t,s,n=[]){if(!lo(e)||!lo(t)||!lo(s))return{draft:co(e,t)?s:e,dropped:[]};let a=[],r={...s};for(let o of Object.keys(s))co(e[o],t[o])||(n.includes(o)?a.push(o):r[o]=e[o]);return{draft:r,dropped:a}}function An(e,t){let s=JSON.stringify(e),[n,a]=$t.useState(e),[r,o]=$t.useState([]),c=$t.useRef(e),d=$t.useRef(e),l=$t.useRef(n);vn(()=>{d.current=e,l.current=n});let i=$t.useRef(t?.when);$t.useEffect(()=>{let v=Object.is(i.current,t?.when)?[]:t?.fields??[];if(i.current=t?.when,co(c.current,d.current)&&v.length===0)return;let g=Id(l.current,c.current,d.current,v);c.current=d.current,a(g.draft),g.dropped.length&&o(g.dropped)},[s,t?.when]);let m=$t.useCallback(v=>{a(v??d.current),o([])},[]);return{draft:n,setDraft:a,dirty:JSON.stringify(n)!==s,reset:m,dropped:r}}function Ln({dirty:e,saving:t,error:s,onSave:n,onDiscard:a}){return e?(0,vt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,vt.jsxs)(x,{type:"button",size:"sm",disabled:t,onClick:n,children:[t&&(0,vt.jsx)(uo.Loader2,{className:"af-animate-spin"}),"Save"]}),(0,vt.jsx)(x,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:a,children:"Discard"}),s&&(0,vt.jsx)("p",{role:"alert",className:J("af-text-sm af-text-destructive"),children:s})]}):null}function On(){let[e,t]=$t.useState(!1),[s,n]=$t.useState(null),a=$t.useCallback(async r=>{t(!0),n(null);try{await r()}catch(o){n(yi(o))}finally{t(!1)}},[]);return{saving:e,error:s,setError:n,run:a}}function ac({what:e}){return(0,vt.jsxs)(Sa,{children:["Only the site owner can change ",e,"."]})}var es=ie(require("react"),1),bn=require("lucide-react");var H=require("react/jsx-runtime"),mo=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ic({site:e,updateSite:t}){return(0,H.jsxs)("div",{className:"af-space-y-4",children:[(0,H.jsx)(hi,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:s=>t({collect_phone_at_checkout:s})}),e.checkout_marketing_consent!==void 0&&(0,H.jsx)(hi,{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:s=>t({checkout_marketing_consent:s})})]})}function sc(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(mt(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(mt(e.free_shipping_over,e.currency))}}function oc({site:e,updateSite:t,refetch:s,providerSlot:n,currencyChanging:a=!1}){let{draft:r,setDraft:o,dirty:c,reset:d,dropped:l}=An(sc(e),{when:e.currency,fields:["rates","threshold"]}),{saving:i,error:m,setError:v,run:g}=On(),u=e.currency.toUpperCase(),f=()=>g(async()=>{let b={},w=[...new Set(r.countries.split(/[\s,]+/).map(N=>N.trim().toUpperCase()).filter(Boolean))],P=w.find(N=>!/^[A-Z]{2}$/.test(N));if(P)throw new Error(`"${P}" isn't a two-letter country code (e.g. US, CA).`);let T=w.length?w:null;mo(T,e.shipping_countries)||(b.shipping_countries=T);let y=[];for(let N of r.rates){let E=N.label.trim(),D=zt(N.amount,e.currency);if(!E)throw new Error("Every rate needs a name.");if(N.amount.trim()===""||D===null)throw new Error(`Enter a price for "${E}" (0 for free).`);y.push({label:E,amount:D})}let C=y.length?y:null;mo(C,e.shipping_rates)||(b.shipping_rates=C);let k=null;if(r.threshold.trim()!==""&&(k=zt(r.threshold,e.currency),k===null||k===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(k!==e.free_shipping_over&&(b.free_shipping_over=k),Object.keys(b).length===0){d();return}("shipping_rates"in b||"free_shipping_over"in b)&&(b.expected_currency=e.currency);let I;try{I=await t(b)}catch(N){throw N instanceof Dt&&N.details?.code==="currency_changed"&&await s?.(),N}d(sc(I))}),p=(b,w)=>o({...r,rates:r.rates.map((P,T)=>T===b?{...P,...w}:P)});return(0,H.jsxs)("fieldset",{disabled:i||a,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:cs,children:["Countries you ship to",(0,H.jsx)(re,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:b=>o({...r,countries:b.target.value})}),(0,H.jsx)(Sa,{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 (",u,")"]}),r.rates.length===0&&(0,H.jsx)(Sa,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((b,w)=>(0,H.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,H.jsx)(re,{"aria-label":`Rate ${w+1} name`,value:b.label,placeholder:"Standard",onChange:P=>p(w,{label:P.target.value})}),(0,H.jsx)(re,{"aria-label":`Rate ${w+1} price`,type:"number",min:"0",step:"any",value:b.amount,placeholder:"0",className:"af-w-32",onChange:P=>p(w,{amount:P.target.value})}),(0,H.jsx)(x,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${w+1}`,onClick:()=>o({...r,rates:r.rates.filter((P,T)=>T!==w)}),children:(0,H.jsx)(bn.X,{})})]},w)),(0,H.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>o({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[(0,H.jsx)(bn.Plus,{})," Add rate"]}),(0,H.jsx)(Sa,{children:"Buyers pick one at checkout. The first is preselected."})]}),(0,H.jsxs)("label",{className:cs,children:["Free shipping over (",u,")",(0,H.jsx)(re,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:b=>o({...r,threshold:b.target.value})}),(0,H.jsx)(Sa,{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 ",u,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),(0,H.jsx)(Ln,{dirty:c,saving:i,error:m,onSave:()=>void f(),onDiscard:()=>{v(null),d()}}),n]})}var fo="exclusive",Dd=[{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 Ad({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)(bn.ExternalLink,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function lc({site:e,updateSite:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=An(e.tax_behavior??fo),{saving:o,error:c,setError:d,run:l}=On(),[i,m]=es.useState(!1),v=e.stripe_tax_enabled,g=v||i,u=()=>l(async()=>{let b=s;if(b===e.tax_behavior){r();return}let w={tax_behavior:b};b!=="inclusive"&&e.tax_rate_bps!=null&&(w.tax_rate_bps=null);let P=await t(w);r(P.tax_behavior??fo)}),f=()=>l(async()=>{let b={stripe_tax_enabled:!0,tax_behavior:s};s!=="inclusive"&&e.tax_rate_bps!=null&&(b.tax_rate_bps=null);let w=await t(b);r(w.tax_behavior??fo),m(!1)}),p=(a||i)&&s!=="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:Dd.map(b=>(0,H.jsx)("li",{children:(0,H.jsx)(Ad,{href:b.href,children:b.label})},b.href))})]}),(0,H.jsx)(hi,{label:"Stripe automatic tax",description:v?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:g,onSave:async b=>{if(i){m(!1),d(null),r();return}if(b&&!e.tax_behavior){m(!0);return}return t({stripe_tax_enabled:b})}}),g&&(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4 af-pl-6",children:[(0,H.jsxs)("label",{className:cs,children:["Do your prices already include tax?",(0,H.jsxs)("select",{"aria-label":"Your prices",className:ec,value:s,onChange:b=>n(b.target.value),children:[(0,H.jsx)("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),(0,H.jsx)("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),(0,H.jsx)(Sa,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),p&&(0,H.jsxs)(Sa,{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)(x,{type:"button",size:"sm",disabled:o,onClick:()=>void f(),children:"Turn on"}),(0,H.jsx)(x,{type:"button",size:"sm",variant:"outline",disabled:o,onClick:()=>{m(!1),d(null),r()},children:"Cancel"})]}),c&&(0,H.jsx)(xr,{children:c})]}):(0,H.jsx)(Ln,{dirty:a,saving:o,error:c,onSave:()=>void u(),onDiscard:()=>{d(null),r()}})]})]})}function nc(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function cc({site:e,updateSite:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=An(nc(e)),{saving:o,error:c,setError:d,run:l}=On(),i=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),m=()=>l(async()=>{let v={},g=null;if(i&&s.rate.trim()!==""){let b=Number(s.rate);if(!Number.isFinite(b)||b<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(b*100)}i&&g!==e.tax_rate_bps&&(v.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(v.tax_behavior="inclusive");let u=s.taxId.trim()||null;u!==e.tax_id&&(v.tax_id=u);let f=s.label.trim()||null;if(f!==e.tax_label&&(v.tax_label=f),Object.keys(v).length===0){r();return}let p=await t(v);r(nc(p))});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:cs,children:["Tax rate (%)",(0,H.jsx)(re,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!i,value:i?s.rate:"",onChange:v=>n({...s,rate:v.target.value})}),(0,H.jsx)(Sa,{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:cs,children:["Tax ID",(0,H.jsx)(re,{"aria-label":"Tax ID",value:s.taxId,maxLength:64,placeholder:"DE123456789",onChange:v=>n({...s,taxId:v.target.value})})]}),(0,H.jsxs)("label",{className:cs,children:["Tax label",(0,H.jsx)(re,{"aria-label":"Tax label",value:s.label,maxLength:24,placeholder:"Tax",onChange:v=>n({...s,label:v.target.value})})]})]}),(0,H.jsx)(Ln,{dirty:a,saving:o,error:c,onSave:()=>void m(),onDiscard:()=>{d(null),r()}})]})}function uc({site:e,updateSite:t,onChangeStart:s}){let[n,a]=es.useState(e.currency.toUpperCase()),[r,o]=es.useState(!1),[c,d]=es.useState(!1),[l,i]=es.useState(null),m=e.currency.toUpperCase(),v=es.useRef(m);es.useEffect(()=>{v.current!==m&&(a(b=>b===v.current?m:b),v.current=m)},[m]);let g=n.trim().toUpperCase(),u=g!==m,f=/^[A-Z]{3}$/.test(g),p=async()=>{d(!0);let b=s?.(),w=!1;i(null);try{let P=await t({currency:g.toLowerCase()});w=!0;let T=P.currency_restatement;T&&!T.applied?i(T.reason?`Not changed: ${T.reason}.`:"The currency was not changed."):(a(P.currency.toUpperCase()),v.current=P.currency.toUpperCase()),o(!1)}catch(P){i(yi(P))}finally{d(!1),b?.(w)}};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:cs,children:["Store currency",(0,H.jsx)(re,{"aria-label":"Store currency",value:n,maxLength:3,className:"af-w-24 af-uppercase",disabled:c||r,onChange:b=>{a(b.target.value),i(null)}})]}),u&&!r&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(x,{type:"button",size:"sm",disabled:!f,onClick:()=>o(!0),children:"Change currency"}),(0,H.jsx)(x,{type:"button",size:"sm",variant:"ghost",onClick:()=>{a(m),i(null)},children:"Discard"})]})]}),(0,H.jsx)(Sa,{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 ",m," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",Z(2e3,m)," becomes ",Z(2e3,g),". 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)(x,{type:"button",size:"sm",disabled:c,onClick:()=>void p(),children:"Confirm change"}),(0,H.jsx)(x,{type:"button",size:"sm",variant:"ghost",disabled:c,onClick:()=>o(!1),children:"Cancel"})]})]}),l&&(0,H.jsx)(xr,{children:l})]})}function rc(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function Ld(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 dc({site:e,save:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=An(rc(e)),{saving:o,error:c,setError:d,run:l}=On();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: ",Ld(e.invoice_reminder_schedule)]}),(0,H.jsxs)("p",{children:["Footer: ",e.invoice_footer||"None"]}),(0,H.jsx)(ac,{what:"invoice defaults"})]});let i=()=>l(async()=>{let m={},v=Number(s.dueDays);if(s.dueDays.trim()===""||!Number.isInteger(v)||v<0||v>90)throw new Error("Due days must be a whole number from 0 to 90.");v!==e.invoice_due_days&&(m.due_days=v);let u=s.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(u.some(w=>!Number.isInteger(w)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let f=[...new Set(u)].sort((w,P)=>w-P);mo(f,e.invoice_reminder_schedule)||(m.reminder_schedule=f);let p=s.footer.trim()||null;if(p!==e.invoice_footer&&(m.footer=p),Object.keys(m).length===0){r();return}let b=await t(m);r(b?rc(b):void 0)});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:cs,children:["Days until due",(0,H.jsx)(re,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:s.dueDays,onChange:m=>n({...s,dueDays:m.target.value})})]}),(0,H.jsxs)("label",{className:cs,children:["Reminder schedule",(0,H.jsx)(re,{"aria-label":"Reminder schedule",value:s.reminders,placeholder:"Off",onChange:m=>n({...s,reminders:m.target.value})}),(0,H.jsx)(Sa,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),(0,H.jsxs)("label",{className:cs,children:["Invoice footer",(0,H.jsx)("textarea",{"aria-label":"Invoice footer",className:tc,maxLength:300,value:s.footer,onChange:m=>n({...s,footer:m.target.value})})]}),(0,H.jsx)(Ln,{dirty:a,saving:o,error:c,onSave:()=>void i(),onDiscard:()=>{d(null),r()}})]})}function fc({site:e,updateSite:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=An(e.default_email_recipients),{saving:o,error:c,setError:d,run:l}=On(),[i,m]=es.useState(""),[v,g]=es.useState(null),u=()=>{let p=i.trim().toLowerCase();if(p){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p)){g("Enter a valid email address.");return}if(s.some(b=>b.toLowerCase()===p)){g("Already added.");return}n([...s,p]),m(""),g(null)}},f=()=>l(async()=>{let p=await t({default_email_recipients:s});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:[s.map(p=>(0,H.jsxs)(oe,{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:()=>n(s.filter(b=>b!==p)),children:(0,H.jsx)(bn.X,{className:"af-h-3 af-w-3"})})]},p)),s.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)(re,{"aria-label":"Add notification email",type:"email",value:i,placeholder:"Add email address",onChange:p=>{m(p.target.value),g(null)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),u())}}),(0,H.jsx)(x,{type:"button",variant:"outline",disabled:!i.trim(),onClick:u,children:"Add"})]}),v&&(0,H.jsx)(xr,{children:v}),(0,H.jsx)(Ln,{dirty:a,saving:o,error:c,onSave:()=>void f(),onDiscard:()=>{d(null),r()}})]})}var Yt=require("react/jsx-runtime");function po({siteId:e,refreshKey:t,section:s,shippingProviderSlot:n,onConnectStripe:a,onUpgradePlan:r,className:o}){let{site:c,isLoading:d,error:l,refetch:i,updateSite:m}=Os({siteId:e,refreshKey:t}),v=Rs.useRef(i),g=Rs.useRef(e);vn(()=>{v.current=i,g.current=e});let u=Rs.useRef({}),[f,p]=Rs.useState([]),b=f.some(C=>C.siteId===e),w=Rs.useCallback(()=>{let C={siteId:e},k=v.current;return p(I=>[...I,C]),I=>{let N=()=>p(D=>D.filter(_=>_!==C));!(g.current===C.siteId)||I&&v.current===k?N():v.current().finally(N)}},[e]),P=C=>k=>{u.current[C]=k},T=c!==null&&c.payments_active;if(Rs.useEffect(()=>{if(!T||!s)return;let C=u.current[s];C&&(C.scrollIntoView?.({behavior:"smooth",block:"start"}),C.focus({preventScroll:!0}))},[T,s]),d)return(0,Yt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Yt.jsx)(mc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!c)return(0,Yt.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(!c.payments_active)return(0,Yt.jsx)(dn,{className:o,onConnectStripe:a,onUpgradePlan:r,whenActive:(0,Yt.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let y={site:c,updateSite:m,refetch:i};return(0,Yt.jsxs)("div",{className:`af-space-y-6 ${o??""}`,children:[l&&(0,Yt.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,Yt.jsx)(Ns,{ref:P("checkout"),id:"checkout",title:"Checkout",children:(0,Yt.jsx)(ic,{...y})}),(0,Yt.jsx)(Ns,{ref:P("shipping"),id:"shipping",title:"Shipping",children:(0,Yt.jsx)(oc,{...y,providerSlot:n,currencyChanging:b})}),(0,Yt.jsx)(Ns,{ref:P("tax"),id:"tax",title:"Tax",children:(0,Yt.jsx)(lc,{...y})}),(0,Yt.jsx)(Ns,{ref:P("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:(0,Yt.jsx)(uc,{...y,onChangeStart:w})})]},e)}var pc=require("lucide-react");var us=require("react/jsx-runtime");function Sr({siteId:e,refreshKey:t,onSaveInvoiceSettings:s,className:n}){let{site:a,isLoading:r,error:o,updateSite:c,refetch:d,saveInvoiceSettings:l}=Os({siteId:e,refreshKey:t,onSaveInvoiceSettings:s});return r?(0,us.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,us.jsx)(pc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):a?(0,us.jsxs)("div",{className:`af-space-y-6 ${n??""}`,children:[o&&(0,us.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,us.jsx)(Ns,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:(0,us.jsx)(dc,{site:a,save:l})}),(0,us.jsx)(Ns,{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,us.jsx)(cc,{site:a,updateSite:c,refetch:d})})]},e):(0,us.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 gc=require("lucide-react");var Bs=require("react/jsx-runtime");function go({siteId:e,refreshKey:t,className:s}){let{site:n,isLoading:a,error:r,updateSite:o,refetch:c}=Os({siteId:e,refreshKey:t});return a?(0,Bs.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Bs.jsx)(gc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):n?(0,Bs.jsxs)("div",{className:`af-space-y-3 ${s??""}`,children:[r&&(0,Bs.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,Bs.jsx)(Ns,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:(0,Bs.jsx)(fc,{site:n,updateSite:o,refetch:c})})]},e):(0,Bs.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 Bn=ie(require("react"),1);var ot=require("react/jsx-runtime");function vo({refreshKey:e,initialInvoiceId:t,onBackToWebsite:s,onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:r,siteId:o,onSaveInvoiceSettings:c,className:d}){let{aggregates:l,isLoading:i,error:m,refetch:v}=cn({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=mn({refreshKey:e}),{api:u}=W(),f=g.filters,p=Bn.useCallback(()=>u.exportRetainersCsv(f),[u,f]),[b,w]=Bn.useState(!1),[P,T]=Bn.useState(null),[y,C]=Bn.useState(!1),k=(0,ot.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:m||!i&&!l?(0,ot.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,ot.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:()=>void v(),children:"Retry totals"})]}):i||!l?(0,ot.jsxs)(ot.Fragment,{children:[(0,ot.jsx)(st,{label:"Outstanding",children:(0,ot.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,ot.jsx)(st,{label:"Overdue",children:(0,ot.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,ot.jsx)(st,{label:"Paid this month",children:(0,ot.jsx)(ae,{className:"af-h-6 af-w-24"})})]}):(0,ot.jsxs)(ot.Fragment,{children:[(0,ot.jsx)(st,{label:"Outstanding",detail:`${l.outstanding.count} open`,children:Z(l.outstanding.amount,l.currency)}),(0,ot.jsx)(st,{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:Z(l.overdue.amount,l.currency)}),(0,ot.jsx)(st,{label:"Paid this month",detail:`${l.paid_this_month.count} paid`,children:Z(l.paid_this_month.amount,l.currency)})]})});return(0,ot.jsxs)(St,{title:"Invoices",onBackToWebsite:s,hideBackButton:b,className:d,children:[k,o&&!b&&(0,ot.jsxs)("div",{className:"af-mb-6",children:[(0,ot.jsx)(x,{type:"button",variant:"outline",size:"sm","aria-expanded":y,"aria-controls":"af-invoice-settings",onClick:()=>C(I=>!I),children:"Invoice settings"}),y&&(0,ot.jsx)("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:(0,ot.jsx)(Sr,{siteId:o,refreshKey:e,onSaveInvoiceSettings:c})})]}),!b&&(0,ot.jsx)(un,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:P?.id??null,onShowCycles:I=>T(N=>N?.id===I.id?null:I),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded,exportCsv:p}),(0,ot.jsx)(Ls,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:w,onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:r,retainerFilter:P?{id:P.id,label:`${P.customer_name??P.customer_email??"Recurring invoices"} \u2014 ${P.description}`}:null,onClearRetainerFilter:()=>T(null)})]})}var Na=ie(require("react"),1),_c=require("lucide-react");var ts=ie(require("react"),1);function wa(e,t,s){let[n,a]=ts.useState(null),[r,o]=ts.useState(!0),[c,d]=ts.useState(null),l=ts.useRef(0),i=ts.useRef(e);i.current=e;let m=ts.useRef(s);m.current=s;let v=ts.useCallback(async()=>{let u=++l.current,f=m.current;o(!0),d(null);try{let p=await i.current();u===l.current&&a({scope:f,value:p})}catch(p){u===l.current&&d(p instanceof Error?p:new Error("Request failed"))}finally{u===l.current&&o(!1)}},[]);ts.useEffect(()=>{v()},[v,t]);let g=n!==null&&n.scope===s;return{data:g?n.value:null,isLoading:r||!g&&c===null,error:c,refetch:v}}var xi={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"]},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 vc(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(xi,e)}function bc(e,t,s){let n=xi[e],a="params"in n?n.params:[],r={...s};delete r.siteId;let o=n.path.replace("{siteId}",encodeURIComponent(t));for(let d of a){let l=r[d];if(typeof l!="string"&&typeof l!="number")throw new Error(`${e} needs ${d}`);o=o.replace(`{${d}}`,encodeURIComponent(String(l))),delete r[d]}let c=n.method==="GET"||n.method==="DELETE"?void 0:r;return{method:n.method,path:o,body:c}}var bo={marketing_disabled:"Email marketing is not available yet.",site_deleted:"This site has been deleted.",sending_not_enabled:"Email sending is not turned on for this site. It needs the Pro plan.",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."},Si=new Set(["domain_not_verified","dmarc_missing","postal_address_missing"]);function yn(e){return e?bo[e]??"Sending is not available right now.":null}var _s=ie(require("react"),1);var hn=50;function wr({siteId:e,q:t="",offset:s=0,refreshKey:n=0}){let{api:a}=W(),r=wa(()=>a.getMarketingContacts(e,{q:t||void 0,limit:hn,offset:s}),`${e}|${t}|${s}|${n}`,e),o=wa(()=>a.getMarketingContactStats(e),`${e}|${n}`,e),c=wa(()=>a.getMarketingTags(e),`${e}|${n}`,e);return{contacts:r,stats:o,tags:c,refetchAll:async()=>{await Promise.all([r.refetch(),o.refetch(),c.refetch()])}}}var Mn=ie(require("react"),1);var Fs=ie(require("react"),1);var ds=require("react/jsx-runtime"),Nr=e=>`af-email-settings-${e}`,yo=Fs.createContext(null);function Wt(){let e=Fs.useContext(yo);if(!e)throw new Error("Email panels render inside EmailView");return e}function wi({onClick:e,children:t}){return(0,ds.jsx)("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function Ni({reason:e}){let{openSetup:t,onOpenStoreSettings:s}=Wt(),n=e&&Si.has(e)?(0,ds.jsx)(wi,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&s?(0,ds.jsx)(wi,{onClick:s,children:"Open Store settings"}):null;return n&&(0,ds.jsxs)(ds.Fragment,{children:[" ",n]})}function Od(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 Fn(e,t){return Od(e)===t?!0:e instanceof Error&&e.message.includes(t)}function Un(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function na(){let{onOrgAction:e}=Wt(),[t,s]=Fs.useState(!1),[n,a]=Fs.useState(null),r=Fs.useCallback(async(o,c={})=>{s(!0),a(null);try{return{ok:!0,result:await e(o,c)}}catch(d){return a(Un(d)),{ok:!1,error:d}}finally{s(!1)}},[e]);return{busy:t,error:n,setError:a,run:r}}function Be({tone:e="info",children:t,className:s}){return(0,ds.jsx)("div",{role:e==="error"?"alert":"status",className:J("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",s),children:t})}function Va({children:e,action:t,id:s}){return(0,ds.jsxs)("div",{id:s,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[(0,ds.jsx)("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function Ue(e){return e.toLocaleString("en-US")}var wt=require("react/jsx-runtime"),Ri="I confirm that everyone in this file agreed to receive marketing email from my business.",Bd={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 Rr({onImported:e}){let{canWrite:t}=Wt(),[s,n]=Mn.useState(""),[a,r]=Mn.useState(null),[o,c]=Mn.useState(""),[d,l]=Mn.useState(!1),[i,m]=Mn.useState(null),v=na(),g=async()=>{if(!d||!s.trim())return;let u=o.split(",").map(p=>p.trim()).filter(Boolean),f=await v.run("importContacts",{csv:s,attested:!0,...u.length?{tags:u}:{}});if(f.ok){let p=f.result;m(p),e?.(p)}};if(i){let u=new Map;for(let f of i.skipped_rows)u.set(f.reason,(u.get(f.reason)??0)+1);return(0,wt.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[(0,wt.jsx)("div",{className:"af-font-medium",children:"Import finished"}),(0,wt.jsxs)("p",{className:"af-text-sm",children:[Ue(i.rows)," rows: ",Ue(i.created)," new, ",Ue(i.updated)," updated, ",Ue(i.skipped)," skipped."]}),u.size>0&&(0,wt.jsx)("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...u].map(([f,p])=>(0,wt.jsxs)("li",{children:[Ue(p)," ",Bd[f]??f]},f))}),(0,wt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),(0,wt.jsx)(x,{type:"button",size:"sm",variant:"outline",onClick:()=>{m(null),n(""),r(null),l(!1)},children:"Import another file"})]})}return(0,wt.jsxs)("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:u=>{u.preventDefault(),g()},children:[(0,wt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,wt.jsx)("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),(0,wt.jsx)("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async u=>{let f=u.target.files?.[0];f&&(r(f.name),n(await f.text()))}}),(0,wt.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.'}),a&&(0,wt.jsx)("span",{className:"af-block af-text-xs",children:a})]}),(0,wt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,wt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),(0,wt.jsx)(re,{"aria-label":"Tags for imported contacts",value:o,onChange:u=>c(u.target.value)})]}),(0,wt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,wt.jsx)("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:d,onChange:u=>l(u.target.checked)}),(0,wt.jsxs)("span",{children:[Ri," Importing people who didn't agree can get your sending paused."]})]}),v.error&&(0,wt.jsx)(Be,{tone:"error",children:v.error}),(0,wt.jsx)(x,{type:"submit",size:"sm",disabled:!t||!d||!s.trim()||v.busy,children:v.busy?"Importing\u2026":"Import contacts"})]})}var de=require("react/jsx-runtime"),Fd={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function yc(){let{siteId:e,canWrite:t,refreshKey:s}=Wt(),[n,a]=_s.useState(""),[r,o]=_s.useState(""),[c,d]=_s.useState(0),[l,i]=_s.useState(0),[m,v]=_s.useState(new Set),[g,u]=_s.useState(!1),f=wr({siteId:e,q:r,offset:c,refreshKey:l+s}),p=na(),b=()=>i(k=>k+1),w=f.stats.data,P=f.contacts.data,T=f.tags.data??[],y=w?w.growth.slice(-4).reduce((k,I)=>k+I.new_subscribers,0):null,C=async()=>{let k=await p.run("exportContacts",{});if(!k.ok||typeof k.result!="string"||typeof document>"u")return;let I=URL.createObjectURL(new Blob([k.result],{type:"text/csv;charset=utf-8"})),N=document.createElement("a");N.href=I,N.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(N),N.click(),document.body.removeChild(N),URL.revokeObjectURL(I)};return(0,de.jsxs)("div",{children:[(0,de.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[(0,de.jsx)(st,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:w?Ue(w.total):(0,de.jsx)(ae,{className:"af-h-6 af-w-16"})}),(0,de.jsx)(st,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:w?Ue(w.mailable):(0,de.jsx)(ae,{className:"af-h-6 af-w-16"})}),(0,de.jsx)(st,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:y!==null?Ue(y):(0,de.jsx)(ae,{className:"af-h-6 af-w-16"})})]}),(0,de.jsxs)("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,de.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:k=>{k.preventDefault(),d(0),o(n.trim())},children:[(0,de.jsx)(re,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:n,onChange:k=>a(k.target.value)}),(0,de.jsx)(x,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),(0,de.jsx)(x,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>u(k=>!k),children:g?"Close import":"Import"}),(0,de.jsx)(x,{type:"button",variant:"outline",size:"sm",disabled:!t||p.busy,onClick:()=>void C(),children:"Export"})]}),g&&(0,de.jsx)("div",{className:"af-mt-3",children:(0,de.jsx)(Rr,{onImported:b})}),p.error&&(0,de.jsx)(Be,{tone:"error",className:"af-mt-2",children:p.error}),t&&m.size>0&&(0,de.jsx)(Md,{tags:T.filter(k=>!k.system),count:m.size,busy:p.busy,onApply:async(k,I)=>{(await p.run("bulkTagContacts",{action:k,tag_id:I,contact_ids:[...m]})).ok&&(v(new Set),b())}}),(0,de.jsx)("div",{className:"af-mt-3",children:f.contacts.error?(0,de.jsx)(Lt,{message:"Couldn't load contacts.",onRetry:()=>void f.contacts.refetch()}):P?P.contacts.length===0?(0,de.jsx)(aa,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):(0,de.jsxs)(de.Fragment,{children:[(0,de.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:P.contacts.map(k=>(0,de.jsx)(Ud,{contact:k,canWrite:t,busy:p.busy,selected:m.has(k.id),onSelect:I=>v(N=>{let E=new Set(N);return I?E.add(k.id):E.delete(k.id),E}),onUnsubscribe:async()=>{(await p.run("unsubscribeContact",{contactId:k.id})).ok&&b()}},k.id))}),(0,de.jsxs)("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[(0,de.jsxs)("span",{children:[Ue(c+1),"\u2013",Ue(c+P.contacts.length)," of ",Ue(P.total)]}),(0,de.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,de.jsx)(x,{type:"button",variant:"ghost",size:"sm",disabled:c===0,onClick:()=>d(Math.max(0,c-hn)),children:"Previous"}),(0,de.jsx)(x,{type:"button",variant:"ghost",size:"sm",disabled:c+P.contacts.length>=P.total,onClick:()=>d(c+hn),children:"Next"})]})]})]}):(0,de.jsx)(ae,{className:"af-h-24 af-w-full"})}),(0,de.jsx)($d,{tags:T,canWrite:t,onChanged:b})]})}function Ud({contact:e,canWrite:t,busy:s,selected:n,onSelect:a,onUnsubscribe:r}){return(0,de.jsxs)("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&(0,de.jsx)("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:n,onChange:o=>a(o.target.checked)}),(0,de.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,de.jsxs)("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?(0,de.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),(0,de.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[(0,de.jsx)(oe,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":Fd[e.status]}),e.tags.map(o=>(0,de.jsx)(oe,{variant:"outline",children:o.label},o.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&(0,de.jsx)(x,{type:"button",variant:"ghost",size:"sm",disabled:s,onClick:r,children:"Unsubscribe"})]})}function Md({tags:e,count:t,busy:s,onApply:n}){let[a,r]=_s.useState("");return(0,de.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,de.jsxs)("span",{children:[Ue(t)," selected"]}),(0,de.jsxs)("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:a,onChange:o=>r(o.target.value),children:[(0,de.jsx)("option",{value:"",children:"Choose a tag\u2026"}),e.map(o=>(0,de.jsx)("option",{value:o.id,children:o.label},o.id))]}),(0,de.jsx)(x,{type:"button",size:"sm",variant:"outline",disabled:!a||s,onClick:()=>n("add",a),children:"Add tag"}),(0,de.jsx)(x,{type:"button",size:"sm",variant:"ghost",disabled:!a||s,onClick:()=>n("remove",a),children:"Remove tag"})]})}function $d({tags:e,canWrite:t,onChanged:s}){let[n,a]=_s.useState(""),[r,o]=_s.useState(null),c=na();return(0,de.jsxs)("div",{children:[(0,de.jsx)(Va,{children:"Tags"}),e.length===0?(0,de.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,de.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(d=>(0,de.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===d.id?(0,de.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async l=>{l.preventDefault(),(await c.run("updateTag",{tagId:d.id,label:r.label.trim()})).ok&&(o(null),s())},children:[(0,de.jsx)(re,{"aria-label":`New name for ${d.label}`,value:r.label,onChange:l=>o({id:d.id,label:l.target.value})}),(0,de.jsx)(x,{type:"submit",size:"sm",disabled:!r.label.trim()||c.busy,children:"Save"})]}):(0,de.jsxs)(de.Fragment,{children:[(0,de.jsxs)("span",{children:[d.label," ",(0,de.jsxs)("span",{className:"af-text-muted-foreground",children:["\xB7 ",Ue(d.total)," contacts, ",Ue(d.mailable)," can be emailed"]})]}),t&&!d.system&&(0,de.jsx)(x,{type:"button",size:"sm",variant:"ghost",onClick:()=>o({id:d.id,label:d.label}),children:"Rename"})]})},d.id))}),t&&(0,de.jsxs)("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async d=>{d.preventDefault(),(await c.run("createTag",{label:n.trim()})).ok&&(a(""),s())},children:[(0,de.jsx)(re,{"aria-label":"New tag",placeholder:"New tag",value:n,maxLength:100,onChange:d=>a(d.target.value)}),(0,de.jsx)(x,{type:"submit",size:"sm",variant:"outline",disabled:!n.trim()||c.busy,children:"Add tag"})]}),c.error&&(0,de.jsx)(Be,{tone:"error",className:"af-mt-2",children:c.error})]})}var lt=ie(require("react"),1),Sc=require("lucide-react");function _r({siteId:e,refreshKey:t=0}){let{api:s}=W();return wa(()=>s.getBroadcasts(e),`${e}|${t}`,e)}function Pr({siteId:e,kind:t,refreshKey:s=0}){let{api:n}=W();return wa(()=>n.getEmailDrafts(e,t),`${e}|${t??""}|${s}`,`${e}|${t??""}`)}var It=ie(require("react"),1);var Ne=require("react/jsx-runtime");function hc({draftId:e,renderCommit:t,onSaved:s}){let{api:n}=W(),{siteId:a,canWrite:r,refreshKey:o}=Wt(),[c,d]=It.useState(null),[l,i]=It.useState(null),[m,v]=It.useState(null),[g,u]=It.useState(null),[f,p]=It.useState(!1),[b,w]=It.useState(null),P=na(),T=na(),y=It.useRef(!1),C=It.useRef(!1),k=It.useCallback(E=>{y.current=E},[]),I=It.useCallback(async(E={})=>{u(null),v(null);let[D,_]=await Promise.allSettled([n.getEmailDraft(a,e),n.previewEmailDraft(a,e)]);if(E.unlessDirty&&y.current){C.current=!0;return}if(D.status==="rejected"){u(Un(D.reason));return}d(D.value),_.status==="fulfilled"?i(_.value):(i(null),v(Fn(_.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:Un(_.reason),code:null}))},[n,a,e]);It.useEffect(()=>{d(null),i(null),I()},[I]);let N=It.useRef(o);return It.useEffect(()=>{if(o!==N.current){if(N.current=o,y.current){C.current=!0;return}I({unlessDirty:!0})}},[o,I]),g?(0,Ne.jsxs)(Be,{tone:"error",children:["Couldn't load this email. ",g]}):c?(0,Ne.jsxs)("div",{className:"af-space-y-4",children:[(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:"Subject"}),(0,Ne.jsx)("div",{className:"af-font-medium",children:c.subject||"(no subject)"}),c.preheader&&(0,Ne.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:c.preheader})]}),f?(0,Ne.jsx)(Vd,{draft:c,onDirtyChange:k,busy:P.busy,error:P.error,onCancel:()=>{y.current=!1,p(!1),C.current&&(C.current=!1,I())},onSave:async E=>{let D=await P.run("updateDraft",{draftId:e,expected_version:c.version,...E});D.ok?(y.current=!1,C.current=!1,p(!1),await I(),s?.()):Fn(D.error,"version_conflict")&&(P.setError("This email changed while you were editing. We've loaded the latest version."),y.current=!1,C.current=!1,p(!1),await I())}},c.version):(0,Ne.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,Ne.jsx)(x,{type:"button",variant:"outline",size:"sm",disabled:!r,onClick:()=>p(!0),children:"Edit text"}),(0,Ne.jsx)(x,{type:"button",variant:"outline",size:"sm",disabled:!r||T.busy,onClick:async()=>{w(null);let E=await T.run("testSendDraft",{draftId:e});E.ok&&w(E.result?.sent_to??"your email")},children:"Send a test to me"})]}),P.error&&!f&&(0,Ne.jsx)(Be,{tone:"warning",children:P.error}),b&&(0,Ne.jsxs)(Be,{tone:"success",children:["Test sent to ",b,"."]}),T.error&&(0,Ne.jsx)(Be,{tone:"error",children:T.error}),l?(0,Ne.jsx)("iframe",{title:"Email preview",sandbox:"",srcDoc:l.html,className:"af-h-[480px] af-w-full af-rounded-md af-border af-bg-white"}):m?(0,Ne.jsxs)(Be,{tone:"warning",children:[m.text,(0,Ne.jsx)(Ni,{reason:m.code})]}):(0,Ne.jsx)(ae,{className:"af-h-40 af-w-full"}),l&&t?.({draft:c,preview:l,reload:I})]}):(0,Ne.jsx)(ae,{className:"af-h-40 af-w-full"})}function Vd({draft:e,busy:t,error:s,onSave:n,onCancel:a,onDirtyChange:r}){let[o,c]=It.useState(e.subject),[d,l]=It.useState(e.preheader??""),[i,m]=It.useState(e.blocks),v=o!==e.subject||d!==(e.preheader??"")||i!==e.blocks;It.useEffect(()=>r(v),[v,r]);let g=(u,f)=>m(p=>p.map((b,w)=>w===u?{...b,...f}:b));return(0,Ne.jsxs)("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:u=>{u.preventDefault(),n({subject:o,preheader:d.trim()||null,blocks:i})},children:[(0,Ne.jsx)(Us,{label:"Subject",children:(0,Ne.jsx)(re,{"aria-label":"Subject",value:o,maxLength:200,onChange:u=>c(u.target.value)})}),(0,Ne.jsx)(Us,{label:"Preview text",children:(0,Ne.jsx)(re,{"aria-label":"Preview text",value:d,maxLength:200,onChange:u=>l(u.target.value)})}),i.map((u,f)=>(0,Ne.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[u.type==="heading"&&(0,Ne.jsx)(Us,{label:"Heading",children:(0,Ne.jsx)(re,{"aria-label":`Heading ${f+1}`,value:u.text,onChange:p=>g(f,{text:p.target.value})})}),u.type==="text"&&(0,Ne.jsx)(Us,{label:"Text",children:(0,Ne.jsx)("textarea",{"aria-label":`Text ${f+1}`,className:"af-min-h-[96px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",value:u.text,onChange:p=>g(f,{text:p.target.value})})}),u.type==="image"&&(0,Ne.jsxs)(Ne.Fragment,{children:[(0,Ne.jsx)(Us,{label:"Image URL",children:(0,Ne.jsx)(re,{"aria-label":`Image URL ${f+1}`,value:u.url,onChange:p=>g(f,{url:p.target.value})})}),(0,Ne.jsx)(Us,{label:"Image description",children:(0,Ne.jsx)(re,{"aria-label":`Image description ${f+1}`,value:u.alt??"",onChange:p=>g(f,{alt:p.target.value})})})]}),u.type==="button"&&(0,Ne.jsxs)(Ne.Fragment,{children:[(0,Ne.jsx)(Us,{label:"Button label",children:(0,Ne.jsx)(re,{"aria-label":`Button label ${f+1}`,value:u.label,onChange:p=>g(f,{label:p.target.value})})}),(0,Ne.jsx)(Us,{label:"Button link",children:(0,Ne.jsx)(re,{"aria-label":`Button link ${f+1}`,value:u.url,onChange:p=>g(f,{url:p.target.value})})})]}),u.type==="cart"&&(0,Ne.jsx)(Us,{label:"Cart button label",children:(0,Ne.jsx)(re,{"aria-label":`Cart button label ${f+1}`,value:u.label,onChange:p=>g(f,{label:p.target.value})})})]},f)),s&&(0,Ne.jsx)(Be,{tone:"error",children:s}),(0,Ne.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ne.jsx)(x,{type:"submit",size:"sm",disabled:t,children:"Save changes"}),(0,Ne.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:a,children:"Cancel"})]})]})}function Us({label:e,children:t}){return(0,Ne.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Ne.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}var ue=require("react/jsx-runtime"),Hd={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function wc({initialDraftId:e}){let{siteId:t,canWrite:s,refreshKey:n}=Wt(),[a,r]=lt.useState(0),o=a+n,[c,d]=lt.useState(e??null),l=Pr({siteId:t,kind:"broadcast",refreshKey:o}),i=_r({siteId:t,refreshKey:o}),m=na();return c?(0,ue.jsxs)("div",{className:"af-space-y-4",children:[(0,ue.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(null),children:[(0,ue.jsx)(Sc.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),(0,ue.jsx)(hc,{draftId:c,onSaved:()=>r(v=>v+1),renderCommit:v=>(0,ue.jsx)(jd,{...v,onCommitted:()=>r(g=>g+1)})})]}):(0,ue.jsxs)("div",{children:[(0,ue.jsx)(Va,{children:"Drafts"}),l.error?(0,ue.jsx)(Lt,{message:"Couldn't load drafts.",onRetry:()=>void l.refetch()}):l.data?l.data.length===0?(0,ue.jsx)(aa,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):(0,ue.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:l.data.map(v=>(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:v.subject||"(no subject)"}),(0,ue.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>d(v.id),children:"Review"})]},v.id))}):(0,ue.jsx)(ae,{className:"af-h-10 af-w-full"}),(0,ue.jsx)(Va,{children:"Sent and scheduled"}),m.error&&(0,ue.jsx)(Be,{tone:"error",children:m.error}),i.error?(0,ue.jsx)(Lt,{message:"Couldn't load broadcasts.",onRetry:()=>void i.refetch()}):i.data?i.data.length===0?(0,ue.jsx)(aa,{children:"Nothing sent yet."}):(0,ue.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:i.data.map(v=>(0,ue.jsx)(zd,{broadcast:v,canCancel:s&&(v.status==="scheduled"||v.status==="unscheduled"||v.status==="sending"),busy:m.busy,onCancel:async()=>{(await m.run("cancelBroadcast",{sendId:v.id})).ok&&r(u=>u+1)}},v.id))}):(0,ue.jsx)(ae,{className:"af-h-10 af-w-full"})]})}function zd({broadcast:e,canCancel:t,busy:s,onCancel: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)(oe,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Hd[e.status]}),t&&(0,ue.jsx)(x,{type:"button",variant:"ghost",size:"sm",disabled:s,onClick:n,children:"Cancel"})]})]}),(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 `:"",Ue(e.recipients.planned)," recipients \xB7 ",Ue(e.stats.delivered)," delivered \xB7 ",Ue(e.stats.opened)," opened \xB7"," ",Ue(e.stats.clicked)," clicked \xB7 ",Ue(e.stats.bounced)," bounced \xB7 ",Ue(e.stats.complained)," complaints \xB7"," ",Ue(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&(0,ue.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:yn(e.status_reason)})]})}var Nc=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function xc(e){let t=e.targeting??null,s=e.proposed_send_at?new Date(e.proposed_send_at):null,n=s!==null&&s.getTime()>Date.now();return{key:Nc(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:n?qd(s):"",suggested:t!==null||s!==null,timePassed:s!==null&&!n}}function qd(e){let t=s=>String(s).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}var Wd=(e,t)=>e.match===t.match&&e.scheduleAt===t.scheduleAt&&e.tagIds.length===t.tagIds.length&&e.tagIds.every(s=>t.tagIds.includes(s));function jd({draft:e,preview:t,reload:s,onCommitted:n}){let{api:a}=W(),{siteId:r,canWrite:o,settings:c,refreshKey:d}=Wt(),[l,i]=lt.useState(null),[m,v]=lt.useState(!1),[g,u]=lt.useState(null),[f,p]=lt.useState(()=>xc(e)),[b,w]=lt.useState(f.tagIds),[P,T]=lt.useState(f.match),[y,C]=lt.useState(f.scheduleAt),[k,I]=lt.useState(0),N=!Wd({tagIds:b,match:P,scheduleAt:y},f),E=Nc(e);lt.useEffect(()=>{if(E===f.key||e.id===f.draftId&&N)return;let te=xc(e);p(te),w(te.tagIds),T(te.match),C(te.scheduleAt),I(0)},[E,e,f,N]);let D=lt.useMemo(()=>l?new Set(l.map(te=>te.id)):null,[l]),_=D!==null&&b.every(te=>D.has(te));lt.useEffect(()=>{if(!D||b.every(we=>D.has(we)))return;let te=we=>we.filter(He=>D.has(He));I(we=>we+b.length-te(b).length),w(te(b)),p(we=>({...we,tagIds:te(we.tagIds)}))},[D,b]);let[Y,Q]=lt.useState(null),[z,le]=lt.useState(null),[fe,he]=lt.useState(null),M=na();lt.useEffect(()=>{a.getMarketingTags(r).then(te=>{i(te),v(!1)},()=>{i(null),v(!0)}),a.getMarketingContactStats(r).then(u,()=>u(null))},[a,r,d]);let ee=y?new Date(y).toISOString():null,U=JSON.stringify([b,P,ee]),ve=Y?.plan??null,me=Y!==null&&Y.key===U,Qe=lt.useRef(0),ke=lt.useCallback(async()=>{let te=++Qe.current;le(null);try{let we=await a.estimateBroadcast(r,{targeting:{tag_ids:b,match:P},scheduled_at:ee});te===Qe.current&&Q({key:U,plan:we})}catch(we){if(te!==Qe.current)return;Q(null),le(Un(we))}},[a,r,b,P,ee,U,d]),Ge=lt.useRef(!1);lt.useEffect(()=>{if(!_&&b.length>0)return;if(!Ge.current){Ge.current=!0,ke();return}let te=setTimeout(()=>void ke(),300);return()=>clearTimeout(te)},[ke,_,b.length]);let Je=c&&!c.readiness.can_send?yn(c.readiness.reason):null,Fe=ve!==null&&!ve.fits,_t=g?Math.max(0,g.by_status.subscribed-g.mailable):null,L=g&&ve&&_t!==null?Math.max(0,g.total-ve.recipients-_t):null,$=!o||M.busy||!ve||!me||Fe||ve.recipients===0||Je!==null||m&&b.length>0,F=async()=>{he(null);let te=await M.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:b,match:P},scheduled_at:ee});if(te.ok){he({tone:"success",text:ee?"Scheduled.":"Sending now."}),n();return}Fn(te.error,"version_conflict")?(M.setError(null),await s(),he({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):Fn(te.error,"over_allowance")&&await ke()},Re=te=>w(we=>we.includes(te)?we.filter(He=>He!==te):[...we,te]);return(0,ue.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[f.suggested&&!N&&(0,ue.jsx)(Be,{children:"Suggested by your assistant \u2014 review before sending."}),(0,ue.jsx)(Va,{children:"Who gets it"}),m&&(0,ue.jsx)(Be,{tone:"warning",children:b.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."}),k>0&&(0,ue.jsx)(Be,{tone:"warning",children:k===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),l&&l.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:l.map(te=>(0,ue.jsxs)("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[(0,ue.jsx)("input",{type:"checkbox",checked:b.includes(te.id),onChange:()=>Re(te.id)}),te.label]},te.id))}),b.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:P,onChange:te=>T(te.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"})]})]}),b.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)(re,{"aria-label":"Schedule time",type:"datetime-local",value:y,onChange:te=>C(te.target.value)})]}),f.timePassed&&!y&&(0,ue.jsx)(Be,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),z?(0,ue.jsxs)(Be,{tone:"error",children:["Couldn't work out the audience. ",z]}):ve?(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)(ho,{label:"Will receive it",value:ve.recipients}),(0,ue.jsx)(ho,{label:"Suppressed (bounced or complained)",value:_t}),(0,ue.jsx)(ho,{label:"Not included",value:L})]}),(0,ue.jsxs)("p",{className:"af-text-muted-foreground",children:[Ue(ve.allowance.remaining)," of ",Ue(ve.allowance.monthly)," emails left this month."]}),ve.sample_size!==null&&(0,ue.jsxs)(Be,{children:["We'll send to ",Ue(ve.sample_size)," people first and check for bounces before sending the rest."]}),ve.ramp_days.length>1&&(0,ue.jsxs)(Be,{children:["Your domain is new, so this goes out over ",ve.ramp_days.length," days:"," ",ve.ramp_days.map(te=>`${Ue(te.recipients)} on ${te.date}`).join(", "),"."]})]}):(0,ue.jsx)(ae,{className:"af-h-12 af-w-full"}),Fe&&ve&&(0,ue.jsxs)(Be,{tone:"warning",children:["This send needs ",Ue(ve.recipients)," emails, but only ",Ue(ve.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),Je&&(0,ue.jsxs)(Be,{tone:"warning",children:[Je,(0,ue.jsx)(Ni,{reason:c?.readiness.reason})]}),fe&&(0,ue.jsx)(Be,{tone:fe.tone,children:fe.text}),M.error&&(0,ue.jsx)(Be,{tone:"error",children:M.error}),(0,ue.jsx)(x,{type:"button",disabled:$,onClick:()=>void F(),children:ee?"Schedule":"Send now"})]})}function ho({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":Ue(t)})]})}var ua=ie(require("react"),1);var ce=require("react/jsx-runtime"),kr="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 Gd(e){let{status:t,dmarc_status:s,sending_domain:n}=e.domain;return!n||t==="none"?"No sending domain yet.":t==="verified"?s==="ok"?`Verified. Emails send from ${n}.`:`${n} is verified, but your domain still needs a DMARC record.`:t==="failed"?`${n} couldn't be verified. Check the DNS records below.`:`Waiting for the DNS records on ${n} to take effect. This can take a few hours.`}function xo({onStartDomainSetup:e}){let{settings:t,refetchSettings:s,canWrite:n,settingsSection:a}=Wt(),r=t!==null;return ua.useEffect(()=>{r&&a&&document.getElementById(Nr(a))?.scrollIntoView?.({block:"start"})},[r,a]),t?(0,ce.jsxs)("div",{children:[(0,ce.jsx)(Va,{id:Nr("domain"),children:"Sending domain"}),(0,ce.jsx)(So,{settings:t,canWrite:n,onStartDomainSetup:e,onChanged:s}),(0,ce.jsx)(Zd,{settings:t}),(0,ce.jsx)(Jd,{settings:t,canWrite:n,onSaved:s},Yd(t)),(0,ce.jsx)(wo,{canWrite:n})]}):(0,ce.jsx)(ae,{className:"af-h-40 af-w-full"})}function So({settings:e,canWrite:t,onStartDomainSetup:s,onChanged:n}){let[a,r]=ua.useState(null),[o,c]=ua.useState(!1),[d,l]=ua.useState(null),i=e.domain.status==="verified"&&e.domain.dmarc_status==="ok";return(0,ce.jsxs)("div",{children:[(0,ce.jsx)("p",{className:"af-text-sm",children:Gd(e)}),!i&&s&&(0,ce.jsx)(x,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||o,onClick:async()=>{c(!0),l(null);try{r(await s()),await n()}catch(m){l(m instanceof Error?m.message:"Couldn't start domain setup.")}finally{c(!1)}},children:e.domain.sending_domain?"Check domain setup":"Set up sending domain"}),d&&(0,ce.jsx)(Be,{tone:"error",className:"af-mt-2",children:d}),a?.records&&a.records.length>0&&(0,ce.jsxs)("div",{className:"af-mt-3 af-space-y-1",children:[(0,ce.jsx)("p",{className:"af-text-sm",children:"Add these records at your domain provider:"}),(0,ce.jsxs)("table",{className:"af-w-full af-text-left af-text-xs",children:[(0,ce.jsx)("thead",{children:(0,ce.jsxs)("tr",{children:[(0,ce.jsx)("th",{className:"af-py-1 af-pr-2",children:"Type"}),(0,ce.jsx)("th",{className:"af-py-1 af-pr-2",children:"Name"}),(0,ce.jsx)("th",{className:"af-py-1 af-pr-2",children:"Value"}),(0,ce.jsx)("th",{className:"af-py-1",children:"Priority"})]})}),(0,ce.jsx)("tbody",{children:a.records.map((m,v)=>(0,ce.jsxs)("tr",{className:"af-border-t af-align-top",children:[(0,ce.jsx)("td",{className:"af-py-1 af-pr-2",children:m.type}),(0,ce.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:m.name}),(0,ce.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:m.value}),(0,ce.jsx)("td",{className:"af-py-1",children:m.priority??""})]},v))})]})]}),a&&(0,ce.jsx)(Kd,{result:a})]})}function Kd({result:e}){return e.status==="no_domain"?(0,ce.jsx)(Be,{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,ce.jsx)(Be,{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,ce.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 Zd({settings:e}){let{monthly:t,sent:s,reserved:n}=e.allowance,a=s+n;return(0,ce.jsxs)("div",{children:[(0,ce.jsx)(Va,{children:"Monthly allowance"}),(0,ce.jsxs)("p",{className:"af-text-sm",children:[Ue(a)," of ",Ue(t)," emails used this month (",Ue(Math.max(0,t-a))," left). Receipts and form notifications don't count."]})]})}function Yd(e){return JSON.stringify([e.business_name,e.postal_address,e.reply_to,e.brand,e.double_opt_in,e.checkout_marketing_consent,e.stripe_account_country])}function Jd({settings:e,canWrite:t,onSaved:s}){let[n,a]=ua.useState(e.business_name??""),[r,o]=ua.useState(e.postal_address??""),[c,d]=ua.useState(e.reply_to??""),[l,i]=ua.useState(e.brand.color),[m,v]=ua.useState(e.brand.logo_url??""),[g,u]=ua.useState(e.double_opt_in),[f,p]=ua.useState(!1),[b,w]=ua.useState(!1),P=na();return(0,ce.jsxs)("form",{onSubmit:async T=>{T.preventDefault(),w(!1),(await P.run("updateSettings",{business_name:n.trim()||null,postal_address:r.trim()||null,reply_to:c.trim()||null,double_opt_in:g,brand:{color:l,logo_url:m.trim()||null}})).ok&&(w(!0),await s())},children:[(0,ce.jsx)(Va,{id:Nr("sender"),children:"Sender details"}),(0,ce.jsxs)("div",{className:"af-space-y-3",children:[(0,ce.jsx)(Cr,{label:"Business name (shown as the sender)",children:(0,ce.jsx)(re,{"aria-label":"Business name",value:n,disabled:!t,onChange:T=>a(T.target.value)})}),(0,ce.jsx)(Cr,{label:"Postal address (required in every email)",children:(0,ce.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",value:r,disabled:!t,onChange:T=>o(T.target.value)})}),(0,ce.jsx)(Cr,{label:"Replies go to (your account email or an address on your domain)",children:(0,ce.jsx)(re,{"aria-label":"Reply-to email",type:"email",value:c,disabled:!t,onChange:T=>d(T.target.value)})})]}),(0,ce.jsx)(Va,{children:"Brand"}),(0,ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-3",children:[(0,ce.jsx)(Cr,{label:"Brand color",children:(0,ce.jsx)(re,{"aria-label":"Brand color",type:"color",className:"af-h-9 af-w-16 af-p-1",value:l,disabled:!t,onChange:T=>i(T.target.value)})}),(0,ce.jsx)(Cr,{label:"Logo URL (https)",children:(0,ce.jsx)(re,{"aria-label":"Logo URL",value:m,disabled:!t,onChange:T=>v(T.target.value)})})]}),(0,ce.jsx)(Va,{id:Nr("signups"),children:"Signups"}),(0,ce.jsx)("div",{className:"af-space-y-3 af-text-sm",children:(0,ce.jsxs)("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[(0,ce.jsxs)("label",{className:"af-flex af-items-center af-gap-2",children:[(0,ce.jsx)("input",{"aria-label":"Double opt-in",type:"checkbox",checked:g,disabled:!t,onChange:T=>u(T.target.checked)}),"Double opt-in"]}),(0,ce.jsx)("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:kr,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:()=>p(!0),onMouseLeave:()=>p(!1),onFocus:()=>p(!0),onBlur:()=>p(!1),children:"?"}),(0,ce.jsx)("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!f,className:"af-absolute af-left-0 af-top-6 af-z-10 af-max-w-sm af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:kr})]})}),P.error&&(0,ce.jsx)(Be,{tone:"error",className:"af-mt-3",children:P.error}),b&&(0,ce.jsx)(Be,{tone:"success",className:"af-mt-3",children:"Saved."}),t&&(0,ce.jsx)(x,{type:"submit",size:"sm",className:"af-mt-3",disabled:P.busy,children:"Save settings"})]})}function wo({canWrite:e,heading:t=!0}){let{api:s}=W(),{siteId:n,refreshKey:a}=Wt(),r=wa(async()=>Promise.all((await s.getForms()).map(l=>s.getForm(l.id))),`${n}|${a}`,n),[o,c]=ua.useState({}),d=na();return!r.data||r.data.length===0?null:(0,ce.jsxs)("div",{children:[t&&(0,ce.jsx)(Va,{children:"Newsletter signup forms"}),(0,ce.jsx)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:"Submitting a newsletter signup form subscribes the visitor. Other forms need their own opt-in checkbox."}),(0,ce.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:r.data.map(l=>(0,ce.jsxs)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:[(0,ce.jsx)("span",{className:"af-truncate",children:l.name}),(0,ce.jsxs)("label",{className:"af-flex af-items-center af-gap-2",children:[(0,ce.jsx)("input",{type:"checkbox","aria-label":`${l.name} is a newsletter signup`,checked:(l.id in o?o[l.id]:l.purpose)==="newsletter",disabled:!e||d.busy,onChange:async i=>{let m=i.target.checked?"newsletter":"general";(await d.run("setFormPurpose",{formId:l.id,purpose:m})).ok&&c(g=>({...g,[l.id]:m}))}}),"Newsletter signup"]})]},l.id))}),d.error&&(0,ce.jsx)(Be,{tone:"error",className:"af-mt-2",children:d.error})]})}function Cr({label:e,children:t}){return(0,ce.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,ce.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}var _i=ie(require("react"),1),Tr=require("lucide-react");var Ae=require("react/jsx-runtime"),Xd=["Signups from your site's forms land here automatically.","The assistant drafts your newsletters. You review and press Send.","Every email carries the unsubscribe link, consent record and postal address the law asks for."];function Rc({onStartDomainSetup:e}){let{api:t}=W(),{siteId:s,settings:n,refetchSettings:a,canWrite:r,refreshKey:o}=Wt(),c=wa(()=>t.getMarketingContactStats(s),`${s}|${o}`,s);if(!n)return null;let d=n.domain.status==="verified"&&n.domain.dmarc_status==="ok",l=!!n.postal_address,i=c.data?.by_status.subscribed??0;return(0,Ae.jsxs)("div",{className:"af-mx-auto af-max-w-2xl",children:[(0,Ae.jsxs)("div",{className:"af-mb-6 af-rounded-lg af-border af-bg-muted/40 af-p-5",children:[(0,Ae.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-gap-2",children:[(0,Ae.jsx)(Tr.Mail,{className:"af-h-5 af-w-5","aria-hidden":!0}),(0,Ae.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Turn visitors into a list you own"})]}),(0,Ae.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Collect subscribers from your site, then send them newsletters from your own domain, branded with your logo and colors."}),(0,Ae.jsx)("ul",{className:"af-mt-3 af-space-y-1.5 af-text-sm",children:Xd.map(m=>(0,Ae.jsxs)("li",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)(Tr.Check,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0 af-text-primary","aria-hidden":!0}),m]},m))}),i>0&&(0,Ae.jsxs)("p",{className:"af-mt-3 af-text-sm af-font-medium",children:[Ue(i)," ",i===1?"subscriber is":"subscribers are"," already waiting for your first email."]})]}),(0,Ae.jsx)("h3",{className:"af-mb-3 af-text-sm af-font-semibold",children:"Set up sending"}),!r&&(0,Ae.jsx)(Be,{className:"af-mb-3",children:"Only the site owner can finish setup."}),(0,Ae.jsxs)("ol",{className:"af-space-y-3",children:[(0,Ae.jsxs)(No,{n:1,title:"Send from your own domain",done:d,children:[(0,Ae.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."}),(0,Ae.jsx)(So,{settings:n,canWrite:r,onStartDomainSetup:e,onChanged:a})]}),(0,Ae.jsx)(No,{n:2,title:"Add your sender details",done:l,summary:l?n.business_name??void 0:void 0,children:(0,Ae.jsx)(Qd,{settings:n,canWrite:r,onSaved:a})}),(0,Ae.jsxs)(No,{n:3,title:"Collect subscribers",optional:!0,children:[(0,Ae.jsx)("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:'Mark a form as a newsletter signup, or ask the assistant to "add a newsletter signup to my footer".'}),(0,Ae.jsx)(wo,{canWrite:r,heading:!1})]})]})]})}function No({n:e,title:t,done:s=!1,optional:n=!1,summary:a,children:r}){return(0,Ae.jsxs)("li",{className:"af-rounded-lg af-border af-p-4","aria-label":`Step ${e}: ${t}${s?" (done)":""}`,children:[(0,Ae.jsxs)("div",{className:"af-flex af-items-center af-gap-3",children:[(0,Ae.jsx)("span",{className:J("af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-xs af-font-semibold",s?"af-bg-primary af-text-primary-foreground":"af-border"),children:s?(0,Ae.jsx)(Tr.Check,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0}):e}),(0,Ae.jsx)("span",{className:"af-text-sm af-font-medium",children:t}),n&&(0,Ae.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Optional"}),s&&a&&(0,Ae.jsx)("span",{className:"af-truncate af-text-xs af-text-muted-foreground",children:a})]}),!s&&(0,Ae.jsx)("div",{className:"af-mt-3 af-pl-9",children:r})]})}function Qd({settings:e,canWrite:t,onSaved:s}){let[n,a]=_i.useState(e.business_name??""),[r,o]=_i.useState(e.postal_address??""),[c,d]=_i.useState(e.reply_to??""),l=na();return(0,Ae.jsxs)("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),(await l.run("updateSettings",{business_name:n.trim()||null,postal_address:r.trim()||null,reply_to:c.trim()||null,double_opt_in:e.double_opt_in})).ok&&await s()},children:[(0,Ae.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Ae.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Business name (shown as the sender)"}),(0,Ae.jsx)(re,{"aria-label":"Business name",value:n,disabled:!t,onChange:i=>a(i.target.value)})]}),(0,Ae.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Ae.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Postal address (required in every email)"}),(0,Ae.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",value:r,disabled:!t,onChange:i=>o(i.target.value)})]}),(0,Ae.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Ae.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Replies go to (optional: your account email or an address on your domain)"}),(0,Ae.jsx)(re,{"aria-label":"Reply-to email",type:"email",value:c,disabled:!t,onChange:i=>d(i.target.value)})]}),l.error&&(0,Ae.jsx)(Be,{tone:"error",children:l.error}),t&&(0,Ae.jsx)(x,{type:"submit",size:"sm",disabled:l.busy||!r.trim(),children:"Save sender details"})]})}var We=require("react/jsx-runtime"),ef=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"settings",label:"Settings"}],tf={broadcast:"broadcasts",welcome:"broadcasts",recovery:"broadcasts"},af={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function Ro(e){return(0,We.jsx)(sf,{...e},e.siteId)}function sf({siteId:e,isOwnerSide:t,needsPaidPlan:s,initialDraftId:n,onOrgAction:a,onRequestReview:r,onStartDomainSetup:o,onBackToWebsite:c,onOpenStoreSettings:d,refreshKey:l=0,className:i}){let{api:m}=W(),v=wa(()=>m.getMarketingSettings(e),`${e}|${l}`,e),[g,u]=Na.useState(n?"broadcasts":"audience"),[f,p]=Na.useState(!n),[b,w]=Na.useState(null),P=_=>b===_?n:void 0,[T,y]=Na.useState(!!n),[C,k]=Na.useState(null),I=Na.useCallback(()=>y(!1),[]),N=Na.useCallback(_=>{u("settings"),k(_??null)},[]),E=!T&&v.data!==null&&Pc(v.data);Na.useEffect(()=>{if(!n||s)return;let _=!0;return m.getEmailDraft(e,n).then(Y=>{_&&(u(tf[Y.kind]),w(Y.kind),p(!0))},()=>_&&p(!0)),()=>{_=!1}},[m,e,n,s]);let D=Na.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:a,settings:v.data,refetchSettings:v.refetch,refreshKey:l,openSetup:I,openSettings:N,settingsSection:C,onOpenStoreSettings:d}),[e,t,a,v.data,v.refetch,l,I,N,C,d]);return s?(0,We.jsx)(St,{title:"Email Marketing",onBackToWebsite:c,className:i,children:(0,We.jsx)(Ks,{icon:_c.Mail,heading:"Email marketing is on the Pro plan.",body:"Upgrade to collect subscribers and send newsletters from your own domain."})}):(0,We.jsx)(St,{title:"Email Marketing",onBackToWebsite:c,className:i,children:(0,We.jsx)(yo.Provider,{value:D,children:E?(0,We.jsx)(Rc,{onStartDomainSetup:o}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(nf,{settingsError:v.error,onRetry:()=>void v.refetch(),onRequestReview:r}),!t&&(0,We.jsx)(Be,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),(0,We.jsx)("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:ef.map(_=>(0,We.jsx)("button",{type:"button",role:"tab","aria-selected":g===_.id,onClick:()=>{u(_.id),k(null)},className:J("af-border-b-2 af-px-3 af-py-2 af-text-sm",g===_.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:_.label},_.id))}),(0,We.jsx)("div",{role:"tabpanel",children:f?g==="audience"?(0,We.jsx)(yc,{}):g==="broadcasts"?(0,We.jsx)(wc,{initialDraftId:P("broadcast")}):(0,We.jsx)(xo,{onStartDomainSetup:o}):(0,We.jsx)(ae,{className:"af-h-24 af-w-full"})})]})})})}function Pc(e){return!e.paused.paused_at&&!e.readiness.can_send&&Si.has(e.readiness.reason??"")}function nf({settingsError:e,onRetry:t,onRequestReview:s}){let{settings:n,openSetup:a}=Wt(),[r,o]=Na.useState("idle");return e?(0,We.jsx)(Lt,{message:"Couldn't load email settings.",onRetry:t}):n?n.paused.paused_at?(0,We.jsxs)(Be,{tone:"warning",className:"af-mb-3",children:[(0,We.jsx)("div",{className:"af-font-medium",children:"Sending is paused."}),(0,We.jsxs)("p",{children:[af[n.paused.reason??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),s&&(r==="sent"?(0,We.jsx)("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):(0,We.jsx)(x,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{o("sending");try{await s(),o("sent")}catch{o("failed")}},children:"Request review"})),r==="failed"&&(0,We.jsx)("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]}):n.readiness.can_send?(0,We.jsxs)(Be,{tone:"success",className:"af-mb-3",children:["Ready to send from ",n.domain.sending_domain??"your domain","."]}):(0,We.jsxs)(Be,{tone:"warning",className:"af-mb-3",children:["You can collect and manage contacts now. ",yn(n.readiness.reason),Pc(n)&&(0,We.jsxs)(We.Fragment,{children:[" ",(0,We.jsx)(wi,{onClick:a,children:"Finish setup"})]})]}):(0,We.jsx)(ae,{className:"af-mb-3 af-h-10 af-w-full"})}var Vt=ie(require("react"),1);var rf=2e3,Jt=()=>({data:null,error:null,isLoading:!0});function xn(e,{refreshKey:t,breakdowns:s=[],filters:n=[]}={}){let{api:a}=W(),[r,o]=Vt.useState(Jt),[c,d]=Vt.useState(Jt),[l,i]=Vt.useState(Jt),[m,v]=Vt.useState(Jt),[g,u]=Vt.useState(Jt),f=M=>Object.fromEntries(M.map(ee=>[ee,Jt()])),[p,b]=Vt.useState(()=>f(s)),w=Vt.useRef(0),P=Vt.useRef(0),T=Vt.useRef("idle"),y=s.join(","),C=Vs()??"",k=JSON.stringify(n),I=`${e}:${y}:${k}:${C}`,[N,E]=Vt.useState({api:a,fetchIdentity:I});(N.api!==a||N.fetchIdentity!==I)&&(E({api:a,fetchIdentity:I}),w.current+=1,o(Jt),d(Jt),i(Jt),v(Jt),b(f(y?y.split(","):[])));let D=`${e}:${String(t??"")}:${C}`,[_,Y]=Vt.useState({api:a,conversionsIdentity:D});(_.api!==a||_.conversionsIdentity!==D)&&(Y({api:a,conversionsIdentity:D}),P.current+=1,T.current="idle",u(Jt));let Q=Vt.useCallback(async M=>{let ee=++w.current,U=y?y.split(","):[];o(Jt),d(Jt),i(Jt),v(Jt),b(Object.fromEntries(U.map(L=>[L,Jt()])));let ve=T.current!=="pending"&&(M?.force===!0||T.current==="idle"),me=(L,$)=>$.then(F=>{ee===w.current&&L({data:F,error:null,isLoading:!1})},F=>{ee===w.current&&L({data:null,error:F instanceof Error?F:new Error("Failed to fetch report"),isLoading:!1})}),Qe=a.getAnalyticsStatus(),ke=me(o,Qe),Ge=Symbol("status-timeout"),Je,Fe=await Promise.race([Qe.then(L=>L,()=>null),new Promise(L=>{Je=setTimeout(()=>L(Ge),rf)})]);if(clearTimeout(Je),ee!==w.current)return;if(Fe===Ge&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Fe!==null&&Fe!==Ge&&(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};d(L),i(L),v(L),b(Object.fromEntries(U.map($=>[$,{...L}]))),ve&&(u(L),T.current="done"),await ke;return}await Promise.all([Fe===Ge?Promise.resolve():ke,me(d,a.getAnalyticsSummary(e,n)),me(i,a.getAnalyticsTimeseries(e,n)),me(v,a.getAnalyticsChannels(e,n)),ve?(()=>{T.current="pending";let L=++P.current;return u(Jt),a.getAnalyticsConversions(e).then($=>{L===P.current&&(u({data:$,error:null,isLoading:!1}),T.current="done")},$=>{L===P.current&&(u({data:null,error:$ instanceof Error?$:new Error("Failed to fetch report"),isLoading:!1}),T.current="done")})})():Promise.resolve(),...U.map(L=>a.getAnalyticsBreakdown(L,e,n).then($=>{ee===w.current&&b(F=>({...F,[L]:{data:$,error:null,isLoading:!1}}))},$=>{ee===w.current&&b(F=>({...F,[L]:{data:null,error:$ instanceof Error?$:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[a,e,y,k,D,C]),z=Vt.useCallback(async()=>{let M=w.current;try{let ee=await a.getAnalyticsStatus();if(M!==w.current)return;o({data:ee,error:null,isLoading:!1})}catch(ee){if(M!==w.current)return;o(U=>({data:U.data,error:ee instanceof Error?ee:new Error("Failed to fetch status"),isLoading:!1}))}},[a]),le=Vt.useCallback(()=>Q({force:!0}),[Q]);Vt.useEffect(()=>{Q()},[Q,t]);let fe=r.isLoading||c.isLoading||l.isLoading||m.isLoading||g.isLoading||Object.values(p).some(M=>M.isLoading),he=[l,c,m,g,...Object.values(p)].map(M=>M.data?.status==="ok"?M.data.timezone:void 0).find(M=>M!==void 0);return{status:r,summary:c,timeseries:l,channels:m,conversions:g,breakdowns:p,reportedZone:he,isLoading:fe,refetch:le,refetchStatus:z}}var Ht=ie(require("react"),1);var Pi=3e4,Ci=3;function Er(e={}){let t="collecting"in e,{collecting:s,statusFailed:n=!1,identity:a}=e,{api:r}=W(),[o,c]=Ht.useState(null),[d,l]=Ht.useState(null),[i,m]=Ht.useState(!1),[v,g]=Ht.useState(null),[u,f]=Ht.useState(!1),[p,b]=Ht.useState(!0),[w,P]=Ht.useState(0),T=Ht.useRef(0),y=Ht.useRef(0),C=Ht.useRef(void 0);s!==void 0&&(C.current=s);let k=t?C.current===!0||C.current===void 0&&n:!0,[I,N]=Ht.useState({api:r,identity:a}),E=a!==void 0&&a!==I.identity;(I.api!==r||E)&&(C.current=void 0,N({api:r,identity:a}),y.current+=1,T.current=0,c(null),l(null),m(!1),g(null),f(!1),b(!0),P(0));let D=Ht.useRef(()=>{}),_=Ht.useRef(null),Y=Ht.useCallback(async()=>{if(_.current!==null&&_.current===y.current)return;let Q=++y.current;_.current=Q;try{let z=await r.getAnalyticsRealtime();if(Q!==y.current)return;if(z.status==="unreachable"){f(!0),m(!0),b(!1),P(le=>le+1);return}T.current=0,f(!1),c(z.data.current_visitors),l(z.as_of),m(!1),g(null),b(!1),P(le=>le+1)}catch(z){if(Q!==y.current)return;T.current+=1,b(!1),P(le=>le+1),m(!0),T.current>=Ci&&g(z instanceof Error?z:new Error("Realtime unavailable"))}finally{_.current===Q&&(_.current=null)}},[r]);return D.current=()=>void Y(),Ht.useEffect(()=>{let Q,z=()=>{Q===void 0&&(Q=setInterval(()=>D.current(),Pi))},le=()=>{Q!==void 0&&(clearInterval(Q),Q=void 0)},fe=()=>{typeof document<"u"&&document.hidden?le():(D.current(),z())};return k?((typeof document>"u"||!document.hidden)&&(D.current(),z()),document?.addEventListener("visibilitychange",fe),()=>{le(),document?.removeEventListener("visibilitychange",fe),y.current+=1}):()=>{document?.removeEventListener("visibilitychange",fe)}},[I.api,I.identity,k]),{currentVisitors:o,asOf:d,isStale:i,error:v,isUnreachable:u,isInitialLoad:p,polls:w}}var Rt=ie(require("react"),1);var Cc=ie(require("react"),1);var Sn=require("react/jsx-runtime");function of(){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 _o({value:e,chosen:t,onChange:s}){let n=Hn(),a=t===null&&n!==null&&e===n,r=Cc.useMemo(()=>{let o=of();return o.includes(e)?o:[e,...o]},[e]);return(0,Sn.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,Sn.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,Sn.jsxs)("select",{value:a?"":e,onChange:o=>s(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[(0,Sn.jsx)("option",{value:"",children:n?`${n.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(o=>(0,Sn.jsx)("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var ki=(e,{published:t}={})=>{let s=t===!1,n=e!=null&&(!e.collecting||s&&e.first_seen===null&&!e.first_seen_unavailable),a=!n&&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:n,awaitingFirstVisit:a,firstVisitTooRecent:r,holdingForFirstData:o,nothingToReport:n||o}};var Ir=ie(require("react"),1),lf=3e4;function Ti({status:e,holdingForFirstData:t,refetchStatus:s,refetch:n}){Ir.useEffect(()=>{if(!t)return;let r,o=()=>{r===void 0&&(r=setInterval(()=>void s(),lf))},c=()=>{r!==void 0&&(clearInterval(r),r=void 0)},d=()=>{typeof document<"u"&&document.hidden?c():(s(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",d),()=>{c(),document?.removeEventListener("visibilitychange",d)}},[t,s]);let a=Ir.useRef(void 0);Ir.useEffect(()=>{if(!e){a.current=void 0;return}let r=a.current;a.current=t,r===!0&&!t&&n()},[e,t,n])}var wn=ie(require("react"),1);var cf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function da(e){let t=Math.abs(e);if(t<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[n,a]of s)if(t>=n){let r=e/n,o=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(o)>=1e3&&n!==1e9?da(o*n):`${o}${a}`}return String(e)}function $n(e){return`${(e*100).toFixed(1)}%`}function Dr(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function Tc(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`:Dr(t)}function Ec(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Ic(e,t){if(!(!Number.isFinite(e)||e<=0))for(let s of t){let n=Math.ceil(e/s);if(n<=5)return Array.from({length:n+1},(a,r)=>Number((r*s).toPrecision(12)))}}function Ar(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Dc(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 Po(e){let t=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${cf[t-1]} ${s}`}function kc(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function uf(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Ac(e,t,s="UTC"){let n=new Map(t.map(o=>[o.date,o])),a=[],r=kc(e.to,s);for(let o=kc(e.from,s);o<r;o=uf(o))a.push(n.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return a}function Lc(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=new Date(`${e}T00:00:00Z`);if(Number.isNaN(n.getTime()))return e;let a=String(n.getUTCDate()).padStart(2,"0");return`${t[n.getUTCDay()]}, ${a} ${s[n.getUTCMonth()]}`}var Ha=require("react/jsx-runtime");function Oc({what:e="This report",onRetry:t,collecting:s}){return(0,Ha.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,Ha.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,Ha.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:s===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),t?(0,Ha.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 Ei({what:e="No data"}){return(0,Ha.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 Ms({sourced:e,error:t,isLoading:s,what:n,onRetry:a,collecting:r,children:o}){return s?(0,Ha.jsx)("div",{role:"status","aria-label":`Loading ${n}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,Ha.jsx)(Oc,{what:n,onRetry:a,collecting:r}):!e||e.status==="unreachable"?(0,Ha.jsx)(Oc,{what:n,onRetry:a,collecting:r}):(0,Ha.jsx)(Ha.Fragment,{children:o(e.data)})}var ft=require("react/jsx-runtime");function Co({rows:e,dimension:t,metric:s,metricLabel:n,secondary:a,emptyCopy:r="No data for this period",onFilter:o,canFilter:c,maxRows:d=9}){let[l,i]=wn.useState(!1);if(e.length===0)return(0,ft.jsx)(Ei,{what:r});let m=e.reduce((u,f)=>Math.max(u,Number(f[s]??0)),0)||1,v=Math.max(0,e.length-d),g=l?e:e.slice(0,d);return(0,ft.jsxs)(ft.Fragment,{children:[(0,ft.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,ft.jsx)("thead",{children:(0,ft.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,ft.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,ft.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:n})]})}),(0,ft.jsx)("tbody",{children:g.map((u,f)=>{let p=Number(u[s]??0),b=u[t]??null,w=Ar(b),P=a?u[a]:null,T=b!==null&&(c?c(b,P):!0);return(0,ft.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,ft.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,ft.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/m*100)}%`}}),b!==null&&o&&T?(0,ft.jsx)("button",{type:"button",onClick:()=>o(b,P),title:`Filter by ${w}`,"aria-label":`Filter by ${w}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:w}):(0,ft.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:w}),P?(0,ft.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:P}):null]}),(0,ft.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:da(p)})]},`${w}-${P??""}-${f}`)})})]}),v>0?(0,ft.jsx)("button",{type:"button",onClick:()=>i(u=>!u),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length}`}):null]})}function Lr({title:e,tabs:t,defaultTabId:s,headerRight:n}){let[a,r]=wn.useState(s),o=t.find(g=>g.id===a)??t[0],c=wn.useId(),d=g=>`${c}-tab-${g}`,l=g=>`${c}-panel-${g}`,i=wn.useRef(null),m=(g,u)=>{g.preventDefault();let f=(u+t.length)%t.length;r(t[f].id),i.current?.querySelectorAll('[role="tab"]')?.[f]?.focus()};return(0,ft.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,ft.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,ft.jsx)("div",{ref:i,role:"tablist","aria-label":e,onKeyDown:g=>{let u=t.findIndex(f=>f.id===a);g.key==="ArrowRight"&&m(g,u+1),g.key==="ArrowLeft"&&m(g,u-1),g.key==="Home"&&m(g,0),g.key==="End"&&m(g,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(g=>(0,ft.jsx)("button",{id:d(g.id),role:"tab",type:"button","aria-selected":g.id===a,"aria-controls":l(g.id),tabIndex:g.id===a?0:-1,onClick:()=>r(g.id),className:g.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:g.label},g.id))}),n]}),o?(0,ft.jsx)("div",{id:l(o.id),role:"tabpanel","aria-labelledby":d(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var Ra=ie(require("react"),1),Qs=ie(require("@radix-ui/react-popover"),1);var Js=3,Xs=100;var je=require("react/jsx-runtime"),Or={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"},df=Object.keys(Or);function Bc(e){let t=Or[e.dimension],s=e.operator==="is_not"?"is not":"is",n=e.values.map(a=>Ar(a)).join(" or ");return`${t} ${s} ${n}`}function ko(e,t){let s=e.findIndex(n=>n.dimension===t.dimension&&(n.operator??"is")===(t.operator??"is"));if(s>=0){let n=[...new Set([...e[s].values,...t.values])];return n.length>Xs||n.length===e[s].values.length?e:e.map((a,r)=>r===s?{...a,values:n}:a)}return t.values.length>Xs||e.length>=Js?e:[...e,t]}function ff(e,t){let s={};for(let[n,a]of Object.entries(t)){let r=e.get(n)??new Set;for(let o of a)r.add(o);e.set(n,r),s[n]=[...r]}return s}function Fc(e,t){let s=e.findIndex(n=>n.dimension===t.dimension&&(n.operator??"is")===(t.operator??"is"));return s>=0?e.map((n,a)=>a===s?t:n):t.values.length>Xs||e.length>=Js?e:[...e,t]}function mf(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Uc(e,t,s,n={}){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=ff(e.byDimension,s);for(let[r,o]of Object.entries(n)){let c=e.foldsByLabel.get(r)??new Set;for(let d of o)c.add(d);e.foldsByLabel.set(r,c)}return{suggestions:a,folds:new Map([...e.foldsByLabel].map(([r,o])=>[r,[...o]]))}}function Mc(e){let{filters:t,onChange:s}=e,n=t.length>=Js;return Ra.useEffect(()=>{if(t.length===0)return;let a=r=>{let o=r.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||r.key==="Escape"&&s([])};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[t.length,s]),(0,je.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((a,r)=>(0,je.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,je.jsx)("span",{className:"af-text-foreground",children:Bc(a)}),(0,je.jsx)("button",{type:"button","aria-label":`Remove filter ${Bc(a)}`,onClick:()=>s(t.filter((o,c)=>c!==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,je.jsx)(pf,{...e,disabled:n}),t.length>0?(0,je.jsx)("button",{type:"button",onClick:()=>s([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function pf({filters:e,onChange:t,suggestions:s,resetKey:n,disabled:a,expandValues:r}){let[o,c]=Ra.useState(!1),d=Ra.useRef(null),[l,i]=Ra.useState(null);Ra.useEffect(()=>{i(d.current?.closest(".aifeatures-admin")??null)},[]);let[m,v]=Ra.useState(null),[g,u]=Ra.useState("is"),[f,p]=Ra.useState(""),[b,w]=Ra.useState([]);Ra.useEffect(()=>{o||(v(null),u("is"),p(""),w([]))},[o]);let P=Ra.useRef(n);P.current!==n&&(P.current=n,o&&c(!1),m!==null&&v(null),b.length>0&&w([]),f!==""&&p(""),g!=="is"&&u("is"));let T=E=>{let D=mf(E);v(D.dimension),w(D.picked),p(D.search),u(D.operator)},C=(m?s[m]??[]:[]).filter(E=>E.toLowerCase().includes(f.trim().toLowerCase())),k=m===null||b.length===0?null:ko(e,{dimension:m,operator:g,values:r?r(m,b):b}),I=k!==null&&k!==e,N=()=>{let E=k;!E||E===e||(t(E),c(!1))};return(0,je.jsxs)(Qs.Root,{open:o,onOpenChange:c,children:[(0,je.jsx)(Qs.Trigger,{asChild:!0,children:(0,je.jsx)("button",{ref:d,type:"button",disabled:!1,title:a?`At most ${Js} 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,je.jsx)(Qs.Portal,{container:l,children:(0,je.jsx)(Qs.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:m===null?(0,je.jsxs)("div",{children:[(0,je.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,je.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:df.filter(E=>s[E]!==void 0).map(E=>{let D=s[E]?.length??0,_=!e.some(Y=>Y.dimension===E)&&e.length>=Js;return(0,je.jsxs)("button",{type:"button",onClick:()=>T(E),disabled:D===0||_,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,je.jsx)("span",{children:Or[E]}),(0,je.jsx)("span",{className:"af-text-muted-foreground",children:D===0?"no data":_?"no room":D})]},E)})})]}):(0,je.jsxs)("div",{children:[(0,je.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,je.jsx)("button",{type:"button",onClick:()=>T(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,je.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Or[m]}),(0,je.jsxs)("select",{"aria-label":"Operator",value:g,onChange:E=>u(E.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,je.jsx)("option",{value:"is",children:"is"}),(0,je.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,je.jsx)("input",{type:"text",value:f,onChange:E=>p(E.target.value),placeholder:"Search\u2026","aria-label":`Search ${Or[m]}`,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,je.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:C.length===0?(0,je.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",f,"\u201D."]}):C.map(E=>(0,je.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,je.jsx)("input",{type:"checkbox",checked:b.includes(E),disabled:!b.includes(E)&&b.length>=Xs,onChange:D=>w(_=>D.target.checked?[..._,E]:_.filter(Y=>Y!==E))}),(0,je.jsx)("span",{className:"af-break-all",children:Ar(E)})]},E))}),(0,je.jsx)("button",{type:"button",onClick:N,disabled:!I,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:b.length<=1?"Apply filter":b.length>=Xs?`Apply filter (${b.length} values \u2014 the maximum)`:`Apply filter (${b.length} values)`})]})})})]})}var Nt=require("react/jsx-runtime"),gf=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:da,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:da,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:da,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:$n,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Dr,chart:"visit_duration_seconds"}];function vf({current:e,previous:t,downIsGood:s}){if(t===0)return null;let n=(e-t)/t;if(Math.abs(n)<5e-4)return null;let a=n>0,r=s?!a:a,o=`${a?"+":""}${(n*100).toFixed(1)}%`;return(0,Nt.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 $c({summary:e,selected:t,onSelect:s}){return(0,Nt.jsx)("div",{className:"af-@container",children:(0,Nt.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:gf.map(n=>{let a=n.chart===t,r=s!==void 0,o=(0,Nt.jsxs)(Nt.Fragment,{children:[(0,Nt.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:n.label}),(0,Nt.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,Nt.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:n.format(n.get(e.current))}),e.previous?(0,Nt.jsx)(vf,{current:n.get(e.current),previous:n.get(e.previous),downIsGood:n.downIsGood}):null]})]});return r?(0,Nt.jsx)("button",{type:"button","aria-pressed":a,onClick:()=>s(n.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},n.key):(0,Nt.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},n.key)})})})}function To({currentVisitors:e,asOf:t,isStale:s,isUnreachable:n,isInitialLoad:a=!1,scopeIsSiteWide:r=!1}){if(a&&!n)return(0,Nt.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,Nt.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,Nt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(n||e===null)return(0,Nt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?Dc(t):"freshness unknown",c=r?" across the whole site, not the current filter,":"",d=s?`${e} current visitors${c} ${o} (not updating)`:`${e} current visitors${c} ${o}`;return(0,Nt.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:d,children:[(0,Nt.jsx)("span",{"aria-hidden":"true",className:s?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),(0,Nt.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,Nt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),(0,Nt.jsx)("span",{className:"af-sr-only",children:d})]})}var Vc=ie(require("react"),1),Hc=require("lucide-react");var Ye=require("react/jsx-runtime");function Ii(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Di({rows:e,denominator:t,windowPrecedesCollection:s=!1,coverageUnknown:n=!1,emptyCopy:a="No conversions in this period",maxRows:r=9,primaryConversion:o}){let[c,d]=Vc.useState(!1),l=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||Ii(p,o)),i=s?(0,Ye.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."}):n?(0,Ye.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,Ye.jsxs)(Ye.Fragment,{children:[(0,Ye.jsx)(Ei,{what:a}),i]});let m=l.slice(0,r),v=o?l.find(p=>Ii(p,o)):void 0,g=v&&!m.includes(v)?l.filter(p=>m.includes(p)||p===v).slice(0,Math.max(0,r-1)).concat(v):m,u=c?e:g,f=Math.max(0,e.length-g.length);return(0,Ye.jsxs)(Ye.Fragment,{children:[(0,Ye.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Ye.jsx)("thead",{children:(0,Ye.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,Ye.jsx)("tbody",{children:u.map((p,b)=>(0,Ye.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":Ii(p,o)?"true":void 0,children:[(0,Ye.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Ii(p,o)?(0,Ye.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,Ye.jsx)(Hc.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,Ye.jsx)("span",{className:"af-font-medium af-text-foreground",children:p.goal}),(0,Ye.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):p.goal}),(0,Ye.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:da(p.visitors)}),(0,Ye.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:da(p.events)}),(0,Ye.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,Ye.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):$n(p.conversion_rate)})]},`${p.goal}-${b}`))})]}),f>0?(0,Ye.jsx)("button",{type:"button",onClick:()=>d(p=>!p),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:c?"Show fewer":`Show all ${e.length} goals`}):null,(0,Ye.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",da(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),i]})}var _a=require("recharts");var Pt=require("react/jsx-runtime"),Ai={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Io={visitors:da,visits:da,pageviews:da,views_per_visit:e=>e.toFixed(2),bounce_rate:$n,visit_duration_seconds:Dr},bf=31,yf=new Set(["visitors","visits","pageviews"]),hf={...Io,bounce_rate:Ec,visit_duration_seconds:Tc},Eo=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],xf=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Sf=[.01,.02,.05,.1,.2,.25,.5,1],wf=[.25,.5,1,2,5,10,25,50],Nf={visitors:Eo,visits:Eo,pageviews:Eo,views_per_visit:wf,bounce_rate:Sf,visit_duration_seconds:xf};function Rf({active:e,payload:t,label:s,metric:n}){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:Ai[n]}),(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:Lc(String(s))}),(0,Pt.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Io[n](Number(a[n]??0))})]})]})}function Li({rows:e,window:t,metric:s,timeZone:n="UTC",height:a=260}){let r=Ac(t,e,n),o=Io[s],c=hf[s],d=Ic(r.reduce((i,m)=>Math.max(i,Number(m[s]??0)),0),Nf[s]),l=`${Ai[s]} by day: ${r.map(i=>`${Po(i.date)}: ${o(Number(i[s]??0))}`).join("; ")}.`;return(0,Pt.jsxs)("figure",{"aria-label":`${Ai[s]} over time`,className:"af-m-0",children:[(0,Pt.jsx)(_a.ResponsiveContainer,{width:"100%",height:a,children:(0,Pt.jsxs)(_a.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)(_a.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,Pt.jsx)(_a.XAxis,{dataKey:"date",tickFormatter:Po,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,Pt.jsx)(_a.YAxis,{allowDecimals:!yf.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...d?{ticks:d,domain:[0,d[d.length-1]]}:{},tickFormatter:i=>c(i),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,Pt.jsx)(_a.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,Pt.jsx)(Rf,{metric:s})}),(0,Pt.jsx)(_a.Area,{type:"linear",dataKey:s,name:Ai[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=bf?{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 pe=require("react/jsx-runtime"),_f="2026-08-13",Pf=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Cf=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function zc({filters:e,onFiltersChange:t,refreshKey:s,onBackToWebsite:n,primaryConversion:a,className:r,published:o,lastPublishedAt:c}){let[d,l]=Rt.useState(30),[i,m]=Rt.useState(()=>$i()),v=e!==void 0&&t!==void 0,[g,u]=Rt.useState(e??[]),{api:f}=W(),[p,b]=Rt.useState(f);p!==f&&(b(f),!v&&g.length>0&&u([]));let w=v?e:g,P=Rt.useCallback(F=>{t&&t(F),v||u(F)},[t,v]),T=Rt.useCallback((F,Re,te)=>{let we=Array.isArray(Re)?Re:[Re];if(we.length===0)return null;let He=ko(w,{dimension:F,operator:"is",values:we});if(te&&(!te.value||(He=Fc(He,{dimension:te.dimension,operator:"is",values:[te.value]}),!He.find(Ct=>Ct.dimension===te.dimension&&Ct.operator!=="is_not")?.values.includes(te.value))))return null;let bt=He.find(Ze=>Ze.dimension===F&&Ze.operator!=="is_not");return we.every(Ze=>bt?.values.includes(Ze))?JSON.stringify(He)===JSON.stringify(w)?null:He:null},[w]),y=Rt.useCallback((F,Re,te)=>T(F,Re,te)!==null,[T]),C=Rt.useCallback((F,Re,te)=>{let we=T(F,Re,te);we&&P(we)},[T,P]),[k,I]=Rt.useState("visitors"),N=xn(d,{refreshKey:s,breakdowns:Cf,filters:w}),E=N.status.data,D=N.reportedZone??E?.timezone,_=D??i??Hn()??"UTC",{notCollecting:Y,awaitingFirstVisit:Q,firstVisitTooRecent:z,holdingForFirstData:le}=ki(E,{published:o}),fe=o===!1,he=Er({collecting:Q||Y?!1:E?.collecting,statusFailed:N.status.error!=null,identity:E?.analytics_id}),M=Rt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),ee=Rt.useMemo(()=>{let F=N.breakdowns.sources?.data,Re={};if(!F||F.status!=="ok")return Re;for(let te of F.data){let we=te.source,He=te.sources;typeof we=="string"&&Array.isArray(He)&&He.length>0&&(Re[we]=He)}return Re},[N.breakdowns.sources?.data]),U=Rt.useMemo(()=>{let F=(we,He)=>{let bt=N.breakdowns[we]?.data;return!bt||bt.status!=="ok"?[]:[...new Set(bt.data.map(Ze=>Ze[He]).filter(Ze=>typeof Ze=="string"&&Ze!==""))]};return{channel:N.channels.data?.status==="ok"?[...new Set(N.channels.data.data.map(we=>we.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]),[ve,me]=Rt.useState({}),Qe=JSON.stringify(U),[ke,Ge]=Rt.useState(new Map),Je=JSON.stringify(ee);Rt.useEffect(()=>{let{suggestions:F,folds:Re}=Uc(M.current,{api:f,period:d},JSON.parse(Qe),JSON.parse(Je));me(F),Ge(Re)},[Qe,Je,f,d]);let Fe=Rt.useCallback((F,Re)=>F!=="source"?Re:[...new Set(Re.flatMap(te=>{let we=[...ke.get(te)??[],...ee[te]??[]];return we.length>0?we:[te]}))],[ke,ee]),_t=Rt.useMemo(()=>{let F=N.conversions.error;return F instanceof Dt&&F.details?.code==="goals_exceed_report_budget"?F.message:null},[N.conversions.error]),L=Rt.useMemo(()=>{let F=[N.summary,N.timeseries,N.channels,...Object.values(N.breakdowns)];for(let Re of F){let te=Re?.error;if(te instanceof Dt&&te.details?.code==="filter_unsupported")return te.message}return null},[N.summary,N.timeseries,N.channels,N.breakdowns]),$=(F,Re,te,we,He,bt,Ze,Ct,xe)=>()=>{let Me=N.breakdowns[F];return(0,pe.jsx)(Ms,{sourced:Me?.data??null,error:Me?.error,isLoading:Me?.isLoading,what:Re,collecting:E?.collecting,onRetry:N.refetch,children:yt=>{let Pa=Kt=>Ct?Fe(Ct,[Kt]):Kt;return(0,pe.jsx)(Co,{rows:yt,dimension:te,metric:we,metricLabel:He,secondary:bt,emptyCopy:w.length>0?"No data for this filter":Ze,canFilter:Ct?(Kt,fa)=>y(Ct,Pa(Kt),xe?{dimension:xe,value:fa}:void 0):()=>!1,onFilter:Ct?(Kt,fa)=>C(Ct,Pa(Kt),xe?{dimension:xe,value:fa}:void 0):void 0})}})};if(Ti({status:E,holdingForFirstData:le,refetchStatus:N.refetchStatus,refetch:N.refetch}),Y){let F=!!c&&String(c).slice(0,10)<_f;return(0,pe.jsx)(St,{title:"Analytics",onBackToWebsite:n,className:r,children:(0,pe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,pe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:fe?"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 Q?(0,pe.jsx)(St,{title:"Analytics",onBackToWebsite:n,className:r,children:(0,pe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,pe.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."})]})}):z?(0,pe.jsxs)(St,{title:"Analytics",onBackToWebsite:n,className:r,children:[(0,pe.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,pe.jsx)(_o,{value:_,chosen:i,onChange:F=>{Vi(F),m(F)}})}),(0,pe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,pe.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,pe.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,pe.jsx)(To,{currentVisitors:he.currentVisitors,asOf:he.asOf,isStale:he.isStale,isUnreachable:he.isUnreachable||he.error!==null,isInitialLoad:he.isInitialLoad})})]})]}):(0,pe.jsx)(St,{title:"Analytics",onBackToWebsite:n,className:r,children:(0,pe.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,pe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,pe.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Pf.map(F=>(0,pe.jsx)("button",{type:"button","aria-pressed":F.value===d,onClick:()=>l(F.value),className:F.value===d?"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,pe.jsx)(_o,{value:_,chosen:i,onChange:F=>{Vi(F),m(F)}}),(0,pe.jsx)(To,{currentVisitors:he.currentVisitors,asOf:he.asOf,isStale:he.isStale,isUnreachable:he.isUnreachable||he.error!==null,isInitialLoad:he.isInitialLoad,scopeIsSiteWide:w.length>0})]}),(0,pe.jsx)(Mc,{filters:w,onChange:P,suggestions:ve,expandValues:Fe,resetKey:f}),L?(0,pe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,pe.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,pe.jsx)("button",{type:"button",onClick:()=>P([]),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,pe.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,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)(Ms,{sourced:N.summary.data,error:N.summary.error,isLoading:N.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:N.refetch,children:F=>(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)($c,{summary:F,selected:k,onSelect:I}),F.previous_unavailable?(0,pe.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,pe.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,pe.jsx)(Ms,{sourced:N.timeseries.data,error:N.timeseries.error,isLoading:N.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:N.refetch,children:F=>{let Re=N.timeseries.data?.status==="ok"?N.timeseries.data.window:{from:"",to:""};return(0,pe.jsx)(Li,{rows:F,window:Re,metric:k,timeZone:D??"UTC"})}})}),(0,pe.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,pe.jsx)(Lr,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,pe.jsx)(Ms,{sourced:N.channels.data,error:N.channels.error,isLoading:N.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:N.refetch,children:F=>(0,pe.jsx)(Co,{rows:F,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:w.length>0?"No data for this filter":"No data for this period",canFilter:Re=>y("channel",Re),onFilter:Re=>C("channel",Re)})})},{id:"sources",label:"Sources",render:$("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:$("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,pe.jsx)(Lr,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:$("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:$("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:$("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,pe.jsx)(Lr,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:$("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:$("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:$("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,pe.jsx)(Lr,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:$("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:$("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:$("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,pe.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,pe.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,pe.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,pe.jsxs)("div",{className:"af-px-3 af-py-2",children:[w.length>0?(0,pe.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",w.length===1?"filter":"filters"," above."]}):null,_t!==null?(0,pe.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,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,pe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:_t})]}):(0,pe.jsx)(Ms,{sourced:N.conversions.data,error:N.conversions.error,isLoading:N.conversions.isLoading,what:"Conversions",collecting:E?.collecting,onRetry:N.refetch,children:F=>{let Re=N.conversions.data?.status==="ok"?N.conversions.data:null;return(0,pe.jsx)(pe.Fragment,{children:(0,pe.jsx)(Di,{rows:F,primaryConversion:a,denominator:Re?.denominator??0,windowPrecedesCollection:Re?.window_precedes_collection??!1,coverageUnknown:Re?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var Zc=ie(require("react"),1),jt=require("lucide-react");var as=ie(require("react"),1),$s=require("lucide-react");var Ce=require("react/jsx-runtime"),qc=90,Wc=100;function kf(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function jc(e){return!!e.label&&e.label!==e.target}function Tf(e,t,s){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:n,with_a_value:a}=t;return n===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<n?s?`These cover ${a.toLocaleString()} of ${n.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${a.toLocaleString()} of ${n.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function Br(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Gc({current:e,onChange:t,onClose:s}){let{api:n}=W(),[a,r]=as.useState(null),[o,c]=as.useState(!1),[d,l]=as.useState({at:"goals"}),[i,m]=as.useState(null),[v,g]=as.useState(null),[u,f]=as.useState(!1),[p,b]=as.useState(null),w=as.useRef(0);as.useEffect(()=>{let C=!0;return r(null),c(!1),l({at:"goals"}),m(null),g(null),f(!1),b(null),w.current+=1,n.getAnalyticsConversions(qc).then(k=>{if(C){if(k.status!=="ok"){c(!0);return}r(k.data)}}).catch(()=>{C&&c(!0)}),()=>{C=!1}},[n]);let P=C=>{l({at:"targets",row:C}),m(null),g(null),f(!1),b(null);let k=++w.current;n.getAnalyticsGoalTargets(C.goal,qc,Wc).then(I=>{if(k===w.current){if(I.status!=="ok"){g("failed");return}m(I.data),f(I.truncated===!0),b(I.coverage??null)}}).catch(I=>{if(k!==w.current)return;let N=I instanceof Dt?I.details?.code:void 0;g(N==="goal_has_no_targets"?"no-values":"failed")})},T=C=>{t(C),s()};if(o)return(0,Ce.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,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,Ce.jsx)($s.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Ce.jsx)("span",{children:"Loading your conversions\u2026"})]});if(d.at==="targets"){let C=d.row,k=new Map;for(let I of i??[])k.set(I.label,(k.get(I.label)??0)+1);return(0,Ce.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,Ce.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,Ce.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>l({at:"goals"}),children:[(0,Ce.jsx)($s.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,Ce.jsx)("span",{children:"All conversions"})]})}),(0,Ce.jsxs)("button",{type:"button","aria-current":e&&Br(C,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:C.goal,implicit:C.implicit}),children:[e&&Br(C,e)&&!e.target&&(0,Ce.jsx)($s.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ce.jsxs)("span",{children:["Any ",C.goal.toLowerCase()]})]}),v==="no-values"&&(0,Ce.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),v==="failed"&&(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,Ce.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>P(C),children:"Try again"})]}),!i&&v===null&&(0,Ce.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,Ce.jsx)($s.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Ce.jsx)("span",{children:"Loading\u2026"})]}),i&&(0,Ce.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Tf(i.length,p,u)}),u&&(0,Ce.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Wc,". If what you want isn\u2019t here, pick the conversion itself instead."]}),i?.some(jc)&&(0,Ce.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(I=>{let N=!!(e&&Br(C,e)&&e.target===I.target),E=k.get(I.label)>1;return jc(I)?(0,Ce.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,Ce.jsxs)("span",{className:"af-min-w-0",children:[(0,Ce.jsx)("span",{className:"af-block af-truncate",children:I.label}),E&&(0,Ce.jsx)("span",{className:"af-block af-truncate af-text-xs",children:I.target})]}),(0,Ce.jsx)("span",{className:"af-shrink-0 af-text-xs",children:I.visitors.toLocaleString()})]},I.target):(0,Ce.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:C.goal,implicit:C.implicit,target:I.target,...I.label&&I.label!==I.target?{label:I.label}:{}}),children:[(0,Ce.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[N&&(0,Ce.jsx)($s.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ce.jsxs)("span",{className:"af-min-w-0",children:[(0,Ce.jsx)("span",{className:"af-block af-truncate",children:I.label}),E&&(0,Ce.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:I.target})]})]}),(0,Ce.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:I.visitors.toLocaleString()})]},I.target)})]})}let y=e?.goal&&!a.some(C=>Br(C,e));return(0,Ce.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[y&&(0,Ce.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,Ce.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(C=>{let k=e?Br(C,e):!1;return(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,Ce.jsxs)("button",{type:"button","aria-current":k?"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:C.goal,implicit:C.implicit}),children:[(0,Ce.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[k&&(0,Ce.jsx)($s.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ce.jsx)("span",{className:"af-truncate",children:C.goal})]}),(0,Ce.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:C.visitors.toLocaleString()})]}),kf(C)&&(0,Ce.jsx)(x,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${C.goal}`,onClick:()=>P(C),children:"Narrow"})]},C.goal)}),e?.goal&&(0,Ce.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 za=require("react/jsx-runtime");function Ef(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let s of t)try{let{hostname:n}=new URL(s);if(n)return n.toLowerCase().replace(/^www\./,"")}catch{}return null}function If(e){if(Do(e,"whatsapp"))return!0;let t=Ef(e);return t===null?!1:["wa.me","whatsapp.com"].some(s=>t===s||t.endsWith(`.${s}`))}function Do(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var Kc=[{goal:"Contact",target:e=>Do(e,"tel"),icon:jt.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Do(e,"mailto"),icon:jt.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:jt.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>If(e),icon:jt.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:jt.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:jt.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:jt.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:jt.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:jt.Download,line:"This site is set up to get your file downloaded."}];function Yc(e){let{goal:t,target:s}=e;return e.implicit!==!0?null:(s?Kc.find(a=>a.goal===t&&a.target?.(s)):void 0)??Kc.find(a=>a.goal===t&&!a.target)??null}function Df(e){return Yc(e)?.icon??jt.Target}function Jc({primaryConversion:e,onChange:t}){let[s,n]=Zc.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?Yc(e):null,o=e?.label?.trim(),c=e?Df(e):jt.Target,d=e?.goal?o?`Your main conversion is ${o}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",l=(0,za.jsxs)(za.Fragment,{children:[(0,za.jsx)(c,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,za.jsx)("span",{children:d})]});return t?(0,za.jsxs)(Jr,{open:s,onOpenChange:n,children:[(0,za.jsx)(Xr,{asChild:!0,children:(0,za.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,za.jsx)(cr,{align:"start",className:"af-w-80 af-p-1",children:s&&(0,za.jsx)(Gc,{current:e,onChange:t,onClose:()=>n(!1)})})]}):(0,za.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:l})}var ra=require("react/jsx-runtime");function Xc({refreshKey:e,onViewAll:t,primaryConversion:s}){let n=xn(7,{refreshKey:e,breakdowns:[]}),a=n.status.data??void 0,{nothingToReport:r,notCollecting:o,holdingForFirstData:c}=ki(a);return Ti({status:a,holdingForFirstData:c,refetchStatus:n.refetchStatus,refetch:n.refetch}),(0,ra.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ra.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,ra.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,ra.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?(0,ra.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,ra.jsxs)(ra.Fragment,{children:[(0,ra.jsx)(Ms,{sourced:n.timeseries.data,error:n.timeseries.error,isLoading:n.timeseries.isLoading,what:"The visitors chart",collecting:a?.collecting,onRetry:n.refetch,children:d=>{let l=n.timeseries.data?.status==="ok"?n.timeseries.data:null;return(0,ra.jsx)(Li,{rows:d,window:l?.window??{from:"",to:""},metric:"visitors",timeZone:l?.timezone,height:140})}}),(0,ra.jsxs)("div",{className:"af-mt-3",children:[(0,ra.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,ra.jsx)(Ms,{sourced:n.conversions.data,error:n.conversions.error,isLoading:n.conversions.isLoading,what:"Conversions",collecting:a?.collecting,onRetry:n.refetch,children:d=>{let l=n.conversions.data?.status==="ok"?n.conversions.data:null;return(0,ra.jsx)(Di,{rows:d,primaryConversion:s,denominator:l?.denominator??0,windowPrecedesCollection:l?.window_precedes_collection??!1,coverageUnknown:l?.first_seen_unavailable??!1})}})]})]})]})}var Gt=require("react/jsx-runtime"),Ao=5;function Lo({title:e,viewAllLabel:t,onViewAll:s}){return(0,Gt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Gt.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),s&&(0,Gt.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:s,children:t})]})}function Qc({refreshKey:e,onBackToWebsite:t,primaryConversion:s,onChangePrimaryConversion:n,onOpenSurface:a,needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:c}){let d=pn({refreshKey:e}),l=(d.summary?.products.count??0)>0||(d.summary?.commerce?.storefront_orders??!1),i=l||(d.summary?.commerce?.invoicing??!1);return(0,Gt.jsx)(St,{title:"Dashboard",onBackToWebsite:t,children:(0,Gt.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,Gt.jsx)(Jc,{primaryConversion:s,onChange:n}),(0,Gt.jsx)(Xc,{refreshKey:e,onViewAll:a&&(()=>a("analytics")),primaryConversion:s}),(0,Gt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Gt.jsx)(Lo,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:a&&(()=>a("leads"))}),(0,Gt.jsx)(yr,{refreshKey:e,maxRows:Ao,onViewAll:a&&(()=>a("leads"))})]}),l&&(0,Gt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Gt.jsx)(Lo,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:a&&(()=>a("orders"))}),(0,Gt.jsx)(Ds,{refreshKey:e,maxRows:Ao,onViewAll:a&&(()=>a("orders"))})]}),i&&(0,Gt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Gt.jsx)(Lo,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:a&&(()=>a("invoices"))}),(0,Gt.jsx)(Ls,{refreshKey:e,maxRows:Ao,onViewAll:a&&(()=>a("invoices")),needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:c})]})]})})}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});
|