@aifeatures/admin-react 0.28.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use client";
2
- import*as fs from"react";var Oo="aifeatures:analytics:timezone",Lo;function Rr(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function mc(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function us(){return Bo()??Rr()}function Bo(){if(Lo!==void 0)return Lo;try{let e=window.localStorage.getItem(Oo);return mc(e)?e:null}catch{return null}}function Fo(e){if(!(e!==null&&!mc(e))){Lo=e;try{e===null?window.localStorage.removeItem(Oo):window.localStorage.setItem(Oo,e)}catch{}}}function oi(e,t){let a=new URLSearchParams({period:String(e)}),s=us();return s&&a.set("timezone",s),t&&t.length>0&&a.set("filters",JSON.stringify(t)),a.toString()}var aa=class extends Error{constructor(a,s,n){super(a);this.status=s;this.details=n;this.name="AifeaturesApiError"}};function li(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 _r(e,t){let a=t.toString();return a?`${e}?${a}`:e}function pc(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 gc(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 Mo(e,t="https://aifeatures.dev"){async function a(n,r={}){let i=`${t}${n}`,l=await fetch(i,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!l.ok){let u;try{u=await l.json()}catch{}throw new aa(li(u?.error,l.status),l.status,u)}if(l.status!==204)return l.json()}async function s(n){let r=await fetch(`${t}${n}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let i;try{i=await r.json()}catch{}throw new aa(li(i?.error,r.status),r.status,i)}return r.blob()}return{async getForms(){return(await a("/api/v1/forms")).forms},async getForm(n){return a(`/api/v1/forms/${n}`)},async createForm(n){return a("/api/v1/forms",{method:"POST",body:JSON.stringify(n)})},async updateForm(n,r){return a(`/api/v1/forms/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(n){await a(`/api/v1/forms/${n}`,{method:"DELETE"})},async getSubmissions(n,r={}){let i=new URLSearchParams;r.limit!==void 0&&i.set("limit",String(r.limit)),r.offset!==void 0&&i.set("offset",String(r.offset));let l=i.toString(),u=`/api/v1/forms/${n}/submissions${l?`?${l}`:""}`;return a(u)},async getSubmission(n){return a(`/api/v1/submissions/${n}`)},async exportSubmissionsCsv(n,r={}){let i=new URLSearchParams;return r.includeSpam&&i.set("include_spam","true"),s(_r(`/api/v1/forms/${encodeURIComponent(n)}/submissions/export`,i))},async deleteSubmission(n){await a(`/api/v1/submissions/${n}`,{method:"DELETE"})},async downloadAttachment(n,r){let i=typeof r=="string"?{name:r}:r,l=i.name,u=i.id??i.name,c=`${t}/api/v1/submissions/${n}/attachments/${encodeURIComponent(u)}`,o=await fetch(c,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let m;try{m=await o.json()}catch{}throw new aa(li(m?.error,o.status),o.status,m)}let f=await o.blob(),b=URL.createObjectURL(f),g=document.createElement("a");g.href=b,g.download=l,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(b)},async getSite(n){return a(`/api/v1/sites/${encodeURIComponent(n)}`)},async updateSite(n,r){return a(`/api/v1/sites/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return a("/api/v1/payments/status")},getPromos(n){let r=new URLSearchParams({limit:"10"});return n&&r.set("cursor",n),a(`/api/v1/promos?${r}`)},getPromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}`)},createPromo(n){return a("/api/v1/promos",{method:"POST",body:JSON.stringify(n)})},disablePromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}/disable`,{method:"POST"})},replacePromo(n,r){return a(`/api/v1/promos/${encodeURIComponent(n)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(n={}){let r=new URLSearchParams;n.include&&r.set("include",n.include);let i=r.toString();return(await a(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(n){return a(`/api/v1/products/${n}`)},async createProduct(n){return a("/api/v1/products",{method:"POST",body:JSON.stringify(n)})},async updateProduct(n,r){return a(`/api/v1/products/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(n){await a(`/api/v1/products/${n}`,{method:"DELETE"})},async attachProductFile(n,r){let i=new FormData;i.append("file",r);let l=await fetch(`${t}/api/v1/products/${n}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!l.ok){let u;try{u=await l.json()}catch{}throw new aa(li(u?.error,l.status),l.status,u)}return l.json()},async attachProductFileFromUrl(n,r){return a(`/api/v1/products/${n}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(n,r){return a(`/api/v1/products/${n}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(n,r){return a(`/api/v1/options/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(n){await a(`/api/v1/options/${n}`,{method:"DELETE"})},async createVariant(n,r){return a(`/api/v1/products/${n}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(n,r){return a(`/api/v1/variants/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(n){await a(`/api/v1/variants/${n}`,{method:"DELETE"})},async setVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(n={}){let r=new URLSearchParams;n.email?r.set("email",n.email):n.q&&r.set("q",n.q),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(n){return a(`/api/v1/customers/${n}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(n={}){let r=pc(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/orders${i?`?${i}`:""}`)},async exportOrdersCsv(n={}){return s(_r("/api/v1/orders/export",pc(n)))},async getOrder(n){return a(`/api/v1/orders/${n}`)},async getInvoices(n={}){let r=new URLSearchParams;n.labels?.length&&r.set("label",n.labels.join(",")),n.customerEmail&&r.set("customer_email",n.customerEmail),n.customerId&&r.set("customer_id",n.customerId),n.q&&r.set("q",n.q),n.from&&r.set("from",n.from),n.to&&r.set("to",n.to),n.includeAggregates&&r.set("include","aggregates"),n.retainerId&&r.set("retainer_id",n.retainerId),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(n){return a(`/api/v1/invoices/${n}`)},async getInvoicePreview(n){return a(`/api/v1/invoices/${n}/preview`)},async getInvoiceSettings(){return a("/api/v1/invoice-settings")},async getRetainers(n={}){let r=gc(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/retainers${i?`?${i}`:""}`)},async exportRetainersCsv(n={}){return s(_r("/api/v1/retainers/export",gc(n)))},async getRetainer(n){return a(`/api/v1/retainers/${n}`)},async resendOrderReceipt(n){await a(`/api/v1/orders/${n}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(n){return a(`/api/v1/orders/${n}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(n,r){return a(`/api/v1/orders/${n}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(n={}){let r=new URLSearchParams;n.status&&r.set("status",n.status),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/subscriptions${i?`?${i}`:""}`)},async exportSubscriptionsCsv(n={}){let r=new URLSearchParams;return n.status&&r.set("status",n.status),s(_r("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let n=new URLSearchParams,r=us();r&&n.set("timezone",r);let i=n.toString();return a(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(n,r){return a(`/api/v1/analytics/summary?${oi(n,r)}`)},async getAnalyticsTimeseries(n,r){return a(`/api/v1/analytics/timeseries?${oi(n,r)}`)},async getAnalyticsRealtime(){return a("/api/v1/analytics/realtime")},async getAnalyticsChannels(n,r){return a(`/api/v1/analytics/channels?${oi(n,r)}`)},async getAnalyticsConversions(n){return a((()=>{let r=new URLSearchParams({period:String(n)}),i=us();return i&&r.set("timezone",i),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(n,r,i){let l=new URLSearchParams({goal:n,period:String(r)}),u=us();return u&&l.set("timezone",u),i!==void 0&&l.set("limit",String(i)),a(`/api/v1/analytics/conversions/targets?${l.toString()}`)},async getAnalyticsBreakdown(n,r,i){let l=n.split("/").map(encodeURIComponent).join("/");return a(`/api/v1/analytics/${l}?${oi(r,i)}`)},async getBusinessSummary(n){let r=new URLSearchParams;r.set("tz_offset_minutes",String(n.tzOffsetMinutes));let i=us();return i&&r.set("timezone",i),a(`/api/v1/summary?${r.toString()}`)},async getPeople(n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/people${i?`?${i}`:""}`)},async exportPeopleCsv(n={}){let r=new URLSearchParams;return n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),s(_r("/api/v1/people/export",r))},async getPerson(n){return a(`/api/v1/people/${encodeURIComponent(n)}`)},async getEventDestinations(){return(await a("/api/v1/event-destinations")).destinations},async createEventDestination(n){return a("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(n)})},async updateEventDestination(n,r){return a(`/api/v1/event-destinations/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(n){await a(`/api/v1/event-destinations/${n}`,{method:"DELETE"})},async rotateEventDestinationSecret(n){return a(`/api/v1/event-destinations/${n}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(n){return(await a(`/api/v1/event-destinations/${n}/secret`)).secret},async getEventDeliveries(n,r){let i=r===void 0?"":`?limit=${r}`;return(await a(`/api/v1/event-destinations/${n}/deliveries${i}`)).deliveries},async retryEventDelivery(n,r){return a(`/api/v1/event-destinations/${n}/deliveries/${r}/retry`,{method:"POST"})},async getMarketingSettings(n){return a(`${Ba(n)}/marketing`)},async getMarketingContacts(n,r={}){let i=new URLSearchParams;r.q&&i.set("q",r.q),r.limit&&i.set("limit",String(r.limit)),r.offset&&i.set("offset",String(r.offset));let l=i.toString();return a(`${Ba(n)}/contacts${l?`?${l}`:""}`)},async getMarketingContactStats(n){return a(`${Ba(n)}/contacts/stats`)},async getMarketingTags(n){return(await a(`${Ba(n)}/contact-tags`)).tags},async getEmailDrafts(n,r){let i=r?`?kind=${r}`:"";return(await a(`${Ba(n)}/marketing/drafts${i}`)).drafts},async getEmailDraft(n,r){return a(`${Ba(n)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(n,r,i){let l=i?.editable?"?mode=editable":"";return a(`${Ba(n)}/marketing/drafts/${encodeURIComponent(r)}/preview${l}`)},async getEmailTemplates(n){return(await a(`${Ba(n)}/marketing/templates`)).templates},async previewEmailTemplate(n,r,i){let l=i?`?draft_id=${encodeURIComponent(i)}`:"";return a(`${Ba(n)}/marketing/templates/${encodeURIComponent(r)}/preview${l}`)},async getBroadcasts(n){return(await a(`${Ba(n)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(n,r){return a(`${Ba(n)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getAutomations(n){return a(`${Ba(n)}/marketing/automations`)},async getAutomation(n,r){return a(`${Ba(n)}/marketing/automations/${encodeURIComponent(r)}`)},async getAutomationStats(n,r){return(await a(`${Ba(n)}/marketing/automations/${encodeURIComponent(r)}/stats`)).steps}}}function Ba(e){return`/api/v1/sites/${encodeURIComponent(e)}`}import{jsx as kr,jsxs as kf}from"react/jsx-runtime";var vc=fs.createContext(null);function Rf(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 _f({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:n}){let r=fs.useMemo(()=>Rf(e),[e]),i=fs.useMemo(()=>Mo(e,t),[e,t]),l=fs.useMemo(()=>({siteToken:e,apiUrl:t,api:i}),[e,t,i]);return r?kr("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:kf("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[kr("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),kr("p",{className:"af-text-sm af-text-destructive",children:r})]})}):kr(vc.Provider,{value:l,children:kr("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:n})})}function H(){let e=fs.useContext(vc);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as rs from"react";import{ArrowLeft as Dm,Settings as Om,Inbox as Lm}from"lucide-react";import*as ci from"react";import*as _n from"@radix-ui/react-tabs";import{clsx as Pf}from"clsx";import{extendTailwindMerge as Cf}from"tailwind-merge";var Tf=Cf({prefix:"af-"});function W(...e){return Tf(Pf(e))}import{jsx as $o}from"react/jsx-runtime";var di=_n.Root,Pr=ci.forwardRef(({className:e,...t},a)=>$o(_n.List,{ref:a,className:W("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}));Pr.displayName=_n.List.displayName;var kn=ci.forwardRef(({className:e,...t},a)=>$o(_n.Trigger,{ref:a,className:W("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}));kn.displayName=_n.Trigger.displayName;var Pn=ci.forwardRef(({className:e,...t},a)=>$o(_n.Content,{ref:a,className:W("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}));Pn.displayName=_n.Content.displayName;import*as bc from"react";import{Slot as Ef}from"@radix-ui/react-slot";import{cva as If}from"class-variance-authority";import{jsx as Df}from"react/jsx-runtime";var Af=If("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),y=bc.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...n},r)=>Df(s?Ef:"button",{className:W(Af({variant:t,size:a,className:e})),ref:r,...n}));y.displayName="Button";import{Inbox as hc,Settings as Bf}from"lucide-react";import*as ts from"react";import{jsx as es}from"react/jsx-runtime";var ct=ts.forwardRef(({className:e,...t},a)=>es("div",{className:"af-relative af-w-full af-overflow-auto",children:es("table",{ref:a,className:W("af-w-full af-caption-bottom af-text-sm",e),...t})}));ct.displayName="Table";var dt=ts.forwardRef(({className:e,...t},a)=>es("thead",{ref:a,className:W("[&_tr]:af-border-b",e),...t}));dt.displayName="TableHeader";var ut=ts.forwardRef(({className:e,...t},a)=>es("tbody",{ref:a,className:W("[&_tr:last-child]:af-border-0",e),...t}));ut.displayName="TableBody";var Of=ts.forwardRef(({className:e,...t},a)=>es("tfoot",{ref:a,className:W("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Of.displayName="TableFooter";var Ie=ts.forwardRef(({className:e,...t},a)=>es("tr",{ref:a,className:W("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Ie.displayName="TableRow";var K=ts.forwardRef(({className:e,...t},a)=>es("th",{ref:a,className:W("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}));K.displayName="TableHead";var Z=ts.forwardRef(({className:e,...t},a)=>es("td",{ref:a,className:W("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));Z.displayName="TableCell";var Lf=ts.forwardRef(({className:e,...t},a)=>es("caption",{ref:a,className:W("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Lf.displayName="TableCaption";import*as Cn from"react";function Js(){let{api:e}=H(),[t,a]=Cn.useState([]),[s,n]=Cn.useState(!0),[r,i]=Cn.useState(null),l=Cn.useCallback(async()=>{try{n(!0),i(null);let f=await e.getForms();a(f)}catch(f){i(f instanceof Error?f:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);Cn.useEffect(()=>{l()},[l]);let u=Cn.useCallback(async f=>{let b=await e.createForm(f);return a(g=>[...g,b]),b},[e]),c=Cn.useCallback(async(f,b)=>{let g=await e.updateForm(f,b);return a(m=>m.map(v=>v.id===f?g:v)),g},[e]),o=Cn.useCallback(async f=>{await e.deleteForm(f),a(b=>b.filter(g=>g.id!==f))},[e]);return{forms:t,isLoading:s,error:r,refetch:l,createForm:u,updateForm:c,deleteForm:o}}import{jsx as Fa,jsxs as as}from"react/jsx-runtime";function ui({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:n}=Js();return s?Fa("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Fa("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?Fa("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:as("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):a.length===0?as("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Fa(hc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),as("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",Fa("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):Fa("div",{className:t,children:as(ct,{children:[Fa(dt,{children:as(Ie,{children:[Fa(K,{children:"Name"}),Fa(K,{className:"af-text-right",children:"Actions"})]})}),Fa(ut,{children:a.map(r=>as(Ie,{children:[Fa(Z,{className:"af-font-medium",children:r.name}),Fa(Z,{className:"af-text-right",children:as("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[as(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[Fa(hc,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),as(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[Fa(Bf,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}import{AlertTriangle as Uf}from"lucide-react";import{cva as Ff}from"class-variance-authority";import{jsx as $f}from"react/jsx-runtime";var Mf=Ff("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 ee({className:e,variant:t,...a}){return $f("div",{className:W(Mf({variant:t}),e),...a})}import{jsx as Ts,jsxs as fi}from"react/jsx-runtime";var Vf={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 mi(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 Uo(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function Hf(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 Cr({deliveries:e,label:t="Email needs attention"}){return Uo(e)?fi("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:[Ts(Uf,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function $n({deliveries:e,problemsOnly:t=!1,className:a=""}){let s=(e??[]).filter(n=>!t||Uo([n]));return s.length?Ts("div",{className:`af-space-y-3 ${a}`,"aria-label":"Email delivery",children:s.map(n=>{let r=mi(n),i=Hf(n);return fi("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[fi("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Ts("span",{className:"af-font-medium",children:Vf[n.kind]??"Email notification"}),Ts(ee,{variant:r.variant,children:r.label})]}),fi("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&Uo([n])&&Ts("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&&Ts("p",{className:"af-mt-1",children:r.detail}),i&&Ts("p",{className:"af-mt-1",children:i})]},n.id)})}):null}import*as ps from"react";import{ArrowLeft as lm,ChevronLeft as cm,ChevronRight as dm,Eye as um,Inbox as fm,Paperclip as mm}from"lucide-react";import*as ms from"react";import*as ze from"@radix-ui/react-select";import{Check as zf,ChevronDown as yc,ChevronUp as jf}from"lucide-react";import{jsx as xa,jsxs as Vo}from"react/jsx-runtime";var un=ze.Root;var fn=ze.Value,Qa=ms.forwardRef(({className:e,children:t,...a},s)=>Vo(ze.Trigger,{ref:s,className:W("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...a,children:[t,xa(ze.Icon,{asChild:!0,children:xa(yc,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Qa.displayName=ze.Trigger.displayName;var xc=ms.forwardRef(({className:e,...t},a)=>xa(ze.ScrollUpButton,{ref:a,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:xa(jf,{className:"af-h-4 af-w-4"})}));xc.displayName=ze.ScrollUpButton.displayName;var wc=ms.forwardRef(({className:e,...t},a)=>xa(ze.ScrollDownButton,{ref:a,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:xa(yc,{className:"af-h-4 af-w-4"})}));wc.displayName=ze.ScrollDownButton.displayName;var en=ms.forwardRef(({className:e,children:t,position:a="popper",...s},n)=>xa(ze.Portal,{children:Vo(ze.Content,{ref:n,className:W("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:a,...s,children:[xa(xc,{}),xa(ze.Viewport,{className:W("af-p-1",a==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),xa(wc,{})]})}));en.displayName=ze.Content.displayName;var qf=ms.forwardRef(({className:e,...t},a)=>xa(ze.Label,{ref:a,className:W("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));qf.displayName=ze.Label.displayName;var St=ms.forwardRef(({className:e,children:t,...a},s)=>Vo(ze.Item,{ref:s,className:W("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...a,children:[xa("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:xa(ze.ItemIndicator,{children:xa(zf,{className:"af-h-4 af-w-4"})})}),xa(ze.ItemText,{children:t})]}));St.displayName=ze.Item.displayName;var Wf=ms.forwardRef(({className:e,...t},a)=>xa(ze.Separator,{ref:a,className:W("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));Wf.displayName=ze.Separator.displayName;import*as Ca from"react";function pi({formId:e,initialPageSize:t=25}){let{api:a}=H(),[s,n]=Ca.useState([]),[r,i]=Ca.useState(0),[l,u]=Ca.useState(!0),[c,o]=Ca.useState(null),[f,b]=Ca.useState(0),[g,m]=Ca.useState(t),v=Ca.useRef(0),d=Ca.useCallback(async()=>{if(!e)return;let k=++v.current;try{u(!0),o(null);let h={limit:g,offset:f*g},N=await a.getSubmissions(e,h);if(k!==v.current)return;if(N.submissions.length===0&&f>0){b(Math.max(0,Math.ceil(N.total/g)-1));return}n(N.submissions),i(N.total)}catch(h){if(k!==v.current)return;o(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{k===v.current&&u(!1)}},[a,e,f,g]);Ca.useEffect(()=>{d()},[d]);let p=Ca.useRef(d);p.current=d;let x=Ca.useCallback(async k=>{await a.deleteSubmission(k),p.current()},[a]),S=Math.ceil(r/g);return{submissions:s,total:r,isLoading:l,error:c,page:f,pageSize:g,hasNextPage:f<S-1,hasPreviousPage:f>0,setPage:b,setPageSize:k=>{m(k),b(0)},refetch:d,deleteSubmission:x}}import*as gi from"react";import{Trash2 as Zf}from"lucide-react";import*as Tr from"react";import*as na from"@radix-ui/react-dialog";import{X as Gf}from"lucide-react";import{jsx as ns,jsxs as Ho}from"react/jsx-runtime";var mn=na.Root;var Kf=na.Portal;var Sc=Tr.forwardRef(({className:e,...t},a)=>ns(na.Overlay,{ref:a,className:W("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Sc.displayName=na.Overlay.displayName;var tn=Tr.forwardRef(({className:e,children:t,...a},s)=>ns(Kf,{children:Ho("div",{className:"aifeatures-admin",children:[ns(Sc,{}),Ho(na.Content,{ref:s,className:W("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...a,children:[t,Ho(na.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:[ns(Gf,{className:"af-h-4 af-w-4"}),ns("span",{className:"af-sr-only",children:"Close"})]})]})]})}));tn.displayName=na.Content.displayName;var an=({className:e,...t})=>ns("div",{className:W("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});an.displayName="DialogHeader";var nn=({className:e,...t})=>ns("div",{className:W("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});nn.displayName="DialogFooter";var sn=Tr.forwardRef(({className:e,...t},a)=>ns(na.Title,{ref:a,className:W("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));sn.displayName=na.Title.displayName;var rn=Tr.forwardRef(({className:e,...t},a)=>ns(na.Description,{ref:a,className:W("af-text-sm af-text-muted-foreground",e),...t}));rn.displayName=na.Description.displayName;import{Fragment as Yf,jsx as Es,jsxs as Er}from"react/jsx-runtime";function Xs({onDelete:e,iconOnly:t}){let[a,s]=gi.useState(!1),[n,r]=gi.useState(!1),[i,l]=gi.useState(null);return Er(Yf,{children:[Er(y,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{l(null),s(!0)},children:[Es(Zf,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),Es(mn,{open:a,onOpenChange:c=>{!c&&!n&&s(!1)},children:Er(tn,{children:[Er(an,{children:[Es(sn,{children:"Delete this submission?"}),Es(rn,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),i&&Es("p",{className:"af-text-sm af-text-destructive",children:i}),Er(nn,{children:[Es(y,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),Es(y,{variant:"destructive",onClick:async()=>{r(!0),l(null);try{await e(),s(!1)}catch(c){l(c instanceof Error?c.message:"Failed to delete submission")}finally{r(!1)}},disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}import*as Rc from"react";import{ArrowLeft as Jf,Download as Xf,Globe as Qf,Clock as em,FileText as tm,Loader2 as am,Monitor as nm,Mail as sm}from"lucide-react";import{jsx as $t,jsxs as At}from"react/jsx-runtime";function Nc(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function rm(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function vi({submission:e,onBack:t,onDelete:a}){let{api:s}=H(),[n,r]=Rc.useState(null),i=c=>c.id??c.name,l=async c=>{r(i(c));try{await s.downloadAttachment(e.id,c)}catch(o){console.error("Download failed:",o)}finally{r(null)}},u=Object.entries(e.data).filter(([c])=>!c.startsWith("_"));return At("div",{children:[At("div",{className:"af-mb-6",children:[At(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[$t(Jf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),At("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[At("div",{children:[$t("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),At("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Nc(e.metadata.submitted_at)]})]}),a&&$t(Xs,{onDelete:a})]})]}),At("div",{className:"af-space-y-6",children:[$t($n,{deliveries:e.email_deliveries}),At("div",{children:[$t("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),At("div",{className:"af-space-y-3",children:[u.map(([c,o])=>At("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[$t("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:c.replace(/_/g," ")}),$t("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof o=="string"&&o.includes(`
3
- `)?$t("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:o}):String(o)})]},c)),u.length===0&&$t("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&At("div",{children:[$t("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),$t("div",{className:"af-space-y-2",children:e.attachments.map((c,o)=>At("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[At("div",{className:"af-flex af-items-center af-gap-2",children:[$t(tm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),$t("span",{className:"af-text-sm",children:c.name}),At("span",{className:"af-text-xs af-text-muted-foreground",children:["(",rm(c.size),")"]})]}),At(y,{variant:"ghost",size:"sm",onClick:()=>l(c),disabled:n===i(c),children:[n===i(c)?$t(am,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):$t(Xf,{className:"af-h-4 af-w-4 af-mr-1"}),n===i(c)?"Downloading...":"Download"]})]},o))})]}),At("div",{children:[$t("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),At("div",{className:"af-space-y-2 af-text-sm",children:[At("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[$t(em,{className:"af-h-4 af-w-4"}),$t("span",{children:Nc(e.metadata.submitted_at)})]}),e.metadata.ip_address&&At("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[$t(Qf,{className:"af-h-4 af-w-4"}),At("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&At("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[$t(nm,{className:"af-h-4 af-w-4 af-mt-0.5"}),$t("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&At("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[$t(sm,{className:"af-h-4 af-w-4"}),At("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{Download as om}from"lucide-react";import*as Is from"react";var im=/^\+[1-9]\d{1,14}$/;function _c(e){let t=e==null?"":String(e),a=!im.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),s=a?`'${t}`:t;return a||/[",;\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function bi(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function hi(e,t){if(typeof document>"u")return;let a=URL.createObjectURL(e),s=document.createElement("a");s.href=a,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(a)}function yi({fetchCsv:e,filename:t}){let[a,s]=Is.useState(!1),[n,r]=Is.useState(null),i=Is.useRef(!1);return{exportCsv:Is.useCallback(async()=>{if(!i.current){i.current=!0,s(!0),r(null);try{let u=await e();hi(u,bi(t))}catch(u){r(u instanceof Error?u:new Error("Export failed"))}finally{i.current=!1,s(!1)}}},[e,t]),exporting:a,error:n}}import{jsx as kc,jsxs as Pc}from"react/jsx-runtime";function wa({fetchCsv:e,filename:t,label:a="Export CSV",disabled:s,className:n}){let{exportCsv:r,exporting:i,error:l}=yi({fetchCsv:e,filename:t});return Pc("span",{className:n,children:[Pc(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||i,"aria-busy":i,children:[kc(om,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Exporting\u2026":a]}),l&&kc("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}import{jsx as Ue,jsxs as jt}from"react/jsx-runtime";function pm(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function gm(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let a of t)if(typeof e[a]=="string")return e[a];return null}var vm=["message","comments","comment","inquiry","question","details","body","notes"];function bm(e){let t=Object.entries(e).filter(([r,i])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof i=="string"&&i.trim()),a=new Map(t.map(([r,i])=>[r.toLowerCase(),i])),n=(vm.map(r=>a.get(r)).find(Boolean)??t.reduce((r,[,i])=>i.length>r.length?i:r,"")).trim().replace(/\s+/g," ");return n.length>80?n.slice(0,80)+"\u2026":n}function xi({formId:e,className:t,defaultSubmissionId:a,submissionId:s,onSelectSubmission:n}){let{api:r}=H(),{submissions:i,total:l,isLoading:u,error:c,page:o,pageSize:f,hasNextPage:b,hasPreviousPage:g,setPage:m,setPageSize:v,deleteSubmission:d}=pi({formId:e}),p=ps.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[x,S]=ps.useState(a??null),k=n?s??null:x,h=n??S,N=U=>!!U&&U.id===k&&U.form_id===e,R=i.find(N),[C,w]=ps.useState(null),P=N(C)?C:null,[I,_]=ps.useState(null);if(ps.useEffect(()=>{if(_(null),!k||R||P)return;let U=!1;return r.getSubmission(k).then(te=>{if(!U){if(te.form_id!==e){_("This submission could not be found.");return}w(te)}}).catch(()=>{U||_("This submission could not be found.")}),()=>{U=!0}},[r,e,k,R,P]),k){let U=R??P;return U?Ue("div",{className:t,children:Ue(vi,{submission:U,onBack:()=>h(null),onDelete:async()=>{await d(U.id),h(null)}})}):I?jt("div",{className:t,children:[jt(y,{variant:"ghost",size:"sm",onClick:()=>h(null),className:"af-mb-2 af--ml-2",children:[Ue(lm,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Ue("p",{className:"af-text-sm af-text-destructive",children:I})]}):Ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ue("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(u)return Ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ue("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(c)return Ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:jt("div",{className:"af-text-destructive",children:["Error: ",c.message]})});if(i.length===0&&o===0)return jt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Ue(fm,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),jt("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",Ue("br",{}),"Submissions will appear here when visitors use your form."]})]});let q=o*f+1,j=Math.min((o+1)*f,l);return jt("div",{className:t,children:[Ue("div",{className:"af-mb-2 af-flex af-justify-end",children:Ue(wa,{fetchCsv:p,filename:"submissions"})}),jt(ct,{children:[Ue(dt,{children:jt(Ie,{children:[Ue(K,{children:"Email"}),Ue(K,{children:"Preview"}),Ue(K,{children:"Date"}),Ue(K,{className:"af-text-right",children:"Actions"})]})}),Ue(ut,{children:i.map(U=>{let te=gm(U.data),ce=bm(U.data);return jt(Ie,{children:[jt(Z,{className:"af-font-medium",children:[jt("div",{className:"af-flex af-items-center af-gap-2",children:[te||Ue("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),U.attachments.length>0&&jt("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${U.attachments.length} attachment(s)`,children:[Ue(mm,{className:"af-h-3 af-w-3"}),Ue("span",{className:"af-text-xs",children:U.attachments.length})]})]}),Ue(Cr,{deliveries:U.email_deliveries,label:"Notification email needs attention"})]}),Ue(Z,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:ce||Ue("span",{className:"af-italic",children:"No preview available"})}),Ue(Z,{className:"af-text-muted-foreground",children:pm(U.metadata.submitted_at)}),jt(Z,{className:"af-text-right",children:[Ue(y,{variant:"ghost",size:"icon",onClick:()=>h(U.id),title:"View details",children:Ue(um,{className:"af-h-4 af-w-4"})}),Ue(Xs,{iconOnly:!0,onDelete:()=>d(U.id)})]})]},U.id)})})]}),jt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[jt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[jt("span",{children:["Showing ",q,"-",j," of ",l]}),jt(un,{value:String(f),onValueChange:U=>v(Number(U)),children:[Ue(Qa,{className:"af-w-[70px] af-h-8",children:Ue(fn,{})}),jt(en,{children:[Ue(St,{value:"10",children:"10"}),Ue(St,{value:"25",children:"25"}),Ue(St,{value:"50",children:"50"}),Ue(St,{value:"100",children:"100"})]})]}),Ue("span",{children:"per page"})]}),jt("div",{className:"af-flex af-items-center af-gap-2",children:[jt(y,{variant:"outline",size:"sm",onClick:()=>m(o-1),disabled:!g,children:[Ue(cm,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),jt(y,{variant:"outline",size:"sm",onClick:()=>m(o+1),disabled:!b,children:["Next",Ue(dm,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as ln from"react";import{Plus as Tm,X as Em,Loader2 as Im,Check as Am}from"lucide-react";import*as Cc from"react";import{jsx as hm}from"react/jsx-runtime";var ae=Cc.forwardRef(({className:e,type:t,...a},s)=>hm("input",{type:t,className:W("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...a}));ae.displayName="Input";import*as Tc from"react";import{cva as ym}from"class-variance-authority";import{jsx as wm}from"react/jsx-runtime";var xm=ym("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Oe=Tc.forwardRef(({className:e,...t},a)=>wm("label",{ref:a,className:W(xm(),e),...t}));Oe.displayName="Label";import*as gn from"react";import{Plus as Nm,Loader2 as zo,Copy as Rm,Check as _m,Trash2 as km,RefreshCw as Pm,AlertTriangle as Cm}from"lucide-react";import*as on from"react";function wi(){let{api:e}=H(),[t,a]=on.useState([]),[s,n]=on.useState(!0),[r,i]=on.useState(null),l=on.useCallback(async()=>{try{n(!0),i(null),a(await e.getEventDestinations())}catch(g){i(g instanceof Error?g:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);on.useEffect(()=>{l()},[l]);let u=on.useCallback(async g=>{let m=await e.createEventDestination(g);return a(v=>[m,...v]),m},[e]),c=on.useCallback(async(g,m)=>{let v=await e.updateEventDestination(g,m);return a(d=>d.map(p=>p.id===g?v:p)),v},[e]),o=on.useCallback(async g=>{await e.deleteEventDestination(g),a(m=>m.filter(v=>v.id!==g))},[e]),f=on.useCallback(async g=>{let m=await e.rotateEventDestinationSecret(g);return a(v=>v.map(d=>d.id===g?m:d)),m},[e]),b=on.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:s,error:r,refetch:l,createDestination:u,updateDestination:c,deleteDestination:o,rotateSecret:f,getSecret:b}}import*as ss from"react";import{Loader2 as Ec,RotateCw as Sm}from"lucide-react";import{jsx as pn,jsxs as Ir}from"react/jsx-runtime";function Si({destinationId:e,limit:t=25,className:a}){let{api:s}=H(),[n,r]=ss.useState([]),[i,l]=ss.useState(!0),[u,c]=ss.useState(null),[o,f]=ss.useState(null),b=ss.useCallback(async()=>{try{l(!0),c(null),r(await s.getEventDeliveries(e,t))}catch(m){c(m instanceof Error?m.message:"Failed to load deliveries")}finally{l(!1)}},[s,e,t]);ss.useEffect(()=>{b()},[b]);let g=async m=>{try{f(m.id),c(null);let v=await s.retryEventDelivery(e,m.id);r(d=>d.map(p=>p.id===m.id?v:p))}catch(v){c(v instanceof Error?v.message:"Retry failed")}finally{f(null)}};return i?Ir("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[pn(Ec,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):u?pn("div",{className:"af-text-sm af-text-destructive af-py-2",children:u}):n.length===0?pn("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):pn("div",{className:a,children:pn("div",{className:"af-divide-y af-border af-rounded",children:n.map(m=>{let v=m.delivered_at!==null;return Ir("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[Ir("div",{className:"af-min-w-0",children:[Ir("div",{className:"af-flex af-items-center af-gap-2",children:[v?pn(ee,{variant:"secondary",children:m.last_status??200}):pn(ee,{variant:"destructive",children:m.last_status??"failed"}),pn("span",{className:"af-text-sm af-truncate",children:m.type})]}),Ir("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[m.event_id," \xB7 ",m.created_at,m.attempts>0&&` \xB7 ${m.attempts} failed ${m.attempts===1?"attempt":"attempts"}`]}),!v&&m.last_error&&pn("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:m.last_error})]}),pn(y,{variant:"ghost",size:"sm",title:"Send this event again",disabled:o===m.id,onClick:()=>g(m),children:o===m.id?pn(Ec,{className:"af-h-4 af-w-4 af-animate-spin"}):pn(Sm,{className:"af-h-4 af-w-4"})})]},m.id)})})})}import{jsx as tt,jsxs as Zt}from"react/jsx-runtime";function Ni({formId:e,topics:t,description:a,className:s}){let{destinations:n,isLoading:r,error:i,createDestination:l,updateDestination:u,deleteDestination:c,rotateSecret:o,getSecret:f}=wi(),[b,g]=gn.useState(""),[m,v]=gn.useState(!1),[d,p]=gn.useState(null),[x,S]=gn.useState(null),[k,h]=gn.useState(null),[N,R]=gn.useState(!1),[C,w]=gn.useState(null),[P,I]=gn.useState(null),[_,q]=gn.useState(null),j=gn.useMemo(()=>n.filter(A=>A.form_id===e),[n,e]),U=async()=>{let A=b.trim();if(A){if(!A.startsWith("https://")){p("Webhook URLs must start with https://");return}try{v(!0),p(null),await l({url:A,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(ne){p(ne instanceof Error?ne.message:"Failed to add webhook")}finally{v(!1)}}},te=async A=>{try{I(A.id),p(null),await o(A.id),R(!1),h(await f(A.id))}catch(ne){p(ne instanceof Error?ne.message:"Failed to rotate secret")}finally{I(null)}},ce=async A=>{try{I(A.id),p(null),await u(A.id,{status:"active"})}catch(ne){p(ne instanceof Error?ne.message:"Failed to re-enable")}finally{I(null)}},me=async()=>{if(C)try{I(C.id),await c(C.id),w(null)}catch(A){p(A instanceof Error?A.message:"Failed to delete")}finally{I(null)}},T=async A=>{if(x===A.id){S(null),h(null);return}try{I(A.id),p(null),R(!1),S(A.id),h(await f(A.id))}catch(ne){S(null),p(ne instanceof Error?ne.message:"Failed to read secret")}finally{I(null)}},V=async()=>{if(k)try{await navigator.clipboard.writeText(k),R(!0)}catch{}};return Zt("div",{className:s,children:[Zt("div",{className:"af-space-y-1",children:[tt(Oe,{children:"Webhooks"}),tt("p",{className:"af-text-sm af-text-muted-foreground",children:a??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),Zt("div",{className:"af-flex af-gap-2 af-mt-4",children:[tt(ae,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:A=>g(A.target.value),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),U())},disabled:m}),Zt(y,{onClick:U,disabled:m||!b.trim(),children:[m?tt(zo,{className:"af-h-4 af-w-4 af-animate-spin"}):tt(Nm,{className:"af-h-4 af-w-4"}),tt("span",{className:"af-ml-1",children:"Add"})]})]}),(d||i)&&tt("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:d||i?.message}),Zt("div",{className:"af-mt-4 af-space-y-2",children:[r&&Zt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[tt(zo,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&j.length===0&&tt("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),j.map(A=>Zt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[Zt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[Zt("div",{className:"af-min-w-0",children:[Zt("div",{className:"af-flex af-items-center af-gap-2",children:[tt("span",{className:"af-font-mono af-text-sm af-truncate",children:A.url}),A.status==="disabled"?tt(ee,{variant:"destructive",children:"Disabled"}):tt(ee,{variant:"secondary",children:"Active"})]}),tt("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:A.topics.includes("*")?"All events":A.topics.join(", ")})]}),Zt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[tt(y,{variant:"ghost",size:"sm",onClick:()=>q(_===A.id?null:A.id),children:_===A.id?"Hide log":"Deliveries"}),tt(y,{variant:"ghost",size:"sm",onClick:()=>T(A),disabled:P===A.id,children:x===A.id?"Hide secret":"Show secret"}),tt(y,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:P===A.id,onClick:()=>w(A),children:tt(km,{className:"af-h-4 af-w-4"})})]})]}),A.status==="disabled"&&Zt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[tt(Cm,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),Zt("div",{className:"af-text-sm",children:[Zt("p",{children:["We stopped sending after repeated failures."," ",A.disabled_reason]}),tt(y,{variant:"outline",size:"sm",className:"af-mt-2",disabled:P===A.id,onClick:()=>ce(A),children:"Re-enable"})]})]}),x===A.id&&k&&Zt("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[tt("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."}),Zt("div",{className:"af-flex af-gap-2",children:[tt(ae,{readOnly:!0,value:k,className:"af-font-mono"}),tt(y,{variant:"outline",title:"Copy signing secret",onClick:V,children:N?tt(_m,{className:"af-h-4 af-w-4"}):tt(Rm,{className:"af-h-4 af-w-4"})}),tt(y,{variant:"outline",title:"Rotate signing secret",disabled:P===A.id,onClick:()=>te(A),children:P===A.id?tt(zo,{className:"af-h-4 af-w-4 af-animate-spin"}):tt(Pm,{className:"af-h-4 af-w-4"})})]})]}),_===A.id&&tt(Si,{destinationId:A.id})]},A.id))]}),tt(mn,{open:!!C,onOpenChange:A=>{!A&&!P&&w(null)},children:Zt(tn,{children:[Zt(an,{children:[tt(sn,{children:"Delete this webhook?"}),Zt(rn,{children:["New submissions will stop being sent to ",C?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),Zt(nn,{children:[tt(y,{variant:"outline",onClick:()=>w(null),disabled:!!P,children:"Cancel"}),tt(y,{variant:"destructive",onClick:me,disabled:!!P,children:P?"Deleting...":"Delete"})]})]})})]})}import{jsx as ot,jsxs as Tn}from"react/jsx-runtime";function Ri({form:e,onSaved:t,className:a}){let{updateForm:s}=Js(),[n,r]=ln.useState(!1),[i,l]=ln.useState(null),[u,c]=ln.useState(null),[o,f]=ln.useState(e.name),[b,g]=ln.useState(e.redirect_url||""),[m,v]=ln.useState(e.email_recipients),[d,p]=ln.useState("");ln.useEffect(()=>{f(e.name),g(e.redirect_url||""),v(e.email_recipients),c(null)},[e]);let x=ln.useCallback(async R=>{try{r(!0),c(null);let C=await s(e.id,R);l(new Date),t?.(C)}catch(C){c(C instanceof Error?C.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);ln.useEffect(()=>{if(i){let R=setTimeout(()=>l(null),2e3);return()=>clearTimeout(R)}},[i]);let S=async()=>{let R=d.trim().toLowerCase();if(!R)return;if(!R.includes("@")){c("Please enter a valid email address");return}if(m.includes(R)){c("This email is already added");return}let C=[...m,R];v(C),p(""),c(null),await x({email_recipients:C})},k=async R=>{let C=m.filter(w=>w!==R);v(C),await x({email_recipients:C})},h=async()=>{o!==e.name&&await x({name:o})},N=async()=>{let R=b||null;R!==e.redirect_url&&await x({redirect_url:R})};return Tn("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(n||i)&&ot("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?Tn("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:[ot(Im,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),ot("span",{className:"af-text-sm",children:"Saving..."})]}):Tn("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:[ot(Am,{className:"af-h-4 af-w-4 af-text-green-600"}),ot("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Tn("div",{className:"af-space-y-2",children:[ot(Oe,{htmlFor:"form-name",children:"Form Name"}),ot(ae,{id:"form-name",value:o,onChange:R=>f(R.target.value),onBlur:h,placeholder:"Contact Form"}),ot("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),Tn("div",{className:"af-space-y-2",children:[ot(Oe,{children:"Email Recipients"}),ot("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),Tn("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[m.map(R=>Tn(ee,{variant:"secondary",className:"af-gap-1",children:[R,ot("button",{type:"button",onClick:()=>k(R),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:ot(Em,{className:"af-h-3 af-w-3"})})]},R)),m.length===0&&ot("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Tn("div",{className:"af-flex af-gap-2",children:[ot(ae,{type:"email",value:d,onChange:R=>p(R.target.value),placeholder:"Add email address",onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),S())},disabled:n}),ot(y,{type:"button",variant:"outline",onClick:S,disabled:!d.trim()||n,children:ot(Tm,{className:"af-h-4 af-w-4"})})]})]}),Tn("div",{className:"af-space-y-2",children:[ot(Oe,{htmlFor:"redirect-url",children:"Redirect URL"}),ot(ae,{id:"redirect-url",value:b,onChange:R=>g(R.target.value),onBlur:N,placeholder:"/thank-you"}),ot("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."})]}),Tn("div",{className:"af-space-y-2",children:[ot(Oe,{children:"Form Endpoint"}),ot("div",{className:"af-flex af-items-center af-gap-2",children:ot("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})}),ot("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),Tn("div",{className:"af-space-y-2",children:[ot(Oe,{children:"Captcha Protection"}),ot("div",{className:"af-flex af-items-center af-gap-2",children:ot(ee,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),ot("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),ot(Ni,{formId:e.id}),u&&ot("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})]})}import{jsx as Ma,jsxs as Un}from"react/jsx-runtime";function Ic({className:e,location:t,onNavigate:a,submissionId:s}){let{api:n}=H(),[r,i]=rs.useState({submissionId:s});rs.useEffect(()=>{s&&i({submissionId:s})},[s]);let l=a?t??{}:r,u=a??i,[c,o]=rs.useState(null),f=`${l.formId??""}|${l.submissionId??""}`,[b,g]=rs.useState(null),m=b?.key===f?b.message:null,v=l.formId??(c&&c.submissionId===l.submissionId?c.formId:void 0);rs.useEffect(()=>{let R=l.submissionId;if(!R||l.formId)return;let C=!1;return n.getSubmission(R).then(w=>{C||(g(null),o({submissionId:R,formId:w.form_id}))}).catch(()=>{C||g({key:f,message:"This submission could not be found."})}),()=>{C=!0}},[n,l.submissionId,l.formId,f]);let[d,p]=rs.useState(null);rs.useEffect(()=>{if(!v||d?.id===v)return;let R=!1;return n.getForm(v).then(C=>{R||(g(null),p(C))}).catch(()=>{R||g({key:f,message:"This form could not be found."})}),()=>{R=!0}},[n,v,d?.id,f]);let x=(R,C)=>{p(R),u({formId:R.id,tab:C})},S=()=>u({});if(!l.formId&&!l.submissionId)return Un("div",{className:e,children:[Un("div",{className:"af-mb-6",children:[Ma("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),Ma("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),Ma(ui,{onSelectForm:x})]});let h=Un(y,{variant:"ghost",size:"sm",onClick:S,className:"af-mb-2 af--ml-2",children:[Ma(Dm,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(m)return Un("div",{className:e,children:[h,Ma("p",{className:"af-text-sm af-text-destructive",children:m})]});if(!v||d?.id!==v)return Ma("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:Ma("div",{className:"af-text-muted-foreground",children:"Loading..."})});let N=l.submissionId?"submissions":l.tab??"submissions";return Un("div",{className:e,children:[Un("div",{className:"af-mb-6",children:[h,Ma("h2",{className:"af-text-lg af-font-semibold",children:d.name})]}),Un(di,{value:N,onValueChange:R=>u({formId:v,tab:R}),children:[Un(Pr,{className:"af-mb-4",children:[Un(kn,{value:"submissions",className:"af-gap-2",children:[Ma(Lm,{className:"af-h-4 af-w-4"}),"Submissions"]}),Un(kn,{value:"settings",className:"af-gap-2",children:[Ma(Om,{className:"af-h-4 af-w-4"}),"Settings"]})]}),Ma(Pn,{value:"submissions",children:Ma(xi,{formId:v,submissionId:l.submissionId,onSelectSubmission:R=>u({formId:v,tab:"submissions",submissionId:R??void 0})})}),Ma(Pn,{value:"settings",children:Ma(Ri,{form:d,onSaved:p})})]})]})}import*as lt from"react";import*as Vn from"react";function gs(){let{api:e}=H(),[t,a]=Vn.useState(null),[s,n]=Vn.useState(!0),[r,i]=Vn.useState(null),l=Vn.useRef(0),u=Vn.useCallback(async()=>{let c=++l.current;try{n(!0),i(null);let o=await e.getPaymentsStatus();if(c!==l.current)return;a(o)}catch(o){if(c!==l.current)return;i(o instanceof Error?o:new Error("Failed to fetch payments status"))}finally{c===l.current&&n(!1)}},[e]);return Vn.useEffect(()=>{u()},[u]),{status:t,isLoading:s,error:r,refetch:u}}var Bm=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function vn(e){return Bm.has(e.toLowerCase())}function Q(e,t,a){let s=vn(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function is(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 va(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=vn(t)?a:a*100;return Math.round(s)}function Dt(e,t){return vn(t)?e:e/100}function _i(e){return e.amount_paid??Math.max(0,is(e)-(e.credit_applied??0))}import{Fragment as $m,jsx as rt,jsxs as mt}from"react/jsx-runtime";function Ar(e){return e instanceof aa&&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 Ac(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${Q(e.amount_off,e.currency)} off`:"Discount unavailable"}function Qs(){let{api:e,siteToken:t}=H();return rt(Fm,{api:e},t)}function Fm({api:e}){let{status:t,error:a}=gs(),[s,n]=lt.useState([]),[r,i]=lt.useState(null),[l,u]=lt.useState(null),[c,o]=lt.useState(!1),[f,b]=lt.useState(!1),[g,m]=lt.useState(""),[v,d]=lt.useState(null),[p,x]=lt.useState(null),[S,k]=lt.useState(!1),h=lt.useRef(0),N=lt.useCallback(async w=>{let P=++h.current;o(!0),m("");try{let I=await e.getPromos(w);if(P!==h.current)return;n(_=>w?[..._,...I.promos.filter(q=>!_.some(j=>j.id===q.id))]:I.promos),i(I.next_cursor),u(I.checkout_enabled)}catch(I){P===h.current&&m(Ar(I))}finally{P===h.current&&o(!1)}},[e]);lt.useEffect(()=>(N(),()=>{h.current++}),[N]);async function R(w){let P=++h.current;o(!0),m(""),k(!1);try{let I=await e.getPromo(w);P===h.current&&d(I)}catch(I){P===h.current&&m(Ar(I))}finally{P===h.current&&o(!1)}}async function C(){if(v){b(!0),o(!0),m("");try{let w=await e.disablePromo(v.id);if(d(w),!["inactive","expired","exhausted"].includes(w.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");k(!1),await N()}catch(w){m(Ar(w))}finally{b(!1),o(!1)}}}return p?rt(Mm,{currency:t?.currency??void 0,replaces:p.replaces,onCancel:()=>x(null),onSave:async w=>{let P=p.replaces?await e.replacePromo(p.replaces.id,w):await e.createPromo(w),I=await e.getPromo(P.id);if(I.status==="pending"||I.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");d(I),x(null),await N()}}):mt("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[mt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[rt("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),rt(y,{disabled:c||!t?.currency,onClick:()=>{m(""),x({})},children:"Create promo code"})]}),rt("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),l===!1&&rt("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&&rt("p",{className:"af-text-sm",children:a?Ar(a):"Connect Stripe and set the payment currency before creating codes."}),g&&mt("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",rt(y,{variant:"outline",disabled:c,onClick:()=>v?void R(v.id):void N(),children:"Refresh"})]}),v?mt("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[rt(y,{variant:"ghost",disabled:f,onClick:()=>{d(null),k(!1),N()},children:"Back to codes"}),mt("h4",{className:"af-font-semibold af-break-all",children:[v.code," \xB7 ",v.name]}),mt("p",{children:[Ac(v)," \xB7 ",v.status]}),mt("p",{className:"af-text-sm",children:[v.times_redeemed==null?"Usage unavailable":`${v.times_redeemed} redemptions`,v.max_redemptions!=null?` / ${v.max_redemptions} maximum`:""]}),mt("p",{className:"af-text-sm",children:[v.minimum_amount!=null&&v.currency?`Minimum order: ${Q(v.minimum_amount,v.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),mt("p",{className:"af-text-sm",children:["Subscription discount:"," ",v.duration==="repeating"?`${v.duration_in_months} months`:v.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),rt("p",{className:"af-text-sm",children:v.expires_at?`Expires ${new Date(v.expires_at).toLocaleString()}`:"No expiry"}),mt("div",{className:"af-flex af-flex-wrap af-gap-2",children:[rt(y,{variant:"outline",disabled:c,onClick:()=>void R(v.id),children:"Refresh details"}),rt(y,{variant:"outline",disabled:c||v.status==="pending"||v.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:v}),children:"Replace with new code"}),rt(y,{variant:"outline",disabled:c||!["active","pending","unavailable"].includes(v.status),onClick:()=>k(!0),children:v.status==="pending"?"Cancel pending offer":"Disable code"})]}),S&&mt("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[mt("p",{className:"af-text-sm",children:[v.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${v.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),rt(y,{disabled:c,onClick:()=>void C(),children:v.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",rt(y,{variant:"ghost",disabled:c,onClick:()=>k(!1),children:"Cancel"})]})]}):mt($m,{children:[s.map(w=>mt("button",{type:"button",disabled:c,onClick:()=>void R(w.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:[mt("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[rt("span",{className:"af-font-semibold af-break-all",children:w.code}),rt("span",{className:"af-text-sm",children:w.status})]}),mt("div",{className:"af-text-sm",children:[Ac(w)," \xB7"," ",w.times_redeemed==null?"Usage unavailable":`${w.times_redeemed} redemptions`]})]},w.id)),!c&&!g&&s.length===0&&rt("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),c&&rt("p",{role:"status",children:"Loading promo codes\u2026"}),r&&rt(y,{variant:"outline",disabled:c,onClick:()=>void N(r),children:"Load more"})]})]})}function Mm({currency:e,replaces:t,onCancel:a,onSave:s}){let[n,r]=lt.useState(""),[i,l]=lt.useState(t?.name??""),[u,c]=lt.useState(t?.amount_off!=null?"fixed":"percent"),[o,f]=lt.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(Dt(t.amount_off,e)):"")),[b,g]=lt.useState(t?.minimum_amount!=null&&e?String(Dt(t.minimum_amount,e)):""),[m,v]=lt.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):""}),[d,p]=lt.useState(t?.max_redemptions?.toString()??""),[x,S]=lt.useState(t?.duration??"once"),[k,h]=lt.useState(t?.duration_in_months?.toString()??"3"),[N,R]=lt.useState(null),[C,w]=lt.useState(!1),[P,I]=lt.useState(""),_=lt.useRef(!1),q=e&&vn(e)?"1":"0.01";async function j(ce){if(ce.preventDefault(),_.current)return;I("");let me=N;if(!me){if(!e){I("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){I("Choose a different code for the replacement.");return}let T=va(o,e),V=b?va(b,e):null;if(u==="fixed"&&(!T||T>999999999999)||b&&(!V||V>999999999999)){I("Enter a positive amount within the supported range.");return}if(m&&new Date(m).getTime()<=Date.now()){I("Choose a future expiry.");return}me={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:i.trim(),duration:x,...u==="percent"?{percent_off:Number(o)}:{amount_off:T,currency:e},...b?{minimum_amount:V,currency:e}:{},...m?{expires_at:new Date(m).toISOString()}:{},...d?{max_redemptions:Number(d)}:{},...x==="repeating"?{duration_in_months:Number(k)}:{}},R(me)}_.current=!0,w(!0);try{await s(me)}catch(T){I(Ar(T)),T instanceof aa&&T.status>=400&&T.status<500&&T.details?.retryable!==!0&&R(null)}finally{_.current=!1,w(!1)}}let U=(ce,me,T,V={})=>mt("label",{className:"af-grid af-gap-1 af-text-sm",children:[ce,rt(ae,{"aria-label":ce,value:me,onChange:A=>T(A.target.value),...V})]}),te="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return mt("form",{onSubmit:j,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[rt("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&rt("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."}),mt("fieldset",{disabled:C||!!N,className:"af-grid af-gap-4",children:[U("Code",n,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),U("Name",i,l,{required:!0,maxLength:40}),mt("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",mt("select",{"aria-label":"Discount type",className:te,value:u,onChange:ce=>c(ce.target.value),children:[rt("option",{value:"percent",children:"Percentage"}),mt("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),U("Discount",o,f,{type:"number",required:!0,min:u==="percent"?"0.01":q,max:u==="percent"?"100":void 0,step:u==="percent"?"0.01":q}),U("Minimum order amount",b,g,{type:"number",min:q,step:q,placeholder:e?.toUpperCase()}),mt("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."]}),U("Expires at (local time)",m,v,{type:"datetime-local",step:1}),U("Maximum redemptions",d,p,{type:"number",min:1,max:1e6,step:1}),mt("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",mt("select",{"aria-label":"Subscription duration",className:te,value:x,onChange:ce=>S(ce.target.value),children:[rt("option",{value:"once",children:"First invoice only"}),rt("option",{value:"forever",children:"Every invoice"}),rt("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&U("Months",k,h,{type:"number",required:!0,min:1,max:36,step:1})]}),P&&rt("p",{role:"alert",className:"af-text-sm af-text-destructive",children:P}),N&&!C&&mt("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",rt("span",{className:"af-break-all",children:N.request_id})]}),mt("div",{className:"af-flex af-flex-wrap af-gap-2",children:[rt(y,{type:"submit",disabled:C,children:C?"Saving\u2026":N?"Retry same request":t?"Create replacement":"Create code"}),rt(y,{type:"button",variant:"ghost",disabled:C||!!N,onClick:a,children:"Cancel"})]})]})}import*as cr from"react";import{ArrowLeft as cg,FileText as dg,Package as ug,Receipt as fg,Settings as mg,Users as pg}from"lucide-react";import*as ki from"react";import{Package as Um,Pencil as Vm,Plus as Dc,Trash2 as Hm}from"lucide-react";import{jsx as ft,jsxs as Sa}from"react/jsx-runtime";function zm(e){if(e.allow_custom_amount){let t=e.min_amount!==null?Q(e.min_amount,e.currency):"?",a=e.max_amount!==null?Q(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":Q(e.unit_amount,e.currency)}function jm(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Pi({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:n,isLoading:r,error:i,deleteProduct:l}=e,[u,c]=ki.useState(null),[o,f]=ki.useState(!1),[b,g]=ki.useState(null),m=async()=>{if(u)try{f(!0),g(null),await l(u.id),c(null)}catch(v){g(v instanceof Error?v.message:"Failed to delete product")}finally{f(!1)}};return r?ft("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ft("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):i?ft("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Sa("div",{className:"af-text-destructive",children:["Error: ",i.message]})}):n.length===0?Sa("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[ft(Um,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Sa("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",ft("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),Sa(y,{variant:"outline",onClick:()=>a?.(),children:[ft(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Sa("div",{className:s,children:[ft("div",{className:"af-flex af-justify-end af-mb-4",children:Sa(y,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[ft(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Sa(ct,{children:[ft(dt,{children:Sa(Ie,{children:[ft(K,{children:"Name"}),ft(K,{children:"Price"}),ft(K,{children:"Fulfillment"}),ft(K,{children:"Status"}),ft(K,{className:"af-text-right",children:"Actions"})]})}),ft(ut,{children:n.map(v=>Sa(Ie,{children:[ft(Z,{className:"af-font-medium",children:v.name}),ft(Z,{children:zm(v)}),ft(Z,{className:"af-text-muted-foreground",children:jm(v)}),ft(Z,{children:ft(ee,{variant:v.active?"success":"secondary",children:v.active?"Active":"Inactive"})}),ft(Z,{className:"af-text-right",children:Sa("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Sa(y,{variant:"ghost",size:"sm",onClick:()=>t?.(v),children:[ft(Vm,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Sa(y,{variant:"ghost",size:"sm",onClick:()=>{g(null),c(v)},children:[ft(Hm,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},v.id))})]}),ft(mn,{open:!!u,onOpenChange:v=>{!v&&!o&&c(null)},children:Sa(tn,{children:[Sa(an,{children:[ft(sn,{children:"Delete product?"}),Sa(rn,{children:['"',u?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&ft("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),Sa(nn,{children:[ft(y,{variant:"outline",onClick:()=>c(null),disabled:o,children:"Cancel"}),ft(y,{variant:"destructive",onClick:m,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})}import*as _t from"react";import{FileText as Wm,Link2 as Gm,Loader2 as Bc,Plus as Km,Upload as Zm,X as Ym}from"lucide-react";import*as Yt from"react";import{Loader2 as Oc,Plus as jo,Trash2 as Lc,X as qm}from"lucide-react";import{jsx as ie,jsxs as Ce}from"react/jsx-runtime";function qo(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Ci({productId:e,currency:t,className:a}){let{api:s}=H(),n=vn(t)?"1":"0.01",[r,i]=Yt.useState(null),[l,u]=Yt.useState(!0),[c,o]=Yt.useState(null),[f,b]=Yt.useState(null),[g,m]=Yt.useState(!1),v=Yt.useRef(!0);Yt.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);let d=Yt.useCallback(async()=>{try{let E=await s.getProduct(e);if(!v.current)return;i(E)}catch(E){if(!v.current)return;o(E instanceof Error?E.message:"Failed to load product")}finally{v.current&&u(!1)}},[s,e]);Yt.useEffect(()=>{d()},[d]);let p=async E=>{b(null),m(!0);try{await E(),await d()}catch(M){v.current&&b(M instanceof Error?M.message:"Something went wrong")}finally{v.current&&m(!1)}},[x,S]=Yt.useState(""),[k,h]=Yt.useState(""),[N,R]=Yt.useState({}),C=()=>p(async()=>{let E=x.trim(),M=k.split(",").map(L=>L.trim()).filter(Boolean);if(!E)throw new Error("Option name is required");if(M.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:E,values:M}),v.current&&(S(""),h(""))}),w=E=>p(async()=>{let M=(N[E.id]??"").trim();if(!M)throw new Error("Enter a value");await s.updateOption(E.id,{add_values:[M]}),v.current&&R(L=>({...L,[E.id]:""}))}),P=(E,M)=>p(()=>s.updateOption(E.id,{remove_values:[M]})),I=E=>p(()=>s.deleteOption(E.id)),[_,q]=Yt.useState(null),[j,U]=Yt.useState(null),[te,ce]=Yt.useState(!1),[me,T]=Yt.useState(null),V=r?.options??[],A=r?.variants??[],ne=()=>{U(null),q({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(V.map(E=>[E.id,E.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},re=E=>{U(null);let M=E.inventory?.on_hand??0,L=M<0?"":String(M);q({variant:E,title:E.title??"",sku:E.sku??"",unitAmount:E.unit_amount!=null?String(Dt(E.unit_amount,t)):"",compareAt:E.compare_at_amount!=null?String(Dt(E.compare_at_amount,t)):"",active:E.active,optionValues:{},tracked:E.inventory?.tracked??!1,onHand:L,initialOnHand:L,allowBackorder:E.inventory?.allow_backorder??!1})},Me=async()=>{if(!_)return;U(null);let E=_.variant?.allow_custom_amount??!1,M=null,L=null;if(!E){if(M=va(_.unitAmount,t),M===null||M<=0){U("Enter a valid price");return}if(_.compareAt.trim()&&(L=va(_.compareAt,t),L===null||L<=M)){U("Compare-at price must be greater than the price");return}}let pe=_.onHand.trim()!==_.initialOnHand.trim(),J=parseInt(_.onHand,10);if(_.tracked&&pe&&(!Number.isFinite(J)||J<0)){U("On-hand quantity must be zero or more");return}try{if(ce(!0),_.variant)await s.updateVariant(_.variant.id,{title:_.title.trim()||null,sku:_.sku.trim()||null,...E?{}:{unit_amount:M,compare_at_amount:L},active:_.active}),await s.setVariantInventory(_.variant.id,{tracked:_.tracked,on_hand:_.tracked&&pe?J:void 0,allow_backorder:_.allowBackorder});else{let se={};for(let Fe of V){let Qe=_.optionValues[Fe.id];if(!Qe){U(`Choose a ${Fe.title}`),ce(!1);return}se[Fe.title]=Qe}await s.createVariant(e,{title:_.title.trim()||null,sku:_.sku.trim()||null,unit_amount:M,compare_at_amount:L,active:_.active,option_values:V.length>0?se:void 0,inventory:_.tracked?{tracked:!0,on_hand:J,allow_backorder:_.allowBackorder}:{tracked:!1,allow_backorder:_.allowBackorder}})}await d(),v.current&&q(null)}catch(se){if(v.current&&U(se instanceof Error?se.message:"Failed to save variant"),_.variant)try{let Fe=await s.getProduct(e);v.current&&i(Fe)}catch{}}finally{v.current&&ce(!1)}},Se=()=>p(async()=>{me&&(await s.deleteVariant(me.id),v.current&&T(null))}),Ee=_?.variant?.allow_custom_amount??!1,Ye=_?.variant!=null&&_.variant.option_values.length===0&&V.length>0&&!_.variant.active,ke=_?.variant?.inventory!=null&&_.variant.inventory.on_hand<0?-_.variant.inventory.on_hand:null;function nt(E){let M=E.inventory;if(!M||!M.tracked)return ie("span",{className:"af-text-muted-foreground",children:"Unlimited"});let L=M.available??M.on_hand;return L<0?Ce("span",{children:[-L," backordered"]}):Ce("span",{children:[L," in stock",M.allow_backorder&&ie("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return l?ie("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:ie(Oc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):c?ie("div",{className:a,children:ie("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c})}):Ce("div",{className:`af-space-y-6 ${a||""}`,children:[Ce("div",{className:"af-space-y-3",children:[Ce("div",{children:[ie(Oe,{children:"Options"}),ie("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),V.length>0&&ie("div",{className:"af-space-y-3",children:V.map(E=>Ce("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[Ce("div",{className:"af-flex af-items-center af-justify-between",children:[ie("span",{className:"af-text-sm af-font-medium",children:E.title}),ie(y,{variant:"ghost",size:"sm",onClick:()=>I(E),disabled:g,children:ie(Lc,{className:"af-h-4 af-w-4"})})]}),ie("div",{className:"af-flex af-flex-wrap af-gap-2",children:E.values.map(M=>Ce(ee,{variant:"secondary",className:"af-gap-1",children:[M.value,ie("button",{type:"button",onClick:()=>P(E,M.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:ie(qm,{className:"af-h-3 af-w-3"})})]},M.id))}),Ce("div",{className:"af-flex af-gap-2",children:[ie(ae,{value:N[E.id]??"",onChange:M=>R(L=>({...L,[E.id]:M.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),w(E))},disabled:g}),ie(y,{type:"button",variant:"outline",size:"sm",onClick:()=>w(E),disabled:g||!(N[E.id]??"").trim(),children:ie(jo,{className:"af-h-4 af-w-4"})})]})]},E.id))}),Ce("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[Ce("div",{className:"af-space-y-1",children:[ie(Oe,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),ie(ae,{id:"new-option-title",value:x,onChange:E=>S(E.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),Ce("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[ie(Oe,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),ie(ae,{id:"new-option-values",value:k,onChange:E=>h(E.target.value),placeholder:"S, M, L",disabled:g})]}),Ce(y,{type:"button",variant:"outline",onClick:C,disabled:g||!x.trim()||!k.trim(),children:[ie(jo,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),Ce("div",{className:"af-space-y-3",children:[Ce("div",{className:"af-flex af-items-center af-justify-between",children:[ie(Oe,{children:"Variants"}),Ce(y,{type:"button",variant:"outline",size:"sm",onClick:ne,disabled:g||V.length===0,children:[ie(jo,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),V.length===0&&ie("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),A.length===0?ie("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):Ce(ct,{children:[ie(dt,{children:Ce(Ie,{children:[ie(K,{children:"Variant"}),ie(K,{children:"SKU"}),ie(K,{children:"Price"}),ie(K,{children:"Stock"}),ie(K,{children:"Status"}),ie(K,{className:"af-text-right",children:"Actions"})]})}),ie(ut,{children:A.map(E=>Ce(Ie,{children:[ie(Z,{className:"af-font-medium",children:qo(E)}),ie(Z,{className:"af-text-muted-foreground",children:E.sku||"-"}),ie(Z,{children:E.unit_amount!=null?Ce("span",{children:[E.compare_at_amount!=null&&ie("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:Q(E.compare_at_amount,E.currency)}),Q(E.unit_amount,E.currency)]}):E.allow_custom_amount?ie("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),ie(Z,{children:nt(E)}),ie(Z,{children:ie(ee,{variant:E.active?"success":"secondary",children:E.active?"Active":"Inactive"})}),ie(Z,{className:"af-text-right",children:Ce("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[ie(y,{variant:"ghost",size:"sm",onClick:()=>re(E),disabled:g,children:"Edit"}),ie(y,{variant:"ghost",size:"icon",onClick:()=>T(E),disabled:g,title:"Delete variant",children:ie(Lc,{className:"af-h-4 af-w-4"})})]})})]},E.id))})]})]}),f&&ie("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f}),ie(mn,{open:_!==null,onOpenChange:E=>{!E&&!te&&q(null)},children:Ce(tn,{children:[Ce(an,{children:[ie(sn,{children:_?.variant?"Edit variant":"Add variant"}),ie(rn,{children:"Price, markdown, and stock live on the variant."})]}),_&&Ce("div",{className:"af-space-y-3",children:[_.variant?_.variant.option_values.length>0&&Ce("div",{className:"af-text-sm",children:[ie("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),qo(_.variant)]}):V.map(E=>Ce("div",{className:"af-space-y-1",children:[ie(Oe,{className:"af-text-xs af-text-muted-foreground",children:E.title}),Ce(un,{value:_.optionValues[E.id]??"",onValueChange:M=>q(L=>L&&{...L,optionValues:{...L.optionValues,[E.id]:M}}),children:[ie(Qa,{children:ie(fn,{placeholder:`Choose ${E.title}`})}),ie(en,{children:E.values.map(M=>ie(St,{value:M.value,children:M.value},M.id))})]})]},E.id)),Ee?Ce("div",{className:"af-space-y-1",children:[ie(Oe,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),ie("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):Ce("div",{className:"af-flex af-gap-3",children:[Ce("div",{className:"af-space-y-1",children:[Ce(Oe,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),ie(ae,{id:"variant-price",type:"number",min:"0",step:n,value:_.unitAmount,onChange:E=>q(M=>M&&{...M,unitAmount:E.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),Ce("div",{className:"af-space-y-1",children:[ie(Oe,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),ie(ae,{id:"variant-compare",type:"number",min:"0",step:n,value:_.compareAt,onChange:E=>q(M=>M&&{...M,compareAt:E.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),Ce("div",{className:"af-space-y-1",children:[ie(Oe,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),ie(ae,{id:"variant-sku",value:_.sku,onChange:E=>q(M=>M&&{...M,sku:E.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),Ce("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[Ce("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ie("input",{type:"checkbox",checked:_.tracked,onChange:E=>q(M=>M&&{...M,tracked:E.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),_.tracked&&Ce("div",{className:"af-space-y-1 af-pl-6",children:[Ce("div",{className:"af-flex af-items-end af-gap-3",children:[Ce("div",{className:"af-space-y-1",children:[ie(Oe,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),ie(ae,{id:"variant-onhand",type:"number",min:"0",step:"1",value:_.onHand,onChange:E=>q(M=>M&&{...M,onHand:E.target.value}),placeholder:ke!=null?"0":void 0,className:"af-w-[100px]"})]}),Ce("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[ie("input",{type:"checkbox",checked:_.allowBackorder,onChange:E=>q(M=>M&&{...M,allowBackorder:E.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),ke!=null&&Ce("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",ke," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),Ce("div",{className:"af-space-y-1",children:[Ce("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ie("input",{type:"checkbox",checked:_.active,onChange:E=>q(M=>M&&{...M,active:E.target.checked}),className:"af-h-4 af-w-4",disabled:Ye}),"Active (buyers can purchase this variant)"]}),Ye&&ie("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&&ie("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:j})]}),Ce(nn,{children:[ie(y,{variant:"outline",onClick:()=>q(null),disabled:te,children:"Cancel"}),Ce(y,{onClick:Me,disabled:te,children:[te?ie(Oc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,_?.variant?"Save":"Add variant"]})]})]})}),ie(mn,{open:me!==null,onOpenChange:E=>{!E&&!g&&T(null)},children:Ce(tn,{children:[Ce(an,{children:[ie(sn,{children:"Delete variant?"}),ie(rn,{children:me&&`"${qo(me)}" will no longer be purchasable. Past orders are unaffected.`})]}),Ce(nn,{children:[ie(y,{variant:"outline",onClick:()=>T(null),disabled:g,children:"Cancel"}),ie(y,{variant:"destructive",onClick:Se,disabled:g,children:"Delete"})]})]})})]})}import{Fragment as Xm,jsx as Te,jsxs as Ge}from"react/jsx-runtime";function Jm(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function Ti({productsState:e,product:t,currency:a,onSaved:s,className:n}){let{createProduct:r,updateProduct:i,attachProductFile:l,attachProductFileFromUrl:u}=e,c=!!t,o=t?.currency??a,f=vn(o)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,m]=_t.useState(!1),[v,d]=_t.useState(null),p=_t.useRef(!0);_t.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);let[x,S]=_t.useState(t?.name??""),[k,h]=_t.useState(t?.description??""),[N,R]=_t.useState(t?.allow_custom_amount?"custom":"fixed"),[C,w]=_t.useState(t?.unit_amount!=null?String(Dt(t.unit_amount,o)):""),[P,I]=_t.useState(t?.min_amount!=null?String(Dt(t.min_amount,o)):""),[_,q]=_t.useState(t?.max_amount!=null?String(Dt(t.max_amount,o)):""),[j,U]=_t.useState(String(t?.max_quantity??10)),te=_t.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(Dt(t.unit_amount,o)):"",minAmount:t?.min_amount!=null?String(Dt(t.min_amount,o)):"",maxAmount:t?.max_amount!=null?String(Dt(t.max_amount,o)):"",maxQuantity:String(t?.max_quantity??10)}).current,[ce,me]=_t.useState(t?.collect_shipping_address??!1),[T,V]=_t.useState(t?.active??!0),[A,ne]=_t.useState(t?.images??[]),[re,Me]=_t.useState(""),[Se,Ee]=_t.useState(t?.fulfillment??null),[Ye,ke]=_t.useState(!1),[nt,E]=_t.useState(""),[M,L]=_t.useState(null),pe=_t.useRef(null),J=g||Ye,se=()=>{let be=re.trim();if(be){if(A.includes(be)){d("This image URL is already added");return}ne($e=>[...$e,be]),Me(""),d(null)}},Fe=be=>{ne($e=>$e.filter(yt=>yt!==be))},Qe=async()=>{if(d(null),!x.trim()){d("Product name is required");return}let be=null,$e=null,yt=null,It=!c||N!==te.pricingMode||(N==="fixed"?C!==te.unitAmount:P!==te.minAmount||_!==te.maxAmount),Mt=!c||j!==te.maxQuantity,et=b||N==="fixed";if(!(b||!It))if(N==="fixed"){if(be=va(C,o),be===null||be<=0){d("Enter a valid price");return}}else{if($e=va(P,o),yt=va(_,o),$e===null||yt===null){d("Enter valid minimum and maximum amounts");return}if(yt<$e){d("Maximum amount must be at least the minimum amount");return}}let ta=parseInt(j,10);if(et&&Mt&&(!Number.isFinite(ta)||ta<1)){d("Max quantity must be at least 1");return}try{m(!0);let Je;if(c&&t){let wt={name:x.trim(),description:k.trim()||null,images:A,collect_shipping_address:ce,active:T};!b&&It&&(wt.allow_custom_amount=N==="custom",N==="fixed"?wt.unit_amount=be:(wt.min_amount=$e,wt.max_amount=yt)),et&&Mt&&(wt.max_quantity=ta),Je=await i(t.id,wt),te.pricingMode=Je.allow_custom_amount?"custom":"fixed",te.unitAmount=Je.unit_amount!=null?String(Dt(Je.unit_amount,o)):"",te.minAmount=Je.min_amount!=null?String(Dt(Je.min_amount,o)):"",te.maxAmount=Je.max_amount!=null?String(Dt(Je.max_amount,o)):"",te.maxQuantity=String(Je.max_quantity)}else{let wt={name:x.trim(),allow_custom_amount:N==="custom",collect_shipping_address:ce,active:T};k.trim()&&(wt.description=k.trim()),A.length>0&&(wt.images=A),N==="fixed"?(wt.unit_amount=be,wt.max_quantity=ta):(wt.min_amount=$e,wt.max_amount=yt),Je=await r(wt)}if(!p.current)return;Ee(Je.fulfillment),s?.(Je)}catch(Je){if(!p.current)return;d(Je instanceof Error?Je.message:"Failed to save product")}finally{p.current&&m(!1)}},Xe=async be=>{let $e=be.target.files?.[0];if(!(!$e||!t))try{ke(!0),L(null);let yt=await l(t.id,$e);if(!p.current)return;Ee(yt.fulfillment),s?.(yt)}catch(yt){if(!p.current)return;L(yt instanceof Error?yt.message:"Failed to upload file")}finally{p.current&&(ke(!1),pe.current&&(pe.current.value=""))}},Et=async()=>{let be=nt.trim();if(!(!be||!t))try{ke(!0),L(null);let $e=await u(t.id,be);if(!p.current)return;Ee($e.fulfillment),E(""),s?.($e)}catch($e){if(!p.current)return;L($e instanceof Error?$e.message:"Failed to fetch file")}finally{p.current&&ke(!1)}};return Ge("div",{className:`af-space-y-6 ${n||""}`,children:[Ge("div",{className:"af-space-y-2",children:[Te(Oe,{htmlFor:"product-name",children:"Name"}),Te(ae,{id:"product-name",value:x,onChange:be=>S(be.target.value),placeholder:"My product"})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{htmlFor:"product-description",children:"Description"}),Te("textarea",{id:"product-description",value:k,onChange:be=>h(be.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"})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{children:"Pricing"}),b?Te("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):Ge(Xm,{children:[Ge(un,{value:N,onValueChange:be=>R(be),children:[Te(Qa,{className:"af-w-[260px]",children:Te(fn,{})}),Ge(en,{children:[Te(St,{value:"fixed",children:"Fixed price"}),Te(St,{value:"custom",children:"Buyer chooses the amount"})]})]}),N==="fixed"?Te("div",{className:"af-flex af-items-end af-gap-3",children:Ge("div",{className:"af-space-y-1",children:[Ge(Oe,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",o.toUpperCase(),")"]}),Te(ae,{id:"product-price",type:"number",min:"0",step:f,value:C,onChange:be=>w(be.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):Ge("div",{className:"af-space-y-1",children:[Ge("div",{className:"af-flex af-items-end af-gap-3",children:[Ge("div",{className:"af-space-y-1",children:[Ge(Oe,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",o.toUpperCase(),")"]}),Te(ae,{id:"product-min-amount",type:"number",min:"0",step:f,value:P,onChange:be=>I(be.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),Ge("div",{className:"af-space-y-1",children:[Ge(Oe,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",o.toUpperCase(),")"]}),Te(ae,{id:"product-max-amount",type:"number",min:"0",step:f,value:_,onChange:be=>q(be.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),Te("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."})]}),Ge("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",o.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||N==="fixed")&&Ge("div",{className:"af-space-y-1",children:[Te(Oe,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),Te(ae,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:j,onChange:be=>U(be.target.value),className:"af-w-[140px]"})]})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{children:"Images"}),Te("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),Ge("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[A.map(be=>Ge(ee,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[Te("span",{className:"af-truncate",children:be}),Te("button",{type:"button",onClick:()=>Fe(be),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:Te(Ym,{className:"af-h-3 af-w-3"})})]},be)),A.length===0&&Te("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),Ge("div",{className:"af-flex af-gap-2",children:[Te(ae,{type:"url",value:re,onChange:be=>Me(be.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:be=>{be.key==="Enter"&&(be.preventDefault(),se())},disabled:g}),Te(y,{type:"button",variant:"outline",onClick:se,disabled:!re.trim()||g,children:Te(Km,{className:"af-h-4 af-w-4"})})]})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{children:"Digital File"}),Te("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."}),c?Ge("div",{className:"af-space-y-3",children:[Se?.type==="download"&&Ge("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Te(Wm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Te("span",{className:"af-text-sm",children:Se.filename}),Se.size!=null&&Ge("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Jm(Se.size),")"]})]}),Se?.type==="redirect"&&Se.url&&Ge("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Te(Gm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Ge("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Se.url]})]}),Ge("div",{className:"af-flex af-items-center af-gap-2",children:[Te("input",{ref:pe,type:"file",onChange:Xe,className:"af-hidden",disabled:J}),Ge(y,{type:"button",variant:"outline",size:"sm",onClick:()=>pe.current?.click(),disabled:J,children:[Ye?Te(Bc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Te(Zm,{className:"af-h-4 af-w-4 af-mr-1"}),Se?.type==="download"?"Replace file":"Upload file"]}),Te("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),Te(ae,{type:"url",value:nt,onChange:be=>E(be.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Ye}),Te(y,{type:"button",variant:"outline",size:"sm",onClick:Et,disabled:!nt.trim()||J,children:"Fetch from URL"})]}),M&&Te("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:M})]}):Te("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{children:"Settings"}),Ge("div",{className:"af-space-y-2",children:[Ge("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Te("input",{type:"checkbox",checked:ce,onChange:be=>me(be.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),Ge("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Te("input",{type:"checkbox",checked:T,onChange:be=>V(be.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),c&&t&&Ge("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[Te(Oe,{children:"Options & Variants"}),Te(Ci,{productId:t.id,currency:o})]}),v&&Te("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),Te("div",{className:"af-flex af-items-center af-gap-2",children:Ge(y,{type:"button",onClick:Qe,disabled:J,children:[g?Te(Bc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,c?"Save changes":"Create product"]})})]})}import*as sa from"react";import{ChevronLeft as Sp,ChevronRight as Gc,Loader2 as Np,Receipt as Rp,Search as _p,SlidersHorizontal as kp}from"lucide-react";import*as Ot from"react";var Qm=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Ei({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=Ot.useState([]),[r,i]=Ot.useState(0),[l,u]=Ot.useState(!0),[c,o]=Ot.useState(null),[f,b]=Ot.useState(0),[g,m]=Ot.useState(e),[v,d]=Ot.useState(void 0),[p,x]=Ot.useState(""),[S,k]=Ot.useState(""),[h,N]=Ot.useState(""),[R,C]=Ot.useState(!1),[w,P]=Ot.useState(!1),[I,_]=Ot.useState(void 0),q=I?I.join(","):"",j=Ot.useMemo(()=>{if(!q)return;let T=new Set(q.split(","));return Qm.filter(V=>!T.has(V))},[q]),U=Ot.useMemo(()=>{let T={};return v?T.status=v:j?T.excludeStatus=j:R||(T.excludeStatus=["pending","expired"]),p.trim()&&(T.customerEmail=p.trim()),S.trim()&&(T.from=S.trim()),h.trim()&&(T.to=h.trim()),w&&(T.unfulfilledOnly=!0),T},[v,j,R,p,S,h,w]),te=Ot.useRef(0),ce=Ot.useCallback(async()=>{let T=++te.current;try{u(!0),o(null);let V={...U,limit:g,offset:f*g},A=await a.getOrders(V);if(T!==te.current)return;n(A.orders),i(A.total)}catch(V){if(T!==te.current)return;o(V instanceof Error?V:new Error("Failed to fetch orders"))}finally{T===te.current&&u(!1)}},[a,f,g,U,t]);Ot.useEffect(()=>{ce()},[ce]);let me=Math.ceil(r/g);return{orders:s,total:r,isLoading:l,error:c,page:f,pageSize:g,hasNextPage:f<me-1,hasPreviousPage:f>0,setPage:b,setPageSize:T=>{m(T),b(0)},status:v,setStatus:T=>{d(T),b(0)},statusIn:I,setStatusIn:T=>{_(T&&T.length>0?T:void 0),b(0)},customerEmail:p,setCustomerEmail:T=>{x(T),b(0)},from:S,setFrom:T=>{k(T),b(0)},to:h,setTo:T=>{N(T),b(0)},showAbandoned:R,setShowAbandoned:T=>{C(T),b(0)},unfulfilledOnly:w,setUnfulfilledOnly:T=>{P(T),b(0)},clearFilters:()=>{d(void 0),_(void 0),C(!1),P(!1),x(""),k(""),N(""),b(0)},filters:U,refetch:ce}}import*as qt from"react";import{ArrowLeft as ap,Check as $c,ChevronLeft as np,ChevronRight as sp,ClipboardCopy as rp,Copy as ip,Download as op,Loader2 as Oi,Mail as Uc,MoreHorizontal as lp,Package as cp,RotateCcw as dp,Truck as up,Undo2 as Vc}from"lucide-react";import*as Fc from"react";import*as Hn from"@radix-ui/react-popover";import{jsx as Wo}from"react/jsx-runtime";var Ii=Hn.Root,Ai=Hn.Trigger;var Dr=Fc.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},n)=>Wo(Hn.Portal,{children:Wo("div",{className:"aifeatures-admin",children:Wo(Hn.Content,{ref:n,align:t,sideOffset:a,className:W("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})})}));Dr.displayName=Hn.Content.displayName;import{jsx as Di}from"react/jsx-runtime";var ep={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function tp(e){return ep[e]??e}function Mc(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 As({status:e,className:t}){return Di(ee,{variant:Mc(e),className:t,children:tp(e)})}function Ds({status:e}){return Di(As,{status:e})}function er({order:e,className:t}){return e.line_items.some(a=>a.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?Di(ee,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?Di(ee,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function os(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as yp,jsx as O,jsxs as le}from"react/jsx-runtime";var qc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Os="af-text-xs af-text-muted-foreground";function Go(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 fp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wc(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 Li=24,mp=["paid","partially_refunded"],pp=["paid","partially_refunded","disputed"],gp=/^[A-Za-z0-9 _-]*$/,Hc=100;function Yo(e,t,a,s,n){let r=mp.includes(s);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${a} of ${Li} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${Li} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?a<Li&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:a<Li&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${a} attempt${a===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${s==="refunded"?"because the order was refunded":s==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function zc({title:e,recipient:t,status:a,attempts:s,side:n,orderStatus:r,action:i,delivery:l}){if(l)return le("div",{children:[O($n,{deliveries:[l]}),i&&O("div",{className:"af-mt-2",children:i})]});let u=Yo(n,a,s,r,t);return le("div",{children:[le("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[le("div",{className:"af-min-w-0",children:[O("div",{className:"af-text-sm",children:e}),t&&O("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),O(ee,{variant:u.variant,className:"af-shrink-0",children:u.label})]}),u.detail&&O("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:u.detail}),i&&O("div",{className:"af-mt-2",children:i})]})}function jc(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=fp(e.address)?e.address:null;if(a){for(let n of["line1","line2"]){let r=a[n];typeof r=="string"&&r&&t.push(r)}let s=["city","state","postal_code"].map(n=>a[n]).filter(n=>typeof n=="string"&&!!n).join(", ");s&&t.push(s),typeof a.country=="string"&&a.country&&t.push(a.country)}return t.length>0?t:Object.entries(e).map(([s,n])=>`${s}: ${Wc(n)}`)}function vp(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Jo({value:e,label:t,children:a,className:s,size:n="icon"}){let[r,i]=qt.useState(!1);if(!vp())return null;let l=async()=>{try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},u=r?O($c,{className:"af-h-3 af-w-3"}):O(ip,{className:"af-h-3 af-w-3"});return n==="icon"?O(y,{variant:"ghost",size:"icon",className:W("af-h-6 af-w-6 af-shrink-0",s),onClick:l,title:t,"aria-label":t,children:u}):le(y,{variant:"outline",size:"sm",className:s,onClick:l,"aria-label":t,children:[r?O($c,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):O(rp,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":a]})}function Ko({label:e,value:t}){return le("div",{children:[O("div",{className:Os,children:e}),le("div",{className:"af-flex af-items-center af-gap-1",children:[O("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),O(Jo,{value:t,label:`Copy ${e}`})]})]})}function bp({src:e}){let[t,a]=qt.useState(!1);return!e||t?O("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:O(cp,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):O("img",{src:e,alt:"","aria-hidden":"true",onError:()=>a(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function zn({title:e,action:t,children:a,className:s}){return le("section",{className:W("af-rounded-lg af-border af-p-4",s),children:[le("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[O("h4",{className:qc,children:e}),t]}),O("div",{className:"af-mt-3",children:a})]})}function $a({label:e,emphasis:t,divider:a,children:s}){return le("div",{className:W("af-flex af-items-baseline af-justify-between af-gap-6",a&&"af-mt-2 af-border-t af-pt-2"),children:[O("span",{className:t?"af-text-base af-font-semibold":Os,children:e}),O("span",{className:W("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function Zo({onSelect:e,disabled:t,icon:a,children:s}){return le(y,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[O("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function hp(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 ${Q(_i(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),s=a?mi(a):Yo("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),s=a?mi(a):Yo("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${Q(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 Bi({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:n=!1,onPrevOrder:r,onNextOrder:i,hasPrevOrder:l=!1,hasNextOrder:u=!1}){let{api:c}=H(),[o,f]=qt.useState(e),[b,g]=qt.useState(null),[m,v]=qt.useState(null),[d,p]=qt.useState(!1),[x,S]=qt.useState(!1),[k,h]=qt.useState(!1),[N,R]=qt.useState(!1),[C,w]=qt.useState(""),[P,I]=qt.useState(!1),[_,q]=qt.useState(null),[j,U]=qt.useState(!1),[te,ce]=qt.useState(""),[me,T]=qt.useState([]),[V,A]=qt.useState(!1),[ne,re]=qt.useState(!1),[Me,Se]=qt.useState(null);qt.useEffect(()=>{f(e)},[e]);let Ee=F=>{let st=F.id===o.id&&F.email_deliveries===void 0?{...F,email_deliveries:o.email_deliveries}:F;f(st),s?.(st)},Ye=Object.entries(o.metadata??{}),ke=Math.max(0,_i(o)-o.amount_refunded),nt=(o.status==="paid"||o.status==="partially_refunded")&&ke>0,E=o.exclusive_tax_total!=null,M=F=>typeof F.amountNet=="number"?F.amountNet+(F.exclusiveTax??0):(typeof F.unitAmount=="number"?F.unitAmount:0)*(typeof F.quantity=="number"&&F.quantity>0?F.quantity:1),L=Math.max(0,(o.shipping_total??0)-(o.shipping_refunded??0)),pe=me.reduce((F,st)=>F+M(o.line_items[st]??{}),0)+(V?L:0),J=o.tax_total??0,se=Math.max(0,(o.exclusive_tax_total??0)-o.line_items.reduce((F,st)=>F+(st.exclusiveTax??0),0)),Fe=E?V&&L>0?se:0:o.automatic_tax&&o.tax_behavior==="exclusive"&&J>0&&o.amount_total+(o.shipping_total??0)>0?Math.min(Math.max(0,J-(o.tax_refunded??0)),Math.round(J*pe/(o.amount_total+(o.shipping_total??0)))):0,Qe=o.source==="subscription"&&(o.credit_applied??0)>0&&o.line_items.length===1?Math.min(pe+Fe,ke):pe+Fe,Xe=me.length>0||V,Et=Xe?Qe:va(te,o.currency),be=vn(o.currency)?"1":"0.01",$e=async()=>{try{p(!0),g(null),v(null),await c.resendOrderReceipt(o.id);let F=await c.getOrder(o.id);Ee(F),v("Receipt email queued.")}catch(F){g(F instanceof Error?F.message:"Failed to resend receipt")}finally{p(!1)}},yt=async()=>{try{S(!0),g(null),v(null);let F=await c.resetOrderDownloads(o.id);Ee(F),h(!1),v("Download count reset.")}catch(F){g(F instanceof Error?F.message:"Failed to reset downloads")}finally{S(!1)}},It=o.line_items.some(F=>F.collectShippingAddress===!0&&!F.refunded&&!F.unavailableReason),Mt=typeof o.merchant_fulfilled_at=="string",et=pp.includes(o.status)||o.status==="refunded"&&o.line_items.some(F=>F.collectShippingAddress===!0&&F.amountNet===0&&!F.refunded&&!F.unavailableReason),ta=C.trim(),Je=gp.test(ta)&&ta.length<=Hc,wt=async F=>{try{I(!0),q(null),v(null);let st=await c.setOrderFulfillment(o.id,{fulfilled:F,...F&&ta?{trackingNumber:ta}:{}});Ee(st),w(""),v(F?"Marked as shipped.":"Marked as not shipped.")}catch(st){st instanceof aa&&st.status===409?q(`This order is ${o.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):q(st instanceof Error?st.message:"Failed to update the order")}finally{I(!1)}},Xa=()=>{Se(null),ce(String(Dt(ke,o.currency))),T([]),A(!1),U(!0)},Mn=F=>T(st=>st.includes(F)?st.filter(La=>La!==F):[...st,F]),ye=async(F,st)=>{if(a)try{re(!0),Se(null),await a(o,F,st);let La=await c.getOrder(o.id);Ee(La),U(!1),v("Refund issued.")}catch(La){Se(La instanceof Error?La.message:"Refund failed")}finally{re(!1)}},Rt=async()=>{if(Xe){if(Qe<=0){Se("The lines you picked were charged nothing");return}if(Qe>ke){Se(`That selection exceeds the refundable remainder (${Q(ke,o.currency)})`);return}await ye(Qe,{...me.length>0?{line_items:[...me].sort((st,La)=>st-La)}:{},...V?{shipping:!0}:{}});return}let F=va(te,o.currency);if(F===null||F<=0){Se("Enter a valid refund amount");return}if(F>ke){Se(`Amount exceeds the refundable remainder (${Q(ke,o.currency)})`);return}await ye(F,{amount:F})},$=()=>ye(ke,{full:!0}),Pe=!o.subscription_history_only&&o.fulfillment_type==="download",zt=!o.subscription_history_only&&n&&It,Rn=hp(o),X=o.shipping_address?jc(o.shipping_address).join(`
4
- `):"",la=o.shipping_total!=null,Do=o.exclusive_tax_total??(o.automatic_tax&&o.tax_behavior==="exclusive"?o.tax_total??0:0),lc=o.exclusive_tax_total!=null?Math.max(0,(o.tax_total??0)-Do):o.automatic_tax&&o.tax_behavior==="exclusive"?0:o.tax_total??0,cc=Do>0,Nf=lc>0,dc=o.amount_subtotal!=null||la||cc||(o.discount_total??0)>0,Nr=[];return o.subscription_history_only||Nr.push(O(Zo,{icon:d?O(Oi,{className:"af-h-4 af-w-4 af-animate-spin"}):O(Uc,{className:"af-h-4 af-w-4"}),disabled:d||o.fulfillment_status!=="fulfilled",onSelect:()=>{R(!1),$e()},children:"Resend receipt"},"resend")),Pe&&Nr.push(O(Zo,{icon:O(dp,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{R(!1),h(!0)},children:"Reset download count"},"reset")),nt&&Nr.push(le("div",{children:[O(Zo,{icon:O(Vc,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{R(!1),Xa()},children:"Refund\u2026"}),!a&&O("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),le("div",{children:[le("div",{className:"af-mb-6",children:[le(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[O(ap,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),le("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[le("div",{className:"af-min-w-0",children:[le("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[O("h3",{className:"af-text-xl af-font-semibold",children:os(o)}),O(As,{status:o.status}),n&&!o.subscription_history_only&&O(er,{order:o}),o.is_test&&O(ee,{variant:"outline",children:"Test"})]}),le("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Go(o.created_at)]}),o.is_test&&O("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),le("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||i)&&le("div",{className:"af-flex af-items-center",children:[O(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!l,"aria-label":"Previous order",children:O(np,{className:"af-h-4 af-w-4"})}),O(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:i,disabled:!u,"aria-label":"Next order",children:O(sp,{className:"af-h-4 af-w-4"})})]}),zt&&(Mt?le("div",{className:"af-flex af-items-center af-gap-1",children:[le("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",o.merchant_fulfilled_at?` \xB7 ${Go(o.merchant_fulfilled_at)}`:""]}),et&&le(y,{variant:"ghost",size:"sm",onClick:()=>wt(!1),disabled:P,children:[P?O(Oi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):O(Vc,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):et?le("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[O(ae,{value:C,onChange:F=>w(F.target.value),placeholder:"Tracking number (optional)",maxLength:Hc,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:P}),le(y,{variant:"default",className:"af-shrink-0",onClick:()=>wt(!0),disabled:P||!Je,children:[P?O(Oi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):O(up,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Nr.length>0&&le(Ii,{open:N,onOpenChange:R,children:[O(Ai,{asChild:!0,children:O(y,{variant:"outline",size:"icon","aria-label":"More actions",children:O(lp,{className:"af-h-4 af-w-4"})})}),O(Dr,{children:O("div",{className:"af-space-y-0.5",children:Nr})})]})]})]}),zt&&!Mt&&!Je&&O("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."}),_&&O("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:_}),m&&O("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:m}),b&&O("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})]}),le("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[le("div",{className:"af-space-y-6",children:[o.line_items.length>0&&O(zn,{title:"Items",children:O("ul",{className:"af-space-y-3",children:o.line_items.map((F,st)=>{let La=typeof F.name=="string"&&F.name?F.name:"Item",uc=typeof F.quantity=="number"&&F.quantity>0?F.quantity:1,fc=typeof F.unitAmount=="number";return le("li",{className:"af-flex af-items-start af-gap-3",children:[O(bp,{src:typeof F.imageUrl=="string"&&F.imageUrl?F.imageUrl:void 0}),le("div",{className:"af-min-w-0 af-flex-1",children:[le("div",{className:"af-text-sm af-font-medium",children:[La,typeof F.variantTitle=="string"&&F.variantTitle&&le("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",F.variantTitle]})]}),le("div",{className:Os,children:[uc," \xD7"," ",fc?Q(F.unitAmount,o.currency):"\u2014"]}),F.unavailableReason==="oversold"&&!F.refunded&&O(ee,{variant:"secondary",className:"af-mt-1",children:F.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),F.refunded===!0&&O(ee,{variant:"secondary",className:"af-mt-1",children:F.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),O("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof F.amountNet=="number"||fc?Q(F.amountNet??F.unitAmount*uc,o.currency):"\u2014"})]},st)})})}),Ye.length>0&&O(zn,{title:"Order details",children:O("dl",{className:"af-space-y-2",children:Ye.map(([F,st])=>le("div",{children:[O("dt",{className:W(Os,"af-capitalize"),children:F.replace(/_/g," ")}),O("dd",{className:"af-text-sm af-break-words",children:Wc(st)})]},F))})}),O(zn,{title:"Totals",children:le("div",{className:"af-w-full",children:[dc&&O($a,{label:"Subtotal",children:Q(o.amount_subtotal??o.amount_total+(o.discount_total??0),o.currency)}),(o.discount_total??0)>0&&le($a,{label:"Discount",children:["\u2212",Q(o.discount_total,o.currency)]}),la&&O($a,{label:"Shipping",children:o.shipping_total===0?"Free":Q(o.shipping_total??0,o.currency)}),cc&&O($a,{label:"Tax",children:Q(Do,o.currency)}),O($a,{label:"Total",emphasis:!0,divider:dc,children:Q(is(o),o.currency)}),(o.credit_applied??0)>0&&le($a,{label:"Credit applied",children:["\u2212",Q(o.credit_applied,o.currency)]}),o.amount_paid!=null&&O($a,{label:"Amount paid",children:Q(o.amount_paid,o.currency)}),Nf&&O($a,{label:"incl. tax",children:Q(lc,o.currency)}),o.base_currency!=null&&o.base_amount_total!=null&&le($a,{label:"Your price",children:[Q(o.base_amount_total,o.base_currency),le("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",o.currency.toUpperCase()]})]}),o.amount_refunded>0&&le(yp,{children:[le($a,{label:"Refunded",children:["\u2212",Q(o.amount_refunded,o.currency),(o.shipping_refunded??0)>0&&le("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",Q(o.shipping_refunded??0,o.currency)," ","shipping"]})]}),O($a,{label:"Net",children:O("span",{className:"af-font-medium",children:Q(Math.max(0,_i(o)-o.amount_refunded),o.currency)})})]})]})}),o.application_fee_state&&le(zn,{title:"Platform fee",children:[o.application_fee_original!=null&&O($a,{label:"Collected",children:Q(o.application_fee_original,o.application_fee_currency??o.currency)}),o.application_fee_returned!=null&&O($a,{label:"Returned",children:Q(o.application_fee_returned,o.application_fee_currency??o.currency)}),o.application_fee_retained!=null&&O($a,{label:"Retained",children:Q(o.application_fee_retained,o.application_fee_currency??o.currency)}),o.application_fee_state!=="complete"&&O("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:o.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),O(zn,{title:"Timeline",children:O("ol",{className:"af-space-y-3",children:Rn.map(F=>le("li",{className:"af-flex af-gap-3",children:[O("span",{"aria-hidden":"true",className:W("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",F.tone==="destructive"?"af-bg-destructive":F.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),le("div",{className:"af-min-w-0",children:[O("div",{className:"af-text-sm af-break-words",children:F.text}),F.at&&O("div",{className:"af-text-xs af-text-muted-foreground",children:Go(F.at)})]})]},F.key))})})]}),le("div",{className:"af-space-y-6",children:[O(zn,{title:"Customer",children:le("div",{className:"af-space-y-2",children:[le("div",{children:[O("div",{className:Os,children:"Email"}),le("div",{className:"af-flex af-items-center af-gap-1",children:[O("span",{className:"af-min-w-0 af-break-all af-text-sm",children:o.customer_email||O("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),o.customer_email&&O(Jo,{value:o.customer_email,label:"Copy email"})]})]}),o.customer_name&&le("div",{children:[O("div",{className:Os,children:"Name"}),O("div",{className:"af-text-sm",children:o.customer_name})]}),o.customer&&le("div",{children:[O("div",{className:Os,children:"Customer record"}),le("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[O("span",{className:"af-break-all af-text-sm",children:o.customer.name||o.customer.email}),O(ee,{variant:"secondary",children:"Linked"})]})]})]})}),o.shipping_address&&O(zn,{title:"Ship to",action:O(Jo,{value:X,label:"Copy address",size:"sm",children:"Copy address"}),children:O("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:jc(o.shipping_address).map((F,st)=>O("div",{children:F},st))})}),o.subscription_history_only?O(zn,{title:"Subscription history",children:O("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."})}):le(zn,{title:"Emails",children:[O($n,{deliveries:o.email_deliveries?.filter(F=>!["purchase_receipt","merchant_sale"].includes(F.kind)),problemsOnly:!0,className:"af-mb-4"}),le("div",{className:"af-space-y-4",children:[O(zc,{side:"buyer",title:"Receipt to buyer",delivery:o.email_deliveries?.find(F=>F.kind==="purchase_receipt"),recipient:o.customer_email,status:o.buyer_email_status,attempts:o.buyer_email_attempts,orderStatus:o.status,action:le(y,{variant:"outline",size:"sm",onClick:$e,disabled:d||o.fulfillment_status!=="fulfilled",children:[d?O(Oi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):O(Uc,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),O(zc,{side:"merchant",title:"Sale alert to you",delivery:o.email_deliveries?.find(F=>F.kind==="merchant_sale"),recipient:null,status:o.merchant_email_status,attempts:o.merchant_email_attempts,orderStatus:o.status})]})]}),Pe&&O(zn,{title:"Download",children:le("div",{className:"af-space-y-2",children:[le("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[O(op,{className:"af-h-4 af-w-4"}),le("span",{children:["Downloaded ",o.download_count," time",o.download_count===1?"":"s"]})]}),o.download_url&&O("a",{href:o.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),le("details",{className:"af-rounded-lg af-border af-p-4",children:[O("summary",{className:W(qc,"af-cursor-pointer af-select-none"),children:"Technical details"}),le("div",{className:"af-mt-3 af-space-y-2",children:[O(Ko,{label:"Order ID",value:o.id}),o.stripe_checkout_session_id&&O(Ko,{label:"Checkout session",value:o.stripe_checkout_session_id}),o.stripe_payment_intent_id&&O(Ko,{label:"Payment",value:o.stripe_payment_intent_id})]})]})]})]}),O(mn,{open:k,onOpenChange:F=>{!F&&!x&&h(!1)},children:le(tn,{children:[le(an,{children:[O(sn,{children:"Reset download count?"}),O(rn,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),le(nn,{children:[O(y,{variant:"outline",onClick:()=>h(!1),disabled:x,children:"Cancel"}),O(y,{onClick:yt,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),O(mn,{open:j,onOpenChange:F=>{!F&&!ne&&U(!1)},children:le(tn,{children:[le(an,{children:[O(sn,{children:"Refund order"}),le(rn,{children:["Refund up to ",Q(ke,o.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),le("div",{className:"af-space-y-4",children:[(o.line_items.length>0||L>0)&&le("div",{className:"af-space-y-2",children:[O(Oe,{children:"Items"}),le("div",{className:"af-space-y-2",children:[o.line_items.map((F,st)=>{let La=F.refunded===!0;return le("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[O("input",{type:"checkbox",checked:me.includes(st),onChange:()=>Mn(st),disabled:ne||La||!!F.unavailableReason||M(F)<=0,className:"af-h-4 af-w-4"}),le("span",{className:La?"af-text-muted-foreground af-line-through":void 0,children:[typeof F.name=="string"&&F.name?F.name:"Item",typeof F.variantTitle=="string"&&F.variantTitle?` \u2014 ${F.variantTitle}`:"",typeof F.quantity=="number"&&F.quantity>1?` \xD7 ${F.quantity}`:""]}),O("span",{className:"af-ml-auto af-text-muted-foreground",children:La?"Refunded":Q(M(F),o.currency)})]},st)}),L>0&&le("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[O("input",{type:"checkbox",checked:V,onChange:F=>A(F.target.checked),disabled:ne,className:"af-h-4 af-w-4"}),O("span",{children:"Shipping"}),O("span",{className:"af-ml-auto af-text-muted-foreground",children:Q(L,o.currency)})]})]})]}),le("div",{className:"af-space-y-2",children:[le(Oe,{htmlFor:"refund-amount",children:["Amount (",o.currency.toUpperCase(),")"]}),O(ae,{id:"refund-amount",type:"number",min:"0",step:be,value:Xe?String(Dt(Qe,o.currency)):te,onChange:F=>ce(F.target.value),disabled:ne||Xe}),Xe&&O("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Me&&O("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Me}),le(nn,{children:[O(y,{variant:"outline",onClick:()=>U(!1),disabled:ne,children:"Cancel"}),O(y,{variant:"outline",onClick:$,disabled:ne,children:"Refund everything"}),O(y,{variant:"destructive",onClick:Rt,disabled:ne,children:ne?"Refunding...":Et!==null&&Et>0?`Refund ${Q(Et,o.currency)}`:"Refund"})]})]})})]})}import*as Fi from"react";import{ArrowLeft as xp,RefreshCw as wp}from"lucide-react";import{jsx as Ua,jsxs as vs}from"react/jsx-runtime";function Ut({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:n}){let r=Fi.useRef(null);return Fi.useEffect(()=>{r.current?.focus()},[]),vs("div",{className:W("af-bg-background",n),children:[vs("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:[Ua("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!a&&vs(y,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[Ua(xp,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Ua("div",{className:"af-p-4",children:s})]})}function G({className:e}){return Ua("div",{"aria-hidden":"true",className:W("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function pt({label:e,children:t,detail:a,valueClassName:s}){return vs("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Ua("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Ua("div",{className:W("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&Ua("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function xt({message:e,onRetry:t}){return vs("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ua("span",{children:e}),vs(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[Ua(wp,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function ca({icon:e,children:t}){return vs("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Ua("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function tr({icon:e,heading:t,body:a,action:s,className:n,children:r}){return vs("div",{className:W("af-px-6 af-py-10 af-text-center",n),children:[Ua(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),Ua("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),Ua("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&Ua(y,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}import{jsx as z,jsxs as Ve}from"react/jsx-runtime";var Pp={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Kc={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Zc(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 Yc(e){let t=Array.isArray(e.line_items)?e.line_items:[],a=t[0];if(!a)return"\u2014";let s=typeof a.name=="string"&&a.name?a.name:"Item",n=typeof a.quantity=="number"&&a.quantity>0?a.quantity:1,r=n>1?`${s} \xD7${n}`:s;return t.length>1?`${r} +${t.length-1} more`:r}function Mi(e){return e.customer?.name||e.customer_name||null}function Cp({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:n=!1,emptyMessage:r,onDetailOpenChange:i,maxRows:l,onViewAll:u}){let c=typeof l=="number",{api:o}=H(),f=Ei({refreshKey:a}),{orders:b,total:g,isLoading:m,error:v,page:d,pageSize:p,hasNextPage:x,hasPreviousPage:S,setPage:k,setPageSize:h,customerEmail:N,setCustomerEmail:R,setStatusIn:C,from:w,setFrom:P,to:I,setTo:_,showAbandoned:q,setShowAbandoned:j,setUnfulfilledOnly:U,filters:te,refetch:ce}=f,me=sa.useCallback(()=>o.exportOrdersCsv(te),[o,te]),[T,V]=sa.useState("list"),[A,ne]=sa.useState(null),[re,Me]=sa.useState(""),[Se,Ee]=sa.useState(""),[Ye,ke]=sa.useState(!c&&n?"needs_shipping":"all"),[nt,E]=sa.useState(!1),[M,L]=sa.useState(!!s&&!c),[pe,J]=sa.useState(null);sa.useEffect(()=>{if(!s||c)return;let X=!1;return L(!0),J(null),o.getOrder(s).then(la=>{X||(ne(la),V("detail"))}).catch(()=>{X||J("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{X||L(!1)}),()=>{X=!0}},[o,s,c]);let se=sa.useCallback(X=>{ke(X);let la=Kc[X];C(la.statusIn),U(la.unfulfilledOnly)},[C,U]);sa.useEffect(()=>{n&&!c&&U(!0)},[]);let Fe=sa.useRef(!n);sa.useEffect(()=>{Fe.current||m||(Fe.current=!0,b.length===0&&se("all"))},[m,b.length,se]);let Qe=T==="detail"&&!!A;sa.useEffect(()=>{i?.(Qe)},[Qe,i]);let Xe=(w?1:0)+(I?1:0)+(q?1:0),Et=Xe>0||!!N||!!Se,be=!!w&&!!I&&w>I,$e=!c||!!u,yt=X=>{if(c){u?.();return}ne(X),V("detail")},It=()=>{V("list"),ne(null),ce()},Mt=X=>{let la=X.trim();if(!la){Ee(""),N&&R("");return}if(la.startsWith("#")||/^\d+$/.test(la)){Ee(la),N&&R("");return}Ee(""),R(la)},et=()=>{Me(""),Ee(""),R(""),P(""),_(""),j(!1),E(!1)},ta=Se.replace(/^#/,"").toLowerCase(),Je=ta?b.filter(X=>String(X.order_number??"")===ta||X.id.toLowerCase().startsWith(ta)):b,wt=c?Je.slice(0,l):Je,Xa=A?b.findIndex(X=>X.id===A.id):-1,Mn=Xa>0,ye=Xa>=0&&Xa<b.length-1;if(M)return z("div",{className:t,children:z("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:z(Np,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(T==="detail"&&A)return z("div",{className:t,children:z(Bi,{order:A,onBack:It,onRefund:e,onOrderUpdated:X=>ne(X),allowFulfillment:n,onPrevOrder:Mn?()=>ne(b[Xa-1]):void 0,onNextOrder:ye?()=>ne(b[Xa+1]):void 0,hasPrevOrder:Mn,hasNextOrder:ye},A.id)});let $=Ve("div",{className:"af-mb-4 af-space-y-3",children:[pe&&z("p",{className:"af-text-xs af-text-muted-foreground",children:pe}),Ve("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[z("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(X=>z("button",{type:"button","aria-pressed":Ye===X,onClick:()=>se(X),className:W("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:Pp[X]},X))}),Ve("div",{className:"af-relative af-w-full af-max-w-xs",children:[z(_p,{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"}),z(ae,{type:"text",value:re,onChange:X=>Me(X.target.value),onBlur:()=>Mt(re),onKeyDown:X=>{X.key==="Enter"&&(X.preventDefault(),Mt(re))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),Ve(y,{type:"button",variant:Xe>0?"secondary":"ghost",size:"sm",onClick:()=>E(X=>!X),"aria-expanded":nt,children:[z(kp,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Xe>0&&z(ee,{variant:"secondary",className:"af-ml-2",children:Xe})]}),Et&&z(y,{type:"button",variant:"ghost",size:"sm",onClick:et,children:"Clear filters"}),z(wa,{fetchCsv:me,filename:"orders",disabled:!!Se,className:"af-ml-auto"})]}),(nt||!!w||!!I)&&Ve("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:[z(Oe,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),z(ae,{id:"orders-from",type:"date",value:w,max:I||void 0,onChange:X=>P(X.target.value),className:"af-w-[170px]"}),z(Oe,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),z(ae,{id:"orders-to",type:"date",value:I,min:w||void 0,onChange:X=>_(X.target.value),className:"af-w-[170px]"}),!Kc[Ye].statusIn&&z(y,{type:"button",variant:q?"secondary":"ghost",size:"sm",onClick:()=>j(!q),"aria-pressed":q,children:q?"Hide abandoned":"Show abandoned"})]}),be&&z("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(m)return Ve("div",{className:t,children:[c?null:$,z("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(X=>Ve("div",{className:"af-rounded-md af-border af-p-3",children:[Ve("div",{className:"af-flex af-items-center af-justify-between",children:[z(G,{className:"af-h-4 af-w-16"}),z(G,{className:"af-h-4 af-w-14"})]}),z(G,{className:"af-mt-2 af-h-3 af-w-40"}),z(G,{className:"af-mt-2 af-h-3 af-w-24"})]},X))}),z("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ve(ct,{children:[z(dt,{children:Ve(Ie,{children:[z(K,{children:"Order"}),z(K,{children:"Date"}),z(K,{children:"Customer"}),z(K,{children:"Items"}),z(K,{className:"af-text-right",children:"Total"}),z(K,{children:"Status"}),z(K,{className:"af-w-8"})]})}),z(ut,{"aria-hidden":"true",children:[0,1,2,3,4].map(X=>Ve(Ie,{children:[z(Z,{children:z(G,{className:"af-h-4 af-w-14"})}),z(Z,{children:z(G,{className:"af-h-4 af-w-24"})}),z(Z,{children:z(G,{className:"af-h-4 af-w-40"})}),z(Z,{children:z(G,{className:"af-h-4 af-w-32"})}),z(Z,{children:z(G,{className:"af-ml-auto af-h-4 af-w-16"})}),z(Z,{children:z(G,{className:"af-h-5 af-w-16"})}),z(Z,{})]},X))})]})}),z("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(v)return Ve("div",{className:t,children:[c?null:$,Ve("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[z("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),z(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>ce(),children:"Try again"})]})]});let Pe=Ye!=="all";if(Je.length===0&&d===0)return Et||Pe?Ve("div",{className:t,children:[!c&&$,z(ca,{children:"No orders match these filters."})]}):z("div",{className:t,children:z(tr,{icon:Rp,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!c&&z(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>j(!0),children:"Show abandoned checkouts"})})});let zt=d*p+1,Rn=Math.min((d+1)*p,g);return Ve("div",{className:t,children:[c?null:$,z("div",{className:"af-space-y-3 lg:af-hidden",children:wt.map(X=>Ve("button",{type:"button",onClick:()=>yt(X),disabled:!$e,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${$e?" hover:af-bg-muted/50":""}`,children:[Ve("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[z("span",{className:"af-font-medium",children:os(X)}),z("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:Q(is(X),X.currency)})]}),Ve("div",{className:"af-mt-1 af-min-w-0",children:[Ve("div",{className:"af-truncate af-text-sm",children:[X.customer_email||z("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Mi(X)&&Ve("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Mi(X)]})]}),z("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Yc(X)}),X.amount_refunded>0&&Ve("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Q(X.amount_refunded,X.currency)," refunded"]})]}),Ve("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[z(As,{status:X.status}),z(Cr,{deliveries:X.email_deliveries}),X.is_test&&z(ee,{variant:"outline",children:"Test"}),n&&z(er,{order:X}),z("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Zc(X.created_at)})]})]},X.id))}),z("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ve(ct,{children:[z(dt,{children:Ve(Ie,{children:[z(K,{children:"Order"}),z(K,{children:"Date"}),z(K,{children:"Customer"}),z(K,{children:"Items"}),z(K,{className:"af-text-right",children:"Total"}),z(K,{children:"Status"}),z(K,{className:"af-w-8"})]})}),z(ut,{children:wt.map(X=>Ve(Ie,{onClick:$e?()=>yt(X):void 0,className:$e?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[Ve(Z,{className:"af-whitespace-nowrap af-font-medium",children:[z("button",{type:"button",onClick:la=>{la.stopPropagation(),yt(X)},disabled:!$e,"aria-label":`Open order ${os(X)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${$e?" hover:af-underline":""}`,children:os(X)}),X.is_test&&z(ee,{variant:"outline",className:"af-ml-2",children:"Test"})]}),z(Z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Zc(X.created_at)}),Ve(Z,{className:"af-max-w-[220px]",children:[z("div",{className:"af-truncate",children:X.customer_email||z("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Mi(X)&&z("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Mi(X)})]}),z(Z,{className:"af-max-w-[220px]",children:z("div",{className:"af-truncate af-text-muted-foreground",children:Yc(X)})}),Ve(Z,{className:"af-whitespace-nowrap af-text-right",children:[z("div",{className:"af-font-medium af-tabular-nums",children:Q(is(X),X.currency)}),X.amount_refunded>0&&Ve("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Q(X.amount_refunded,X.currency)," ","refunded"]})]}),z(Z,{children:Ve("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[z(As,{status:X.status}),z(Cr,{deliveries:X.email_deliveries}),n&&z(er,{order:X})]})}),z(Z,{className:"af-w-8 af-text-right",children:z(Gc,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},X.id))})]})}),c?null:Ve("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Ve("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[z("span",{children:ta?`${Je.length} matching this page`:`Showing ${zt}-${Rn} of ${g}`}),Ve(un,{value:String(p),onValueChange:X=>h(Number(X)),children:[z(Qa,{className:"af-w-[70px] af-h-8",children:z(fn,{})}),Ve(en,{children:[z(St,{value:"10",children:"10"}),z(St,{value:"25",children:"25"}),z(St,{value:"50",children:"50"}),z(St,{value:"100",children:"100"})]})]}),z("span",{children:"per page"})]}),Ve("div",{className:"af-flex af-items-center af-gap-2",children:[Ve(y,{variant:"outline",size:"sm",onClick:()=>k(d-1),disabled:!S,children:[z(Sp,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ve(y,{variant:"outline",size:"sm",onClick:()=>k(d+1),disabled:!x,children:["Next",z(Gc,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function bs(e){return z(Cp,{...e},e.maxRows==null?"full":"compact")}import*as ar from"react";import{ChevronLeft as Ap,ChevronRight as Dp,Eye as Op,Search as Lp,Users as Bp}from"lucide-react";import*as Va from"react";function $i({initialPageSize:e=25}={}){let{api:t}=H(),[a,s]=Va.useState([]),[n,r]=Va.useState(0),[i,l]=Va.useState(!0),[u,c]=Va.useState(null),[o,f]=Va.useState(0),[b,g]=Va.useState(e),[m,v]=Va.useState(""),d=Va.useRef(0),p=Va.useCallback(async()=>{let S=++d.current;try{l(!0),c(null);let k={limit:b,offset:o*b};m.trim()&&(k.email=m.trim());let h=await t.getCustomers(k);if(S!==d.current)return;s(h.customers),r(h.total)}catch(k){if(S!==d.current)return;c(k instanceof Error?k:new Error("Failed to fetch customers"))}finally{S===d.current&&l(!1)}},[t,o,b,m]);Va.useEffect(()=>{p()},[p]);let x=Math.ceil(n/b);return{customers:a,total:n,isLoading:i,error:u,page:o,pageSize:b,hasNextPage:o<x-1,hasPreviousPage:o>0,setPage:f,setPageSize:S=>{g(S),f(0)},email:m,setEmail:S=>{v(S),f(0)},refetch:p}}import*as Ls from"react";import{ArrowLeft as Tp,Loader2 as Ep}from"lucide-react";import{jsx as it,jsxs as ba}from"react/jsx-runtime";function Jc(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 Ip(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let a=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return a&&t.push(a),e.country&&t.push(e.country),t}function Ui({customer:e,onBack:t,className:a}){let{api:s}=H(),[n,r]=Ls.useState(null),[i,l]=Ls.useState([]),[u,c]=Ls.useState(!0),[o,f]=Ls.useState(null);Ls.useEffect(()=>{let m=!1;return c(!0),f(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([v,d])=>{m||(r(v),l(d.orders))}).catch(v=>{m||f(v instanceof Error?v.message:"Failed to load customer")}).finally(()=>{m||c(!1)}),()=>{m=!0}},[s,e.id,e.email]);let b=n?.addresses??[],g=n?.order_count??i.length;return ba("div",{className:a,children:[ba("div",{className:"af-mb-6",children:[ba(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[it(Tp,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),it("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),ba("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Jc(e.created_at)]})]}),u?it("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:it(Ep,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):o?it("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o}):ba("div",{className:"af-space-y-6",children:[it($n,{deliveries:n?.email_deliveries}),ba("div",{children:[it("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),ba("div",{className:"af-space-y-1 af-text-sm",children:[ba("div",{className:"af-flex af-gap-2",children:[it("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),it("span",{children:e.email})]}),e.name&&ba("div",{className:"af-flex af-gap-2",children:[it("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),it("span",{children:e.name})]}),e.phone&&ba("div",{className:"af-flex af-gap-2",children:[it("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),it("span",{children:e.phone})]}),ba("div",{className:"af-flex af-gap-2",children:[it("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),it("span",{children:g})]})]})]}),b.length>0&&ba("div",{children:[it("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),it("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(m=>ba("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[m.is_default&&it(ee,{variant:"secondary",className:"af-mb-1",children:"Default"}),Ip(m).map((v,d)=>it("div",{children:v},d))]},m.id))})]}),ba("div",{children:[it("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),i.length===0?it("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):ba(ct,{children:[it(dt,{children:ba(Ie,{children:[it(K,{children:"Date"}),it(K,{children:"Amount"}),it(K,{children:"Status"})]})}),it(ut,{children:i.map(m=>ba(Ie,{children:[it(Z,{className:"af-text-muted-foreground",children:Jc(m.created_at)}),it(Z,{children:Q(is(m),m.currency)}),it(Z,{children:it(Ds,{status:m.status})})]},m.id))})]})]})]})]})}import{Fragment as Mp,jsx as He,jsxs as Jt}from"react/jsx-runtime";function Fp(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 Vi({className:e}){let{customers:t,total:a,isLoading:s,error:n,page:r,pageSize:i,hasNextPage:l,hasPreviousPage:u,setPage:c,setPageSize:o,email:f,setEmail:b,refetch:g}=$i(),{api:m}=H(),v=ar.useCallback(()=>m.exportCustomersCsv(),[m]),[d,p]=ar.useState("list"),[x,S]=ar.useState(null),[k,h]=ar.useState(""),N=I=>{S(I),p("detail")},R=()=>{p("list"),S(null),g()};if(d==="detail"&&x)return He("div",{className:e,children:He(Ui,{customer:x,onBack:R})});let C=Jt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[He(ae,{type:"email",value:k,onChange:I=>h(I.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),b(k.trim()))}}),Jt(y,{type:"button",variant:"outline",size:"sm",onClick:()=>b(k.trim()),children:[He(Lp,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),f&&He(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),b("")},children:"Clear"}),He(wa,{fetchCsv:v,filename:"customers",className:"af-ml-auto"})]});if(s)return Jt("div",{className:e,children:[C,He("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:He("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return Jt("div",{className:e,children:[C,He("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Jt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&r===0)return Jt("div",{className:e,children:[f&&C,Jt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[He(Bp,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),He("p",{className:"af-text-muted-foreground af-text-center",children:f?"No customers match that email.":Jt(Mp,{children:["No customers yet.",He("br",{}),"Customers appear here after their first purchase."]})})]})]});let w=r*i+1,P=Math.min((r+1)*i,a);return Jt("div",{className:e,children:[C,Jt(ct,{children:[He(dt,{children:Jt(Ie,{children:[He(K,{children:"Email"}),He(K,{children:"Name"}),He(K,{children:"Phone"}),He(K,{children:"Customer since"}),He(K,{className:"af-text-right",children:"Actions"})]})}),He(ut,{children:t.map(I=>Jt(Ie,{children:[He(Z,{className:"af-font-medium",children:I.email}),He(Z,{children:I.name||He("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),He(Z,{children:I.phone||He("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),He(Z,{className:"af-text-muted-foreground",children:Fp(I.created_at)}),He(Z,{className:"af-text-right",children:He(y,{variant:"ghost",size:"icon",onClick:()=>N(I),title:"View customer",children:He(Op,{className:"af-h-4 af-w-4"})})})]},I.id))})]}),Jt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Jt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Jt("span",{children:["Showing ",w,"-",P," of ",a]}),Jt(un,{value:String(i),onValueChange:I=>o(Number(I)),children:[He(Qa,{className:"af-w-[70px] af-h-8",children:He(fn,{})}),Jt(en,{children:[He(St,{value:"10",children:"10"}),He(St,{value:"25",children:"25"}),He(St,{value:"50",children:"50"}),He(St,{value:"100",children:"100"})]})]}),He("span",{children:"per page"})]}),Jt("div",{className:"af-flex af-items-center af-gap-2",children:[Jt(y,{variant:"outline",size:"sm",onClick:()=>c(r-1),disabled:!u,children:[He(Ap,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Jt(y,{variant:"outline",size:"sm",onClick:()=>c(r+1),disabled:!l,children:["Next",He(Dp,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as je from"react";import{ArrowLeft as $p,ChevronLeft as Up,ChevronRight as Xc,Copy as Vp,Download as Hp,ExternalLink as zp,FileText as td,Loader2 as jp,Search as qp}from"lucide-react";import*as Xt from"react";function nr({initialPageSize:e=25,refreshKey:t,includeAggregates:a=!1}={}){let{api:s}=H(),[n,r]=Xt.useState([]),[i,l]=Xt.useState(0),[u,c]=Xt.useState(null),[o,f]=Xt.useState(!0),[b,g]=Xt.useState(null),[m,v]=Xt.useState(0),[d,p]=Xt.useState(e),[x,S]=Xt.useState(void 0),[k,h]=Xt.useState(""),[N,R]=Xt.useState(""),[C,w]=Xt.useState(""),[P,I]=Xt.useState(""),[_,q]=Xt.useState(""),j=x?x.join(","):"",U=Xt.useRef(0),te=Xt.useCallback(async()=>{let me=++U.current;f(!0),g(null);try{let T={labels:j?j.split(","):void 0,customerEmail:k||void 0,q:N||void 0,from:C||void 0,to:P||void 0,retainerId:_||void 0,includeAggregates:a,limit:d,offset:m*d},V=await s.getInvoices(T);if(me!==U.current)return;if(m>0&&m*d>=V.total){v(Math.max(0,Math.ceil(V.total/d)-1));return}r(V.invoices),l(V.total),a&&c(V.aggregates??null)}catch(T){if(me!==U.current)return;g(T instanceof Error?T:new Error("Failed to fetch invoices"))}finally{me===U.current&&f(!1)}},[s,j,k,N,C,P,_,m,d,a]);Xt.useEffect(()=>{te()},[te,t]);let ce=me=>T=>{v(0),me(T)};return{invoices:n,total:i,aggregates:u,isLoading:o,error:b,page:m,pageSize:d,hasNextPage:(m+1)*d<i,hasPreviousPage:m>0,setPage:v,setPageSize:ce(p),labels:x,setLabels:ce(S),customerEmail:k,setCustomerEmail:ce(h),q:N,setQ:ce(R),from:C,setFrom:ce(w),to:P,setTo:ce(I),retainerId:_,setRetainerId:ce(q),clearFilters:()=>{v(0),S(void 0),h(""),R(""),w(""),I(""),q("")},refetch:te}}import{Fragment as Xp,jsx as B,jsxs as oe}from"react/jsx-runtime";var Wp={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 tl(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Wp[e.label]??e.label}function Gp(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 el={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Kp={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Or({invoice:e,className:t}){return oe("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[B(ee,{variant:Gp(e.label),className:t,children:tl(e)}),e.collection_method==="charge_automatically"&&B(ee,{variant:"secondary",children:"Managed in Stripe"})]})}function ji({delivery:e,className:t}){if(!e)return null;let a=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return B(ee,{variant:a,className:t,children:el[e.state]??e.state})}function sr(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function hn(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t);return Number.isNaN(a.getTime())?e:a.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Qc={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Hi={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},Xo=100,Qo=5e3;async function Zp(e,t){let a=[],s=0;for(let n=0;n<Qo;n+=Xo){let r=await e.getInvoices({...t,limit:Xo,offset:n});if(s=r.total,a.push(...r.invoices),r.invoices.length<Xo||a.length>=s)break}return{invoices:a.slice(0,Qo),total:s,truncated:s>a.length||s>Qo}}function ad(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],a=e.map(s=>[s.id,sr(s),tl(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),Q(s.amount_subtotal,s.currency),Q(s.tax_total,s.currency),Q(s.amount_total,s.currency),s.amount_due===null?"":Q(s.amount_due,s.currency),s.amount_paid===null?"":Q(s.amount_paid,s.currency),Q(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?"":Q(s.discount_total,s.currency),s.collection_method??""]);return[t,...a].map(s=>s.map(_c).join(",")).join(`
5
- `)}function Yp(e){hi(new Blob([ad(e)],{type:"text/csv;charset=utf-8"}),bi("invoices"))}function Jp({className:e,refreshKey:t,initialInvoiceId:a,onDetailOpenChange:s,onConnectStripe:n,onUpgradePlan:r,needsPaidPlan:i=!1,retainerFilter:l=null,onClearRetainerFilter:u,maxRows:c,onViewAll:o}){let f=typeof c=="number",{api:b}=H(),{invoices:g,total:m,isLoading:v,error:d,page:p,pageSize:x,hasNextPage:S,hasPreviousPage:k,setPage:h,labels:N,setLabels:R,customerEmail:C,setCustomerEmail:w,q:P,setQ:I,from:_,setFrom:q,to:j,setTo:U,retainerId:te,setRetainerId:ce,refetch:me}=nr({refreshKey:t}),[T,V]=je.useState(typeof c=="number"?"all":"open"),[A,ne]=je.useState(""),[re,Me]=je.useState(null),Se=je.useRef(0),Ee=!f||!!o,Ye=je.useCallback($=>{if(f){o?.();return}Se.current++,nt(!1),Me($)},[f,o]),[ke,nt]=je.useState(!1),[E,M]=je.useState(0),[L,pe]=je.useState(null),[J,se]=je.useState(!1),[Fe,Qe]=je.useState(0);je.useEffect(()=>{Me($=>{if(!$)return $;let Pe=g.find(zt=>zt.id===$.id);return Pe&&Pe!==$?Pe:$})},[g]);let[Xe,Et]=je.useState(!1),[be,$e]=je.useState(null),yt=async()=>{if(!Xe){Et(!0),$e(null);try{let{invoices:$,total:Pe,truncated:zt}=await Zp(b,{labels:N,customerEmail:C,q:P,from:_,to:j,retainerId:te});Yp($),$e(zt?`Exported the first ${$.length.toLocaleString()} of ${Pe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{$e("Couldn't export \u2014 try again.")}finally{Et(!1)}}},It=!C&&!P&&!_&&!j&&!te,[Mt,et]=je.useState(null);je.useEffect(()=>{if(v||m>0||!It||T!=="open")return;let $=!1;return b.getInvoices({limit:1}).then(Pe=>{$||et(Pe.total>0)}).catch(()=>{$||et(!0)}),()=>{$=!0}},[b,v,m,It,T,t]),je.useEffect(()=>{R(f?Hi.all:Hi.open)},[]),je.useEffect(()=>{let $=l?.id??"";$!==te&&(ce($),$&&(V("all"),R(Hi.all),w(""),I(""),ne(""),q(""),U("")))},[l?.id]),je.useEffect(()=>{let $=!1;return se(!1),b.getInvoiceSettings().then(Pe=>{$||pe({payments_active:Pe.payments_active,blocked:Pe.blocked})}).catch(()=>{$||se(!0)}),()=>{$=!0}},[b,t,Fe]),je.useEffect(()=>{if(!a||f)return;let $=!1,Pe=Se.current;return nt(!1),b.getInvoice(a).then(zt=>{!$&&Pe===Se.current&&Me(zt)}).catch(()=>{!$&&Pe===Se.current&&nt(!0)}),()=>{$=!0}},[b,a,E,f]),je.useEffect(()=>{s?.(re!==null)},[re,s]);let ta=$=>{V($),R(Hi[$])},Je=$=>{let Pe=$.trim();if(!Pe){P&&I(""),C&&w("");return}if(Pe.includes("@")){P&&I(""),w(Pe);return}C&&w(""),I(Pe.replace(/^#/,""))},wt=g,Xa=f?wt.slice(0,c):wt,Mn=ke&&oe("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. ",B(y,{type:"button",variant:"link",size:"sm",onClick:()=>M($=>$+1),children:"Retry opening invoice"})]});if(re)return oe("div",{className:e,children:[Mn,B(al,{invoice:re,refreshKey:t,onBack:()=>{Ye(null),me()}},re.id)]});let ye=oe("div",{className:"af-mb-4 af-space-y-3",children:[J&&oe("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",B(y,{type:"button",variant:"link",size:"sm",onClick:()=>Qe($=>$+1),children:"Retry setup check"})]}),Mn,L?.blocked&&oe("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",L.blocked.reason?`: ${L.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),l&&oe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[oe(ee,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",l.label]}),u&&B(y,{type:"button",variant:"link",size:"sm",onClick:u,children:"Clear schedule filter"})]}),oe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[B("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(Qc).map($=>B("button",{type:"button","aria-pressed":T===$,onClick:()=>ta($),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",T===$?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Qc[$]},$))}),oe("div",{className:"af-relative af-w-full af-max-w-xs",children:[B(qp,{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"}),B(ae,{type:"text",value:A,onChange:$=>ne($.target.value),onBlur:()=>Je(A),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),Je(A))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),oe("div",{className:"af-flex af-items-center af-gap-2",children:[B(Oe,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),B(ae,{id:"invoices-from",type:"date",value:_,max:j||void 0,onChange:$=>q($.target.value),className:"af-invoice-date af-w-[150px]"})]}),oe("div",{className:"af-flex af-items-center af-gap-2",children:[B(Oe,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),B(ae,{id:"invoices-to",type:"date",value:j,min:_||void 0,onChange:$=>U($.target.value),className:"af-invoice-date af-w-[150px]"})]}),oe(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void yt(),disabled:Xe||v||!!d||m===0,"aria-busy":Xe,children:[B(Hp,{className:"af-h-4 af-w-4 af-mr-1"}),Xe?"Exporting\u2026":"Export CSV (all matching)"]})]}),be&&B("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:be})]});return v?oe("div",{className:e,children:[f?null:ye,B("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map($=>oe("div",{className:"af-rounded-md af-border af-p-3",children:[oe("div",{className:"af-flex af-items-center af-justify-between",children:[B(G,{className:"af-h-4 af-w-20"}),B(G,{className:"af-h-4 af-w-16"})]}),B(G,{className:"af-mt-2 af-h-3 af-w-40"})]},$))})]}):d?oe("div",{className:e,children:[f?null:ye,oe("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",B(y,{type:"button",variant:"link",size:"sm",onClick:()=>void me(),children:"Retry"})]})]}):m===0&&It&&(T==="all"||Mt===!1)&&(T==="open"||T==="all")?L?.blocked?oe("div",{className:e,children:[f?null:ye,B(zi,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):i?oe("div",{className:e,children:[f?null:ye,B(zi,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):L&&!L.payments_active?oe("div",{className:e,children:[f?null:ye,B(zi,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):oe("div",{className:e,children:[f?null:ye,B(zi,{heading:"No invoices yet",body:!L||J?"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."})]}):oe("div",{className:e,children:[f?null:ye,Xa.length===0?B("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."}):oe(Xp,{children:[B("div",{className:"af-space-y-3 lg:af-hidden",children:Xa.map($=>oe("button",{type:"button",onClick:()=>Ye($),disabled:!Ee,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ee?" hover:af-bg-muted/50":""}`,children:[oe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[B("span",{className:"af-font-medium",children:sr($)}),B(Or,{invoice:$})]}),B("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:$.customer_name??$.customer_email??"\u2014"}),$.delivery&&B("div",{className:"af-mt-1",children:B(ji,{delivery:$.delivery})}),oe("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[B("span",{children:$.collection_method==="charge_automatically"?"Automatic collection":$.due_at?`Due ${hn($.due_at)}`:"Due on receipt"}),B("span",{className:"af-font-medium af-tabular-nums",children:Q($.amount_due??$.amount_total,$.currency)})]})]},$.id))}),B("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(ct,{children:[B(dt,{children:oe(Ie,{children:[B(K,{children:"Invoice"}),B(K,{children:"Created"}),B(K,{children:"Customer"}),B(K,{children:"Due"}),B(K,{className:"af-text-right",children:"Amount"}),B(K,{children:"Status"}),B(K,{children:"Delivery"}),B(K,{className:"af-w-8"})]})}),B(ut,{children:Xa.map($=>oe(Ie,{className:Ee?"af-cursor-pointer":void 0,onClick:Ee?()=>Ye($):void 0,children:[B(Z,{className:"af-font-medium",children:B("button",{type:"button",disabled:!Ee,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ee?" hover:af-underline":""}`,onClick:Pe=>{Pe.stopPropagation(),Ye($)},"aria-label":`Open invoice ${sr($)}`,children:sr($)})}),B(Z,{children:hn($.created_at)}),oe(Z,{children:[B("div",{children:$.customer_name??"\u2014"}),B("div",{className:"af-text-xs af-text-muted-foreground",children:$.customer_email})]}),B(Z,{children:$.collection_method==="charge_automatically"?"Automatic":$.due_at?hn($.due_at):"On receipt"}),B(Z,{className:"af-text-right af-tabular-nums",children:Q($.amount_due??$.amount_total,$.currency)}),B(Z,{children:B(Or,{invoice:$})}),B(Z,{children:B(ji,{delivery:$.delivery})}),B(Z,{children:B(Xc,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},$.id))})]})}),f?null:oe("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[oe("span",{children:[m," invoice",m===1?"":"s"]}),oe("div",{className:"af-flex af-items-center af-gap-1",children:[B(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(p-1),disabled:!k,"aria-label":"Previous page",children:B(Up,{className:"af-h-4 af-w-4"})}),oe("span",{className:"af-tabular-nums",children:[p*x+1,"\u2013",Math.min((p+1)*x,m)]}),B(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(p+1),disabled:!S,"aria-label":"Next page",children:B(Xc,{className:"af-h-4 af-w-4"})})]})]})]})]})}function zi({heading:e,body:t,action:a}){return B(tr,{icon:td,heading:e,body:t,action:a})}function ys(e){return B(Jp,{...e},e.maxRows==null?"full":"compact")}var ls="af-text-xs af-text-muted-foreground";function ed(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function al({invoice:e,onBack:t,refreshKey:a,className:s}){let{api:n}=H(),r=je.useRef(null);je.useEffect(()=>{r.current?.focus()},[e.id]);let[i,l]=je.useState(!1),[u,c]=je.useState(null),[o,f]=je.useState(!1),[b,g]=je.useState(!1),m=je.useRef(0),[v,d]=je.useState(null),[p,x]=je.useState(!1),[S,k]=je.useState(0);je.useEffect(()=>{let _=!1;return x(!1),n.getInvoice(e.id).then(q=>{_||d({source:e,value:q})}).catch(()=>{_||x(!0)}),()=>{_=!0}},[n,e,a,S]);let h=v?.source===e?v.value:e,N=h.collection_method==="charge_automatically";je.useEffect(()=>(m.current++,c(null),f(!1),g(!1),l(!1),()=>{m.current++}),[n,h,a]);let R=_=>_==null?"\u2014":Q(_,h.currency),C=async()=>{if(!(!h.pay_url||!ed()))try{await navigator.clipboard.writeText(h.pay_url),l(!0),setTimeout(()=>l(!1),1500)}catch{}},w=async()=>{if(u){c(null);return}let _=++m.current;g(!1),f(!0);try{let q=await n.getInvoicePreview(h.id);_===m.current&&c(q)}catch{_===m.current&&g(!0)}finally{_===m.current&&f(!1)}},P=h.bill_to,I=P?[P.company,P.name,P.address?.line1,P.address?.line2,[P.address?.city,P.address?.state,P.address?.postal_code].filter(Boolean).join(", "),P.address?.country,P.tax_id?`${P.tax_id.value}`:null,P.po_number?`PO ${P.po_number}`:null,P.service_period?`Service period: ${P.service_period}`:null].filter(_=>!!_&&_.length>0):[];return oe("div",{className:s,children:[oe("div",{className:"af-mb-4",children:[oe(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[B($p,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),oe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[oe("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",sr(h)]}),B(Or,{invoice:h}),B(ji,{delivery:h.delivery})]}),oe("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[h.customer_name??h.customer_email,h.customer_name&&h.customer_email?` \xB7 ${h.customer_email}`:""]})]}),p&&oe("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. ",B(y,{type:"button",variant:"link",size:"sm",onClick:()=>k(_=>_+1),children:"Retry details"})]}),h.label==="failed"&&B("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),h.label==="creating"&&B("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."}),oe("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[oe("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[oe("section",{className:"af-rounded-md af-border af-p-4",children:[oe(ct,{children:[B(dt,{children:oe(Ie,{children:[B(K,{children:"Description"}),B(K,{className:"af-text-right",children:"Qty"}),B(K,{className:"af-text-right",children:"Amount"})]})}),B(ut,{children:h.line_items.map((_,q)=>oe(Ie,{children:[B(Z,{style:{overflowWrap:"anywhere"},children:_.description}),B(Z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_.quantity}),B(Z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:R(_.amount)})]},q))})]}),oe("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[B(hs,{label:"Subtotal",value:R(h.amount_subtotal)}),(h.discount_total??0)>0&&B(hs,{label:"Discount",value:`-${R(h.discount_total)}`}),h.tax_total>0&&B(hs,{label:h.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:R(h.tax_total)}),B(hs,{label:"Total",value:R(h.amount_total),strong:!0}),h.credit_applied>0&&B(hs,{label:"Credit applied",value:`-${R(h.credit_applied)}`}),h.amount_due!==null&&h.amount_due!==h.amount_total&&B(hs,{label:"Amount due",value:R(h.amount_due),strong:!0}),h.amount_paid!==null&&h.amount_paid>0&&B(hs,{label:"Amount paid",value:R(h.amount_paid)}),h.amount_refunded>0&&B(hs,{label:"Refunded",value:R(h.amount_refunded)})]}),h.credit_notes?.length>0&&oe("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[B("div",{className:ls,children:"Credit notes"}),h.credit_notes.map(_=>oe("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[oe("span",{className:"af-text-muted-foreground",children:[hn(_.created_at)," \xB7 ",_.origin==="dashboard"?"issued in Stripe":"refund",_.stripe_credit_note_id?"":" \xB7 being created"]}),oe("span",{className:"af-tabular-nums",children:["-",Q(_.amount,_.currency)]})]},_.id))]})]}),(h.note||h.footer)&&oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[h.note&&oe("div",{children:[B("div",{className:ls,children:"Note"}),B("div",{className:"af-whitespace-pre-wrap af-break-words",children:h.note})]}),h.footer&&oe("div",{children:[B("div",{className:ls,children:"Footer"}),B("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:h.footer})]})]}),u&&!N&&oe("section",{className:"af-rounded-md af-border af-p-4",children:[oe("div",{className:W(ls,"af-break-words"),children:["Email preview \u2014 ",u.subject]}),B("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),B("iframe",{title:"Invoice email preview",srcDoc:u.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),oe("div",{className:"af-min-w-0 af-space-y-4",children:[oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[B(bn,{label:"Created",value:hn(h.created_at)}),B(bn,{label:"Due",value:h.collection_method==="charge_automatically"?"Managed in Stripe":h.due_at?hn(h.due_at):"On receipt"}),h.paid_at&&B(bn,{label:"Paid",value:hn(h.paid_at)}),h.payment_method&&B(bn,{label:"Paid by",value:h.paid_out_of_band?`${h.payment_method} (recorded outside Stripe)`:h.payment_method}),h.payment_state!=="none"&&B(bn,{label:"Payment",value:h.payment_state==="processing"?"Processing":h.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),h.delivery&&B(bn,{label:"Delivery",value:`${el[h.delivery.state]} \xB7 ${h.delivery.recipient}`}),h.marked_uncollectible_at&&B(bn,{label:"Written off",value:hn(h.marked_uncollectible_at)}),h.correction_reason&&B(bn,{label:"Correction",value:h.correction_reason}),h.replaced_by_order_id&&B(bn,{label:"Replaced by",value:h.replaced_by_order_id}),h.collection_method==="charge_automatically"?B(bn,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):h.retainer_id&&B(bn,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),h.replaces_order_id&&B(bn,{label:"Replaces",value:h.replaces_order_id})]}),oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[B("div",{className:ls,children:"Reminders"}),N?B("div",{children:"View automatic payment reminders in Stripe."}):h.reminders.disabled?B("div",{children:"Off for this invoice."}):h.reminders.paused_until?oe("div",{children:["Paused until ",hn(h.reminders.paused_until),"."]}):h.reminders.next_at?oe("div",{children:["Next on ",hn(h.reminders.next_at),"."]}):h.reminders.final_sent_at?oe("div",{children:["Final reminder sent ",hn(h.reminders.final_sent_at),"."]}):B("div",{children:"None scheduled."}),!N&&oe("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",h.reminders.schedule.length===0?"none":h.reminders.schedule.map(_=>_<0?`${-_}d before`:_===0?"due day":`${_}d after`).join(", ")]})]}),h.communications&&h.communications.length>0&&oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[B("div",{className:ls,children:"Email delivery history"}),h.communications.map(_=>oe("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[oe("span",{className:"af-min-w-0 af-break-words",children:[Kp[_.kind]??_.kind,_.kind==="reminder"&&_.slot!==null?` #${_.slot}`:"",oe("span",{className:"af-text-muted-foreground",children:[" \xB7 ",_.recipient]})]}),oe("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[el[_.state]??_.state," \xB7 ",hn(_.state_at??_.created_at)]})]},_.id))]}),I.length>0&&oe("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[B("div",{className:ls,children:"Bill to"}),I.map((_,q)=>B("div",{className:"af-break-words",children:_},q))]}),oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[h.pay_url&&oe(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void C(),disabled:!ed(),children:[B(Vp,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Copied":N?"Copy invoice link":"Copy pay link"]}),h.pdf_url&&B(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:oe("a",{href:h.pdf_url,target:"_blank",rel:"noreferrer",children:[B(zp,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!N&&oe(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void w(),disabled:o,children:[o?B(jp,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):B(td,{className:"af-h-4 af-w-4 af-mr-1"}),u?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!N&&B("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),h.pay_url&&B("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:h.pay_url}),B("p",{className:"af-text-xs af-text-muted-foreground",children:N?"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 bn({label:e,value:t}){return oe("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[B("span",{className:W(ls,"af-shrink-0"),children:e}),B("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function hs({label:e,value:t,strong:a}){return oe("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[B("dt",{className:W(ls,a&&"af-font-medium af-text-foreground"),children:e}),B("dd",{className:W("af-tabular-nums",a&&"af-font-semibold"),children:t})]})}import{Repeat as Qp}from"lucide-react";import{jsx as Wt,jsxs as En}from"react/jsx-runtime";var eg={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},nd={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function tg(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 sd(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>nd[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>nd[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":eg[e.status]}function rd(e){let t=e.interval==="year"?"every year":"every month";return`${Q(e.amount,e.currency)} ${t}`}function ag(e){return e.status==="canceled"?`Ended ${qi(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${qi(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 ${qi(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${qi(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function qi(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),a=new Date(t);return Number.isNaN(a.getTime())?e.slice(0,10):a.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function nl({retainer:e,className:t}){return Wt(ee,{variant:tg(e.status),className:W("af-max-w-full af-whitespace-normal af-break-words",t),children:sd(e)})}function rr({retainers:e,isLoading:t,error:a,onRetry:s,onShowCycles:n,activeRetainerId:r,total:i,endedTotal:l=0,isLoadingMore:u=!1,onLoadMore:c,includeEnded:o=!1,onIncludeEndedChange:f,exportCsv:b,className:g}){let m=!!f;if(!t&&!a&&e.length===0&&!(m&&(o||l>0)))return null;let v=i!==void 0?Math.max(0,i-e.length):0;return En("section",{className:W("af-mb-6",g),"aria-label":"Recurring invoices",children:[En("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[Wt(Qp,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),Wt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),Wt("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),m&&Wt(y,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":o,onClick:()=>f?.(!o),children:o?"Hide ended recurring invoices":l>0&&e.length===0?`Show ended recurring invoices (${l})`:"Show ended recurring invoices"}),b&&Wt(wa,{fetchCsv:b,filename:"retainers",className:m?void 0:"af-ml-auto"})]}),a?En("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",Wt(y,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?Wt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(d=>En("div",{className:"af-rounded-md af-border af-p-3",children:[Wt(G,{className:"af-h-4 af-w-48"}),Wt(G,{className:"af-mt-2 af-h-3 af-w-32"})]},d))}):e.length===0?Wt("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:o?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):Wt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(d=>{let p=r===d.id;return En("li",{className:W("af-rounded-md af-border af-p-3",p&&"af-border-primary af-bg-muted/40"),children:[En("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[En("div",{className:"af-min-w-0",children:[Wt("div",{className:"af-truncate af-font-medium",children:d.customer_name??d.customer_email??"\u2014"}),Wt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:d.description})]}),Wt(nl,{retainer:d})]}),d.collection_method==="charge_automatically"?En("div",{className:"af-mt-2 af-space-y-1",children:[Wt(ee,{variant:"secondary",children:"Managed in Stripe"}),Wt("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."})]}):Wt("div",{className:"af-mt-2 af-text-sm",children:rd(d)}),En("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:[En("span",{children:[ag(d)," \xB7 ",d.cycles.count===0?"no invoices yet":`${d.cycles.paid} paid${d.cycles.open>0?`, ${d.cycles.open} open`:""}`]}),d.cycles.count>0&&Wt(y,{type:"button",variant:p?"secondary":"ghost",size:"sm",onClick:()=>n(d),"aria-pressed":p,children:p?"Showing invoices":"View invoices"})]}),d.status==="failed"&&d.operation?.last_error&&En("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",d.operation.last_error,". Ask in the chat to try again."]})]},d.id)})}),!t&&!a&&v>0&&c&&Wt("div",{className:"af-mt-2",children:Wt(y,{type:"button",variant:"outline",size:"sm",onClick:c,disabled:u,children:u?"Loading\u2026":`Load more (${v} more)`})})]})}import*as od from"react";import{AlertTriangle as id,CheckCircle2 as ng,CreditCard as sl,Loader2 as sg,RefreshCw as rg}from"lucide-react";import{jsx as kt,jsxs as da}from"react/jsx-runtime";function ir({onConnectStripe:e,onUpgradePlan:t,whenActive:a,className:s}){let{status:n,isLoading:r,error:i,refetch:l}=gs(),[u,c]=od.useState(!1),o=async()=>{c(!0);try{await l()}finally{c(!1)}};return r&&!n?kt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:kt("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!n?kt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:da("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):n.status==="active"?a!==void 0?kt("div",{className:s,children:a}):kt("div",{className:s,children:da("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:[kt(ng,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),da("div",{children:[kt("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),da("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",n.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):da("div",{className:`af-space-y-4 ${s||""}`,children:[n.reason==="needs_stripe"&&da("div",{className:"af-space-y-3",children:[da("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[kt(sl,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),da("div",{children:[kt("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),kt("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?da(y,{onClick:e,children:[kt(sl,{className:"af-h-4 af-w-4 af-mr-1"}),n.stripe_account_connected?"Finish setting up":"Set up payments"]}):kt("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),n.reason==="needs_paid_plan"&&da("div",{className:"af-space-y-3",children:[da("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[kt(id,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),da("div",{children:[kt("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),kt("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?kt(y,{onClick:t,children:"Upgrade plan"}):kt("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),n.reason==="account_disabled"&&da("div",{className:"af-space-y-3",children:[da("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:[kt(id,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),da("div",{children:[kt("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),n.stripe_account_connected?kt("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."}):kt("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."})]})]}),da("div",{className:"af-flex af-gap-2",children:[e&&n.stripe_account_connected&&da(y,{onClick:e,children:[kt(sl,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),da(y,{variant:"outline",onClick:o,disabled:u,children:[u?kt(sg,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):kt(rg,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as Ta from"react";function rl(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function or({includeStats:e=!1,refreshKey:t}={}){let{api:a}=H(),[s,n]=Ta.useState([]),[r,i]=Ta.useState(!0),[l,u]=Ta.useState(null),c=Ta.useRef(0),o=Ta.useCallback(async()=>{let d=++c.current;try{i(!0),u(null);let p=await a.getProducts(e?{include:"stats"}:{});if(d!==c.current)return;n(p)}catch(p){if(d!==c.current)return;u(p instanceof Error?p:new Error("Failed to fetch products"))}finally{d===c.current&&i(!1)}},[a,e,t]);Ta.useEffect(()=>{o()},[o]);let f=Ta.useCallback(async d=>{let p=await a.createProduct(d);return n(x=>[p,...x]),p},[a]),b=Ta.useCallback(async(d,p)=>{let x=await a.updateProduct(d,p);return n(S=>rl(S,d,x)),x},[a]),g=Ta.useCallback(async d=>{await a.deleteProduct(d),n(p=>p.filter(x=>x.id!==d))},[a]),m=Ta.useCallback(async(d,p)=>{let x=await a.attachProductFile(d,p);return n(S=>rl(S,d,x)),x},[a]),v=Ta.useCallback(async(d,p)=>{let x=await a.attachProductFileFromUrl(d,p);return n(S=>rl(S,d,x)),x},[a]);return{products:s,isLoading:r,error:l,refetch:o,createProduct:f,updateProduct:b,deleteProduct:g,attachProductFile:m,attachProductFileFromUrl:v}}import*as Ea from"react";var il=["creating","active","paused","canceling"],ig=["canceled","failed"],og={statuses:il},lg={};function lr({refreshKey:e,includeEnded:t=!1,limit:a=50}={}){let{api:s}=H(),[n,r]=Ea.useState([]),[i,l]=Ea.useState(0),[u,c]=Ea.useState(0),[o,f]=Ea.useState(!0),[b,g]=Ea.useState(!1),[m,v]=Ea.useState(null),[d,p]=Ea.useState(t),x=Ea.useRef(0),S=Ea.useCallback(async()=>{let h=++x.current;f(!0),g(!1),v(null);try{let N=await s.getRetainers({statuses:d?void 0:il,limit:a,offset:0});if(h!==x.current)return;if(r(N.retainers),l(N.total),!d&&N.total===0){let R=await s.getRetainers({statuses:ig,limit:1,offset:0});if(h!==x.current)return;c(R.total)}else c(0)}catch(N){if(h!==x.current)return;v(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{h===x.current&&f(!1)}},[s,d,a]);Ea.useEffect(()=>{S()},[S,e]);let k=Ea.useCallback(async()=>{if(o||b||n.length>=i)return;let h=x.current;g(!0);try{let N=await s.getRetainers({statuses:d?void 0:il,limit:a,offset:n.length});if(h!==x.current)return;r(R=>{let C=new Set(R.map(w=>w.id));return[...R,...N.retainers.filter(w=>!C.has(w.id))]}),l(N.total)}catch(N){if(h!==x.current)return;v(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{h===x.current&&g(!1)}},[s,d,a,o,b,n.length,i]);return{retainers:n,total:i,endedTotal:u,hasMore:n.length<i,isLoading:o,isLoadingMore:b,error:m,includeEnded:d,setIncludeEnded:p,loadMore:k,refetch:S,filters:d?lg:og}}import{Fragment as vg,jsx as gt,jsxs as Ha}from"react/jsx-runtime";function ld({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:n}){let[r,i]=cr.useState(t),[l,u]=cr.useState("list"),[c,o]=cr.useState(null),f=or(),{status:b,error:g}=gs(),m=b?.currency,v=S=>{o(S),u("edit")},d=()=>{o(null),u("create")},p=()=>{u("list"),o(null)},x=S=>{o(S),u("edit")};return Ha("div",{className:e,children:[Ha("div",{className:"af-mb-6",children:[gt("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),gt("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Ha(di,{value:r,onValueChange:S=>i(S),children:[Ha(Pr,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Ha(kn,{value:"products",className:"af-gap-2",children:[gt(ug,{className:"af-h-4 af-w-4"}),"Products"]}),Ha(kn,{value:"orders",className:"af-gap-2",children:[gt(fg,{className:"af-h-4 af-w-4"}),"Orders"]}),Ha(kn,{value:"invoices",className:"af-gap-2",children:[gt(dg,{className:"af-h-4 af-w-4"}),"Invoices"]}),Ha(kn,{value:"customers",className:"af-gap-2",children:[gt(pg,{className:"af-h-4 af-w-4"}),"Customers"]}),gt(kn,{value:"promos",children:"Promo codes"}),Ha(kn,{value:"setup",className:"af-gap-2",children:[gt(mg,{className:"af-h-4 af-w-4"}),"Setup"]})]}),gt(Pn,{value:"products",children:l==="list"?gt(Pi,{productsState:f,onSelectProduct:v,onCreateProduct:d}):Ha("div",{children:[Ha("div",{className:"af-mb-6",children:[Ha(y,{variant:"ghost",size:"sm",onClick:p,className:"af-mb-2 af--ml-2",children:[gt(cg,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),gt("h3",{className:"af-text-lg af-font-semibold",children:l==="create"?"New Product":c?.name})]}),l==="create"&&!m?gt("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?Ha("div",{className:"af-text-destructive",children:["Error: ",g.message]}):gt("div",{className:"af-text-muted-foreground",children:"Loading..."})}):gt(Ti,{productsState:f,product:l==="edit"?c:null,currency:m??"usd",onSaved:x},l==="edit"?c?.id??"edit":"new")]})}),gt(Pn,{value:"orders",children:gt(bs,{onRefund:s})}),gt(Pn,{value:"invoices",children:gt(gg,{onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),gt(Pn,{value:"customers",children:gt(Vi,{})}),gt(Pn,{value:"promos",children:gt(Qs,{})}),gt(Pn,{value:"setup",children:gt(ir,{onConnectStripe:a,onUpgradePlan:n})})]})]})}function gg({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a}){let s=lr(),[n,r]=cr.useState(null),[i,l]=cr.useState(!1);return Ha(vg,{children:[!i&&gt(rr,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:n?.id??null,onShowCycles:u=>r(c=>c?.id===u.id?null:u),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),gt(ys,{onDetailOpenChange:l,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}import*as dd from"react";import*as jn from"react";function dr({refreshKey:e}={}){let{api:t}=H(),[a,s]=jn.useState(null),[n,r]=jn.useState(!0),[i,l]=jn.useState(null),u=jn.useRef(0),c=jn.useCallback(async()=>{let o=++u.current;try{r(!0),l(null);let f=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(o!==u.current)return;s(f)}catch(f){if(o!==u.current)return;l(f instanceof Error?f:new Error("Failed to fetch summary"))}finally{o===u.current&&r(!1)}},[t,e]);return jn.useEffect(()=>{c()},[c]),{summary:a,isLoading:n,error:i,refetch:c}}import{Fragment as ol,jsx as ua,jsxs as ll}from"react/jsx-runtime";function cd(e,t){if(e.settled.complete)return{headline:Q(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:Q(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${Q(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:Q(0,t),extra:[]}}function ud({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:n,className:r}){let{summary:i,isLoading:l,error:u,refetch:c}=dr({refreshKey:e}),[o,f]=dd.useState(!1),b=ua("div",{className:"af-mb-6",children:u&&!i?ua(xt,{message:"Couldn't load your revenue summary.",onRetry:()=>c()}):ua("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:l||!i?ll(ol,{children:[ua(pt,{label:"This week",children:ua(G,{className:"af-h-6 af-w-24"})}),ua(pt,{label:"Today",children:ua(G,{className:"af-h-6 af-w-24"})}),ua(pt,{label:"Needs attention",children:ua(G,{className:"af-h-6 af-w-10"})})]}):ua(ol,{children:(()=>{let g=cd(i.revenue.d7,i.currency),m=cd(i.revenue.today,i.currency);return ll(ol,{children:[ua(pt,{label:"This week",detail:g.extra.length>0?ua("div",{children:g.extra.map(v=>ua("div",{children:v},v))}):void 0,children:g.headline}),ua(pt,{label:"Today",detail:m.extra.length>0?ua("div",{children:m.extra.map(v=>ua("div",{children:v},v))}):void 0,children:m.headline}),ua(pt,{label:"Needs attention",valueClassName:i.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:i.needs_attention.count===0?"All clear":i.needs_attention.items[0]?.title??void 0,children:i.needs_attention.count})]})})()})})});return ll(Ut,{title:"Orders",onBackToWebsite:n,hideBackButton:o,className:r,children:[b,ua(bs,{refreshKey:e,initialOrderId:t,onDetailOpenChange:f,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as yn from"react";import{ImageOff as wg,Package as Sg,Search as Ng}from"lucide-react";import*as qn from"react";import{ArrowLeft as yg,ImageOff as xg}from"lucide-react";import{jsx as In,jsxs as Lr}from"react/jsx-runtime";var fd="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",xs="af-text-xs af-text-muted-foreground",Wi="af-text-sm af-font-medium af-tabular-nums",bg=3;function hg(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let u=e.min_amount??t?.min_amount??null,c=e.max_amount??t?.max_amount??null;return u!==null&&c!==null?{text:`Buyer chooses (${Q(u,a)} \u2013 ${Q(c,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(n===null||r===null)return{text:"Varies by variant",compareAt:null};let i=n===r?Q(n,a):`${Q(n,a)} \u2013 ${Q(r,a)}`,l=t?.compare_at_amount??null;return{text:i,compareAt:l!==null&&l>r?Q(l,a):null}}function Gi({product:e,className:t}){let a=hg(e);return Lr("div",{className:t,children:[In("span",{className:Wi,children:a.text}),a.compareAt&&In("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function Ki({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?In(ee,{variant:"destructive",children:"Out of stock"}):t.low_stock?Lr(ee,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?In(ee,{variant:"secondary",children:"Backorder"}):t.available===null?null:Lr(ee,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?In(ee,{variant:"warning",children:"Low stock"}):null}function Zi(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Yi(e){return e.map(t=>Q(t.amount,t.currency)).join(" + ")}function md(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${Q(e.min_amount,e.currency)} \u2013 ${Q(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":Q(e.unit_amount,e.currency)}function pd({variant:e}){let t=e.inventory;if(!t||!t.tracked)return In("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?Lr("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[In("span",{className:"af-tabular-nums",children:Math.max(0,a)}),In(ee,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?In(ee,{variant:"destructive",children:"Out of stock"}):Lr("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[In("span",{className:"af-tabular-nums",children:a}),a<=bg&&In(ee,{variant:"warning",children:"Low"})]})}import{jsx as we,jsxs as Pt}from"react/jsx-runtime";function Br({title:e,children:t,className:a}){return Pt("section",{className:W("af-rounded-lg af-border af-p-4",a),children:[we("h4",{className:fd,children:e}),we("div",{className:"af-mt-3",children:t})]})}function gd({src:e,className:t}){let[a,s]=qn.useState(!1);return qn.useEffect(()=>s(!1),[e]),!e||a?we("div",{"aria-hidden":"true",className:W("af-flex af-items-center af-justify-center af-bg-muted",t),children:we(xg,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):we("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:W("af-object-cover",t)})}function vd({product:e,showStats:t=!1,onBack:a}){let{api:s}=H(),[n,r]=qn.useState(null),[i,l]=qn.useState(!0),[u,c]=qn.useState(null),[o,f]=qn.useState(0),[b,g]=qn.useState(0);qn.useEffect(()=>{let h=!1;return l(!0),c(null),s.getProduct(e.id).then(N=>{h||r(N)}).catch(N=>{h||c(N instanceof Error?N:new Error("Failed to load product"))}).finally(()=>{h||l(!1)}),()=>{h=!0}},[s,e.id,o]);let m=n?{...e,...n}:e,v=m.images.length>0?m.images:e.images,d=v[b]??v[0],p=Zi(m),x=t?m.stats:void 0,S=n?.variants??[],k=S.length>1;return Pt("div",{children:[Pt("div",{className:"af-mb-6",children:[Pt(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[we(yg,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),Pt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[we("h3",{className:"af-text-xl af-font-semibold af-break-words",children:m.name}),we(ee,{variant:m.active?"success":"secondary",children:m.active?"Active":"Draft"}),we(Ki,{product:m})]}),we(Gi,{product:m,className:"af-mt-1"}),!m.active&&we("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),Pt("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[Pt("div",{className:"af-space-y-2",children:[we(gd,{src:d,className:"af-h-48 af-w-full af-rounded-md af-border"}),v.length>1&&we("div",{className:"af-flex af-flex-wrap af-gap-2",children:v.map((h,N)=>we("button",{type:"button",onClick:()=>g(N),"aria-label":`Show photo ${N+1} of ${v.length}`,"aria-pressed":N===b,className:W("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",N===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:we(gd,{src:h,className:"af-h-12 af-w-12 af-rounded-md"})},`${h}-${N}`))})]}),Pt("div",{className:"af-space-y-6",children:[m.description&&we(Br,{title:"Description",children:we("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:m.description})}),i?Pt(Br,{title:"Variants",children:[we("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(h=>Pt("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[we(G,{className:"af-h-4 af-w-28"}),we(G,{className:"af-h-4 af-w-20"}),we(G,{className:"af-h-4 af-w-16"})]},h))}),we("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):u?we(xt,{message:"Couldn't load this product's variants.",onRetry:()=>f(h=>h+1)}):k?we(Br,{title:`Variants \xB7 ${S.length}`,children:we("div",{className:"af-overflow-x-auto",children:Pt(ct,{children:[we(dt,{children:Pt(Ie,{children:[we(K,{children:"Variant"}),we(K,{children:"SKU"}),we(K,{className:"af-text-right",children:"Price"}),we(K,{children:"Stock"})]})}),we(ut,{children:S.map(h=>Pt(Ie,{children:[Pt(Z,{className:"af-font-medium",children:[h.title||h.option_values.map(N=>N.value).join(" / ")||"\u2014",!h.active&&we(ee,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),we(Z,{className:"af-text-muted-foreground",children:h.sku?we("code",{className:"af-font-mono af-text-xs af-break-all",children:h.sku}):"\u2014"}),Pt(Z,{className:"af-whitespace-nowrap af-text-right",children:[we("div",{className:Wi,children:md(h)}),h.compare_at_amount!==null&&h.unit_amount!==null&&h.compare_at_amount>h.unit_amount&&we("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:Q(h.compare_at_amount,h.currency)})]}),we(Z,{className:"af-text-sm",children:we(pd,{variant:h})})]},h.id))})]})})}):null,we(Br,{title:"Details",children:Pt("dl",{className:"af-space-y-2",children:[Pt("div",{children:[we("dt",{className:xs,children:"Delivery"}),we("dd",{className:"af-text-sm",children:p==="Digital download"?m.fulfillment.filename??"Digital download":p??"Nothing to deliver"})]}),m.fulfillment.type==="redirect"&&m.fulfillment.url&&Pt("div",{children:[we("dt",{className:xs,children:"Sends buyers to"}),we("dd",{className:"af-break-all af-text-sm",children:m.fulfillment.url})]}),Pt("div",{children:[we("dt",{className:xs,children:"Shipping address"}),we("dd",{className:"af-text-sm",children:m.collect_shipping_address?"Collected at checkout":"Not collected"})]}),Pt("div",{children:[we("dt",{className:xs,children:"Most one buyer can order"}),we("dd",{className:"af-text-sm af-tabular-nums",children:m.max_quantity})]})]})}),x&&we(Br,{title:"Last 30 days",children:Pt("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[Pt("div",{children:[we("dt",{className:xs,children:"Units sold"}),we("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),Pt("div",{children:[we("dt",{className:xs,children:"Orders"}),we("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),Pt("div",{children:[we("dt",{className:xs,children:"Gross"}),we("dd",{className:Wi,children:x.gross.length>0?Yi(x.gross):"\u2014"})]})]})}),we("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}import{Fragment as ws,jsx as ve,jsxs as Ct}from"react/jsx-runtime";var Rg={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},_g=["all","active","draft","low_stock","out_of_stock"];function bd(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function hd(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function kg(e){return e.inventory?.out_of_stock??!1}function Pg(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return hd(e);case"out_of_stock":return kg(e);default:return!0}}function Cg({product:e,showStats:t,onOpen:a}){let s=e.images[0],n=t?e.stats:void 0,r=Zi(e),i=e.variant_count??0;return Ct("button",{type:"button",onClick:a,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?ve("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):ve("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:ve(wg,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Ct("div",{className:"af-space-y-2 af-p-3",children:[Ct("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ct("div",{className:"af-min-w-0",children:[ve("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),ve(Gi,{product:e,className:"af-mt-0.5"})]}),!e.active&&ve(ee,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Ct("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ve(Ki,{product:e}),i>1&&Ct(ee,{variant:"outline",children:[i," variants"]}),r&&ve(ee,{variant:"outline",children:r})]}),n&&Ct("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Yi(n.gross)}`:""," ",ve("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Tg(){return ve("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=>Ct("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[ve("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),Ct("div",{className:"af-space-y-2 af-p-3",children:[ve(G,{className:"af-w-32"}),ve(G,{className:"af-w-16"}),ve(G,{className:"af-h-5 af-w-24"})]})]},e))})}function yd({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:n,isLoading:r,error:i,refetch:l}=or({includeStats:t,refreshKey:e}),[u,c]=yn.useState(!1),[o,f]=yn.useState(null),[b,g]=yn.useState("all"),{api:m}=H(),v=yn.useCallback(()=>m.exportProductsCsv(),[m]),[d,p]=yn.useState(""),[x,S]=yn.useState("newest"),k=yn.useMemo(()=>{if(!t)return null;let j=null;for(let U of n)!U.stats||U.stats.units_sold===0||(!j||U.stats.units_sold>(j.stats?.units_sold??0))&&(j=U);return j},[n,t]),h=yn.useMemo(()=>n.filter(hd).length,[n]),N=d.trim().toLowerCase(),R=yn.useMemo(()=>{let U=[...n.filter(te=>Pg(te,b)&&(!N||te.name.toLowerCase().includes(N)))];return x==="name"?U.sort((te,ce)=>te.name.localeCompare(ce.name)):x==="best_selling"?U.sort((te,ce)=>(ce.stats?.units_sold??0)-(te.stats?.units_sold??0)):U.sort((te,ce)=>bd(ce.created_at)-bd(te.created_at)),U},[n,b,N,x]),C=b!=="all"||!!N,w=()=>{g("all"),p("")},P=r||i!==null&&n.length===0,I=ve("div",{className:"af-mb-6",children:ve("div",{className:W("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:P?Ct(ws,{children:[ve(pt,{label:"Products",children:ve(G,{className:"af-h-6 af-w-10"})}),t?Ct(ws,{children:[ve(pt,{label:"Best seller",children:ve(G,{className:"af-h-6 af-w-28"})}),ve(pt,{label:"Low stock",children:ve(G,{className:"af-h-6 af-w-10"})})]}):ve(pt,{label:"Active",children:ve(G,{className:"af-h-6 af-w-10"})})]}):Ct(ws,{children:[ve(pt,{label:"Products",children:n.length}),t?Ct(ws,{children:[ve(pt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:k?`${k.stats?.units_sold??0} sold, last 30 days`:void 0,children:k?ve("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:k.name}):ve("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),ve(pt,{label:"Low stock",children:h})]}):ve(pt,{label:"Active",children:n.filter(j=>j.active).length})]})})}),_=Ct("div",{className:"af-mb-4 af-space-y-3",children:[Ct("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ve("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:_g.map(j=>ve("button",{type:"button","aria-pressed":b===j,onClick:()=>g(j),className:W("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:Rg[j]},j))}),Ct("div",{className:"af-relative af-w-full af-max-w-xs",children:[ve(Ng,{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"}),ve(ae,{type:"text",value:d,onChange:j=>p(j.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Ct(un,{value:x,onValueChange:j=>S(j),children:[ve(Qa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:ve(fn,{})}),Ct(en,{children:[ve(St,{value:"newest",children:"Newest"}),ve(St,{value:"name",children:"Name A\u2013Z"}),t&&ve(St,{value:"best_selling",children:"Best selling"})]})]}),C&&ve(y,{type:"button",variant:"ghost",size:"sm",onClick:w,children:"Clear filters"}),ve(wa,{fetchCsv:v,filename:"products",label:C?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&n.length===0?ve(G,{className:"af-h-4 af-w-28"}):ve("p",{className:"af-text-sm af-text-muted-foreground",children:C?`${R.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),q;return o?q=ve(vd,{product:o,showStats:t,onBack:()=>{f(null),l()}},o.id):r&&n.length===0?q=Ct(ws,{children:[_,ve(Tg,{}),ve("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):i&&n.length===0?q=ve("div",{className:"af-flex af-justify-center af-py-8",children:ve(xt,{message:"Couldn't load your products.",onRetry:()=>l()})}):n.length===0?q=Ct(ca,{icon:ve(Sg,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",ve("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):q=Ct(ws,{children:[_,i&&ve("div",{className:"af-mb-4",children:ve(xt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>l()})}),R.length===0?Ct(ca,{children:["No products match these filters.",ve("br",{}),ve(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:w,children:"Show all products"})]}):ve("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:R.map(j=>ve(Cg,{product:j,showStats:t,onOpen:()=>f(j)},j.id))})]}),ve(Ut,{title:"Products",onBackToWebsite:a,hideBackButton:!!o,className:s,children:u?Ct(ws,{children:[ve(y,{variant:"ghost",onClick:()=>c(!1),children:"Back to products"}),ve(Qs,{})]}):Ct(ws,{children:[!o&&ve("div",{className:"af-mb-4 af-flex af-justify-end",children:ve(y,{variant:"outline",onClick:()=>c(!0),children:"Promo codes"})}),!o&&I,q]})})}import*as ja from"react";import{ArrowLeft as _d,Check as Eg,ChevronLeft as xd,ChevronRight as wd,ClipboardCopy as Ig,Mail as dl,Search as Ag,Users as Dg}from"lucide-react";import*as za from"react";function Ji({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=za.useState([]),[r,i]=za.useState(!0),[l,u]=za.useState(null),[c,o]=za.useState(0),[f]=za.useState(e),[b,g]=za.useState(""),[m,v]=za.useState(void 0),d=za.useRef(0),p=za.useCallback(async({afterRemoval:x=!1}={})=>{let S=++d.current;try{i(!0),u(null);let k={limit:f,offset:c*f};b.trim()&&(k.q=b.trim()),m&&(k.source=m);let h=await a.getPeople(k);if(S!==d.current)return;if(x&&h.people.length===0&&c>0){o(c-1);return}n(h.people)}catch(k){if(S!==d.current)return;u(k instanceof Error?k:new Error("Failed to fetch people"))}finally{S===d.current&&i(!1)}},[a,c,f,b,m,t]);return za.useEffect(()=>{p()},[p]),{people:s,isLoading:r,error:l,page:c,pageSize:f,hasNextPage:s.length===f,hasPreviousPage:c>0,setPage:o,q:b,setQ:x=>{g(x),o(0)},source:m,setSource:x=>{v(x),o(0)},refetch:()=>p(),refetchAfterRemoval:()=>p({afterRemoval:!0})}}import*as Wn from"react";function Xi(e,{refreshKey:t}={}){let{api:a}=H(),[s,n]=Wn.useState(null),[r,i]=Wn.useState(e!==null),[l,u]=Wn.useState(null),c=Wn.useRef(0),o=Wn.useCallback(async()=>{if(e===null){n(null),i(!1),u(null);return}let f=++c.current;try{i(!0),u(null);let b=await a.getPerson(e);if(f!==c.current)return;n(b)}catch(b){if(f!==c.current)return;u(b instanceof Error?b:new Error("Failed to fetch person"))}finally{f===c.current&&i(!1)}},[a,e,t]);return Wn.useEffect(()=>{o()},[o]),{person:s,isLoading:r,error:l,refetch:o}}import{jsx as D,jsxs as xe}from"react/jsx-runtime";var cl="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Og="af-text-xs af-text-muted-foreground";function ur(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 ul(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function Lg(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Bg({value:e,label:t}){let[a,s]=ja.useState(!1);return Lg()?xe(y,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[a?D(Eg,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):D(Ig,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function Sd(e){return xe("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&xe(ee,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&D(ee,{variant:"secondary",children:"Contact form"})]})}function Nd(e){return e.name?e.name:e.email?e.email:D("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Fg=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Mg=40;function $g(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),s=t.find(([n,r])=>Fg.test(n)&&typeof r=="string"&&r.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=Mg).sort((n,r)=>String(r[1]).trim().length-String(n[1]).trim().length)[0];return s?{message:String(s[1]),rest:t.filter(([n])=>n!==s[0])}:{message:null,rest:t}}function Ug(e){return e.replace(/_/g," ")}function Vg(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Hg({data:e}){let{message:t,rest:a}=$g(e);return t===null&&a.length===0?D("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):xe("div",{className:"af-space-y-3",children:[t!==null&&D("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),a.length>0&&D("dl",{className:"af-space-y-1",children:a.map(([s,n])=>xe("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[D("dt",{className:W(Og,"af-w-28 af-shrink-0 af-capitalize"),children:Ug(s)}),D("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Vg(n)})]},s))})]})}function kd({formName:e,createdAt:t,data:a,onDelete:s}){return xe("div",{className:"af-rounded-md af-border af-p-3",children:[xe("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[D(ee,{variant:"outline",children:"Form submission (unverified)"}),e&&D("span",{className:"af-text-xs af-text-muted-foreground",children:e}),D("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:ur(t)}),D(Xs,{iconOnly:!0,onDelete:s})]}),D(Hg,{data:a})]})}function zg(e){return e.charged_total??e.amount_total}function jg({email:e,refreshKey:t,onBack:a,onRemoved:s}){let{api:n}=H(),{person:r,isLoading:i,error:l,refetch:u}=Xi(e,{refreshKey:t}),c=async f=>{await n.deleteSubmission(f),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?u():a()},o=ul(e,r?.submissions[0]?.form_name);return xe("div",{children:[xe("div",{className:"af-mb-6",children:[xe(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[D(_d,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),xe("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[xe("div",{className:"af-min-w-0",children:[i?D(G,{className:"af-h-7 af-w-48"}):D("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),xe("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[D("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),D(Bg,{value:e,label:"Copy email address"})]})]}),D(y,{asChild:!0,children:xe("a",{href:o,children:[D(dl,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),i?xe("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(f=>xe("div",{className:"af-rounded-md af-border af-p-3",children:[D(G,{className:"af-w-40"}),D(G,{className:"af-mt-2 af-w-64"})]},f)),D("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):l||!r?D("div",{className:"af-flex af-justify-center af-py-8",children:D(xt,{message:"Couldn't load this person.",onRetry:()=>u()})}):xe("div",{className:"af-space-y-6",children:[r.customer&&xe("div",{children:[D("h4",{className:W(cl,"af-mb-3"),children:"Customer"}),xe("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&xe("div",{className:"af-flex af-gap-2",children:[D("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),D("dd",{children:r.customer.name})]}),r.customer.phone&&xe("div",{className:"af-flex af-gap-2",children:[D("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),D("dd",{children:r.customer.phone})]}),xe("div",{className:"af-flex af-gap-2",children:[D("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),D("dd",{children:ur(r.customer.created_at)})]})]})]}),r.orders.length>0&&xe("div",{children:[D("h4",{className:W(cl,"af-mb-3"),children:"Purchases"}),D("div",{className:"af-overflow-x-auto",children:xe(ct,{children:[D(dt,{children:xe(Ie,{children:[D(K,{children:"Order"}),D(K,{children:"Date"}),D(K,{className:"af-text-right",children:"Total"}),D(K,{children:"Status"})]})}),D(ut,{children:r.orders.map(f=>xe(Ie,{children:[D(Z,{className:"af-whitespace-nowrap af-font-medium",children:os(f)}),D(Z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ur(f.created_at)}),D(Z,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:Q(zg(f),f.currency)}),D(Z,{children:D(Ds,{status:f.status})})]},f.id))})]})}),D("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&&xe("div",{children:[D("h4",{className:W(cl,"af-mb-3"),children:"Messages"}),D("div",{className:"af-space-y-3",children:r.submissions.map(f=>D(kd,{formName:f.form_name,createdAt:f.created_at,data:f.data,onDelete:()=>c(f.id)},f.id))})]})]})]})}function qg({submissionId:e,onBack:t,onRemoved:a}){let{api:s}=H(),[n,r]=ja.useState(null),[i,l]=ja.useState(!0),[u,c]=ja.useState(null),[o,f]=ja.useState(0);return ja.useEffect(()=>{let b=!1;return l(!0),c(null),s.getSubmission(e).then(g=>{b||r(g)}).catch(g=>{b||c(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{b||l(!1)}),()=>{b=!0}},[s,e,o]),xe("div",{children:[xe("div",{className:"af-mb-6",children:[xe(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[D(_d,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),D("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?D(G,{className:"af-mt-1 af-h-4 af-w-32"}):n&&D("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:ur(n.metadata.submitted_at)})]}),i?xe("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[D(G,{className:"af-w-40"}),D(G,{className:"af-mt-2 af-w-64"}),D(G,{className:"af-mt-2 af-w-52"}),D("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):u||!n?D("div",{className:"af-flex af-justify-center af-py-8",children:D(xt,{message:"Couldn't load this submission.",onRetry:()=>f(b=>b+1)})}):xe("div",{className:"af-space-y-3",children:[D(kd,{formName:null,createdAt:n.metadata.submitted_at,data:n.data,onDelete:async()=>{await s.deleteSubmission(e),a(),t()}}),D("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 Wg={all:"All",customers:"Customers",leads:"Leads"},Gg=["all","customers","leads"],Rd={all:void 0,customers:"customer",leads:"lead"};function Kg({refreshKey:e,onBackToWebsite:t,className:a,maxRows:s,onViewAll:n}){let r=typeof s=="number",{people:i,isLoading:l,error:u,page:c,pageSize:o,hasNextPage:f,hasPreviousPage:b,setPage:g,q:m,setQ:v,source:d,setSource:p,refetch:x,refetchAfterRemoval:S}=Ji({refreshKey:e}),[k,h]=ja.useState({kind:"list"}),[N,R]=ja.useState(""),C=d==="customer"?"customers":d==="lead"?"leads":"all",w=V=>{Rd[V]!==d&&p(Rd[V])},{api:P}=H(),I=ja.useCallback(()=>P.exportPeopleCsv({...m?{q:m}:{},...d?{source:d}:{}}),[P,m,d]),_=!r||!!n,q=V=>{if(r){n?.();return}V.email?h({kind:"person",email:V.email}):V.submission_id&&h({kind:"submission",submissionId:V.submission_id})},j=ja.useRef(!1),U=()=>{j.current=!0},te=()=>{h({kind:"list"}),j.current?(j.current=!1,S()):x()},ce=V=>{let A=V.trim();A!==m&&v(A)},me=r?i.slice(0,s):i,T;if(k.kind==="person")T=D(jg,{email:k.email,refreshKey:e,onBack:te,onRemoved:U});else if(k.kind==="submission")T=D(qg,{submissionId:k.submissionId,onBack:te,onRemoved:U});else{let V=xe("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[D("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:Gg.map(A=>D("button",{type:"button","aria-pressed":C===A,onClick:()=>w(A),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",C===A?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Wg[A]},A))}),xe("div",{className:"af-relative af-w-full af-max-w-xs",children:[D(Ag,{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"}),D(ae,{type:"text",value:N,onChange:A=>R(A.target.value),onBlur:()=>ce(N),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),ce(N))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),m&&D(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{R(""),v("")},children:"Clear search"}),D(wa,{fetchCsv:I,filename:"people",className:"af-ml-auto"})]});if(l)T=xe("div",{children:[r?null:V,D("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(A=>xe("div",{className:"af-rounded-md af-border af-p-3",children:[xe("div",{className:"af-flex af-items-center af-justify-between",children:[D(G,{className:"af-h-4 af-w-32"}),D(G,{className:"af-h-4 af-w-16"})]}),D(G,{className:"af-mt-2 af-h-5 af-w-28"}),D(G,{className:"af-mt-2 af-h-3 af-w-56"})]},A))}),D("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:xe(ct,{children:[D(dt,{children:xe(Ie,{children:[D(K,{children:"Person"}),D(K,{children:"Came from"}),D(K,{children:"Latest message"}),D(K,{children:"Last activity"}),D(K,{className:"af-w-8"}),D(K,{className:"af-w-8"})]})}),D(ut,{"aria-hidden":"true",children:[0,1,2,3,4].map(A=>xe(Ie,{children:[D(Z,{children:D(G,{className:"af-h-4 af-w-40"})}),D(Z,{children:D(G,{className:"af-h-5 af-w-24"})}),D(Z,{children:D(G,{className:"af-h-4 af-w-56"})}),D(Z,{children:D(G,{className:"af-h-4 af-w-24"})}),D(Z,{}),D(Z,{})]},A))})]})}),D("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(u)T=xe("div",{children:[r?null:V,D("div",{className:"af-flex af-justify-center af-py-8",children:D(xt,{message:"Couldn't load your leads.",onRetry:()=>x()})})]});else if(me.length===0&&c===0){let A=!!m||C!=="all";T=xe("div",{children:[A&&V,A?D(ca,{children:m?"Nobody matches that search.":C==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):D(tr,{icon:Dg,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(i.length===0)T=xe("div",{children:[r?null:V,D(ca,{children:"No more results."}),D("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:xe(y,{variant:"outline",size:"sm",onClick:()=>g(c-1),children:[D(xd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let A=c*o+1,ne=c*o+i.length;T=xe("div",{children:[r?null:V,D("div",{className:"af-space-y-3 lg:af-hidden",children:me.map((re,Me)=>xe("div",{onClick:_?()=>q(re):void 0,className:`af-rounded-md af-border af-p-3${_?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[xe("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[xe("div",{className:"af-min-w-0",children:[D("button",{type:"button",onClick:Se=>{Se.stopPropagation(),q(re)},disabled:!_,"aria-label":`Open ${re.name||re.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:Nd(re)}),re.name&&re.email&&D("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:re.email})]}),xe("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[D("span",{className:"af-text-xs af-text-muted-foreground",children:ur(re.last_activity_at)}),re.email&&D(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:D("a",{href:ul(re.email),onClick:Se=>Se.stopPropagation(),"aria-label":`Email ${re.email}`,children:D(dl,{className:"af-h-4 af-w-4"})})})]})]}),D("div",{className:"af-mt-2",children:Sd(re)}),re.latest_message_excerpt&&D("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:re.latest_message_excerpt})]},re.email??re.submission_id??Me))}),D("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:xe(ct,{children:[D(dt,{children:xe(Ie,{children:[D(K,{children:"Person"}),D(K,{children:"Came from"}),D(K,{children:"Latest message"}),D(K,{children:"Last activity"}),D(K,{className:"af-w-8",children:D("span",{className:"af-sr-only",children:"Reply"})}),D(K,{className:"af-w-8"})]})}),D(ut,{children:me.map((re,Me)=>xe(Ie,{onClick:_?()=>q(re):void 0,className:_?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[xe(Z,{className:"af-max-w-[260px] af-font-medium",children:[D("button",{type:"button",onClick:Se=>{Se.stopPropagation(),q(re)},disabled:!_,"aria-label":`Open ${re.name||re.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:Nd(re)}),re.name&&re.email&&D("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:re.email})]}),D(Z,{children:Sd(re)}),D(Z,{className:"af-max-w-[320px]",children:re.latest_message_excerpt?D("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:re.latest_message_excerpt}):D("span",{className:"af-text-muted-foreground",children:"\u2014"})}),D(Z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ur(re.last_activity_at)}),D(Z,{className:"af-w-8",children:re.email&&D(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:D("a",{href:ul(re.email),onClick:Se=>Se.stopPropagation(),"aria-label":`Email ${re.email}`,children:D(dl,{className:"af-h-4 af-w-4"})})})}),D(Z,{className:"af-w-8 af-text-right",children:D(wd,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},re.email??re.submission_id??Me))})]})}),!r&&xe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[D("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${A}-${ne}`}),xe("div",{className:"af-flex af-items-center af-gap-2",children:[xe(y,{variant:"outline",size:"sm",onClick:()=>g(c-1),disabled:!b,children:[D(xd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),xe(y,{variant:"outline",size:"sm",onClick:()=>g(c+1),disabled:!f,children:["Next",D(wd,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?D("div",{className:a,children:T}):D(Ut,{title:"Leads",onBackToWebsite:t,hideBackButton:k.kind!=="list",className:a,children:T})}function Qi(e){return D(Kg,{...e},e.maxRows==null?"full":"compact")}import*as Ad from"react";import{ChevronLeft as Pd,ChevronRight as Zg,Repeat as Yg}from"lucide-react";import*as qa from"react";function eo({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=qa.useState([]),[r,i]=qa.useState(0),[l,u]=qa.useState(!0),[c,o]=qa.useState(null),[f,b]=qa.useState(0),[g,m]=qa.useState(e),[v,d]=qa.useState(void 0),p=qa.useRef(0),x=qa.useCallback(async()=>{let k=++p.current;try{u(!0),o(null);let h={limit:g,offset:f*g};v&&(h.status=v);let N=await a.getSubscriptions(h);if(k!==p.current)return;n(N.subscriptions),i(N.total)}catch(h){if(k!==p.current)return;o(h instanceof Error?h:new Error("Failed to fetch subscriptions"))}finally{k===p.current&&u(!1)}},[a,f,g,v,t]);qa.useEffect(()=>{x()},[x]);let S=Math.ceil(r/g);return{subscriptions:s,total:r,isLoading:l,error:c,page:f,pageSize:g,hasNextPage:f<S-1,hasPreviousPage:f>0,setPage:b,setPageSize:k=>{m(k),b(0)},status:v,setStatus:k=>{d(k),b(0)},refetch:x}}import{jsx as de,jsxs as Tt}from"react/jsx-runtime";function Cd(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 Td({sub:e}){return e.status==="canceled"?de(ee,{variant:"outline",children:"Canceled"}):e.status==="past_due"?de(ee,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?de(ee,{variant:"warning",children:"Scheduled to cancel"}):de(ee,{variant:"success",children:"Active"}):de(ee,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Jg(e,t){let a=Q(t,e.currency);return e.plan_interval_count===1?`${a} / ${e.plan_interval}`:`${a} every ${e.plan_interval_count} ${e.plan_interval}s`}function Ed({sub:e}){let t=e.current_amount!==e.plan_amount;return Tt("div",{children:[de("div",{className:"af-font-medium af-tabular-nums",children:Jg(e,e.current_amount)}),t&&Tt("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",Q(e.plan_amount,e.currency)]})]})}function Id(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Cd(e.current_period_end)}`:"Ends at period end":e.current_period_end?Cd(e.current_period_end):"\u2014"}function Dd({refreshKey:e,onBackToWebsite:t,className:a}){let{subscriptions:s,total:n,isLoading:r,error:i,page:l,pageSize:u,hasNextPage:c,hasPreviousPage:o,setPage:f,status:b,refetch:g}=eo({refreshKey:e}),{api:m}=H(),v=Ad.useCallback(()=>m.exportSubscriptionsCsv(b?{status:b}:{}),[m,b]),d;if(r)d=Tt("div",{children:[de("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(p=>Tt("div",{className:"af-rounded-md af-border af-p-3",children:[Tt("div",{className:"af-flex af-items-center af-justify-between",children:[de(G,{className:"af-h-4 af-w-40"}),de(G,{className:"af-h-4 af-w-20"})]}),de(G,{className:"af-mt-2 af-h-3 af-w-32"}),de(G,{className:"af-mt-2 af-h-5 af-w-24"})]},p))}),de("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Tt(ct,{children:[de(dt,{children:Tt(Ie,{children:[de(K,{children:"Subscriber"}),de(K,{children:"Plan"}),de(K,{className:"af-text-right",children:"Amount"}),de(K,{children:"Renews"}),de(K,{children:"Status"})]})}),de(ut,{"aria-hidden":"true",children:[0,1,2,3,4].map(p=>Tt(Ie,{children:[de(Z,{children:de(G,{className:"af-h-4 af-w-44"})}),de(Z,{children:de(G,{className:"af-h-4 af-w-32"})}),de(Z,{className:"af-text-right",children:de(G,{className:"af-ml-auto af-h-4 af-w-24"})}),de(Z,{children:de(G,{className:"af-h-4 af-w-24"})}),de(Z,{children:de(G,{className:"af-h-5 af-w-20"})})]},p))})]})}),de("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(i)d=de("div",{className:"af-flex af-justify-center af-py-8",children:de(xt,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(s.length===0&&l===0)d=de(ca,{icon:de(Yg,{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)d=Tt("div",{children:[de(ca,{children:"No more results."}),de("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Tt(y,{variant:"outline",size:"sm",onClick:()=>f(l-1),children:[de(Pd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let p=l*u+1,x=l*u+s.length;d=Tt("div",{children:[de("div",{className:"af-mb-3 af-flex af-justify-end",children:de(wa,{fetchCsv:v,filename:"subscriptions"})}),de("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(S=>Tt("div",{className:"af-rounded-md af-border af-p-3",children:[Tt("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Tt("div",{className:"af-min-w-0",children:[de("div",{className:"af-truncate af-text-sm af-font-medium",children:S.customer_email||de("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),de("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:S.plan_title||"Untitled plan"})]}),de("div",{className:"af-shrink-0 af-text-right",children:de(Ed,{sub:S})})]}),Tt("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[de(Td,{sub:S}),S.is_test&&de(ee,{variant:"outline",children:"Test"}),de("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Id(S)})]}),de($n,{deliveries:S.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},S.id))}),de("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Tt(ct,{children:[de(dt,{children:Tt(Ie,{children:[de(K,{children:"Subscriber"}),de(K,{children:"Plan"}),de(K,{className:"af-text-right",children:"Amount"}),de(K,{children:"Renews"}),de(K,{children:"Status"})]})}),de(ut,{children:s.map(S=>Tt(Ie,{children:[de(Z,{className:"af-max-w-[240px]",children:de("div",{className:"af-truncate af-font-medium",children:S.customer_email||de("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),de(Z,{className:"af-max-w-[220px]",children:de("div",{className:"af-truncate",children:S.plan_title||de("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),de(Z,{className:"af-whitespace-nowrap af-text-right",children:de(Ed,{sub:S})}),de(Z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Id(S)}),Tt(Z,{children:[Tt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[de(Td,{sub:S}),S.is_test&&de(ee,{variant:"outline",children:"Test"})]}),de($n,{deliveries:S.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},S.id))})]})}),Tt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[de("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${p}-${x} of ${n}`}),Tt("div",{className:"af-flex af-items-center af-gap-2",children:[Tt(y,{variant:"outline",size:"sm",onClick:()=>f(l-1),disabled:!o,children:[de(Pd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Tt(y,{variant:"outline",size:"sm",onClick:()=>f(l+1),disabled:!c,children:["Next",de(Zg,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return de(Ut,{title:"Subscriptions",onBackToWebsite:t,className:a,children:d})}import*as Zn from"react";import{Loader2 as ov}from"lucide-react";import*as Na from"react";import*as to from"react";var Bs=typeof window>"u"?to.useEffect:to.useLayoutEffect;var ao=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},Xg=(e,t)=>e instanceof Error?e:new Error(t);function Qg(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 Od(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function Ss({siteId:e,refreshKey:t,onSaveInvoiceSettings:a}){let{api:s}=H(),[n,r]=Na.useState(null),[i,l]=Na.useState(!0),[u,c]=Na.useState(null),o=Na.useRef(null),[f,b]=Na.useState(()=>Od(s,e)),g=f.api!==s||f.siteId!==e,m=f;g&&(m=Od(s,e),b(m),r(null),l(!0),c(null));let v=Na.useRef(m);Bs(()=>{v.current!==m&&(v.current=m,o.current=null)},[m]);let d=(w,P)=>v.current===w&&P>w.applied,p=(w,P,I)=>d(w,P)?(w.applied=P,o.current=I,r(I),l(!1),!0):!1,x=async w=>{for(;w.writing;)await w.idle;let P=++w.seq;try{let I=await w.api.getSite(w.siteId);return p(w,P,I)&&c(null),{seq:P,error:null}}catch(I){return{seq:P,error:Xg(I,"Failed to load store settings")}}},S=(w,P)=>{let I=async()=>{if(v.current!==w)throw new Error("Not saved: the store switched to another site first.");w.writing=!0,w.idle=new Promise(q=>{w.markIdle=q});try{return await P(++w.seq)}finally{w.writing=!1,w.markIdle()}},_=w.queue.then(I,I);return w.queue=_.catch(()=>{}),_},k=Na.useCallback(async()=>{let w=await x(m);w.error&&d(m,w.seq)&&(c(w.error),l(!1))},[m]);Na.useEffect(()=>{k()},[k,t]);let h=Na.useCallback(w=>S(m,async P=>{let I=await m.api.updateSite(m.siteId,w),{currency_restatement:_,...q}=I;return p(m,P,q)&&c(j=>j instanceof ao?j:null),I}),[m]),N=Na.useRef(a);Bs(()=>{N.current=a});let R=Na.useCallback(async(w,P)=>{await S(m,()=>w());let I=await x(m);return I.error&&d(m,I.seq)&&o.current&&(p(m,I.seq,{...o.current,...P}),c(new ao(`Saved, but couldn't refresh settings: ${I.error.message}`))),v.current===m?o.current:null},[m]),C=Na.useCallback(w=>{let P=N.current;return R(()=>P(w),Qg(w))},[R]);return{site:g?null:n,isLoading:g||i,error:g?null:u,refetch:k,updateSite:h,saveInvoiceSettings:a?C:null}}import*as ra from"react";import{Loader2 as Ld}from"lucide-react";import{jsx as xn,jsxs as Gn}from"react/jsx-runtime";function no(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var An="af-grid af-gap-1 af-text-sm",Bd="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",Fd="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 Wa({children:e}){return xn("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Fr({children:e}){return xn("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var Kn=ra.forwardRef(function({id:t,title:a,description:s,children:n},r){let i=`af-store-${t}-title`;return Gn("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":i,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[Gn("div",{className:"af-space-y-1",children:[xn("h3",{id:i,className:"af-text-sm af-font-semibold",children:a}),s&&xn(Wa,{children:s})]}),n]})});function so({label:e,description:t,checked:a,onSave:s,disabled:n=!1,disabledReason:r}){let[i,l]=ra.useState(null),[u,c]=ra.useState(null),o=i??a,f=async b=>{l(b),c(null);try{await s(b)}catch(g){c(no(g))}finally{l(null)}};return Gn("div",{className:"af-space-y-1",children:[Gn("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[xn("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":o,checked:o,disabled:n||i!==null,onChange:b=>void f(b.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),Gn("span",{className:"af-space-y-0.5",children:[Gn("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,i!==null&&xn(Ld,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&xn(Wa,{children:t})]})]}),(n&&r||u)&&Gn("div",{className:"af-space-y-1 af-pl-6",children:[n&&r&&xn(Wa,{children:r}),u&&xn(Fr,{children:u})]})]})}var ml=(e,t)=>JSON.stringify(e)===JSON.stringify(t),fl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ev(e,t,a,s=[]){if(!fl(e)||!fl(t)||!fl(a))return{draft:ml(e,t)?a:e,dropped:[]};let n=[],r={...a};for(let i of Object.keys(a))ml(e[i],t[i])||(s.includes(i)?n.push(i):r[i]=e[i]);return{draft:r,dropped:n}}function fr(e,t){let a=JSON.stringify(e),[s,n]=ra.useState(e),[r,i]=ra.useState([]),l=ra.useRef(e),u=ra.useRef(e),c=ra.useRef(s);Bs(()=>{u.current=e,c.current=s});let o=ra.useRef(t?.when);ra.useEffect(()=>{let b=Object.is(o.current,t?.when)?[]:t?.fields??[];if(o.current=t?.when,ml(l.current,u.current)&&b.length===0)return;let g=ev(c.current,l.current,u.current,b);l.current=u.current,n(g.draft),g.dropped.length&&i(g.dropped)},[a,t?.when]);let f=ra.useCallback(b=>{n(b??u.current),i([])},[]);return{draft:s,setDraft:n,dirty:JSON.stringify(s)!==a,reset:f,dropped:r}}function mr({dirty:e,saving:t,error:a,onSave:s,onDiscard:n}){return e?Gn("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[Gn(y,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&xn(Ld,{className:"af-animate-spin"}),"Save"]}),xn(y,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:n,children:"Discard"}),a&&xn("p",{role:"alert",className:W("af-text-sm af-text-destructive"),children:a})]}):null}function pr(){let[e,t]=ra.useState(!1),[a,s]=ra.useState(null),n=ra.useCallback(async r=>{t(!0),s(null);try{await r()}catch(i){s(no(i))}finally{t(!1)}},[]);return{saving:e,error:a,setError:s,run:n}}function Md({what:e}){return Gn(Wa,{children:["Only the site owner can change ",e,"."]})}import*as wn from"react";import{ExternalLink as tv,Plus as av,X as Hd}from"lucide-react";import{Fragment as iv,jsx as Ne,jsxs as De}from"react/jsx-runtime";var gl=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function zd({site:e,updateSite:t}){return De("div",{className:"af-space-y-4",children:[Ne(so,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:a=>t({collect_phone_at_checkout:a})}),e.checkout_marketing_consent!==void 0&&Ne(so,{label:"Ask buyers for marketing consent at checkout",description:"Adds Stripe's consent checkbox to your checkout. Buyers who tick it join your email list, and buyers who leave without paying can get your abandoned-cart recovery emails.",checked:e.checkout_marketing_consent&&e.stripe_account_country==="US",disabled:e.stripe_account_country!=="US",disabledReason:e.stripe_account_country?'Only available for US stores: Stripe offers its consent checkbox to US businesses only. Your checkout shows an "Email me" box instead.':"Available once your Stripe account is connected and its country has synced.",onSave:a=>t({checkout_marketing_consent:a})})]})}function $d(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(Dt(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(Dt(e.free_shipping_over,e.currency))}}function jd({site:e,updateSite:t,refetch:a,providerSlot:s,currencyChanging:n=!1}){let{draft:r,setDraft:i,dirty:l,reset:u,dropped:c}=fr($d(e),{when:e.currency,fields:["rates","threshold"]}),{saving:o,error:f,setError:b,run:g}=pr(),m=e.currency.toUpperCase(),v=()=>g(async()=>{let p={},x=[...new Set(r.countries.split(/[\s,]+/).map(w=>w.trim().toUpperCase()).filter(Boolean))],S=x.find(w=>!/^[A-Z]{2}$/.test(w));if(S)throw new Error(`"${S}" isn't a two-letter country code (e.g. US, CA).`);let k=x.length?x:null;gl(k,e.shipping_countries)||(p.shipping_countries=k);let h=[];for(let w of r.rates){let P=w.label.trim(),I=va(w.amount,e.currency);if(!P)throw new Error("Every rate needs a name.");if(w.amount.trim()===""||I===null)throw new Error(`Enter a price for "${P}" (0 for free).`);h.push({label:P,amount:I})}let N=h.length?h:null;gl(N,e.shipping_rates)||(p.shipping_rates=N);let R=null;if(r.threshold.trim()!==""&&(R=va(r.threshold,e.currency),R===null||R===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(R!==e.free_shipping_over&&(p.free_shipping_over=R),Object.keys(p).length===0){u();return}("shipping_rates"in p||"free_shipping_over"in p)&&(p.expected_currency=e.currency);let C;try{C=await t(p)}catch(w){throw w instanceof aa&&w.details?.code==="currency_changed"&&await a?.(),w}u($d(C))}),d=(p,x)=>i({...r,rates:r.rates.map((S,k)=>k===p?{...S,...x}:S)});return De("fieldset",{disabled:o||n,className:"af-space-y-4",children:[De("label",{className:An,children:["Countries you ship to",Ne(ae,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:p=>i({...r,countries:p.target.value})}),Ne(Wa,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),De("div",{className:"af-space-y-2",children:[De("p",{className:"af-text-sm",children:["Flat shipping rates (",m,")"]}),r.rates.length===0&&Ne(Wa,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((p,x)=>De("div",{className:"af-flex af-items-center af-gap-2",children:[Ne(ae,{"aria-label":`Rate ${x+1} name`,value:p.label,placeholder:"Standard",onChange:S=>d(x,{label:S.target.value})}),Ne(ae,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:p.amount,placeholder:"0",className:"af-w-32",onChange:S=>d(x,{amount:S.target.value})}),Ne(y,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${x+1}`,onClick:()=>i({...r,rates:r.rates.filter((S,k)=>k!==x)}),children:Ne(Hd,{})})]},x)),De(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[Ne(av,{})," Add rate"]}),Ne(Wa,{children:"Buyers pick one at checkout. The first is preselected."})]}),De("label",{className:An,children:["Free shipping over (",m,")",Ne(ae,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:p=>i({...r,threshold:p.target.value})}),Ne(Wa,{children:"Orders at or above this get the cheapest rate free."})]}),c.length>0&&De("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",m,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),Ne(mr,{dirty:l,saving:o,error:f,onSave:()=>void v(),onDiscard:()=>{b(null),u()}}),s]})}var pl="exclusive",nv=[{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 sv({href:e,children:t}){return De("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,Ne(tv,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function qd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=fr(e.tax_behavior??pl),{saving:i,error:l,setError:u,run:c}=pr(),[o,f]=wn.useState(!1),b=e.stripe_tax_enabled,g=b||o,m=()=>c(async()=>{let p=a;if(p===e.tax_behavior){r();return}let x={tax_behavior:p};p!=="inclusive"&&e.tax_rate_bps!=null&&(x.tax_rate_bps=null);let S=await t(x);r(S.tax_behavior??pl)}),v=()=>c(async()=>{let p={stripe_tax_enabled:!0,tax_behavior:a};a!=="inclusive"&&e.tax_rate_bps!=null&&(p.tax_rate_bps=null);let x=await t(p);r(x.tax_behavior??pl),f(!1)}),d=(n||o)&&a!=="inclusive"&&e.tax_rate_bps!=null;return De("div",{className:"af-space-y-5",children:[De("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[Ne("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."}),Ne("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."}),Ne("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:nv.map(p=>Ne("li",{children:Ne(sv,{href:p.href,children:p.label})},p.href))})]}),Ne(so,{label:"Stripe automatic tax",description:b?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:g,onSave:async p=>{if(o){f(!1),u(null),r();return}if(p&&!e.tax_behavior){f(!0);return}return t({stripe_tax_enabled:p})}}),g&&De("fieldset",{disabled:i,className:"af-space-y-4 af-pl-6",children:[De("label",{className:An,children:["Do your prices already include tax?",De("select",{"aria-label":"Your prices",className:Bd,value:a,onChange:p=>s(p.target.value),children:[Ne("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),Ne("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),Ne(Wa,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),d&&De(Wa,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),o?De("div",{className:"af-space-y-2",children:[De("div",{className:"af-flex af-gap-2",children:[Ne(y,{type:"button",size:"sm",disabled:i,onClick:()=>void v(),children:"Turn on"}),Ne(y,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>{f(!1),u(null),r()},children:"Cancel"})]}),l&&Ne(Fr,{children:l})]}):Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void m(),onDiscard:()=>{u(null),r()}})]})]})}function Ud(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function Wd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=fr(Ud(e)),{saving:i,error:l,setError:u,run:c}=pr(),o=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),f=()=>c(async()=>{let b={},g=null;if(o&&a.rate.trim()!==""){let p=Number(a.rate);if(!Number.isFinite(p)||p<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(p*100)}o&&g!==e.tax_rate_bps&&(b.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let m=a.taxId.trim()||null;m!==e.tax_id&&(b.tax_id=m);let v=a.label.trim()||null;if(v!==e.tax_label&&(b.tax_label=v),Object.keys(b).length===0){r();return}let d=await t(b);r(Ud(d))});return De("fieldset",{disabled:i,className:"af-space-y-4",children:[De("label",{className:An,children:["Tax rate (%)",Ne(ae,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!o,value:o?a.rate:"",onChange:b=>s({...a,rate:b.target.value})}),Ne(Wa,{children:o?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),De("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[De("label",{className:An,children:["Tax ID",Ne(ae,{"aria-label":"Tax ID",value:a.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...a,taxId:b.target.value})})]}),De("label",{className:An,children:["Tax label",Ne(ae,{"aria-label":"Tax label",value:a.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...a,label:b.target.value})})]})]}),Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void f(),onDiscard:()=>{u(null),r()}})]})}function Gd({site:e,updateSite:t,onChangeStart:a}){let[s,n]=wn.useState(e.currency.toUpperCase()),[r,i]=wn.useState(!1),[l,u]=wn.useState(!1),[c,o]=wn.useState(null),f=e.currency.toUpperCase(),b=wn.useRef(f);wn.useEffect(()=>{b.current!==f&&(n(p=>p===b.current?f:p),b.current=f)},[f]);let g=s.trim().toUpperCase(),m=g!==f,v=/^[A-Z]{3}$/.test(g),d=async()=>{u(!0);let p=a?.(),x=!1;o(null);try{let S=await t({currency:g.toLowerCase()});x=!0;let k=S.currency_restatement;k&&!k.applied?o(k.reason?`Not changed: ${k.reason}.`:"The currency was not changed."):(n(S.currency.toUpperCase()),b.current=S.currency.toUpperCase()),i(!1)}catch(S){o(no(S))}finally{u(!1),p?.(x)}};return De("div",{className:"af-space-y-3",children:[De("div",{className:"af-flex af-items-end af-gap-2",children:[De("label",{className:An,children:["Store currency",Ne(ae,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:l||r,onChange:p=>{n(p.target.value),o(null)}})]}),m&&!r&&De(iv,{children:[Ne(y,{type:"button",size:"sm",disabled:!v,onClick:()=>i(!0),children:"Change currency"}),Ne(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>{n(f),o(null)},children:"Discard"})]})]}),Ne(Wa,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&De("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[De("p",{className:"af-text-sm",children:["Change the store currency from ",f," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",Q(2e3,f)," becomes ",Q(2e3,g),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),De("div",{className:"af-flex af-gap-2",children:[Ne(y,{type:"button",size:"sm",disabled:l,onClick:()=>void d(),children:"Confirm change"}),Ne(y,{type:"button",size:"sm",variant:"ghost",disabled:l,onClick:()=>i(!1),children:"Cancel"})]})]}),c&&Ne(Fr,{children:c})]})}function Vd(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function rv(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 Kd({site:e,save:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=fr(Vd(e)),{saving:i,error:l,setError:u,run:c}=pr();if(!t)return De("div",{className:"af-space-y-2 af-text-sm",children:[De("p",{children:["Due ",e.invoice_due_days," days after sending"]}),De("p",{children:["Reminders: ",rv(e.invoice_reminder_schedule)]}),De("p",{children:["Footer: ",e.invoice_footer||"None"]}),Ne(Md,{what:"invoice defaults"})]});let o=()=>c(async()=>{let f={},b=Number(a.dueDays);if(a.dueDays.trim()===""||!Number.isInteger(b)||b<0||b>90)throw new Error("Due days must be a whole number from 0 to 90.");b!==e.invoice_due_days&&(f.due_days=b);let m=a.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(m.some(x=>!Number.isInteger(x)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let v=[...new Set(m)].sort((x,S)=>x-S);gl(v,e.invoice_reminder_schedule)||(f.reminder_schedule=v);let d=a.footer.trim()||null;if(d!==e.invoice_footer&&(f.footer=d),Object.keys(f).length===0){r();return}let p=await t(f);r(p?Vd(p):void 0)});return De("fieldset",{disabled:i,className:"af-space-y-4",children:[De("label",{className:An,children:["Days until due",Ne(ae,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:a.dueDays,onChange:f=>s({...a,dueDays:f.target.value})})]}),De("label",{className:An,children:["Reminder schedule",Ne(ae,{"aria-label":"Reminder schedule",value:a.reminders,placeholder:"Off",onChange:f=>s({...a,reminders:f.target.value})}),Ne(Wa,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),De("label",{className:An,children:["Invoice footer",Ne("textarea",{"aria-label":"Invoice footer",className:Fd,maxLength:300,value:a.footer,onChange:f=>s({...a,footer:f.target.value})})]}),Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void o(),onDiscard:()=>{u(null),r()}})]})}function Zd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=fr(e.default_email_recipients),{saving:i,error:l,setError:u,run:c}=pr(),[o,f]=wn.useState(""),[b,g]=wn.useState(null),m=()=>{let d=o.trim().toLowerCase();if(d){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d)){g("Enter a valid email address.");return}if(a.some(p=>p.toLowerCase()===d)){g("Already added.");return}s([...a,d]),f(""),g(null)}},v=()=>c(async()=>{let d=await t({default_email_recipients:a});r(d.default_email_recipients)});return De("fieldset",{disabled:i,className:"af-space-y-3",children:[De("div",{className:"af-flex af-flex-wrap af-gap-2",children:[a.map(d=>De(ee,{variant:"secondary",className:"af-gap-1",children:[d,Ne("button",{type:"button","aria-label":`Remove ${d}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(a.filter(p=>p!==d)),children:Ne(Hd,{className:"af-h-3 af-w-3"})})]},d)),a.length===0&&Ne("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),De("div",{className:"af-flex af-gap-2",children:[Ne(ae,{"aria-label":"Add notification email",type:"email",value:o,placeholder:"Add email address",onChange:d=>{f(d.target.value),g(null)},onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),m())}}),Ne(y,{type:"button",variant:"outline",disabled:!o.trim(),onClick:m,children:"Add"})]}),b&&Ne(Fr,{children:b}),Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void v(),onDiscard:()=>{u(null),r()}})]})}import{jsx as cn,jsxs as Yd}from"react/jsx-runtime";function Jd({siteId:e,refreshKey:t,section:a,shippingProviderSlot:s,onConnectStripe:n,onUpgradePlan:r,className:i}){let{site:l,isLoading:u,error:c,refetch:o,updateSite:f}=Ss({siteId:e,refreshKey:t}),b=Zn.useRef(o),g=Zn.useRef(e);Bs(()=>{b.current=o,g.current=e});let m=Zn.useRef({}),[v,d]=Zn.useState([]),p=v.some(N=>N.siteId===e),x=Zn.useCallback(()=>{let N={siteId:e},R=b.current;return d(C=>[...C,N]),C=>{let w=()=>d(I=>I.filter(_=>_!==N));!(g.current===N.siteId)||C&&b.current===R?w():b.current().finally(w)}},[e]),S=N=>R=>{m.current[N]=R},k=l!==null&&l.payments_active;if(Zn.useEffect(()=>{if(!k||!a)return;let N=m.current[a];N&&(N.scrollIntoView?.({behavior:"smooth",block:"start"}),N.focus({preventScroll:!0}))},[k,a]),u)return Yd("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[cn(ov,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!l)return cn("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c?.message??"Could not load store settings."});if(!l.payments_active)return cn(ir,{className:i,onConnectStripe:n,onUpgradePlan:r,whenActive:cn("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let h={site:l,updateSite:f,refetch:o};return Yd("div",{className:`af-space-y-6 ${i??""}`,children:[c&&cn("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c.message}),cn(Kn,{ref:S("checkout"),id:"checkout",title:"Checkout",children:cn(zd,{...h})}),cn(Kn,{ref:S("shipping"),id:"shipping",title:"Shipping",children:cn(jd,{...h,providerSlot:s,currencyChanging:p})}),cn(Kn,{ref:S("tax"),id:"tax",title:"Tax",children:cn(qd,{...h})}),cn(Kn,{ref:S("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:cn(Gd,{...h,onChangeStart:x})})]},e)}import{Loader2 as lv}from"lucide-react";import{jsx as Fs,jsxs as Xd}from"react/jsx-runtime";function ro({siteId:e,refreshKey:t,onSaveInvoiceSettings:a,className:s}){let{site:n,isLoading:r,error:i,updateSite:l,refetch:u,saveInvoiceSettings:c}=Ss({siteId:e,refreshKey:t,onSaveInvoiceSettings:a});return r?Xd("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Fs(lv,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):n?Xd("div",{className:`af-space-y-6 ${s??""}`,children:[i&&Fs("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i.message}),Fs(Kn,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:Fs(Kd,{site:n,save:c})}),Fs(Kn,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:Fs(Wd,{site:n,updateSite:l,refetch:u})})]},e):Fs("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i?.message??"Could not load invoice settings."})}import{Loader2 as cv}from"lucide-react";import{jsx as Mr,jsxs as Qd}from"react/jsx-runtime";function eu({siteId:e,refreshKey:t,className:a}){let{site:s,isLoading:n,error:r,updateSite:i,refetch:l}=Ss({siteId:e,refreshKey:t});return n?Qd("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Mr(cv,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?Qd("div",{className:`af-space-y-3 ${a??""}`,children:[r&&Mr("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}),Mr(Kn,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:Mr(Zd,{site:s,updateSite:i,refetch:l})})]},e):Mr("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."})}import*as gr from"react";import{Fragment as tu,jsx as Ra,jsxs as $r}from"react/jsx-runtime";function au({refreshKey:e,initialInvoiceId:t,onBackToWebsite:a,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,siteId:i,onSaveInvoiceSettings:l,className:u}){let{aggregates:c,isLoading:o,error:f,refetch:b}=nr({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=lr({refreshKey:e}),{api:m}=H(),v=g.filters,d=gr.useCallback(()=>m.exportRetainersCsv(v),[m,v]),[p,x]=gr.useState(!1),[S,k]=gr.useState(null),[h,N]=gr.useState(!1),R=Ra("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:f||!o&&!c?$r("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. ",Ra(y,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):o||!c?$r(tu,{children:[Ra(pt,{label:"Outstanding",children:Ra(G,{className:"af-h-6 af-w-24"})}),Ra(pt,{label:"Overdue",children:Ra(G,{className:"af-h-6 af-w-24"})}),Ra(pt,{label:"Paid this month",children:Ra(G,{className:"af-h-6 af-w-24"})})]}):$r(tu,{children:[Ra(pt,{label:"Outstanding",detail:`${c.outstanding.count} open`,children:Q(c.outstanding.amount,c.currency)}),Ra(pt,{label:"Overdue",detail:c.overdue.count===0?"Nothing overdue":`${c.overdue.count} overdue`,valueClassName:c.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:Q(c.overdue.amount,c.currency)}),Ra(pt,{label:"Paid this month",detail:`${c.paid_this_month.count} paid`,children:Q(c.paid_this_month.amount,c.currency)})]})});return $r(Ut,{title:"Invoices",onBackToWebsite:a,hideBackButton:p,className:u,children:[R,i&&!p&&$r("div",{className:"af-mb-6",children:[Ra(y,{type:"button",variant:"outline",size:"sm","aria-expanded":h,"aria-controls":"af-invoice-settings",onClick:()=>N(C=>!C),children:"Invoice settings"}),h&&Ra("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:Ra(ro,{siteId:i,refreshKey:e,onSaveInvoiceSettings:l})})]}),!p&&Ra(rr,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:S?.id??null,onShowCycles:C=>k(w=>w?.id===C.id?null:C),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded,exportCsv:d}),Ra(ys,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:x,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,retainerFilter:S?{id:S.id,label:`${S.customer_name??S.customer_email??"Recurring invoices"} \u2014 ${S.description}`}:null,onClearRetainerFilter:()=>k(null)})]})}import*as ea from"react";import*as Sn from"react";function Lt(e,t,a){let[s,n]=Sn.useState(null),[r,i]=Sn.useState(!0),[l,u]=Sn.useState(null),c=Sn.useRef(0),o=Sn.useRef(e);o.current=e;let f=Sn.useRef(a);f.current=a;let b=Sn.useCallback(async()=>{let m=++c.current,v=f.current;i(!0),u(null);try{let d=await o.current();m===c.current&&n({scope:v,value:d})}catch(d){m===c.current&&u(d instanceof Error?d:new Error("Request failed"))}finally{m===c.current&&i(!1)}},[]);Sn.useEffect(()=>{b()},[b,t]);let g=s!==null&&s.scope===a;return{data:g?s.value:null,isLoading:r||!g&&l===null,error:l,refetch:b}}var vl={commitBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts"},cancelBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts/{sendId}/cancel",params:["sendId"]},createDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts"},updateDraft:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},deleteDraft:{method:"DELETE",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},testSendDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/test",params:["draftId"]},setDraftTemplate:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}/template",params:["draftId"]},duplicateDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/duplicate",params:["draftId"]},copyEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/copy",params:["templateId"]},archiveEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/archive",params:["templateId"]},unarchiveEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/unarchive",params:["templateId"]},deleteEmailTemplate:{method:"DELETE",path:"/sites/{siteId}/marketing/templates/{templateId}",params:["templateId"]},updateAutomation:{method:"PUT",path:"/sites/{siteId}/marketing/automations/{automationId}",params:["automationId"]},addSuggestedAutomation:{method:"POST",path:"/sites/{siteId}/marketing/automation-suggestions"},turnOnAutomation:{method:"POST",path:"/sites/{siteId}/marketing/automations/{automationId}/turn-on",params:["automationId"]},turnOffAutomation:{method:"POST",path:"/sites/{siteId}/marketing/automations/{automationId}/turn-off",params:["automationId"]},deleteAutomation:{method:"DELETE",path:"/sites/{siteId}/marketing/automations/{automationId}",params:["automationId"]},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"]}};function dv(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(vl,e)}function uv(e,t,a){let s=vl[e],n="params"in s?s.params:[],r={...a};delete r.siteId;let i=s.path.replace("{siteId}",encodeURIComponent(t));for(let u of n){let c=r[u];if(typeof c!="string"&&typeof c!="number")throw new Error(`${e} needs ${u}`);i=i.replace(`{${u}}`,encodeURIComponent(String(c))),delete r[u]}let l=s.method==="GET"||s.method==="DELETE"?void 0:r;return{method:s.method,path:i,body:l}}var nu={marketing_disabled:"Email marketing is not available yet.",site_deleted:"This site has been deleted.",sending_not_enabled:"Email isn't turned on for this site yet.",sending_paused:"Sending is paused while we review this site.",domain_not_verified:"Verify your sending domain before you can send.",dmarc_missing:"Your domain needs a DMARC record before you can send.",postal_address_missing:"Add your business postal address before you can send. Every email has to show it.",allowance_exhausted:"You've used this month's email allowance. Sending resumes next month or when you upgrade.",ramp_limit:"Today's sending limit for a new domain is used up. Sending continues tomorrow.",sample_failed:"Too many emails in the first batch bounced, so the rest of this send was stopped."},Ur=new Set(["sending_not_enabled","domain_not_verified","dmarc_missing","postal_address_missing"]);function Ns(e){return e?nu[e]??"Sending is not available right now.":null}import*as Yn from"react";var vr=50;function io({siteId:e,q:t="",offset:a=0,refreshKey:s=0}){let{api:n}=H(),r=Lt(()=>n.getMarketingContacts(e,{q:t||void 0,limit:vr,offset:a}),`${e}|${t}|${a}|${s}`,e),i=Lt(()=>n.getMarketingContactStats(e),`${e}|${s}`,e),l=Lt(()=>n.getMarketingTags(e),`${e}|${s}`,e);return{contacts:r,stats:i,tags:l,refetchAll:async()=>{await Promise.all([r.refetch(),i.refetch(),l.refetch()])}}}import*as $s from"react";import*as Dn from"react";import{Fragment as fv,jsx as Vr,jsxs as ru}from"react/jsx-runtime";var Hr=e=>`af-email-settings-${e}`,bl=Dn.createContext(null);function Ke(){let e=Dn.useContext(bl);if(!e)throw new Error("Email panels render inside EmailView");return e}function su(e){let{setInlineEditOpen:t}=Ke();Dn.useEffect(()=>(t(e),()=>t(!1)),[e,t])}function hl(e){return e.status==="sending"||e.status==="sent"||(e.status==="cancelled"||e.status==="failed")&&e.recipients.consumed>0}function oo(e,t){return new Set([...e.filter(a=>a.sent).map(a=>a.id),...t.filter(hl).flatMap(a=>a.draft_id?[a.draft_id]:[])])}function fa({onClick:e,children:t}){return Vr("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function br({reason:e}){let{openSetup:t,onOpenStoreSettings:a}=Ke(),s=e&&Ur.has(e)?Vr(fa,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&a?Vr(fa,{onClick:a,children:"Open Store settings"}):null;return s&&ru(fv,{children:[" ",s]})}function Rs(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 Ga(e,t){return Rs(e)===t?!0:e instanceof Error&&e.message.includes(t)}function hr(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function vt(){let{onOrgAction:e}=Ke(),[t,a]=Dn.useState(!1),[s,n]=Dn.useState(null),r=Dn.useCallback(async(i,l={})=>{a(!0),n(null);try{return{ok:!0,result:await e(i,l)}}catch(u){return n(hr(u)),{ok:!1,error:u}}finally{a(!1)}},[e]);return{busy:t,error:s,setError:n,run:r}}function ue({tone:e="info",children:t,className:a}){return Vr("div",{role:e==="error"?"alert":"status",className:W("af-rounded-md af-border af-px-3 af-py-2 af-text-sm",e==="warning"&&"af-border-yellow-300 af-bg-yellow-50 af-text-yellow-900",e==="error"&&"af-border-destructive af-bg-destructive/10 af-text-destructive",e==="success"&&"af-border-green-300 af-bg-green-50 af-text-green-900",a),children:t})}function _a({children:e,action:t,id:a}){return ru("div",{id:a,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[Vr("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function Ae(e){return e.toLocaleString("en-US")}function Ms(e,t){return`${e} ${t}${e===1?"":"s"}`}import{jsx as Ia,jsxs as cs}from"react/jsx-runtime";var yl="I confirm that everyone in this file agreed to receive marketing email from my business.",mv={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 lo({onImported:e}){let{canWrite:t}=Ke(),[a,s]=$s.useState(""),[n,r]=$s.useState(null),[i,l]=$s.useState(""),[u,c]=$s.useState(!1),[o,f]=$s.useState(!1),[b,g]=$s.useState(null),m=vt(),v=async()=>{if(!u||!a.trim())return;let d=i.split(",").map(x=>x.trim()).filter(Boolean),p=await m.run("importContacts",{csv:a,attested:!0,...d.length?{tags:d}:{},...o?{enroll_automations:!0}:{}});if(p.ok){let x=p.result;g(x),e?.(x)}};if(b){let d=new Map;for(let p of b.skipped_rows)d.set(p.reason,(d.get(p.reason)??0)+1);return cs("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[Ia("div",{className:"af-font-medium",children:"Import finished"}),cs("p",{className:"af-text-sm",children:[Ae(b.rows)," rows: ",Ae(b.created)," new, ",Ae(b.updated)," updated, ",Ae(b.skipped)," skipped."]}),d.size>0&&Ia("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...d].map(([p,x])=>cs("li",{children:[Ae(x)," ",mv[p]??p]},p))}),Ia("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),Ia(y,{type:"button",size:"sm",variant:"outline",onClick:()=>{g(null),s(""),r(null),c(!1)},children:"Import another file"})]})}return cs("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:d=>{d.preventDefault(),v()},children:[cs("label",{className:"af-block af-space-y-1",children:[Ia("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),Ia("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async d=>{let p=d.target.files?.[0];p&&(r(p.name),s(await p.text()))}}),Ia("span",{className:"af-block af-text-xs af-text-muted-foreground",children:'Needs an "email" column. Tags in a "tags" column are applied too.'}),n&&Ia("span",{className:"af-block af-text-xs",children:n})]}),cs("label",{className:"af-block af-space-y-1",children:[Ia("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),Ia(ae,{"aria-label":"Tags for imported contacts",value:i,onChange:d=>l(d.target.value)})]}),cs("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[Ia("input",{"aria-label":"Send these contacts into matching automations",type:"checkbox",className:"af-mt-1",checked:o,onChange:d=>f(d.target.checked)}),Ia("span",{children:"Send these contacts into matching automations. Leave this off when they were already welcomed on another platform."})]}),cs("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[Ia("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:u,onChange:d=>c(d.target.checked)}),cs("span",{children:[yl," Importing people who didn't agree can get your sending paused."]})]}),m.error&&Ia(ue,{tone:"error",children:m.error}),Ia(y,{type:"submit",size:"sm",disabled:!t||!u||!a.trim()||m.busy,children:m.busy?"Importing\u2026":"Import contacts"})]})}import{Fragment as ou,jsx as Le,jsxs as Vt}from"react/jsx-runtime";var pv={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function iu(){let{siteId:e,canWrite:t,refreshKey:a}=Ke(),[s,n]=Yn.useState(""),[r,i]=Yn.useState(""),[l,u]=Yn.useState(0),[c,o]=Yn.useState(0),[f,b]=Yn.useState(new Set),[g,m]=Yn.useState(!1),v=io({siteId:e,q:r,offset:l,refreshKey:c+a}),d=vt(),p=()=>o(R=>R+1),x=v.stats.data,S=v.contacts.data,k=v.tags.data??[],h=x?x.growth.slice(-4).reduce((R,C)=>R+C.new_subscribers,0):null,N=async()=>{let R=await d.run("exportContacts",{});if(!R.ok||typeof R.result!="string"||typeof document>"u")return;let C=URL.createObjectURL(new Blob([R.result],{type:"text/csv;charset=utf-8"})),w=document.createElement("a");w.href=C,w.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(C)};return Vt("div",{children:[Vt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[Le(pt,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:x?Ae(x.total):Le(G,{className:"af-h-6 af-w-16"})}),Le(pt,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:x?Ae(x.mailable):Le(G,{className:"af-h-6 af-w-16"})}),Le(pt,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:h!==null?Ae(h):Le(G,{className:"af-h-6 af-w-16"})})]}),Vt("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[Vt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:R=>{R.preventDefault(),u(0),i(s.trim())},children:[Le(ae,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:s,onChange:R=>n(R.target.value)}),Le(y,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),Le(y,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>m(R=>!R),children:g?"Close import":"Import"}),Le(y,{type:"button",variant:"outline",size:"sm",disabled:!t||d.busy,onClick:()=>void N(),children:"Export"})]}),g&&Le("div",{className:"af-mt-3",children:Le(lo,{onImported:p})}),d.error&&Le(ue,{tone:"error",className:"af-mt-2",children:d.error}),t&&f.size>0&&Le(vv,{tags:k.filter(R=>!R.system),count:f.size,busy:d.busy,onApply:async(R,C)=>{(await d.run("bulkTagContacts",{action:R,tag_id:C,contact_ids:[...f]})).ok&&(b(new Set),p())}}),Le("div",{className:"af-mt-3",children:v.contacts.error?Le(xt,{message:"Couldn't load contacts.",onRetry:()=>void v.contacts.refetch()}):S?S.contacts.length===0?Le(ca,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):Vt(ou,{children:[Le("ul",{className:"af-divide-y af-rounded-md af-border",children:S.contacts.map(R=>Le(gv,{contact:R,canWrite:t,busy:d.busy,selected:f.has(R.id),onSelect:C=>b(w=>{let P=new Set(w);return C?P.add(R.id):P.delete(R.id),P}),onUnsubscribe:async()=>{(await d.run("unsubscribeContact",{contactId:R.id})).ok&&p()}},R.id))}),Vt("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[Vt("span",{children:[Ae(l+1),"\u2013",Ae(l+S.contacts.length)," of ",Ae(S.total)]}),Vt("div",{className:"af-flex af-gap-2",children:[Le(y,{type:"button",variant:"ghost",size:"sm",disabled:l===0,onClick:()=>u(Math.max(0,l-vr)),children:"Previous"}),Le(y,{type:"button",variant:"ghost",size:"sm",disabled:l+S.contacts.length>=S.total,onClick:()=>u(l+vr),children:"Next"})]})]})]}):Le(G,{className:"af-h-24 af-w-full"})}),Le(bv,{tags:k,canWrite:t,onChanged:p})]})}function gv({contact:e,canWrite:t,busy:a,selected:s,onSelect:n,onUnsubscribe:r}){return Vt("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&Le("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:s,onChange:i=>n(i.target.checked)}),Vt("div",{className:"af-min-w-0 af-flex-1",children:[Vt("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?Vt("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),Vt("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[Le(ee,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":pv[e.status]}),e.tags.map(i=>Le(ee,{variant:"outline",children:i.label},i.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&Le(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:r,children:"Unsubscribe"})]})}function vv({tags:e,count:t,busy:a,onApply:s}){let[n,r]=Yn.useState("");return Vt("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:[Vt("span",{children:[Ae(t)," selected"]}),Vt("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:n,onChange:i=>r(i.target.value),children:[Le("option",{value:"",children:"Choose a tag\u2026"}),e.map(i=>Le("option",{value:i.id,children:i.label},i.id))]}),Le(y,{type:"button",size:"sm",variant:"outline",disabled:!n||a,onClick:()=>s("add",n),children:"Add tag"}),Le(y,{type:"button",size:"sm",variant:"ghost",disabled:!n||a,onClick:()=>s("remove",n),children:"Remove tag"})]})}function bv({tags:e,canWrite:t,onChanged:a}){let[s,n]=Yn.useState(""),[r,i]=Yn.useState(null),l=vt();return Vt("div",{children:[Le(_a,{children:"Tags"}),e.length===0?Le("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."}):Le("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(u=>Le("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:r?.id===u.id?Vt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async c=>{c.preventDefault(),(await l.run("updateTag",{tagId:u.id,label:r.label.trim()})).ok&&(i(null),a())},children:[Le(ae,{"aria-label":`New name for ${u.label}`,value:r.label,onChange:c=>i({id:u.id,label:c.target.value})}),Le(y,{type:"submit",size:"sm",disabled:!r.label.trim()||l.busy,children:"Save"})]}):Vt(ou,{children:[Vt("span",{children:[u.label," ",Vt("span",{className:"af-text-muted-foreground",children:["\xB7 ",Ae(u.total)," contacts, ",Ae(u.mailable)," can be emailed"]})]}),t&&!u.system&&Le(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>i({id:u.id,label:u.label}),children:"Rename"})]})},u.id))}),t&&Vt("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async u=>{u.preventDefault(),(await l.run("createTag",{label:s.trim()})).ok&&(n(""),a())},children:[Le(ae,{"aria-label":"New tag",placeholder:"New tag",value:s,maxLength:100,onChange:u=>n(u.target.value)}),Le(y,{type:"submit",size:"sm",variant:"outline",disabled:!s.trim()||l.busy,children:"Add tag"})]}),l.error&&Le(ue,{tone:"error",className:"af-mt-2",children:l.error})]})}import*as Nt from"react";import{ArrowLeft as Cv}from"lucide-react";function yr({siteId:e,refreshKey:t=0}){let{api:a}=H();return Lt(()=>a.getBroadcasts(e),`${e}|${t}`,e)}function xr({siteId:e,kind:t,refreshKey:a=0}){let{api:s}=H();return Lt(()=>s.getEmailDrafts(e,t),`${e}|${t??""}|${a}`,`${e}|${t??""}`)}import*as We from"react";var zr=e=>typeof e=="number"&&Number.isFinite(e);function xl(e){if(!e||typeof e!="object")return null;let t=e;return zr(t.x)&&zr(t.y)&&zr(t.width)&&zr(t.height)?{x:t.x,y:t.y,width:t.width,height:t.height}:null}var wl=(e,t)=>Number.isInteger(e)&&e>=0&&e<t;function lu(e,t,a){if(!t||e.source!==t)return null;let s=e.data;if(!s||typeof s!="object"||s.af!=="email-editor")return null;switch(s.type){case"hover":{if(s.section===null)return{type:"hover",section:null,rect:null};let n=xl(s.rect);return wl(s.section,a)&&n?{type:"hover",section:s.section,rect:n}:null}case"focus":case"open":{let n=xl(s.rect);return wl(s.section,a)&&n?{type:s.type,section:s.section,rect:n}:null}case"layout":{if(!zr(s.height)||!Array.isArray(s.sections))return null;let n=s.sections.flatMap(r=>{let i=r,l=i?xl(i.rect):null;return i&&wl(i.section,a)&&l?[{section:i.section,rect:l}]:[]});return{type:"layout",height:s.height,sections:n}}case"template":return s.region==="header"||s.region==="footer"?{type:"template",region:s.region}:null;default:return null}}var jr=(e,t,a)=>Math.min(Math.max(e,t),Math.max(t,a));function Sl(e,t){let a=jr(e.x,0,t.width),s=jr(e.y,0,t.height);return{x:a,y:s,width:jr(e.width,0,t.width-a),height:jr(e.height,0,t.height-s)}}var qr={min:240,max:6e3,initial:480},cu=e=>jr(Math.ceil(e),qr.min,qr.max);import*as Us from"react";import{jsx as ka,jsxs as On}from"react/jsx-runtime";var Nl={heading:"Heading",text:"Text",button:"Button",image:"Image",cart:"Cart"};function uu(e){switch(e){case"heading":case"text":return{type:e,text:""};case"button":return{type:e,label:"",url:"https://"};case"image":return{type:e,url:"",alt:""};case"cart":return{type:e,label:"Return to your cart"}}}function Rl(e){switch(e.type){case"heading":case"text":return e.text;case"button":return`${e.label}
2
+ import*as fs from"react";var Do="aifeatures:analytics:timezone",Oo;function Rr(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function mc(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function us(){return Lo()??Rr()}function Lo(){if(Oo!==void 0)return Oo;try{let e=window.localStorage.getItem(Do);return mc(e)?e:null}catch{return null}}function Bo(e){if(!(e!==null&&!mc(e))){Oo=e;try{e===null?window.localStorage.removeItem(Do):window.localStorage.setItem(Do,e)}catch{}}}function oi(e,t){let a=new URLSearchParams({period:String(e)}),s=us();return s&&a.set("timezone",s),t&&t.length>0&&a.set("filters",JSON.stringify(t)),a.toString()}var aa=class extends Error{constructor(a,s,n){super(a);this.status=s;this.details=n;this.name="AifeaturesApiError"}};function li(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 _r(e,t){let a=t.toString();return a?`${e}?${a}`:e}function pc(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 gc(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 Fo(e,t="https://aifeatures.dev"){async function a(n,r={}){let i=`${t}${n}`,l=await fetch(i,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!l.ok){let u;try{u=await l.json()}catch{}throw new aa(li(u?.error,l.status),l.status,u)}if(l.status!==204)return l.json()}async function s(n){let r=await fetch(`${t}${n}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let i;try{i=await r.json()}catch{}throw new aa(li(i?.error,r.status),r.status,i)}return r.blob()}return{async getForms(){return(await a("/api/v1/forms")).forms},async getForm(n){return a(`/api/v1/forms/${n}`)},async createForm(n){return a("/api/v1/forms",{method:"POST",body:JSON.stringify(n)})},async updateForm(n,r){return a(`/api/v1/forms/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(n){await a(`/api/v1/forms/${n}`,{method:"DELETE"})},async getSubmissions(n,r={}){let i=new URLSearchParams;r.limit!==void 0&&i.set("limit",String(r.limit)),r.offset!==void 0&&i.set("offset",String(r.offset));let l=i.toString(),u=`/api/v1/forms/${n}/submissions${l?`?${l}`:""}`;return a(u)},async getSubmission(n){return a(`/api/v1/submissions/${n}`)},async exportSubmissionsCsv(n,r={}){let i=new URLSearchParams;return r.includeSpam&&i.set("include_spam","true"),s(_r(`/api/v1/forms/${encodeURIComponent(n)}/submissions/export`,i))},async deleteSubmission(n){await a(`/api/v1/submissions/${n}`,{method:"DELETE"})},async downloadAttachment(n,r){let i=typeof r=="string"?{name:r}:r,l=i.name,u=i.id??i.name,c=`${t}/api/v1/submissions/${n}/attachments/${encodeURIComponent(u)}`,o=await fetch(c,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let m;try{m=await o.json()}catch{}throw new aa(li(m?.error,o.status),o.status,m)}let f=await o.blob(),b=URL.createObjectURL(f),g=document.createElement("a");g.href=b,g.download=l,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(b)},async getSite(n){return a(`/api/v1/sites/${encodeURIComponent(n)}`)},async updateSite(n,r){return a(`/api/v1/sites/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return a("/api/v1/payments/status")},getPromos(n){let r=new URLSearchParams({limit:"10"});return n&&r.set("cursor",n),a(`/api/v1/promos?${r}`)},getPromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}`)},createPromo(n){return a("/api/v1/promos",{method:"POST",body:JSON.stringify(n)})},disablePromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}/disable`,{method:"POST"})},replacePromo(n,r){return a(`/api/v1/promos/${encodeURIComponent(n)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(n={}){let r=new URLSearchParams;n.include&&r.set("include",n.include);let i=r.toString();return(await a(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(n){return a(`/api/v1/products/${n}`)},async createProduct(n){return a("/api/v1/products",{method:"POST",body:JSON.stringify(n)})},async updateProduct(n,r){return a(`/api/v1/products/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(n){await a(`/api/v1/products/${n}`,{method:"DELETE"})},async attachProductFile(n,r){let i=new FormData;i.append("file",r);let l=await fetch(`${t}/api/v1/products/${n}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!l.ok){let u;try{u=await l.json()}catch{}throw new aa(li(u?.error,l.status),l.status,u)}return l.json()},async attachProductFileFromUrl(n,r){return a(`/api/v1/products/${n}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(n,r){return a(`/api/v1/products/${n}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(n,r){return a(`/api/v1/options/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(n){await a(`/api/v1/options/${n}`,{method:"DELETE"})},async createVariant(n,r){return a(`/api/v1/products/${n}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(n,r){return a(`/api/v1/variants/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(n){await a(`/api/v1/variants/${n}`,{method:"DELETE"})},async setVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(n={}){let r=new URLSearchParams;n.email?r.set("email",n.email):n.q&&r.set("q",n.q),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(n){return a(`/api/v1/customers/${n}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(n={}){let r=pc(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/orders${i?`?${i}`:""}`)},async exportOrdersCsv(n={}){return s(_r("/api/v1/orders/export",pc(n)))},async getOrder(n){return a(`/api/v1/orders/${n}`)},async getInvoices(n={}){let r=new URLSearchParams;n.labels?.length&&r.set("label",n.labels.join(",")),n.customerEmail&&r.set("customer_email",n.customerEmail),n.customerId&&r.set("customer_id",n.customerId),n.q&&r.set("q",n.q),n.from&&r.set("from",n.from),n.to&&r.set("to",n.to),n.includeAggregates&&r.set("include","aggregates"),n.retainerId&&r.set("retainer_id",n.retainerId),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(n){return a(`/api/v1/invoices/${n}`)},async getInvoicePreview(n){return a(`/api/v1/invoices/${n}/preview`)},async getInvoiceSettings(){return a("/api/v1/invoice-settings")},async getRetainers(n={}){let r=gc(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/retainers${i?`?${i}`:""}`)},async exportRetainersCsv(n={}){return s(_r("/api/v1/retainers/export",gc(n)))},async getRetainer(n){return a(`/api/v1/retainers/${n}`)},async resendOrderReceipt(n){await a(`/api/v1/orders/${n}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(n){return a(`/api/v1/orders/${n}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(n,r){return a(`/api/v1/orders/${n}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(n={}){let r=new URLSearchParams;n.status&&r.set("status",n.status),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/subscriptions${i?`?${i}`:""}`)},async exportSubscriptionsCsv(n={}){let r=new URLSearchParams;return n.status&&r.set("status",n.status),s(_r("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let n=new URLSearchParams,r=us();r&&n.set("timezone",r);let i=n.toString();return a(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(n,r){return a(`/api/v1/analytics/summary?${oi(n,r)}`)},async getAnalyticsTimeseries(n,r){return a(`/api/v1/analytics/timeseries?${oi(n,r)}`)},async getAnalyticsRealtime(){return a("/api/v1/analytics/realtime")},async getAnalyticsChannels(n,r){return a(`/api/v1/analytics/channels?${oi(n,r)}`)},async getAnalyticsConversions(n){return a((()=>{let r=new URLSearchParams({period:String(n)}),i=us();return i&&r.set("timezone",i),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(n,r,i){let l=new URLSearchParams({goal:n,period:String(r)}),u=us();return u&&l.set("timezone",u),i!==void 0&&l.set("limit",String(i)),a(`/api/v1/analytics/conversions/targets?${l.toString()}`)},async getAnalyticsBreakdown(n,r,i){let l=n.split("/").map(encodeURIComponent).join("/");return a(`/api/v1/analytics/${l}?${oi(r,i)}`)},async getBusinessSummary(n){let r=new URLSearchParams;r.set("tz_offset_minutes",String(n.tzOffsetMinutes));let i=us();return i&&r.set("timezone",i),a(`/api/v1/summary?${r.toString()}`)},async getPeople(n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/people${i?`?${i}`:""}`)},async exportPeopleCsv(n={}){let r=new URLSearchParams;return n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),s(_r("/api/v1/people/export",r))},async getPerson(n){return a(`/api/v1/people/${encodeURIComponent(n)}`)},async getEventDestinations(){return(await a("/api/v1/event-destinations")).destinations},async createEventDestination(n){return a("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(n)})},async updateEventDestination(n,r){return a(`/api/v1/event-destinations/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(n){await a(`/api/v1/event-destinations/${n}`,{method:"DELETE"})},async rotateEventDestinationSecret(n){return a(`/api/v1/event-destinations/${n}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(n){return(await a(`/api/v1/event-destinations/${n}/secret`)).secret},async getEventDeliveries(n,r){let i=r===void 0?"":`?limit=${r}`;return(await a(`/api/v1/event-destinations/${n}/deliveries${i}`)).deliveries},async retryEventDelivery(n,r){return a(`/api/v1/event-destinations/${n}/deliveries/${r}/retry`,{method:"POST"})},async getMarketingSettings(n){return a(`${Fa(n)}/marketing`)},async getMarketingContacts(n,r={}){let i=new URLSearchParams;r.q&&i.set("q",r.q),r.limit&&i.set("limit",String(r.limit)),r.offset&&i.set("offset",String(r.offset));let l=i.toString();return a(`${Fa(n)}/contacts${l?`?${l}`:""}`)},async getMarketingContactStats(n){return a(`${Fa(n)}/contacts/stats`)},async getMarketingTags(n){return(await a(`${Fa(n)}/contact-tags`)).tags},async getEmailDrafts(n,r){let i=r?`?kind=${r}`:"";return(await a(`${Fa(n)}/marketing/drafts${i}`)).drafts},async getEmailDraft(n,r){return a(`${Fa(n)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(n,r,i){let l=i?.editable?"?mode=editable":"";return a(`${Fa(n)}/marketing/drafts/${encodeURIComponent(r)}/preview${l}`)},async getEmailTemplates(n){return(await a(`${Fa(n)}/marketing/templates`)).templates},async previewEmailTemplate(n,r,i){let l=i?`?draft_id=${encodeURIComponent(i)}`:"";return a(`${Fa(n)}/marketing/templates/${encodeURIComponent(r)}/preview${l}`)},async getBroadcasts(n){return(await a(`${Fa(n)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(n,r){return a(`${Fa(n)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getAutomations(n){return a(`${Fa(n)}/marketing/automations`)},async getAutomation(n,r){return a(`${Fa(n)}/marketing/automations/${encodeURIComponent(r)}`)},async getAutomationStats(n,r){return(await a(`${Fa(n)}/marketing/automations/${encodeURIComponent(r)}/stats`)).steps}}}function Fa(e){return`/api/v1/sites/${encodeURIComponent(e)}`}import{jsx as kr,jsxs as kf}from"react/jsx-runtime";var vc=fs.createContext(null);function Rf(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 _f({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:n}){let r=fs.useMemo(()=>Rf(e),[e]),i=fs.useMemo(()=>Fo(e,t),[e,t]),l=fs.useMemo(()=>({siteToken:e,apiUrl:t,api:i}),[e,t,i]);return r?kr("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:kf("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[kr("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),kr("p",{className:"af-text-sm af-text-destructive",children:r})]})}):kr(vc.Provider,{value:l,children:kr("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:n})})}function H(){let e=fs.useContext(vc);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as rs from"react";import{ArrowLeft as Dm,Settings as Om,Inbox as Lm}from"lucide-react";import*as ci from"react";import*as kn from"@radix-ui/react-tabs";import{clsx as Pf}from"clsx";import{extendTailwindMerge as Cf}from"tailwind-merge";var Tf=Cf({prefix:"af-"});function W(...e){return Tf(Pf(e))}import{jsx as Mo}from"react/jsx-runtime";var di=kn.Root,Pr=ci.forwardRef(({className:e,...t},a)=>Mo(kn.List,{ref:a,className:W("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}));Pr.displayName=kn.List.displayName;var Pn=ci.forwardRef(({className:e,...t},a)=>Mo(kn.Trigger,{ref:a,className:W("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}));Pn.displayName=kn.Trigger.displayName;var Cn=ci.forwardRef(({className:e,...t},a)=>Mo(kn.Content,{ref:a,className:W("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}));Cn.displayName=kn.Content.displayName;import*as bc from"react";import{Slot as Ef}from"@radix-ui/react-slot";import{cva as If}from"class-variance-authority";import{jsx as Df}from"react/jsx-runtime";var Af=If("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),y=bc.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...n},r)=>Df(s?Ef:"button",{className:W(Af({variant:t,size:a,className:e})),ref:r,...n}));y.displayName="Button";import{Inbox as hc,Settings as Bf}from"lucide-react";import*as ts from"react";import{jsx as es}from"react/jsx-runtime";var ct=ts.forwardRef(({className:e,...t},a)=>es("div",{className:"af-relative af-w-full af-overflow-auto",children:es("table",{ref:a,className:W("af-w-full af-caption-bottom af-text-sm",e),...t})}));ct.displayName="Table";var dt=ts.forwardRef(({className:e,...t},a)=>es("thead",{ref:a,className:W("[&_tr]:af-border-b",e),...t}));dt.displayName="TableHeader";var ut=ts.forwardRef(({className:e,...t},a)=>es("tbody",{ref:a,className:W("[&_tr:last-child]:af-border-0",e),...t}));ut.displayName="TableBody";var Of=ts.forwardRef(({className:e,...t},a)=>es("tfoot",{ref:a,className:W("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Of.displayName="TableFooter";var Ie=ts.forwardRef(({className:e,...t},a)=>es("tr",{ref:a,className:W("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Ie.displayName="TableRow";var Z=ts.forwardRef(({className:e,...t},a)=>es("th",{ref:a,className:W("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));Z.displayName="TableHead";var Y=ts.forwardRef(({className:e,...t},a)=>es("td",{ref:a,className:W("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));Y.displayName="TableCell";var Lf=ts.forwardRef(({className:e,...t},a)=>es("caption",{ref:a,className:W("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Lf.displayName="TableCaption";import*as Tn from"react";function Js(){let{api:e}=H(),[t,a]=Tn.useState([]),[s,n]=Tn.useState(!0),[r,i]=Tn.useState(null),l=Tn.useCallback(async()=>{try{n(!0),i(null);let f=await e.getForms();a(f)}catch(f){i(f instanceof Error?f:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);Tn.useEffect(()=>{l()},[l]);let u=Tn.useCallback(async f=>{let b=await e.createForm(f);return a(g=>[...g,b]),b},[e]),c=Tn.useCallback(async(f,b)=>{let g=await e.updateForm(f,b);return a(m=>m.map(v=>v.id===f?g:v)),g},[e]),o=Tn.useCallback(async f=>{await e.deleteForm(f),a(b=>b.filter(g=>g.id!==f))},[e]);return{forms:t,isLoading:s,error:r,refetch:l,createForm:u,updateForm:c,deleteForm:o}}import{jsx as Ma,jsxs as as}from"react/jsx-runtime";function ui({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:n}=Js();return s?Ma("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ma("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?Ma("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:as("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):a.length===0?as("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Ma(hc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),as("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",Ma("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):Ma("div",{className:t,children:as(ct,{children:[Ma(dt,{children:as(Ie,{children:[Ma(Z,{children:"Name"}),Ma(Z,{className:"af-text-right",children:"Actions"})]})}),Ma(ut,{children:a.map(r=>as(Ie,{children:[Ma(Y,{className:"af-font-medium",children:r.name}),Ma(Y,{className:"af-text-right",children:as("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[as(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[Ma(hc,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),as(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[Ma(Bf,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}import{AlertTriangle as Uf}from"lucide-react";import{cva as Ff}from"class-variance-authority";import{jsx as $f}from"react/jsx-runtime";var Mf=Ff("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 ee({className:e,variant:t,...a}){return $f("div",{className:W(Mf({variant:t}),e),...a})}import{jsx as Ts,jsxs as fi}from"react/jsx-runtime";var Vf={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 mi(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 $o(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function Hf(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 Cr({deliveries:e,label:t="Email needs attention"}){return $o(e)?fi("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:[Ts(Uf,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function $n({deliveries:e,problemsOnly:t=!1,className:a=""}){let s=(e??[]).filter(n=>!t||$o([n]));return s.length?Ts("div",{className:`af-space-y-3 ${a}`,"aria-label":"Email delivery",children:s.map(n=>{let r=mi(n),i=Hf(n);return fi("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[fi("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Ts("span",{className:"af-font-medium",children:Vf[n.kind]??"Email notification"}),Ts(ee,{variant:r.variant,children:r.label})]}),fi("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&$o([n])&&Ts("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&&Ts("p",{className:"af-mt-1",children:r.detail}),i&&Ts("p",{className:"af-mt-1",children:i})]},n.id)})}):null}import*as ps from"react";import{ArrowLeft as lm,ChevronLeft as cm,ChevronRight as dm,Eye as um,Inbox as fm,Paperclip as mm}from"lucide-react";import*as ms from"react";import*as ze from"@radix-ui/react-select";import{Check as zf,ChevronDown as yc,ChevronUp as jf}from"lucide-react";import{jsx as xa,jsxs as Uo}from"react/jsx-runtime";var fn=ze.Root;var mn=ze.Value,Qa=ms.forwardRef(({className:e,children:t,...a},s)=>Uo(ze.Trigger,{ref:s,className:W("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...a,children:[t,xa(ze.Icon,{asChild:!0,children:xa(yc,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Qa.displayName=ze.Trigger.displayName;var xc=ms.forwardRef(({className:e,...t},a)=>xa(ze.ScrollUpButton,{ref:a,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:xa(jf,{className:"af-h-4 af-w-4"})}));xc.displayName=ze.ScrollUpButton.displayName;var wc=ms.forwardRef(({className:e,...t},a)=>xa(ze.ScrollDownButton,{ref:a,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:xa(yc,{className:"af-h-4 af-w-4"})}));wc.displayName=ze.ScrollDownButton.displayName;var en=ms.forwardRef(({className:e,children:t,position:a="popper",...s},n)=>xa(ze.Portal,{children:Uo(ze.Content,{ref:n,className:W("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:a,...s,children:[xa(xc,{}),xa(ze.Viewport,{className:W("af-p-1",a==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),xa(wc,{})]})}));en.displayName=ze.Content.displayName;var qf=ms.forwardRef(({className:e,...t},a)=>xa(ze.Label,{ref:a,className:W("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));qf.displayName=ze.Label.displayName;var St=ms.forwardRef(({className:e,children:t,...a},s)=>Uo(ze.Item,{ref:s,className:W("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...a,children:[xa("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:xa(ze.ItemIndicator,{children:xa(zf,{className:"af-h-4 af-w-4"})})}),xa(ze.ItemText,{children:t})]}));St.displayName=ze.Item.displayName;var Wf=ms.forwardRef(({className:e,...t},a)=>xa(ze.Separator,{ref:a,className:W("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));Wf.displayName=ze.Separator.displayName;import*as Ca from"react";function pi({formId:e,initialPageSize:t=25}){let{api:a}=H(),[s,n]=Ca.useState([]),[r,i]=Ca.useState(0),[l,u]=Ca.useState(!0),[c,o]=Ca.useState(null),[f,b]=Ca.useState(0),[g,m]=Ca.useState(t),v=Ca.useRef(0),d=Ca.useCallback(async()=>{if(!e)return;let k=++v.current;try{u(!0),o(null);let h={limit:g,offset:f*g},N=await a.getSubmissions(e,h);if(k!==v.current)return;if(N.submissions.length===0&&f>0){b(Math.max(0,Math.ceil(N.total/g)-1));return}n(N.submissions),i(N.total)}catch(h){if(k!==v.current)return;o(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{k===v.current&&u(!1)}},[a,e,f,g]);Ca.useEffect(()=>{d()},[d]);let p=Ca.useRef(d);p.current=d;let x=Ca.useCallback(async k=>{await a.deleteSubmission(k),p.current()},[a]),S=Math.ceil(r/g);return{submissions:s,total:r,isLoading:l,error:c,page:f,pageSize:g,hasNextPage:f<S-1,hasPreviousPage:f>0,setPage:b,setPageSize:k=>{m(k),b(0)},refetch:d,deleteSubmission:x}}import*as gi from"react";import{Trash2 as Zf}from"lucide-react";import*as Tr from"react";import*as na from"@radix-ui/react-dialog";import{X as Gf}from"lucide-react";import{jsx as ns,jsxs as Vo}from"react/jsx-runtime";var pn=na.Root;var Kf=na.Portal;var Sc=Tr.forwardRef(({className:e,...t},a)=>ns(na.Overlay,{ref:a,className:W("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Sc.displayName=na.Overlay.displayName;var tn=Tr.forwardRef(({className:e,children:t,...a},s)=>ns(Kf,{children:Vo("div",{className:"aifeatures-admin",children:[ns(Sc,{}),Vo(na.Content,{ref:s,className:W("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...a,children:[t,Vo(na.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:[ns(Gf,{className:"af-h-4 af-w-4"}),ns("span",{className:"af-sr-only",children:"Close"})]})]})]})}));tn.displayName=na.Content.displayName;var an=({className:e,...t})=>ns("div",{className:W("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});an.displayName="DialogHeader";var nn=({className:e,...t})=>ns("div",{className:W("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});nn.displayName="DialogFooter";var sn=Tr.forwardRef(({className:e,...t},a)=>ns(na.Title,{ref:a,className:W("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));sn.displayName=na.Title.displayName;var rn=Tr.forwardRef(({className:e,...t},a)=>ns(na.Description,{ref:a,className:W("af-text-sm af-text-muted-foreground",e),...t}));rn.displayName=na.Description.displayName;import{Fragment as Yf,jsx as Es,jsxs as Er}from"react/jsx-runtime";function Xs({onDelete:e,iconOnly:t}){let[a,s]=gi.useState(!1),[n,r]=gi.useState(!1),[i,l]=gi.useState(null);return Er(Yf,{children:[Er(y,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{l(null),s(!0)},children:[Es(Zf,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),Es(pn,{open:a,onOpenChange:c=>{!c&&!n&&s(!1)},children:Er(tn,{children:[Er(an,{children:[Es(sn,{children:"Delete this submission?"}),Es(rn,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),i&&Es("p",{className:"af-text-sm af-text-destructive",children:i}),Er(nn,{children:[Es(y,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),Es(y,{variant:"destructive",onClick:async()=>{r(!0),l(null);try{await e(),s(!1)}catch(c){l(c instanceof Error?c.message:"Failed to delete submission")}finally{r(!1)}},disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}import*as Rc from"react";import{ArrowLeft as Jf,Download as Xf,Globe as Qf,Clock as em,FileText as tm,Loader2 as am,Monitor as nm,Mail as sm}from"lucide-react";import{jsx as $t,jsxs as Dt}from"react/jsx-runtime";function Nc(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function rm(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function vi({submission:e,onBack:t,onDelete:a}){let{api:s}=H(),[n,r]=Rc.useState(null),i=c=>c.id??c.name,l=async c=>{r(i(c));try{await s.downloadAttachment(e.id,c)}catch(o){console.error("Download failed:",o)}finally{r(null)}},u=Object.entries(e.data).filter(([c])=>!c.startsWith("_"));return Dt("div",{children:[Dt("div",{className:"af-mb-6",children:[Dt(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[$t(Jf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Dt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[Dt("div",{children:[$t("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),Dt("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Nc(e.metadata.submitted_at)]})]}),a&&$t(Xs,{onDelete:a})]})]}),Dt("div",{className:"af-space-y-6",children:[$t($n,{deliveries:e.email_deliveries}),Dt("div",{children:[$t("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),Dt("div",{className:"af-space-y-3",children:[u.map(([c,o])=>Dt("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[$t("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:c.replace(/_/g," ")}),$t("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof o=="string"&&o.includes(`
3
+ `)?$t("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:o}):String(o)})]},c)),u.length===0&&$t("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&Dt("div",{children:[$t("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),$t("div",{className:"af-space-y-2",children:e.attachments.map((c,o)=>Dt("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[Dt("div",{className:"af-flex af-items-center af-gap-2",children:[$t(tm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),$t("span",{className:"af-text-sm",children:c.name}),Dt("span",{className:"af-text-xs af-text-muted-foreground",children:["(",rm(c.size),")"]})]}),Dt(y,{variant:"ghost",size:"sm",onClick:()=>l(c),disabled:n===i(c),children:[n===i(c)?$t(am,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):$t(Xf,{className:"af-h-4 af-w-4 af-mr-1"}),n===i(c)?"Downloading...":"Download"]})]},o))})]}),Dt("div",{children:[$t("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),Dt("div",{className:"af-space-y-2 af-text-sm",children:[Dt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[$t(em,{className:"af-h-4 af-w-4"}),$t("span",{children:Nc(e.metadata.submitted_at)})]}),e.metadata.ip_address&&Dt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[$t(Qf,{className:"af-h-4 af-w-4"}),Dt("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&Dt("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[$t(nm,{className:"af-h-4 af-w-4 af-mt-0.5"}),$t("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&Dt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[$t(sm,{className:"af-h-4 af-w-4"}),Dt("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{Download as om}from"lucide-react";import*as Is from"react";var im=/^\+[1-9]\d{1,14}$/;function _c(e){let t=e==null?"":String(e),a=!im.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),s=a?`'${t}`:t;return a||/[",;\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function bi(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function hi(e,t){if(typeof document>"u")return;let a=URL.createObjectURL(e),s=document.createElement("a");s.href=a,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(a)}function yi({fetchCsv:e,filename:t}){let[a,s]=Is.useState(!1),[n,r]=Is.useState(null),i=Is.useRef(!1);return{exportCsv:Is.useCallback(async()=>{if(!i.current){i.current=!0,s(!0),r(null);try{let u=await e();hi(u,bi(t))}catch(u){r(u instanceof Error?u:new Error("Export failed"))}finally{i.current=!1,s(!1)}}},[e,t]),exporting:a,error:n}}import{jsx as kc,jsxs as Pc}from"react/jsx-runtime";function wa({fetchCsv:e,filename:t,label:a="Export CSV",disabled:s,className:n}){let{exportCsv:r,exporting:i,error:l}=yi({fetchCsv:e,filename:t});return Pc("span",{className:n,children:[Pc(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||i,"aria-busy":i,children:[kc(om,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Exporting\u2026":a]}),l&&kc("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}import{jsx as Ue,jsxs as qt}from"react/jsx-runtime";function pm(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function gm(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let a of t)if(typeof e[a]=="string")return e[a];return null}var vm=["message","comments","comment","inquiry","question","details","body","notes"];function bm(e){let t=Object.entries(e).filter(([r,i])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof i=="string"&&i.trim()),a=new Map(t.map(([r,i])=>[r.toLowerCase(),i])),n=(vm.map(r=>a.get(r)).find(Boolean)??t.reduce((r,[,i])=>i.length>r.length?i:r,"")).trim().replace(/\s+/g," ");return n.length>80?n.slice(0,80)+"\u2026":n}function xi({formId:e,className:t,defaultSubmissionId:a,submissionId:s,onSelectSubmission:n}){let{api:r}=H(),{submissions:i,total:l,isLoading:u,error:c,page:o,pageSize:f,hasNextPage:b,hasPreviousPage:g,setPage:m,setPageSize:v,deleteSubmission:d}=pi({formId:e}),p=ps.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[x,S]=ps.useState(a??null),k=n?s??null:x,h=n??S,N=U=>!!U&&U.id===k&&U.form_id===e,R=i.find(N),[C,w]=ps.useState(null),P=N(C)?C:null,[I,_]=ps.useState(null);if(ps.useEffect(()=>{if(_(null),!k||R||P)return;let U=!1;return r.getSubmission(k).then(te=>{if(!U){if(te.form_id!==e){_("This submission could not be found.");return}w(te)}}).catch(()=>{U||_("This submission could not be found.")}),()=>{U=!0}},[r,e,k,R,P]),k){let U=R??P;return U?Ue("div",{className:t,children:Ue(vi,{submission:U,onBack:()=>h(null),onDelete:async()=>{await d(U.id),h(null)}})}):I?qt("div",{className:t,children:[qt(y,{variant:"ghost",size:"sm",onClick:()=>h(null),className:"af-mb-2 af--ml-2",children:[Ue(lm,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Ue("p",{className:"af-text-sm af-text-destructive",children:I})]}):Ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ue("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(u)return Ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ue("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(c)return Ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:qt("div",{className:"af-text-destructive",children:["Error: ",c.message]})});if(i.length===0&&o===0)return qt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Ue(fm,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),qt("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",Ue("br",{}),"Submissions will appear here when visitors use your form."]})]});let q=o*f+1,j=Math.min((o+1)*f,l);return qt("div",{className:t,children:[Ue("div",{className:"af-mb-2 af-flex af-justify-end",children:Ue(wa,{fetchCsv:p,filename:"submissions"})}),qt(ct,{children:[Ue(dt,{children:qt(Ie,{children:[Ue(Z,{children:"Email"}),Ue(Z,{children:"Preview"}),Ue(Z,{children:"Date"}),Ue(Z,{className:"af-text-right",children:"Actions"})]})}),Ue(ut,{children:i.map(U=>{let te=gm(U.data),ce=bm(U.data);return qt(Ie,{children:[qt(Y,{className:"af-font-medium",children:[qt("div",{className:"af-flex af-items-center af-gap-2",children:[te||Ue("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),U.attachments.length>0&&qt("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${U.attachments.length} attachment(s)`,children:[Ue(mm,{className:"af-h-3 af-w-3"}),Ue("span",{className:"af-text-xs",children:U.attachments.length})]})]}),Ue(Cr,{deliveries:U.email_deliveries,label:"Notification email needs attention"})]}),Ue(Y,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:ce||Ue("span",{className:"af-italic",children:"No preview available"})}),Ue(Y,{className:"af-text-muted-foreground",children:pm(U.metadata.submitted_at)}),qt(Y,{className:"af-text-right",children:[Ue(y,{variant:"ghost",size:"icon",onClick:()=>h(U.id),title:"View details",children:Ue(um,{className:"af-h-4 af-w-4"})}),Ue(Xs,{iconOnly:!0,onDelete:()=>d(U.id)})]})]},U.id)})})]}),qt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[qt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[qt("span",{children:["Showing ",q,"-",j," of ",l]}),qt(fn,{value:String(f),onValueChange:U=>v(Number(U)),children:[Ue(Qa,{className:"af-w-[70px] af-h-8",children:Ue(mn,{})}),qt(en,{children:[Ue(St,{value:"10",children:"10"}),Ue(St,{value:"25",children:"25"}),Ue(St,{value:"50",children:"50"}),Ue(St,{value:"100",children:"100"})]})]}),Ue("span",{children:"per page"})]}),qt("div",{className:"af-flex af-items-center af-gap-2",children:[qt(y,{variant:"outline",size:"sm",onClick:()=>m(o-1),disabled:!g,children:[Ue(cm,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),qt(y,{variant:"outline",size:"sm",onClick:()=>m(o+1),disabled:!b,children:["Next",Ue(dm,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as ln from"react";import{Plus as Tm,X as Em,Loader2 as Im,Check as Am}from"lucide-react";import*as Cc from"react";import{jsx as hm}from"react/jsx-runtime";var ae=Cc.forwardRef(({className:e,type:t,...a},s)=>hm("input",{type:t,className:W("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...a}));ae.displayName="Input";import*as Tc from"react";import{cva as ym}from"class-variance-authority";import{jsx as wm}from"react/jsx-runtime";var xm=ym("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Oe=Tc.forwardRef(({className:e,...t},a)=>wm("label",{ref:a,className:W(xm(),e),...t}));Oe.displayName="Label";import*as vn from"react";import{Plus as Nm,Loader2 as Ho,Copy as Rm,Check as _m,Trash2 as km,RefreshCw as Pm,AlertTriangle as Cm}from"lucide-react";import*as on from"react";function wi(){let{api:e}=H(),[t,a]=on.useState([]),[s,n]=on.useState(!0),[r,i]=on.useState(null),l=on.useCallback(async()=>{try{n(!0),i(null),a(await e.getEventDestinations())}catch(g){i(g instanceof Error?g:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);on.useEffect(()=>{l()},[l]);let u=on.useCallback(async g=>{let m=await e.createEventDestination(g);return a(v=>[m,...v]),m},[e]),c=on.useCallback(async(g,m)=>{let v=await e.updateEventDestination(g,m);return a(d=>d.map(p=>p.id===g?v:p)),v},[e]),o=on.useCallback(async g=>{await e.deleteEventDestination(g),a(m=>m.filter(v=>v.id!==g))},[e]),f=on.useCallback(async g=>{let m=await e.rotateEventDestinationSecret(g);return a(v=>v.map(d=>d.id===g?m:d)),m},[e]),b=on.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:s,error:r,refetch:l,createDestination:u,updateDestination:c,deleteDestination:o,rotateSecret:f,getSecret:b}}import*as ss from"react";import{Loader2 as Ec,RotateCw as Sm}from"lucide-react";import{jsx as gn,jsxs as Ir}from"react/jsx-runtime";function Si({destinationId:e,limit:t=25,className:a}){let{api:s}=H(),[n,r]=ss.useState([]),[i,l]=ss.useState(!0),[u,c]=ss.useState(null),[o,f]=ss.useState(null),b=ss.useCallback(async()=>{try{l(!0),c(null),r(await s.getEventDeliveries(e,t))}catch(m){c(m instanceof Error?m.message:"Failed to load deliveries")}finally{l(!1)}},[s,e,t]);ss.useEffect(()=>{b()},[b]);let g=async m=>{try{f(m.id),c(null);let v=await s.retryEventDelivery(e,m.id);r(d=>d.map(p=>p.id===m.id?v:p))}catch(v){c(v instanceof Error?v.message:"Retry failed")}finally{f(null)}};return i?Ir("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[gn(Ec,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):u?gn("div",{className:"af-text-sm af-text-destructive af-py-2",children:u}):n.length===0?gn("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):gn("div",{className:a,children:gn("div",{className:"af-divide-y af-border af-rounded",children:n.map(m=>{let v=m.delivered_at!==null;return Ir("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[Ir("div",{className:"af-min-w-0",children:[Ir("div",{className:"af-flex af-items-center af-gap-2",children:[v?gn(ee,{variant:"secondary",children:m.last_status??200}):gn(ee,{variant:"destructive",children:m.last_status??"failed"}),gn("span",{className:"af-text-sm af-truncate",children:m.type})]}),Ir("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[m.event_id," \xB7 ",m.created_at,m.attempts>0&&` \xB7 ${m.attempts} failed ${m.attempts===1?"attempt":"attempts"}`]}),!v&&m.last_error&&gn("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:m.last_error})]}),gn(y,{variant:"ghost",size:"sm",title:"Send this event again",disabled:o===m.id,onClick:()=>g(m),children:o===m.id?gn(Ec,{className:"af-h-4 af-w-4 af-animate-spin"}):gn(Sm,{className:"af-h-4 af-w-4"})})]},m.id)})})})}import{jsx as tt,jsxs as Zt}from"react/jsx-runtime";function Ni({formId:e,topics:t,description:a,className:s}){let{destinations:n,isLoading:r,error:i,createDestination:l,updateDestination:u,deleteDestination:c,rotateSecret:o,getSecret:f}=wi(),[b,g]=vn.useState(""),[m,v]=vn.useState(!1),[d,p]=vn.useState(null),[x,S]=vn.useState(null),[k,h]=vn.useState(null),[N,R]=vn.useState(!1),[C,w]=vn.useState(null),[P,I]=vn.useState(null),[_,q]=vn.useState(null),j=vn.useMemo(()=>n.filter(A=>A.form_id===e),[n,e]),U=async()=>{let A=b.trim();if(A){if(!A.startsWith("https://")){p("Webhook URLs must start with https://");return}try{v(!0),p(null),await l({url:A,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(ne){p(ne instanceof Error?ne.message:"Failed to add webhook")}finally{v(!1)}}},te=async A=>{try{I(A.id),p(null),await o(A.id),R(!1),h(await f(A.id))}catch(ne){p(ne instanceof Error?ne.message:"Failed to rotate secret")}finally{I(null)}},ce=async A=>{try{I(A.id),p(null),await u(A.id,{status:"active"})}catch(ne){p(ne instanceof Error?ne.message:"Failed to re-enable")}finally{I(null)}},me=async()=>{if(C)try{I(C.id),await c(C.id),w(null)}catch(A){p(A instanceof Error?A.message:"Failed to delete")}finally{I(null)}},T=async A=>{if(x===A.id){S(null),h(null);return}try{I(A.id),p(null),R(!1),S(A.id),h(await f(A.id))}catch(ne){S(null),p(ne instanceof Error?ne.message:"Failed to read secret")}finally{I(null)}},V=async()=>{if(k)try{await navigator.clipboard.writeText(k),R(!0)}catch{}};return Zt("div",{className:s,children:[Zt("div",{className:"af-space-y-1",children:[tt(Oe,{children:"Webhooks"}),tt("p",{className:"af-text-sm af-text-muted-foreground",children:a??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),Zt("div",{className:"af-flex af-gap-2 af-mt-4",children:[tt(ae,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:A=>g(A.target.value),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),U())},disabled:m}),Zt(y,{onClick:U,disabled:m||!b.trim(),children:[m?tt(Ho,{className:"af-h-4 af-w-4 af-animate-spin"}):tt(Nm,{className:"af-h-4 af-w-4"}),tt("span",{className:"af-ml-1",children:"Add"})]})]}),(d||i)&&tt("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:d||i?.message}),Zt("div",{className:"af-mt-4 af-space-y-2",children:[r&&Zt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[tt(Ho,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&j.length===0&&tt("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),j.map(A=>Zt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[Zt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[Zt("div",{className:"af-min-w-0",children:[Zt("div",{className:"af-flex af-items-center af-gap-2",children:[tt("span",{className:"af-font-mono af-text-sm af-truncate",children:A.url}),A.status==="disabled"?tt(ee,{variant:"destructive",children:"Disabled"}):tt(ee,{variant:"secondary",children:"Active"})]}),tt("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:A.topics.includes("*")?"All events":A.topics.join(", ")})]}),Zt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[tt(y,{variant:"ghost",size:"sm",onClick:()=>q(_===A.id?null:A.id),children:_===A.id?"Hide log":"Deliveries"}),tt(y,{variant:"ghost",size:"sm",onClick:()=>T(A),disabled:P===A.id,children:x===A.id?"Hide secret":"Show secret"}),tt(y,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:P===A.id,onClick:()=>w(A),children:tt(km,{className:"af-h-4 af-w-4"})})]})]}),A.status==="disabled"&&Zt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[tt(Cm,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),Zt("div",{className:"af-text-sm",children:[Zt("p",{children:["We stopped sending after repeated failures."," ",A.disabled_reason]}),tt(y,{variant:"outline",size:"sm",className:"af-mt-2",disabled:P===A.id,onClick:()=>ce(A),children:"Re-enable"})]})]}),x===A.id&&k&&Zt("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[tt("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."}),Zt("div",{className:"af-flex af-gap-2",children:[tt(ae,{readOnly:!0,value:k,className:"af-font-mono"}),tt(y,{variant:"outline",title:"Copy signing secret",onClick:V,children:N?tt(_m,{className:"af-h-4 af-w-4"}):tt(Rm,{className:"af-h-4 af-w-4"})}),tt(y,{variant:"outline",title:"Rotate signing secret",disabled:P===A.id,onClick:()=>te(A),children:P===A.id?tt(Ho,{className:"af-h-4 af-w-4 af-animate-spin"}):tt(Pm,{className:"af-h-4 af-w-4"})})]})]}),_===A.id&&tt(Si,{destinationId:A.id})]},A.id))]}),tt(pn,{open:!!C,onOpenChange:A=>{!A&&!P&&w(null)},children:Zt(tn,{children:[Zt(an,{children:[tt(sn,{children:"Delete this webhook?"}),Zt(rn,{children:["New submissions will stop being sent to ",C?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),Zt(nn,{children:[tt(y,{variant:"outline",onClick:()=>w(null),disabled:!!P,children:"Cancel"}),tt(y,{variant:"destructive",onClick:me,disabled:!!P,children:P?"Deleting...":"Delete"})]})]})})]})}import{jsx as ot,jsxs as En}from"react/jsx-runtime";function Ri({form:e,onSaved:t,className:a}){let{updateForm:s}=Js(),[n,r]=ln.useState(!1),[i,l]=ln.useState(null),[u,c]=ln.useState(null),[o,f]=ln.useState(e.name),[b,g]=ln.useState(e.redirect_url||""),[m,v]=ln.useState(e.email_recipients),[d,p]=ln.useState("");ln.useEffect(()=>{f(e.name),g(e.redirect_url||""),v(e.email_recipients),c(null)},[e]);let x=ln.useCallback(async R=>{try{r(!0),c(null);let C=await s(e.id,R);l(new Date),t?.(C)}catch(C){c(C instanceof Error?C.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);ln.useEffect(()=>{if(i){let R=setTimeout(()=>l(null),2e3);return()=>clearTimeout(R)}},[i]);let S=async()=>{let R=d.trim().toLowerCase();if(!R)return;if(!R.includes("@")){c("Please enter a valid email address");return}if(m.includes(R)){c("This email is already added");return}let C=[...m,R];v(C),p(""),c(null),await x({email_recipients:C})},k=async R=>{let C=m.filter(w=>w!==R);v(C),await x({email_recipients:C})},h=async()=>{o!==e.name&&await x({name:o})},N=async()=>{let R=b||null;R!==e.redirect_url&&await x({redirect_url:R})};return En("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(n||i)&&ot("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?En("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:[ot(Im,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),ot("span",{className:"af-text-sm",children:"Saving..."})]}):En("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:[ot(Am,{className:"af-h-4 af-w-4 af-text-green-600"}),ot("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),En("div",{className:"af-space-y-2",children:[ot(Oe,{htmlFor:"form-name",children:"Form Name"}),ot(ae,{id:"form-name",value:o,onChange:R=>f(R.target.value),onBlur:h,placeholder:"Contact Form"}),ot("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),En("div",{className:"af-space-y-2",children:[ot(Oe,{children:"Email Recipients"}),ot("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),En("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[m.map(R=>En(ee,{variant:"secondary",className:"af-gap-1",children:[R,ot("button",{type:"button",onClick:()=>k(R),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:ot(Em,{className:"af-h-3 af-w-3"})})]},R)),m.length===0&&ot("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),En("div",{className:"af-flex af-gap-2",children:[ot(ae,{type:"email",value:d,onChange:R=>p(R.target.value),placeholder:"Add email address",onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),S())},disabled:n}),ot(y,{type:"button",variant:"outline",onClick:S,disabled:!d.trim()||n,children:ot(Tm,{className:"af-h-4 af-w-4"})})]})]}),En("div",{className:"af-space-y-2",children:[ot(Oe,{htmlFor:"redirect-url",children:"Redirect URL"}),ot(ae,{id:"redirect-url",value:b,onChange:R=>g(R.target.value),onBlur:N,placeholder:"/thank-you"}),ot("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."})]}),En("div",{className:"af-space-y-2",children:[ot(Oe,{children:"Form Endpoint"}),ot("div",{className:"af-flex af-items-center af-gap-2",children:ot("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})}),ot("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),En("div",{className:"af-space-y-2",children:[ot(Oe,{children:"Captcha Protection"}),ot("div",{className:"af-flex af-items-center af-gap-2",children:ot(ee,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),ot("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),ot(Ni,{formId:e.id}),u&&ot("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})]})}import{jsx as $a,jsxs as Un}from"react/jsx-runtime";function Ic({className:e,location:t,onNavigate:a,submissionId:s}){let{api:n}=H(),[r,i]=rs.useState({submissionId:s});rs.useEffect(()=>{s&&i({submissionId:s})},[s]);let l=a?t??{}:r,u=a??i,[c,o]=rs.useState(null),f=`${l.formId??""}|${l.submissionId??""}`,[b,g]=rs.useState(null),m=b?.key===f?b.message:null,v=l.formId??(c&&c.submissionId===l.submissionId?c.formId:void 0);rs.useEffect(()=>{let R=l.submissionId;if(!R||l.formId)return;let C=!1;return n.getSubmission(R).then(w=>{C||(g(null),o({submissionId:R,formId:w.form_id}))}).catch(()=>{C||g({key:f,message:"This submission could not be found."})}),()=>{C=!0}},[n,l.submissionId,l.formId,f]);let[d,p]=rs.useState(null);rs.useEffect(()=>{if(!v||d?.id===v)return;let R=!1;return n.getForm(v).then(C=>{R||(g(null),p(C))}).catch(()=>{R||g({key:f,message:"This form could not be found."})}),()=>{R=!0}},[n,v,d?.id,f]);let x=(R,C)=>{p(R),u({formId:R.id,tab:C})},S=()=>u({});if(!l.formId&&!l.submissionId)return Un("div",{className:e,children:[Un("div",{className:"af-mb-6",children:[$a("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),$a("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),$a(ui,{onSelectForm:x})]});let h=Un(y,{variant:"ghost",size:"sm",onClick:S,className:"af-mb-2 af--ml-2",children:[$a(Dm,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(m)return Un("div",{className:e,children:[h,$a("p",{className:"af-text-sm af-text-destructive",children:m})]});if(!v||d?.id!==v)return $a("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:$a("div",{className:"af-text-muted-foreground",children:"Loading..."})});let N=l.submissionId?"submissions":l.tab??"submissions";return Un("div",{className:e,children:[Un("div",{className:"af-mb-6",children:[h,$a("h2",{className:"af-text-lg af-font-semibold",children:d.name})]}),Un(di,{value:N,onValueChange:R=>u({formId:v,tab:R}),children:[Un(Pr,{className:"af-mb-4",children:[Un(Pn,{value:"submissions",className:"af-gap-2",children:[$a(Lm,{className:"af-h-4 af-w-4"}),"Submissions"]}),Un(Pn,{value:"settings",className:"af-gap-2",children:[$a(Om,{className:"af-h-4 af-w-4"}),"Settings"]})]}),$a(Cn,{value:"submissions",children:$a(xi,{formId:v,submissionId:l.submissionId,onSelectSubmission:R=>u({formId:v,tab:"submissions",submissionId:R??void 0})})}),$a(Cn,{value:"settings",children:$a(Ri,{form:d,onSaved:p})})]})]})}import*as lt from"react";import*as Vn from"react";function gs(){let{api:e}=H(),[t,a]=Vn.useState(null),[s,n]=Vn.useState(!0),[r,i]=Vn.useState(null),l=Vn.useRef(0),u=Vn.useCallback(async()=>{let c=++l.current;try{n(!0),i(null);let o=await e.getPaymentsStatus();if(c!==l.current)return;a(o)}catch(o){if(c!==l.current)return;i(o instanceof Error?o:new Error("Failed to fetch payments status"))}finally{c===l.current&&n(!1)}},[e]);return Vn.useEffect(()=>{u()},[u]),{status:t,isLoading:s,error:r,refetch:u}}var Bm=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function bn(e){return Bm.has(e.toLowerCase())}function Q(e,t,a){let s=bn(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function is(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 va(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=bn(t)?a:a*100;return Math.round(s)}function Ot(e,t){return bn(t)?e:e/100}function _i(e){return e.amount_paid??Math.max(0,is(e)-(e.credit_applied??0))}import{Fragment as $m,jsx as rt,jsxs as mt}from"react/jsx-runtime";function Ar(e){return e instanceof aa&&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 Ac(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${Q(e.amount_off,e.currency)} off`:"Discount unavailable"}function Qs(){let{api:e,siteToken:t}=H();return rt(Fm,{api:e},t)}function Fm({api:e}){let{status:t,error:a}=gs(),[s,n]=lt.useState([]),[r,i]=lt.useState(null),[l,u]=lt.useState(null),[c,o]=lt.useState(!1),[f,b]=lt.useState(!1),[g,m]=lt.useState(""),[v,d]=lt.useState(null),[p,x]=lt.useState(null),[S,k]=lt.useState(!1),h=lt.useRef(0),N=lt.useCallback(async w=>{let P=++h.current;o(!0),m("");try{let I=await e.getPromos(w);if(P!==h.current)return;n(_=>w?[..._,...I.promos.filter(q=>!_.some(j=>j.id===q.id))]:I.promos),i(I.next_cursor),u(I.checkout_enabled)}catch(I){P===h.current&&m(Ar(I))}finally{P===h.current&&o(!1)}},[e]);lt.useEffect(()=>(N(),()=>{h.current++}),[N]);async function R(w){let P=++h.current;o(!0),m(""),k(!1);try{let I=await e.getPromo(w);P===h.current&&d(I)}catch(I){P===h.current&&m(Ar(I))}finally{P===h.current&&o(!1)}}async function C(){if(v){b(!0),o(!0),m("");try{let w=await e.disablePromo(v.id);if(d(w),!["inactive","expired","exhausted"].includes(w.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");k(!1),await N()}catch(w){m(Ar(w))}finally{b(!1),o(!1)}}}return p?rt(Mm,{currency:t?.currency??void 0,replaces:p.replaces,onCancel:()=>x(null),onSave:async w=>{let P=p.replaces?await e.replacePromo(p.replaces.id,w):await e.createPromo(w),I=await e.getPromo(P.id);if(I.status==="pending"||I.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");d(I),x(null),await N()}}):mt("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[mt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[rt("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),rt(y,{disabled:c||!t?.currency,onClick:()=>{m(""),x({})},children:"Create promo code"})]}),rt("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),l===!1&&rt("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&&rt("p",{className:"af-text-sm",children:a?Ar(a):"Connect Stripe and set the payment currency before creating codes."}),g&&mt("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",rt(y,{variant:"outline",disabled:c,onClick:()=>v?void R(v.id):void N(),children:"Refresh"})]}),v?mt("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[rt(y,{variant:"ghost",disabled:f,onClick:()=>{d(null),k(!1),N()},children:"Back to codes"}),mt("h4",{className:"af-font-semibold af-break-all",children:[v.code," \xB7 ",v.name]}),mt("p",{children:[Ac(v)," \xB7 ",v.status]}),mt("p",{className:"af-text-sm",children:[v.times_redeemed==null?"Usage unavailable":`${v.times_redeemed} redemptions`,v.max_redemptions!=null?` / ${v.max_redemptions} maximum`:""]}),mt("p",{className:"af-text-sm",children:[v.minimum_amount!=null&&v.currency?`Minimum order: ${Q(v.minimum_amount,v.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),mt("p",{className:"af-text-sm",children:["Subscription discount:"," ",v.duration==="repeating"?`${v.duration_in_months} months`:v.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),rt("p",{className:"af-text-sm",children:v.expires_at?`Expires ${new Date(v.expires_at).toLocaleString()}`:"No expiry"}),mt("div",{className:"af-flex af-flex-wrap af-gap-2",children:[rt(y,{variant:"outline",disabled:c,onClick:()=>void R(v.id),children:"Refresh details"}),rt(y,{variant:"outline",disabled:c||v.status==="pending"||v.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:v}),children:"Replace with new code"}),rt(y,{variant:"outline",disabled:c||!["active","pending","unavailable"].includes(v.status),onClick:()=>k(!0),children:v.status==="pending"?"Cancel pending offer":"Disable code"})]}),S&&mt("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[mt("p",{className:"af-text-sm",children:[v.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${v.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),rt(y,{disabled:c,onClick:()=>void C(),children:v.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",rt(y,{variant:"ghost",disabled:c,onClick:()=>k(!1),children:"Cancel"})]})]}):mt($m,{children:[s.map(w=>mt("button",{type:"button",disabled:c,onClick:()=>void R(w.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:[mt("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[rt("span",{className:"af-font-semibold af-break-all",children:w.code}),rt("span",{className:"af-text-sm",children:w.status})]}),mt("div",{className:"af-text-sm",children:[Ac(w)," \xB7"," ",w.times_redeemed==null?"Usage unavailable":`${w.times_redeemed} redemptions`]})]},w.id)),!c&&!g&&s.length===0&&rt("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),c&&rt("p",{role:"status",children:"Loading promo codes\u2026"}),r&&rt(y,{variant:"outline",disabled:c,onClick:()=>void N(r),children:"Load more"})]})]})}function Mm({currency:e,replaces:t,onCancel:a,onSave:s}){let[n,r]=lt.useState(""),[i,l]=lt.useState(t?.name??""),[u,c]=lt.useState(t?.amount_off!=null?"fixed":"percent"),[o,f]=lt.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(Ot(t.amount_off,e)):"")),[b,g]=lt.useState(t?.minimum_amount!=null&&e?String(Ot(t.minimum_amount,e)):""),[m,v]=lt.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):""}),[d,p]=lt.useState(t?.max_redemptions?.toString()??""),[x,S]=lt.useState(t?.duration??"once"),[k,h]=lt.useState(t?.duration_in_months?.toString()??"3"),[N,R]=lt.useState(null),[C,w]=lt.useState(!1),[P,I]=lt.useState(""),_=lt.useRef(!1),q=e&&bn(e)?"1":"0.01";async function j(ce){if(ce.preventDefault(),_.current)return;I("");let me=N;if(!me){if(!e){I("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){I("Choose a different code for the replacement.");return}let T=va(o,e),V=b?va(b,e):null;if(u==="fixed"&&(!T||T>999999999999)||b&&(!V||V>999999999999)){I("Enter a positive amount within the supported range.");return}if(m&&new Date(m).getTime()<=Date.now()){I("Choose a future expiry.");return}me={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:i.trim(),duration:x,...u==="percent"?{percent_off:Number(o)}:{amount_off:T,currency:e},...b?{minimum_amount:V,currency:e}:{},...m?{expires_at:new Date(m).toISOString()}:{},...d?{max_redemptions:Number(d)}:{},...x==="repeating"?{duration_in_months:Number(k)}:{}},R(me)}_.current=!0,w(!0);try{await s(me)}catch(T){I(Ar(T)),T instanceof aa&&T.status>=400&&T.status<500&&T.details?.retryable!==!0&&R(null)}finally{_.current=!1,w(!1)}}let U=(ce,me,T,V={})=>mt("label",{className:"af-grid af-gap-1 af-text-sm",children:[ce,rt(ae,{"aria-label":ce,value:me,onChange:A=>T(A.target.value),...V})]}),te="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return mt("form",{onSubmit:j,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[rt("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&rt("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."}),mt("fieldset",{disabled:C||!!N,className:"af-grid af-gap-4",children:[U("Code",n,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),U("Name",i,l,{required:!0,maxLength:40}),mt("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",mt("select",{"aria-label":"Discount type",className:te,value:u,onChange:ce=>c(ce.target.value),children:[rt("option",{value:"percent",children:"Percentage"}),mt("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),U("Discount",o,f,{type:"number",required:!0,min:u==="percent"?"0.01":q,max:u==="percent"?"100":void 0,step:u==="percent"?"0.01":q}),U("Minimum order amount",b,g,{type:"number",min:q,step:q,placeholder:e?.toUpperCase()}),mt("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."]}),U("Expires at (local time)",m,v,{type:"datetime-local",step:1}),U("Maximum redemptions",d,p,{type:"number",min:1,max:1e6,step:1}),mt("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",mt("select",{"aria-label":"Subscription duration",className:te,value:x,onChange:ce=>S(ce.target.value),children:[rt("option",{value:"once",children:"First invoice only"}),rt("option",{value:"forever",children:"Every invoice"}),rt("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&U("Months",k,h,{type:"number",required:!0,min:1,max:36,step:1})]}),P&&rt("p",{role:"alert",className:"af-text-sm af-text-destructive",children:P}),N&&!C&&mt("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",rt("span",{className:"af-break-all",children:N.request_id})]}),mt("div",{className:"af-flex af-flex-wrap af-gap-2",children:[rt(y,{type:"submit",disabled:C,children:C?"Saving\u2026":N?"Retry same request":t?"Create replacement":"Create code"}),rt(y,{type:"button",variant:"ghost",disabled:C||!!N,onClick:a,children:"Cancel"})]})]})}import*as cr from"react";import{ArrowLeft as cg,FileText as dg,Package as ug,Receipt as fg,Settings as mg,Users as pg}from"lucide-react";import*as ki from"react";import{Package as Um,Pencil as Vm,Plus as Dc,Trash2 as Hm}from"lucide-react";import{jsx as ft,jsxs as Sa}from"react/jsx-runtime";function zm(e){if(e.allow_custom_amount){let t=e.min_amount!==null?Q(e.min_amount,e.currency):"?",a=e.max_amount!==null?Q(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":Q(e.unit_amount,e.currency)}function jm(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Pi({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:n,isLoading:r,error:i,deleteProduct:l}=e,[u,c]=ki.useState(null),[o,f]=ki.useState(!1),[b,g]=ki.useState(null),m=async()=>{if(u)try{f(!0),g(null),await l(u.id),c(null)}catch(v){g(v instanceof Error?v.message:"Failed to delete product")}finally{f(!1)}};return r?ft("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ft("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):i?ft("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Sa("div",{className:"af-text-destructive",children:["Error: ",i.message]})}):n.length===0?Sa("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[ft(Um,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Sa("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",ft("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),Sa(y,{variant:"outline",onClick:()=>a?.(),children:[ft(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Sa("div",{className:s,children:[ft("div",{className:"af-flex af-justify-end af-mb-4",children:Sa(y,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[ft(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Sa(ct,{children:[ft(dt,{children:Sa(Ie,{children:[ft(Z,{children:"Name"}),ft(Z,{children:"Price"}),ft(Z,{children:"Fulfillment"}),ft(Z,{children:"Status"}),ft(Z,{className:"af-text-right",children:"Actions"})]})}),ft(ut,{children:n.map(v=>Sa(Ie,{children:[ft(Y,{className:"af-font-medium",children:v.name}),ft(Y,{children:zm(v)}),ft(Y,{className:"af-text-muted-foreground",children:jm(v)}),ft(Y,{children:ft(ee,{variant:v.active?"success":"secondary",children:v.active?"Active":"Inactive"})}),ft(Y,{className:"af-text-right",children:Sa("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Sa(y,{variant:"ghost",size:"sm",onClick:()=>t?.(v),children:[ft(Vm,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Sa(y,{variant:"ghost",size:"sm",onClick:()=>{g(null),c(v)},children:[ft(Hm,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},v.id))})]}),ft(pn,{open:!!u,onOpenChange:v=>{!v&&!o&&c(null)},children:Sa(tn,{children:[Sa(an,{children:[ft(sn,{children:"Delete product?"}),Sa(rn,{children:['"',u?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&ft("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),Sa(nn,{children:[ft(y,{variant:"outline",onClick:()=>c(null),disabled:o,children:"Cancel"}),ft(y,{variant:"destructive",onClick:m,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})}import*as _t from"react";import{FileText as Wm,Link2 as Gm,Loader2 as Bc,Plus as Km,Upload as Zm,X as Ym}from"lucide-react";import*as Yt from"react";import{Loader2 as Oc,Plus as zo,Trash2 as Lc,X as qm}from"lucide-react";import{jsx as ie,jsxs as Ce}from"react/jsx-runtime";function jo(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Ci({productId:e,currency:t,className:a}){let{api:s}=H(),n=bn(t)?"1":"0.01",[r,i]=Yt.useState(null),[l,u]=Yt.useState(!0),[c,o]=Yt.useState(null),[f,b]=Yt.useState(null),[g,m]=Yt.useState(!1),v=Yt.useRef(!0);Yt.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);let d=Yt.useCallback(async()=>{try{let E=await s.getProduct(e);if(!v.current)return;i(E)}catch(E){if(!v.current)return;o(E instanceof Error?E.message:"Failed to load product")}finally{v.current&&u(!1)}},[s,e]);Yt.useEffect(()=>{d()},[d]);let p=async E=>{b(null),m(!0);try{await E(),await d()}catch(M){v.current&&b(M instanceof Error?M.message:"Something went wrong")}finally{v.current&&m(!1)}},[x,S]=Yt.useState(""),[k,h]=Yt.useState(""),[N,R]=Yt.useState({}),C=()=>p(async()=>{let E=x.trim(),M=k.split(",").map(L=>L.trim()).filter(Boolean);if(!E)throw new Error("Option name is required");if(M.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:E,values:M}),v.current&&(S(""),h(""))}),w=E=>p(async()=>{let M=(N[E.id]??"").trim();if(!M)throw new Error("Enter a value");await s.updateOption(E.id,{add_values:[M]}),v.current&&R(L=>({...L,[E.id]:""}))}),P=(E,M)=>p(()=>s.updateOption(E.id,{remove_values:[M]})),I=E=>p(()=>s.deleteOption(E.id)),[_,q]=Yt.useState(null),[j,U]=Yt.useState(null),[te,ce]=Yt.useState(!1),[me,T]=Yt.useState(null),V=r?.options??[],A=r?.variants??[],ne=()=>{U(null),q({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(V.map(E=>[E.id,E.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},re=E=>{U(null);let M=E.inventory?.on_hand??0,L=M<0?"":String(M);q({variant:E,title:E.title??"",sku:E.sku??"",unitAmount:E.unit_amount!=null?String(Ot(E.unit_amount,t)):"",compareAt:E.compare_at_amount!=null?String(Ot(E.compare_at_amount,t)):"",active:E.active,optionValues:{},tracked:E.inventory?.tracked??!1,onHand:L,initialOnHand:L,allowBackorder:E.inventory?.allow_backorder??!1})},Me=async()=>{if(!_)return;U(null);let E=_.variant?.allow_custom_amount??!1,M=null,L=null;if(!E){if(M=va(_.unitAmount,t),M===null||M<=0){U("Enter a valid price");return}if(_.compareAt.trim()&&(L=va(_.compareAt,t),L===null||L<=M)){U("Compare-at price must be greater than the price");return}}let pe=_.onHand.trim()!==_.initialOnHand.trim(),J=parseInt(_.onHand,10);if(_.tracked&&pe&&(!Number.isFinite(J)||J<0)){U("On-hand quantity must be zero or more");return}try{if(ce(!0),_.variant)await s.updateVariant(_.variant.id,{title:_.title.trim()||null,sku:_.sku.trim()||null,...E?{}:{unit_amount:M,compare_at_amount:L},active:_.active}),await s.setVariantInventory(_.variant.id,{tracked:_.tracked,on_hand:_.tracked&&pe?J:void 0,allow_backorder:_.allowBackorder});else{let se={};for(let Fe of V){let Qe=_.optionValues[Fe.id];if(!Qe){U(`Choose a ${Fe.title}`),ce(!1);return}se[Fe.title]=Qe}await s.createVariant(e,{title:_.title.trim()||null,sku:_.sku.trim()||null,unit_amount:M,compare_at_amount:L,active:_.active,option_values:V.length>0?se:void 0,inventory:_.tracked?{tracked:!0,on_hand:J,allow_backorder:_.allowBackorder}:{tracked:!1,allow_backorder:_.allowBackorder}})}await d(),v.current&&q(null)}catch(se){if(v.current&&U(se instanceof Error?se.message:"Failed to save variant"),_.variant)try{let Fe=await s.getProduct(e);v.current&&i(Fe)}catch{}}finally{v.current&&ce(!1)}},Se=()=>p(async()=>{me&&(await s.deleteVariant(me.id),v.current&&T(null))}),Ee=_?.variant?.allow_custom_amount??!1,Ye=_?.variant!=null&&_.variant.option_values.length===0&&V.length>0&&!_.variant.active,ke=_?.variant?.inventory!=null&&_.variant.inventory.on_hand<0?-_.variant.inventory.on_hand:null;function nt(E){let M=E.inventory;if(!M||!M.tracked)return ie("span",{className:"af-text-muted-foreground",children:"Unlimited"});let L=M.available??M.on_hand;return L<0?Ce("span",{children:[-L," backordered"]}):Ce("span",{children:[L," in stock",M.allow_backorder&&ie("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return l?ie("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:ie(Oc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):c?ie("div",{className:a,children:ie("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c})}):Ce("div",{className:`af-space-y-6 ${a||""}`,children:[Ce("div",{className:"af-space-y-3",children:[Ce("div",{children:[ie(Oe,{children:"Options"}),ie("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),V.length>0&&ie("div",{className:"af-space-y-3",children:V.map(E=>Ce("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[Ce("div",{className:"af-flex af-items-center af-justify-between",children:[ie("span",{className:"af-text-sm af-font-medium",children:E.title}),ie(y,{variant:"ghost",size:"sm",onClick:()=>I(E),disabled:g,children:ie(Lc,{className:"af-h-4 af-w-4"})})]}),ie("div",{className:"af-flex af-flex-wrap af-gap-2",children:E.values.map(M=>Ce(ee,{variant:"secondary",className:"af-gap-1",children:[M.value,ie("button",{type:"button",onClick:()=>P(E,M.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:ie(qm,{className:"af-h-3 af-w-3"})})]},M.id))}),Ce("div",{className:"af-flex af-gap-2",children:[ie(ae,{value:N[E.id]??"",onChange:M=>R(L=>({...L,[E.id]:M.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),w(E))},disabled:g}),ie(y,{type:"button",variant:"outline",size:"sm",onClick:()=>w(E),disabled:g||!(N[E.id]??"").trim(),children:ie(zo,{className:"af-h-4 af-w-4"})})]})]},E.id))}),Ce("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[Ce("div",{className:"af-space-y-1",children:[ie(Oe,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),ie(ae,{id:"new-option-title",value:x,onChange:E=>S(E.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),Ce("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[ie(Oe,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),ie(ae,{id:"new-option-values",value:k,onChange:E=>h(E.target.value),placeholder:"S, M, L",disabled:g})]}),Ce(y,{type:"button",variant:"outline",onClick:C,disabled:g||!x.trim()||!k.trim(),children:[ie(zo,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),Ce("div",{className:"af-space-y-3",children:[Ce("div",{className:"af-flex af-items-center af-justify-between",children:[ie(Oe,{children:"Variants"}),Ce(y,{type:"button",variant:"outline",size:"sm",onClick:ne,disabled:g||V.length===0,children:[ie(zo,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),V.length===0&&ie("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),A.length===0?ie("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):Ce(ct,{children:[ie(dt,{children:Ce(Ie,{children:[ie(Z,{children:"Variant"}),ie(Z,{children:"SKU"}),ie(Z,{children:"Price"}),ie(Z,{children:"Stock"}),ie(Z,{children:"Status"}),ie(Z,{className:"af-text-right",children:"Actions"})]})}),ie(ut,{children:A.map(E=>Ce(Ie,{children:[ie(Y,{className:"af-font-medium",children:jo(E)}),ie(Y,{className:"af-text-muted-foreground",children:E.sku||"-"}),ie(Y,{children:E.unit_amount!=null?Ce("span",{children:[E.compare_at_amount!=null&&ie("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:Q(E.compare_at_amount,E.currency)}),Q(E.unit_amount,E.currency)]}):E.allow_custom_amount?ie("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),ie(Y,{children:nt(E)}),ie(Y,{children:ie(ee,{variant:E.active?"success":"secondary",children:E.active?"Active":"Inactive"})}),ie(Y,{className:"af-text-right",children:Ce("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[ie(y,{variant:"ghost",size:"sm",onClick:()=>re(E),disabled:g,children:"Edit"}),ie(y,{variant:"ghost",size:"icon",onClick:()=>T(E),disabled:g,title:"Delete variant",children:ie(Lc,{className:"af-h-4 af-w-4"})})]})})]},E.id))})]})]}),f&&ie("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f}),ie(pn,{open:_!==null,onOpenChange:E=>{!E&&!te&&q(null)},children:Ce(tn,{children:[Ce(an,{children:[ie(sn,{children:_?.variant?"Edit variant":"Add variant"}),ie(rn,{children:"Price, markdown, and stock live on the variant."})]}),_&&Ce("div",{className:"af-space-y-3",children:[_.variant?_.variant.option_values.length>0&&Ce("div",{className:"af-text-sm",children:[ie("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),jo(_.variant)]}):V.map(E=>Ce("div",{className:"af-space-y-1",children:[ie(Oe,{className:"af-text-xs af-text-muted-foreground",children:E.title}),Ce(fn,{value:_.optionValues[E.id]??"",onValueChange:M=>q(L=>L&&{...L,optionValues:{...L.optionValues,[E.id]:M}}),children:[ie(Qa,{children:ie(mn,{placeholder:`Choose ${E.title}`})}),ie(en,{children:E.values.map(M=>ie(St,{value:M.value,children:M.value},M.id))})]})]},E.id)),Ee?Ce("div",{className:"af-space-y-1",children:[ie(Oe,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),ie("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):Ce("div",{className:"af-flex af-gap-3",children:[Ce("div",{className:"af-space-y-1",children:[Ce(Oe,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),ie(ae,{id:"variant-price",type:"number",min:"0",step:n,value:_.unitAmount,onChange:E=>q(M=>M&&{...M,unitAmount:E.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),Ce("div",{className:"af-space-y-1",children:[ie(Oe,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),ie(ae,{id:"variant-compare",type:"number",min:"0",step:n,value:_.compareAt,onChange:E=>q(M=>M&&{...M,compareAt:E.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),Ce("div",{className:"af-space-y-1",children:[ie(Oe,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),ie(ae,{id:"variant-sku",value:_.sku,onChange:E=>q(M=>M&&{...M,sku:E.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),Ce("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[Ce("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ie("input",{type:"checkbox",checked:_.tracked,onChange:E=>q(M=>M&&{...M,tracked:E.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),_.tracked&&Ce("div",{className:"af-space-y-1 af-pl-6",children:[Ce("div",{className:"af-flex af-items-end af-gap-3",children:[Ce("div",{className:"af-space-y-1",children:[ie(Oe,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),ie(ae,{id:"variant-onhand",type:"number",min:"0",step:"1",value:_.onHand,onChange:E=>q(M=>M&&{...M,onHand:E.target.value}),placeholder:ke!=null?"0":void 0,className:"af-w-[100px]"})]}),Ce("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[ie("input",{type:"checkbox",checked:_.allowBackorder,onChange:E=>q(M=>M&&{...M,allowBackorder:E.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),ke!=null&&Ce("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",ke," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),Ce("div",{className:"af-space-y-1",children:[Ce("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ie("input",{type:"checkbox",checked:_.active,onChange:E=>q(M=>M&&{...M,active:E.target.checked}),className:"af-h-4 af-w-4",disabled:Ye}),"Active (buyers can purchase this variant)"]}),Ye&&ie("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&&ie("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:j})]}),Ce(nn,{children:[ie(y,{variant:"outline",onClick:()=>q(null),disabled:te,children:"Cancel"}),Ce(y,{onClick:Me,disabled:te,children:[te?ie(Oc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,_?.variant?"Save":"Add variant"]})]})]})}),ie(pn,{open:me!==null,onOpenChange:E=>{!E&&!g&&T(null)},children:Ce(tn,{children:[Ce(an,{children:[ie(sn,{children:"Delete variant?"}),ie(rn,{children:me&&`"${jo(me)}" will no longer be purchasable. Past orders are unaffected.`})]}),Ce(nn,{children:[ie(y,{variant:"outline",onClick:()=>T(null),disabled:g,children:"Cancel"}),ie(y,{variant:"destructive",onClick:Se,disabled:g,children:"Delete"})]})]})})]})}import{Fragment as Xm,jsx as Te,jsxs as Ge}from"react/jsx-runtime";function Jm(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function Ti({productsState:e,product:t,currency:a,onSaved:s,className:n}){let{createProduct:r,updateProduct:i,attachProductFile:l,attachProductFileFromUrl:u}=e,c=!!t,o=t?.currency??a,f=bn(o)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,m]=_t.useState(!1),[v,d]=_t.useState(null),p=_t.useRef(!0);_t.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);let[x,S]=_t.useState(t?.name??""),[k,h]=_t.useState(t?.description??""),[N,R]=_t.useState(t?.allow_custom_amount?"custom":"fixed"),[C,w]=_t.useState(t?.unit_amount!=null?String(Ot(t.unit_amount,o)):""),[P,I]=_t.useState(t?.min_amount!=null?String(Ot(t.min_amount,o)):""),[_,q]=_t.useState(t?.max_amount!=null?String(Ot(t.max_amount,o)):""),[j,U]=_t.useState(String(t?.max_quantity??10)),te=_t.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(Ot(t.unit_amount,o)):"",minAmount:t?.min_amount!=null?String(Ot(t.min_amount,o)):"",maxAmount:t?.max_amount!=null?String(Ot(t.max_amount,o)):"",maxQuantity:String(t?.max_quantity??10)}).current,[ce,me]=_t.useState(t?.collect_shipping_address??!1),[T,V]=_t.useState(t?.active??!0),[A,ne]=_t.useState(t?.images??[]),[re,Me]=_t.useState(""),[Se,Ee]=_t.useState(t?.fulfillment??null),[Ye,ke]=_t.useState(!1),[nt,E]=_t.useState(""),[M,L]=_t.useState(null),pe=_t.useRef(null),J=g||Ye,se=()=>{let he=re.trim();if(he){if(A.includes(he)){d("This image URL is already added");return}ne($e=>[...$e,he]),Me(""),d(null)}},Fe=he=>{ne($e=>$e.filter(yt=>yt!==he))},Qe=async()=>{if(d(null),!x.trim()){d("Product name is required");return}let he=null,$e=null,yt=null,At=!c||N!==te.pricingMode||(N==="fixed"?C!==te.unitAmount:P!==te.minAmount||_!==te.maxAmount),Mt=!c||j!==te.maxQuantity,et=b||N==="fixed";if(!(b||!At))if(N==="fixed"){if(he=va(C,o),he===null||he<=0){d("Enter a valid price");return}}else{if($e=va(P,o),yt=va(_,o),$e===null||yt===null){d("Enter valid minimum and maximum amounts");return}if(yt<$e){d("Maximum amount must be at least the minimum amount");return}}let ta=parseInt(j,10);if(et&&Mt&&(!Number.isFinite(ta)||ta<1)){d("Max quantity must be at least 1");return}try{m(!0);let Je;if(c&&t){let wt={name:x.trim(),description:k.trim()||null,images:A,collect_shipping_address:ce,active:T};!b&&At&&(wt.allow_custom_amount=N==="custom",N==="fixed"?wt.unit_amount=he:(wt.min_amount=$e,wt.max_amount=yt)),et&&Mt&&(wt.max_quantity=ta),Je=await i(t.id,wt),te.pricingMode=Je.allow_custom_amount?"custom":"fixed",te.unitAmount=Je.unit_amount!=null?String(Ot(Je.unit_amount,o)):"",te.minAmount=Je.min_amount!=null?String(Ot(Je.min_amount,o)):"",te.maxAmount=Je.max_amount!=null?String(Ot(Je.max_amount,o)):"",te.maxQuantity=String(Je.max_quantity)}else{let wt={name:x.trim(),allow_custom_amount:N==="custom",collect_shipping_address:ce,active:T};k.trim()&&(wt.description=k.trim()),A.length>0&&(wt.images=A),N==="fixed"?(wt.unit_amount=he,wt.max_quantity=ta):(wt.min_amount=$e,wt.max_amount=yt),Je=await r(wt)}if(!p.current)return;Ee(Je.fulfillment),s?.(Je)}catch(Je){if(!p.current)return;d(Je instanceof Error?Je.message:"Failed to save product")}finally{p.current&&m(!1)}},Xe=async he=>{let $e=he.target.files?.[0];if(!(!$e||!t))try{ke(!0),L(null);let yt=await l(t.id,$e);if(!p.current)return;Ee(yt.fulfillment),s?.(yt)}catch(yt){if(!p.current)return;L(yt instanceof Error?yt.message:"Failed to upload file")}finally{p.current&&(ke(!1),pe.current&&(pe.current.value=""))}},It=async()=>{let he=nt.trim();if(!(!he||!t))try{ke(!0),L(null);let $e=await u(t.id,he);if(!p.current)return;Ee($e.fulfillment),E(""),s?.($e)}catch($e){if(!p.current)return;L($e instanceof Error?$e.message:"Failed to fetch file")}finally{p.current&&ke(!1)}};return Ge("div",{className:`af-space-y-6 ${n||""}`,children:[Ge("div",{className:"af-space-y-2",children:[Te(Oe,{htmlFor:"product-name",children:"Name"}),Te(ae,{id:"product-name",value:x,onChange:he=>S(he.target.value),placeholder:"My product"})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{htmlFor:"product-description",children:"Description"}),Te("textarea",{id:"product-description",value:k,onChange:he=>h(he.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"})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{children:"Pricing"}),b?Te("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):Ge(Xm,{children:[Ge(fn,{value:N,onValueChange:he=>R(he),children:[Te(Qa,{className:"af-w-[260px]",children:Te(mn,{})}),Ge(en,{children:[Te(St,{value:"fixed",children:"Fixed price"}),Te(St,{value:"custom",children:"Buyer chooses the amount"})]})]}),N==="fixed"?Te("div",{className:"af-flex af-items-end af-gap-3",children:Ge("div",{className:"af-space-y-1",children:[Ge(Oe,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",o.toUpperCase(),")"]}),Te(ae,{id:"product-price",type:"number",min:"0",step:f,value:C,onChange:he=>w(he.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):Ge("div",{className:"af-space-y-1",children:[Ge("div",{className:"af-flex af-items-end af-gap-3",children:[Ge("div",{className:"af-space-y-1",children:[Ge(Oe,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",o.toUpperCase(),")"]}),Te(ae,{id:"product-min-amount",type:"number",min:"0",step:f,value:P,onChange:he=>I(he.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),Ge("div",{className:"af-space-y-1",children:[Ge(Oe,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",o.toUpperCase(),")"]}),Te(ae,{id:"product-max-amount",type:"number",min:"0",step:f,value:_,onChange:he=>q(he.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),Te("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."})]}),Ge("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",o.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||N==="fixed")&&Ge("div",{className:"af-space-y-1",children:[Te(Oe,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),Te(ae,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:j,onChange:he=>U(he.target.value),className:"af-w-[140px]"})]})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{children:"Images"}),Te("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),Ge("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[A.map(he=>Ge(ee,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[Te("span",{className:"af-truncate",children:he}),Te("button",{type:"button",onClick:()=>Fe(he),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:Te(Ym,{className:"af-h-3 af-w-3"})})]},he)),A.length===0&&Te("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),Ge("div",{className:"af-flex af-gap-2",children:[Te(ae,{type:"url",value:re,onChange:he=>Me(he.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:he=>{he.key==="Enter"&&(he.preventDefault(),se())},disabled:g}),Te(y,{type:"button",variant:"outline",onClick:se,disabled:!re.trim()||g,children:Te(Km,{className:"af-h-4 af-w-4"})})]})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{children:"Digital File"}),Te("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."}),c?Ge("div",{className:"af-space-y-3",children:[Se?.type==="download"&&Ge("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Te(Wm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Te("span",{className:"af-text-sm",children:Se.filename}),Se.size!=null&&Ge("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Jm(Se.size),")"]})]}),Se?.type==="redirect"&&Se.url&&Ge("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Te(Gm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Ge("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Se.url]})]}),Ge("div",{className:"af-flex af-items-center af-gap-2",children:[Te("input",{ref:pe,type:"file",onChange:Xe,className:"af-hidden",disabled:J}),Ge(y,{type:"button",variant:"outline",size:"sm",onClick:()=>pe.current?.click(),disabled:J,children:[Ye?Te(Bc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Te(Zm,{className:"af-h-4 af-w-4 af-mr-1"}),Se?.type==="download"?"Replace file":"Upload file"]}),Te("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),Te(ae,{type:"url",value:nt,onChange:he=>E(he.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Ye}),Te(y,{type:"button",variant:"outline",size:"sm",onClick:It,disabled:!nt.trim()||J,children:"Fetch from URL"})]}),M&&Te("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:M})]}):Te("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),Ge("div",{className:"af-space-y-2",children:[Te(Oe,{children:"Settings"}),Ge("div",{className:"af-space-y-2",children:[Ge("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Te("input",{type:"checkbox",checked:ce,onChange:he=>me(he.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),Ge("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Te("input",{type:"checkbox",checked:T,onChange:he=>V(he.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),c&&t&&Ge("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[Te(Oe,{children:"Options & Variants"}),Te(Ci,{productId:t.id,currency:o})]}),v&&Te("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),Te("div",{className:"af-flex af-items-center af-gap-2",children:Ge(y,{type:"button",onClick:Qe,disabled:J,children:[g?Te(Bc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,c?"Save changes":"Create product"]})})]})}import*as sa from"react";import{ChevronLeft as Sp,ChevronRight as Gc,Loader2 as Np,Receipt as Rp,Search as _p,SlidersHorizontal as kp}from"lucide-react";import*as Lt from"react";var Qm=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Ei({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=Lt.useState([]),[r,i]=Lt.useState(0),[l,u]=Lt.useState(!0),[c,o]=Lt.useState(null),[f,b]=Lt.useState(0),[g,m]=Lt.useState(e),[v,d]=Lt.useState(void 0),[p,x]=Lt.useState(""),[S,k]=Lt.useState(""),[h,N]=Lt.useState(""),[R,C]=Lt.useState(!1),[w,P]=Lt.useState(!1),[I,_]=Lt.useState(void 0),q=I?I.join(","):"",j=Lt.useMemo(()=>{if(!q)return;let T=new Set(q.split(","));return Qm.filter(V=>!T.has(V))},[q]),U=Lt.useMemo(()=>{let T={};return v?T.status=v:j?T.excludeStatus=j:R||(T.excludeStatus=["pending","expired"]),p.trim()&&(T.customerEmail=p.trim()),S.trim()&&(T.from=S.trim()),h.trim()&&(T.to=h.trim()),w&&(T.unfulfilledOnly=!0),T},[v,j,R,p,S,h,w]),te=Lt.useRef(0),ce=Lt.useCallback(async()=>{let T=++te.current;try{u(!0),o(null);let V={...U,limit:g,offset:f*g},A=await a.getOrders(V);if(T!==te.current)return;n(A.orders),i(A.total)}catch(V){if(T!==te.current)return;o(V instanceof Error?V:new Error("Failed to fetch orders"))}finally{T===te.current&&u(!1)}},[a,f,g,U,t]);Lt.useEffect(()=>{ce()},[ce]);let me=Math.ceil(r/g);return{orders:s,total:r,isLoading:l,error:c,page:f,pageSize:g,hasNextPage:f<me-1,hasPreviousPage:f>0,setPage:b,setPageSize:T=>{m(T),b(0)},status:v,setStatus:T=>{d(T),b(0)},statusIn:I,setStatusIn:T=>{_(T&&T.length>0?T:void 0),b(0)},customerEmail:p,setCustomerEmail:T=>{x(T),b(0)},from:S,setFrom:T=>{k(T),b(0)},to:h,setTo:T=>{N(T),b(0)},showAbandoned:R,setShowAbandoned:T=>{C(T),b(0)},unfulfilledOnly:w,setUnfulfilledOnly:T=>{P(T),b(0)},clearFilters:()=>{d(void 0),_(void 0),C(!1),P(!1),x(""),k(""),N(""),b(0)},filters:U,refetch:ce}}import*as Wt from"react";import{ArrowLeft as ap,Check as $c,ChevronLeft as np,ChevronRight as sp,ClipboardCopy as rp,Copy as ip,Download as op,Loader2 as Oi,Mail as Uc,MoreHorizontal as lp,Package as cp,RotateCcw as dp,Truck as up,Undo2 as Vc}from"lucide-react";import*as Fc from"react";import*as Hn from"@radix-ui/react-popover";import{jsx as qo}from"react/jsx-runtime";var Ii=Hn.Root,Ai=Hn.Trigger;var Dr=Fc.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},n)=>qo(Hn.Portal,{children:qo("div",{className:"aifeatures-admin",children:qo(Hn.Content,{ref:n,align:t,sideOffset:a,className:W("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})})}));Dr.displayName=Hn.Content.displayName;import{jsx as Di}from"react/jsx-runtime";var ep={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function tp(e){return ep[e]??e}function Mc(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 As({status:e,className:t}){return Di(ee,{variant:Mc(e),className:t,children:tp(e)})}function Ds({status:e}){return Di(As,{status:e})}function er({order:e,className:t}){return e.line_items.some(a=>a.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?Di(ee,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?Di(ee,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function os(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as yp,jsx as O,jsxs as le}from"react/jsx-runtime";var qc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Os="af-text-xs af-text-muted-foreground";function Wo(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 fp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wc(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 Li=24,mp=["paid","partially_refunded"],pp=["paid","partially_refunded","disputed"],gp=/^[A-Za-z0-9 _-]*$/,Hc=100;function Zo(e,t,a,s,n){let r=mp.includes(s);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${a} of ${Li} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${Li} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?a<Li&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:a<Li&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${a} attempt${a===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${s==="refunded"?"because the order was refunded":s==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function zc({title:e,recipient:t,status:a,attempts:s,side:n,orderStatus:r,action:i,delivery:l}){if(l)return le("div",{children:[O($n,{deliveries:[l]}),i&&O("div",{className:"af-mt-2",children:i})]});let u=Zo(n,a,s,r,t);return le("div",{children:[le("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[le("div",{className:"af-min-w-0",children:[O("div",{className:"af-text-sm",children:e}),t&&O("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),O(ee,{variant:u.variant,className:"af-shrink-0",children:u.label})]}),u.detail&&O("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:u.detail}),i&&O("div",{className:"af-mt-2",children:i})]})}function jc(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=fp(e.address)?e.address:null;if(a){for(let n of["line1","line2"]){let r=a[n];typeof r=="string"&&r&&t.push(r)}let s=["city","state","postal_code"].map(n=>a[n]).filter(n=>typeof n=="string"&&!!n).join(", ");s&&t.push(s),typeof a.country=="string"&&a.country&&t.push(a.country)}return t.length>0?t:Object.entries(e).map(([s,n])=>`${s}: ${Wc(n)}`)}function vp(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Yo({value:e,label:t,children:a,className:s,size:n="icon"}){let[r,i]=Wt.useState(!1);if(!vp())return null;let l=async()=>{try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},u=r?O($c,{className:"af-h-3 af-w-3"}):O(ip,{className:"af-h-3 af-w-3"});return n==="icon"?O(y,{variant:"ghost",size:"icon",className:W("af-h-6 af-w-6 af-shrink-0",s),onClick:l,title:t,"aria-label":t,children:u}):le(y,{variant:"outline",size:"sm",className:s,onClick:l,"aria-label":t,children:[r?O($c,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):O(rp,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":a]})}function Go({label:e,value:t}){return le("div",{children:[O("div",{className:Os,children:e}),le("div",{className:"af-flex af-items-center af-gap-1",children:[O("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),O(Yo,{value:t,label:`Copy ${e}`})]})]})}function bp({src:e}){let[t,a]=Wt.useState(!1);return!e||t?O("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:O(cp,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):O("img",{src:e,alt:"","aria-hidden":"true",onError:()=>a(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function zn({title:e,action:t,children:a,className:s}){return le("section",{className:W("af-rounded-lg af-border af-p-4",s),children:[le("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[O("h4",{className:qc,children:e}),t]}),O("div",{className:"af-mt-3",children:a})]})}function Ua({label:e,emphasis:t,divider:a,children:s}){return le("div",{className:W("af-flex af-items-baseline af-justify-between af-gap-6",a&&"af-mt-2 af-border-t af-pt-2"),children:[O("span",{className:t?"af-text-base af-font-semibold":Os,children:e}),O("span",{className:W("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function Ko({onSelect:e,disabled:t,icon:a,children:s}){return le(y,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[O("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function hp(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 ${Q(_i(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),s=a?mi(a):Zo("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),s=a?mi(a):Zo("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${Q(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 Bi({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:n=!1,onPrevOrder:r,onNextOrder:i,hasPrevOrder:l=!1,hasNextOrder:u=!1}){let{api:c}=H(),[o,f]=Wt.useState(e),[b,g]=Wt.useState(null),[m,v]=Wt.useState(null),[d,p]=Wt.useState(!1),[x,S]=Wt.useState(!1),[k,h]=Wt.useState(!1),[N,R]=Wt.useState(!1),[C,w]=Wt.useState(""),[P,I]=Wt.useState(!1),[_,q]=Wt.useState(null),[j,U]=Wt.useState(!1),[te,ce]=Wt.useState(""),[me,T]=Wt.useState([]),[V,A]=Wt.useState(!1),[ne,re]=Wt.useState(!1),[Me,Se]=Wt.useState(null);Wt.useEffect(()=>{f(e)},[e]);let Ee=F=>{let st=F.id===o.id&&F.email_deliveries===void 0?{...F,email_deliveries:o.email_deliveries}:F;f(st),s?.(st)},Ye=Object.entries(o.metadata??{}),ke=Math.max(0,_i(o)-o.amount_refunded),nt=(o.status==="paid"||o.status==="partially_refunded")&&ke>0,E=o.exclusive_tax_total!=null,M=F=>typeof F.amountNet=="number"?F.amountNet+(F.exclusiveTax??0):(typeof F.unitAmount=="number"?F.unitAmount:0)*(typeof F.quantity=="number"&&F.quantity>0?F.quantity:1),L=Math.max(0,(o.shipping_total??0)-(o.shipping_refunded??0)),pe=me.reduce((F,st)=>F+M(o.line_items[st]??{}),0)+(V?L:0),J=o.tax_total??0,se=Math.max(0,(o.exclusive_tax_total??0)-o.line_items.reduce((F,st)=>F+(st.exclusiveTax??0),0)),Fe=E?V&&L>0?se:0:o.automatic_tax&&o.tax_behavior==="exclusive"&&J>0&&o.amount_total+(o.shipping_total??0)>0?Math.min(Math.max(0,J-(o.tax_refunded??0)),Math.round(J*pe/(o.amount_total+(o.shipping_total??0)))):0,Qe=o.source==="subscription"&&(o.credit_applied??0)>0&&o.line_items.length===1?Math.min(pe+Fe,ke):pe+Fe,Xe=me.length>0||V,It=Xe?Qe:va(te,o.currency),he=bn(o.currency)?"1":"0.01",$e=async()=>{try{p(!0),g(null),v(null),await c.resendOrderReceipt(o.id);let F=await c.getOrder(o.id);Ee(F),v("Receipt email queued.")}catch(F){g(F instanceof Error?F.message:"Failed to resend receipt")}finally{p(!1)}},yt=async()=>{try{S(!0),g(null),v(null);let F=await c.resetOrderDownloads(o.id);Ee(F),h(!1),v("Download count reset.")}catch(F){g(F instanceof Error?F.message:"Failed to reset downloads")}finally{S(!1)}},At=o.line_items.some(F=>F.collectShippingAddress===!0&&!F.refunded&&!F.unavailableReason),Mt=typeof o.merchant_fulfilled_at=="string",et=pp.includes(o.status)||o.status==="refunded"&&o.line_items.some(F=>F.collectShippingAddress===!0&&F.amountNet===0&&!F.refunded&&!F.unavailableReason),ta=C.trim(),Je=gp.test(ta)&&ta.length<=Hc,wt=async F=>{try{I(!0),q(null),v(null);let st=await c.setOrderFulfillment(o.id,{fulfilled:F,...F&&ta?{trackingNumber:ta}:{}});Ee(st),w(""),v(F?"Marked as shipped.":"Marked as not shipped.")}catch(st){st instanceof aa&&st.status===409?q(`This order is ${o.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):q(st instanceof Error?st.message:"Failed to update the order")}finally{I(!1)}},Xa=()=>{Se(null),ce(String(Ot(ke,o.currency))),T([]),A(!1),U(!0)},Mn=F=>T(st=>st.includes(F)?st.filter(Ba=>Ba!==F):[...st,F]),ye=async(F,st)=>{if(a)try{re(!0),Se(null),await a(o,F,st);let Ba=await c.getOrder(o.id);Ee(Ba),U(!1),v("Refund issued.")}catch(Ba){Se(Ba instanceof Error?Ba.message:"Refund failed")}finally{re(!1)}},Rt=async()=>{if(Xe){if(Qe<=0){Se("The lines you picked were charged nothing");return}if(Qe>ke){Se(`That selection exceeds the refundable remainder (${Q(ke,o.currency)})`);return}await ye(Qe,{...me.length>0?{line_items:[...me].sort((st,Ba)=>st-Ba)}:{},...V?{shipping:!0}:{}});return}let F=va(te,o.currency);if(F===null||F<=0){Se("Enter a valid refund amount");return}if(F>ke){Se(`Amount exceeds the refundable remainder (${Q(ke,o.currency)})`);return}await ye(F,{amount:F})},$=()=>ye(ke,{full:!0}),Pe=!o.subscription_history_only&&o.fulfillment_type==="download",jt=!o.subscription_history_only&&n&&At,_n=hp(o),X=o.shipping_address?jc(o.shipping_address).join(`
4
+ `):"",la=o.shipping_total!=null,Ao=o.exclusive_tax_total??(o.automatic_tax&&o.tax_behavior==="exclusive"?o.tax_total??0:0),lc=o.exclusive_tax_total!=null?Math.max(0,(o.tax_total??0)-Ao):o.automatic_tax&&o.tax_behavior==="exclusive"?0:o.tax_total??0,cc=Ao>0,Nf=lc>0,dc=o.amount_subtotal!=null||la||cc||(o.discount_total??0)>0,Nr=[];return o.subscription_history_only||Nr.push(O(Ko,{icon:d?O(Oi,{className:"af-h-4 af-w-4 af-animate-spin"}):O(Uc,{className:"af-h-4 af-w-4"}),disabled:d||o.fulfillment_status!=="fulfilled",onSelect:()=>{R(!1),$e()},children:"Resend receipt"},"resend")),Pe&&Nr.push(O(Ko,{icon:O(dp,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{R(!1),h(!0)},children:"Reset download count"},"reset")),nt&&Nr.push(le("div",{children:[O(Ko,{icon:O(Vc,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{R(!1),Xa()},children:"Refund\u2026"}),!a&&O("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),le("div",{children:[le("div",{className:"af-mb-6",children:[le(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[O(ap,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),le("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[le("div",{className:"af-min-w-0",children:[le("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[O("h3",{className:"af-text-xl af-font-semibold",children:os(o)}),O(As,{status:o.status}),n&&!o.subscription_history_only&&O(er,{order:o}),o.is_test&&O(ee,{variant:"outline",children:"Test"})]}),le("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Wo(o.created_at)]}),o.is_test&&O("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),le("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||i)&&le("div",{className:"af-flex af-items-center",children:[O(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!l,"aria-label":"Previous order",children:O(np,{className:"af-h-4 af-w-4"})}),O(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:i,disabled:!u,"aria-label":"Next order",children:O(sp,{className:"af-h-4 af-w-4"})})]}),jt&&(Mt?le("div",{className:"af-flex af-items-center af-gap-1",children:[le("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",o.merchant_fulfilled_at?` \xB7 ${Wo(o.merchant_fulfilled_at)}`:""]}),et&&le(y,{variant:"ghost",size:"sm",onClick:()=>wt(!1),disabled:P,children:[P?O(Oi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):O(Vc,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):et?le("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[O(ae,{value:C,onChange:F=>w(F.target.value),placeholder:"Tracking number (optional)",maxLength:Hc,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:P}),le(y,{variant:"default",className:"af-shrink-0",onClick:()=>wt(!0),disabled:P||!Je,children:[P?O(Oi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):O(up,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Nr.length>0&&le(Ii,{open:N,onOpenChange:R,children:[O(Ai,{asChild:!0,children:O(y,{variant:"outline",size:"icon","aria-label":"More actions",children:O(lp,{className:"af-h-4 af-w-4"})})}),O(Dr,{children:O("div",{className:"af-space-y-0.5",children:Nr})})]})]})]}),jt&&!Mt&&!Je&&O("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."}),_&&O("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:_}),m&&O("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:m}),b&&O("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})]}),le("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[le("div",{className:"af-space-y-6",children:[o.line_items.length>0&&O(zn,{title:"Items",children:O("ul",{className:"af-space-y-3",children:o.line_items.map((F,st)=>{let Ba=typeof F.name=="string"&&F.name?F.name:"Item",uc=typeof F.quantity=="number"&&F.quantity>0?F.quantity:1,fc=typeof F.unitAmount=="number";return le("li",{className:"af-flex af-items-start af-gap-3",children:[O(bp,{src:typeof F.imageUrl=="string"&&F.imageUrl?F.imageUrl:void 0}),le("div",{className:"af-min-w-0 af-flex-1",children:[le("div",{className:"af-text-sm af-font-medium",children:[Ba,typeof F.variantTitle=="string"&&F.variantTitle&&le("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",F.variantTitle]})]}),le("div",{className:Os,children:[uc," \xD7"," ",fc?Q(F.unitAmount,o.currency):"\u2014"]}),F.unavailableReason==="oversold"&&!F.refunded&&O(ee,{variant:"secondary",className:"af-mt-1",children:F.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),F.refunded===!0&&O(ee,{variant:"secondary",className:"af-mt-1",children:F.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),O("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof F.amountNet=="number"||fc?Q(F.amountNet??F.unitAmount*uc,o.currency):"\u2014"})]},st)})})}),Ye.length>0&&O(zn,{title:"Order details",children:O("dl",{className:"af-space-y-2",children:Ye.map(([F,st])=>le("div",{children:[O("dt",{className:W(Os,"af-capitalize"),children:F.replace(/_/g," ")}),O("dd",{className:"af-text-sm af-break-words",children:Wc(st)})]},F))})}),O(zn,{title:"Totals",children:le("div",{className:"af-w-full",children:[dc&&O(Ua,{label:"Subtotal",children:Q(o.amount_subtotal??o.amount_total+(o.discount_total??0),o.currency)}),(o.discount_total??0)>0&&le(Ua,{label:"Discount",children:["\u2212",Q(o.discount_total,o.currency)]}),la&&O(Ua,{label:"Shipping",children:o.shipping_total===0?"Free":Q(o.shipping_total??0,o.currency)}),cc&&O(Ua,{label:"Tax",children:Q(Ao,o.currency)}),O(Ua,{label:"Total",emphasis:!0,divider:dc,children:Q(is(o),o.currency)}),(o.credit_applied??0)>0&&le(Ua,{label:"Credit applied",children:["\u2212",Q(o.credit_applied,o.currency)]}),o.amount_paid!=null&&O(Ua,{label:"Amount paid",children:Q(o.amount_paid,o.currency)}),Nf&&O(Ua,{label:"incl. tax",children:Q(lc,o.currency)}),o.base_currency!=null&&o.base_amount_total!=null&&le(Ua,{label:"Your price",children:[Q(o.base_amount_total,o.base_currency),le("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",o.currency.toUpperCase()]})]}),o.amount_refunded>0&&le(yp,{children:[le(Ua,{label:"Refunded",children:["\u2212",Q(o.amount_refunded,o.currency),(o.shipping_refunded??0)>0&&le("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",Q(o.shipping_refunded??0,o.currency)," ","shipping"]})]}),O(Ua,{label:"Net",children:O("span",{className:"af-font-medium",children:Q(Math.max(0,_i(o)-o.amount_refunded),o.currency)})})]})]})}),o.application_fee_state&&le(zn,{title:"Platform fee",children:[o.application_fee_original!=null&&O(Ua,{label:"Collected",children:Q(o.application_fee_original,o.application_fee_currency??o.currency)}),o.application_fee_returned!=null&&O(Ua,{label:"Returned",children:Q(o.application_fee_returned,o.application_fee_currency??o.currency)}),o.application_fee_retained!=null&&O(Ua,{label:"Retained",children:Q(o.application_fee_retained,o.application_fee_currency??o.currency)}),o.application_fee_state!=="complete"&&O("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:o.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),O(zn,{title:"Timeline",children:O("ol",{className:"af-space-y-3",children:_n.map(F=>le("li",{className:"af-flex af-gap-3",children:[O("span",{"aria-hidden":"true",className:W("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",F.tone==="destructive"?"af-bg-destructive":F.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),le("div",{className:"af-min-w-0",children:[O("div",{className:"af-text-sm af-break-words",children:F.text}),F.at&&O("div",{className:"af-text-xs af-text-muted-foreground",children:Wo(F.at)})]})]},F.key))})})]}),le("div",{className:"af-space-y-6",children:[O(zn,{title:"Customer",children:le("div",{className:"af-space-y-2",children:[le("div",{children:[O("div",{className:Os,children:"Email"}),le("div",{className:"af-flex af-items-center af-gap-1",children:[O("span",{className:"af-min-w-0 af-break-all af-text-sm",children:o.customer_email||O("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),o.customer_email&&O(Yo,{value:o.customer_email,label:"Copy email"})]})]}),o.customer_name&&le("div",{children:[O("div",{className:Os,children:"Name"}),O("div",{className:"af-text-sm",children:o.customer_name})]}),o.customer&&le("div",{children:[O("div",{className:Os,children:"Customer record"}),le("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[O("span",{className:"af-break-all af-text-sm",children:o.customer.name||o.customer.email}),O(ee,{variant:"secondary",children:"Linked"})]})]})]})}),o.shipping_address&&O(zn,{title:"Ship to",action:O(Yo,{value:X,label:"Copy address",size:"sm",children:"Copy address"}),children:O("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:jc(o.shipping_address).map((F,st)=>O("div",{children:F},st))})}),o.subscription_history_only?O(zn,{title:"Subscription history",children:O("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."})}):le(zn,{title:"Emails",children:[O($n,{deliveries:o.email_deliveries?.filter(F=>!["purchase_receipt","merchant_sale"].includes(F.kind)),problemsOnly:!0,className:"af-mb-4"}),le("div",{className:"af-space-y-4",children:[O(zc,{side:"buyer",title:"Receipt to buyer",delivery:o.email_deliveries?.find(F=>F.kind==="purchase_receipt"),recipient:o.customer_email,status:o.buyer_email_status,attempts:o.buyer_email_attempts,orderStatus:o.status,action:le(y,{variant:"outline",size:"sm",onClick:$e,disabled:d||o.fulfillment_status!=="fulfilled",children:[d?O(Oi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):O(Uc,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),O(zc,{side:"merchant",title:"Sale alert to you",delivery:o.email_deliveries?.find(F=>F.kind==="merchant_sale"),recipient:null,status:o.merchant_email_status,attempts:o.merchant_email_attempts,orderStatus:o.status})]})]}),Pe&&O(zn,{title:"Download",children:le("div",{className:"af-space-y-2",children:[le("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[O(op,{className:"af-h-4 af-w-4"}),le("span",{children:["Downloaded ",o.download_count," time",o.download_count===1?"":"s"]})]}),o.download_url&&O("a",{href:o.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),le("details",{className:"af-rounded-lg af-border af-p-4",children:[O("summary",{className:W(qc,"af-cursor-pointer af-select-none"),children:"Technical details"}),le("div",{className:"af-mt-3 af-space-y-2",children:[O(Go,{label:"Order ID",value:o.id}),o.stripe_checkout_session_id&&O(Go,{label:"Checkout session",value:o.stripe_checkout_session_id}),o.stripe_payment_intent_id&&O(Go,{label:"Payment",value:o.stripe_payment_intent_id})]})]})]})]}),O(pn,{open:k,onOpenChange:F=>{!F&&!x&&h(!1)},children:le(tn,{children:[le(an,{children:[O(sn,{children:"Reset download count?"}),O(rn,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),le(nn,{children:[O(y,{variant:"outline",onClick:()=>h(!1),disabled:x,children:"Cancel"}),O(y,{onClick:yt,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),O(pn,{open:j,onOpenChange:F=>{!F&&!ne&&U(!1)},children:le(tn,{children:[le(an,{children:[O(sn,{children:"Refund order"}),le(rn,{children:["Refund up to ",Q(ke,o.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),le("div",{className:"af-space-y-4",children:[(o.line_items.length>0||L>0)&&le("div",{className:"af-space-y-2",children:[O(Oe,{children:"Items"}),le("div",{className:"af-space-y-2",children:[o.line_items.map((F,st)=>{let Ba=F.refunded===!0;return le("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[O("input",{type:"checkbox",checked:me.includes(st),onChange:()=>Mn(st),disabled:ne||Ba||!!F.unavailableReason||M(F)<=0,className:"af-h-4 af-w-4"}),le("span",{className:Ba?"af-text-muted-foreground af-line-through":void 0,children:[typeof F.name=="string"&&F.name?F.name:"Item",typeof F.variantTitle=="string"&&F.variantTitle?` \u2014 ${F.variantTitle}`:"",typeof F.quantity=="number"&&F.quantity>1?` \xD7 ${F.quantity}`:""]}),O("span",{className:"af-ml-auto af-text-muted-foreground",children:Ba?"Refunded":Q(M(F),o.currency)})]},st)}),L>0&&le("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[O("input",{type:"checkbox",checked:V,onChange:F=>A(F.target.checked),disabled:ne,className:"af-h-4 af-w-4"}),O("span",{children:"Shipping"}),O("span",{className:"af-ml-auto af-text-muted-foreground",children:Q(L,o.currency)})]})]})]}),le("div",{className:"af-space-y-2",children:[le(Oe,{htmlFor:"refund-amount",children:["Amount (",o.currency.toUpperCase(),")"]}),O(ae,{id:"refund-amount",type:"number",min:"0",step:he,value:Xe?String(Ot(Qe,o.currency)):te,onChange:F=>ce(F.target.value),disabled:ne||Xe}),Xe&&O("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Me&&O("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Me}),le(nn,{children:[O(y,{variant:"outline",onClick:()=>U(!1),disabled:ne,children:"Cancel"}),O(y,{variant:"outline",onClick:$,disabled:ne,children:"Refund everything"}),O(y,{variant:"destructive",onClick:Rt,disabled:ne,children:ne?"Refunding...":It!==null&&It>0?`Refund ${Q(It,o.currency)}`:"Refund"})]})]})})]})}import*as Fi from"react";import{ArrowLeft as xp,RefreshCw as wp}from"lucide-react";import{jsx as Ta,jsxs as vs}from"react/jsx-runtime";function Ut({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:n}){let r=Fi.useRef(null);return Fi.useEffect(()=>{r.current?.focus()},[]),vs("div",{className:W("af-bg-background",n),children:[vs("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:[Ta("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!a&&vs(y,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[Ta(xp,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Ta("div",{className:"af-p-4",children:s})]})}function G({className:e}){return Ta("div",{"aria-hidden":"true",className:W("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function pt({label:e,children:t,detail:a,valueClassName:s}){return vs("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Ta("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Ta("div",{className:W("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&Ta("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function xt({message:e,onRetry:t}){return vs("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ta("span",{children:e}),vs(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[Ta(wp,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function ca({icon:e,children:t,action:a}){return vs("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Ta("p",{className:"af-text-muted-foreground af-text-center",children:t}),a&&Ta("div",{className:"af-mt-3",children:a})]})}function tr({icon:e,heading:t,body:a,action:s,className:n,children:r}){return vs("div",{className:W("af-px-6 af-py-10 af-text-center",n),children:[Ta(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),Ta("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),Ta("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&Ta(y,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}import{jsx as z,jsxs as Ve}from"react/jsx-runtime";var Pp={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Kc={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Zc(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 Yc(e){let t=Array.isArray(e.line_items)?e.line_items:[],a=t[0];if(!a)return"\u2014";let s=typeof a.name=="string"&&a.name?a.name:"Item",n=typeof a.quantity=="number"&&a.quantity>0?a.quantity:1,r=n>1?`${s} \xD7${n}`:s;return t.length>1?`${r} +${t.length-1} more`:r}function Mi(e){return e.customer?.name||e.customer_name||null}function Cp({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:n=!1,emptyMessage:r,onDetailOpenChange:i,maxRows:l,onViewAll:u}){let c=typeof l=="number",{api:o}=H(),f=Ei({refreshKey:a}),{orders:b,total:g,isLoading:m,error:v,page:d,pageSize:p,hasNextPage:x,hasPreviousPage:S,setPage:k,setPageSize:h,customerEmail:N,setCustomerEmail:R,setStatusIn:C,from:w,setFrom:P,to:I,setTo:_,showAbandoned:q,setShowAbandoned:j,setUnfulfilledOnly:U,filters:te,refetch:ce}=f,me=sa.useCallback(()=>o.exportOrdersCsv(te),[o,te]),[T,V]=sa.useState("list"),[A,ne]=sa.useState(null),[re,Me]=sa.useState(""),[Se,Ee]=sa.useState(""),[Ye,ke]=sa.useState(!c&&n?"needs_shipping":"all"),[nt,E]=sa.useState(!1),[M,L]=sa.useState(!!s&&!c),[pe,J]=sa.useState(null);sa.useEffect(()=>{if(!s||c)return;let X=!1;return L(!0),J(null),o.getOrder(s).then(la=>{X||(ne(la),V("detail"))}).catch(()=>{X||J("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{X||L(!1)}),()=>{X=!0}},[o,s,c]);let se=sa.useCallback(X=>{ke(X);let la=Kc[X];C(la.statusIn),U(la.unfulfilledOnly)},[C,U]);sa.useEffect(()=>{n&&!c&&U(!0)},[]);let Fe=sa.useRef(!n);sa.useEffect(()=>{Fe.current||m||(Fe.current=!0,b.length===0&&se("all"))},[m,b.length,se]);let Qe=T==="detail"&&!!A;sa.useEffect(()=>{i?.(Qe)},[Qe,i]);let Xe=(w?1:0)+(I?1:0)+(q?1:0),It=Xe>0||!!N||!!Se,he=!!w&&!!I&&w>I,$e=!c||!!u,yt=X=>{if(c){u?.();return}ne(X),V("detail")},At=()=>{V("list"),ne(null),ce()},Mt=X=>{let la=X.trim();if(!la){Ee(""),N&&R("");return}if(la.startsWith("#")||/^\d+$/.test(la)){Ee(la),N&&R("");return}Ee(""),R(la)},et=()=>{Me(""),Ee(""),R(""),P(""),_(""),j(!1),E(!1)},ta=Se.replace(/^#/,"").toLowerCase(),Je=ta?b.filter(X=>String(X.order_number??"")===ta||X.id.toLowerCase().startsWith(ta)):b,wt=c?Je.slice(0,l):Je,Xa=A?b.findIndex(X=>X.id===A.id):-1,Mn=Xa>0,ye=Xa>=0&&Xa<b.length-1;if(M)return z("div",{className:t,children:z("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:z(Np,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(T==="detail"&&A)return z("div",{className:t,children:z(Bi,{order:A,onBack:At,onRefund:e,onOrderUpdated:X=>ne(X),allowFulfillment:n,onPrevOrder:Mn?()=>ne(b[Xa-1]):void 0,onNextOrder:ye?()=>ne(b[Xa+1]):void 0,hasPrevOrder:Mn,hasNextOrder:ye},A.id)});let $=Ve("div",{className:"af-mb-4 af-space-y-3",children:[pe&&z("p",{className:"af-text-xs af-text-muted-foreground",children:pe}),Ve("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[z("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(X=>z("button",{type:"button","aria-pressed":Ye===X,onClick:()=>se(X),className:W("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:Pp[X]},X))}),Ve("div",{className:"af-relative af-w-full af-max-w-xs",children:[z(_p,{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"}),z(ae,{type:"text",value:re,onChange:X=>Me(X.target.value),onBlur:()=>Mt(re),onKeyDown:X=>{X.key==="Enter"&&(X.preventDefault(),Mt(re))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),Ve(y,{type:"button",variant:Xe>0?"secondary":"ghost",size:"sm",onClick:()=>E(X=>!X),"aria-expanded":nt,children:[z(kp,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Xe>0&&z(ee,{variant:"secondary",className:"af-ml-2",children:Xe})]}),It&&z(y,{type:"button",variant:"ghost",size:"sm",onClick:et,children:"Clear filters"}),z(wa,{fetchCsv:me,filename:"orders",disabled:!!Se,className:"af-ml-auto"})]}),(nt||!!w||!!I)&&Ve("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:[z(Oe,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),z(ae,{id:"orders-from",type:"date",value:w,max:I||void 0,onChange:X=>P(X.target.value),className:"af-w-[170px]"}),z(Oe,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),z(ae,{id:"orders-to",type:"date",value:I,min:w||void 0,onChange:X=>_(X.target.value),className:"af-w-[170px]"}),!Kc[Ye].statusIn&&z(y,{type:"button",variant:q?"secondary":"ghost",size:"sm",onClick:()=>j(!q),"aria-pressed":q,children:q?"Hide abandoned":"Show abandoned"})]}),he&&z("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(m)return Ve("div",{className:t,children:[c?null:$,z("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(X=>Ve("div",{className:"af-rounded-md af-border af-p-3",children:[Ve("div",{className:"af-flex af-items-center af-justify-between",children:[z(G,{className:"af-h-4 af-w-16"}),z(G,{className:"af-h-4 af-w-14"})]}),z(G,{className:"af-mt-2 af-h-3 af-w-40"}),z(G,{className:"af-mt-2 af-h-3 af-w-24"})]},X))}),z("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ve(ct,{children:[z(dt,{children:Ve(Ie,{children:[z(Z,{children:"Order"}),z(Z,{children:"Date"}),z(Z,{children:"Customer"}),z(Z,{children:"Items"}),z(Z,{className:"af-text-right",children:"Total"}),z(Z,{children:"Status"}),z(Z,{className:"af-w-8"})]})}),z(ut,{"aria-hidden":"true",children:[0,1,2,3,4].map(X=>Ve(Ie,{children:[z(Y,{children:z(G,{className:"af-h-4 af-w-14"})}),z(Y,{children:z(G,{className:"af-h-4 af-w-24"})}),z(Y,{children:z(G,{className:"af-h-4 af-w-40"})}),z(Y,{children:z(G,{className:"af-h-4 af-w-32"})}),z(Y,{children:z(G,{className:"af-ml-auto af-h-4 af-w-16"})}),z(Y,{children:z(G,{className:"af-h-5 af-w-16"})}),z(Y,{})]},X))})]})}),z("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(v)return Ve("div",{className:t,children:[c?null:$,Ve("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[z("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),z(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>ce(),children:"Try again"})]})]});let Pe=Ye!=="all";if(Je.length===0&&d===0)return It||Pe?Ve("div",{className:t,children:[!c&&$,z(ca,{children:"No orders match these filters."})]}):z("div",{className:t,children:z(tr,{icon:Rp,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!c&&z(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>j(!0),children:"Show abandoned checkouts"})})});let jt=d*p+1,_n=Math.min((d+1)*p,g);return Ve("div",{className:t,children:[c?null:$,z("div",{className:"af-space-y-3 lg:af-hidden",children:wt.map(X=>Ve("button",{type:"button",onClick:()=>yt(X),disabled:!$e,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${$e?" hover:af-bg-muted/50":""}`,children:[Ve("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[z("span",{className:"af-font-medium",children:os(X)}),z("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:Q(is(X),X.currency)})]}),Ve("div",{className:"af-mt-1 af-min-w-0",children:[Ve("div",{className:"af-truncate af-text-sm",children:[X.customer_email||z("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Mi(X)&&Ve("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Mi(X)]})]}),z("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Yc(X)}),X.amount_refunded>0&&Ve("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Q(X.amount_refunded,X.currency)," refunded"]})]}),Ve("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[z(As,{status:X.status}),z(Cr,{deliveries:X.email_deliveries}),X.is_test&&z(ee,{variant:"outline",children:"Test"}),n&&z(er,{order:X}),z("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Zc(X.created_at)})]})]},X.id))}),z("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ve(ct,{children:[z(dt,{children:Ve(Ie,{children:[z(Z,{children:"Order"}),z(Z,{children:"Date"}),z(Z,{children:"Customer"}),z(Z,{children:"Items"}),z(Z,{className:"af-text-right",children:"Total"}),z(Z,{children:"Status"}),z(Z,{className:"af-w-8"})]})}),z(ut,{children:wt.map(X=>Ve(Ie,{onClick:$e?()=>yt(X):void 0,className:$e?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[Ve(Y,{className:"af-whitespace-nowrap af-font-medium",children:[z("button",{type:"button",onClick:la=>{la.stopPropagation(),yt(X)},disabled:!$e,"aria-label":`Open order ${os(X)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${$e?" hover:af-underline":""}`,children:os(X)}),X.is_test&&z(ee,{variant:"outline",className:"af-ml-2",children:"Test"})]}),z(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Zc(X.created_at)}),Ve(Y,{className:"af-max-w-[220px]",children:[z("div",{className:"af-truncate",children:X.customer_email||z("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Mi(X)&&z("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Mi(X)})]}),z(Y,{className:"af-max-w-[220px]",children:z("div",{className:"af-truncate af-text-muted-foreground",children:Yc(X)})}),Ve(Y,{className:"af-whitespace-nowrap af-text-right",children:[z("div",{className:"af-font-medium af-tabular-nums",children:Q(is(X),X.currency)}),X.amount_refunded>0&&Ve("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Q(X.amount_refunded,X.currency)," ","refunded"]})]}),z(Y,{children:Ve("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[z(As,{status:X.status}),z(Cr,{deliveries:X.email_deliveries}),n&&z(er,{order:X})]})}),z(Y,{className:"af-w-8 af-text-right",children:z(Gc,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},X.id))})]})}),c?null:Ve("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Ve("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[z("span",{children:ta?`${Je.length} matching this page`:`Showing ${jt}-${_n} of ${g}`}),Ve(fn,{value:String(p),onValueChange:X=>h(Number(X)),children:[z(Qa,{className:"af-w-[70px] af-h-8",children:z(mn,{})}),Ve(en,{children:[z(St,{value:"10",children:"10"}),z(St,{value:"25",children:"25"}),z(St,{value:"50",children:"50"}),z(St,{value:"100",children:"100"})]})]}),z("span",{children:"per page"})]}),Ve("div",{className:"af-flex af-items-center af-gap-2",children:[Ve(y,{variant:"outline",size:"sm",onClick:()=>k(d-1),disabled:!S,children:[z(Sp,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ve(y,{variant:"outline",size:"sm",onClick:()=>k(d+1),disabled:!x,children:["Next",z(Gc,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function bs(e){return z(Cp,{...e},e.maxRows==null?"full":"compact")}import*as ar from"react";import{ChevronLeft as Ap,ChevronRight as Dp,Eye as Op,Search as Lp,Users as Bp}from"lucide-react";import*as Va from"react";function $i({initialPageSize:e=25}={}){let{api:t}=H(),[a,s]=Va.useState([]),[n,r]=Va.useState(0),[i,l]=Va.useState(!0),[u,c]=Va.useState(null),[o,f]=Va.useState(0),[b,g]=Va.useState(e),[m,v]=Va.useState(""),d=Va.useRef(0),p=Va.useCallback(async()=>{let S=++d.current;try{l(!0),c(null);let k={limit:b,offset:o*b};m.trim()&&(k.email=m.trim());let h=await t.getCustomers(k);if(S!==d.current)return;s(h.customers),r(h.total)}catch(k){if(S!==d.current)return;c(k instanceof Error?k:new Error("Failed to fetch customers"))}finally{S===d.current&&l(!1)}},[t,o,b,m]);Va.useEffect(()=>{p()},[p]);let x=Math.ceil(n/b);return{customers:a,total:n,isLoading:i,error:u,page:o,pageSize:b,hasNextPage:o<x-1,hasPreviousPage:o>0,setPage:f,setPageSize:S=>{g(S),f(0)},email:m,setEmail:S=>{v(S),f(0)},refetch:p}}import*as Ls from"react";import{ArrowLeft as Tp,Loader2 as Ep}from"lucide-react";import{jsx as it,jsxs as ba}from"react/jsx-runtime";function Jc(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 Ip(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let a=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return a&&t.push(a),e.country&&t.push(e.country),t}function Ui({customer:e,onBack:t,className:a}){let{api:s}=H(),[n,r]=Ls.useState(null),[i,l]=Ls.useState([]),[u,c]=Ls.useState(!0),[o,f]=Ls.useState(null);Ls.useEffect(()=>{let m=!1;return c(!0),f(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([v,d])=>{m||(r(v),l(d.orders))}).catch(v=>{m||f(v instanceof Error?v.message:"Failed to load customer")}).finally(()=>{m||c(!1)}),()=>{m=!0}},[s,e.id,e.email]);let b=n?.addresses??[],g=n?.order_count??i.length;return ba("div",{className:a,children:[ba("div",{className:"af-mb-6",children:[ba(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[it(Tp,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),it("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),ba("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Jc(e.created_at)]})]}),u?it("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:it(Ep,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):o?it("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o}):ba("div",{className:"af-space-y-6",children:[it($n,{deliveries:n?.email_deliveries}),ba("div",{children:[it("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),ba("div",{className:"af-space-y-1 af-text-sm",children:[ba("div",{className:"af-flex af-gap-2",children:[it("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),it("span",{children:e.email})]}),e.name&&ba("div",{className:"af-flex af-gap-2",children:[it("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),it("span",{children:e.name})]}),e.phone&&ba("div",{className:"af-flex af-gap-2",children:[it("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),it("span",{children:e.phone})]}),ba("div",{className:"af-flex af-gap-2",children:[it("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),it("span",{children:g})]})]})]}),b.length>0&&ba("div",{children:[it("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),it("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(m=>ba("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[m.is_default&&it(ee,{variant:"secondary",className:"af-mb-1",children:"Default"}),Ip(m).map((v,d)=>it("div",{children:v},d))]},m.id))})]}),ba("div",{children:[it("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),i.length===0?it("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):ba(ct,{children:[it(dt,{children:ba(Ie,{children:[it(Z,{children:"Date"}),it(Z,{children:"Amount"}),it(Z,{children:"Status"})]})}),it(ut,{children:i.map(m=>ba(Ie,{children:[it(Y,{className:"af-text-muted-foreground",children:Jc(m.created_at)}),it(Y,{children:Q(is(m),m.currency)}),it(Y,{children:it(Ds,{status:m.status})})]},m.id))})]})]})]})]})}import{Fragment as Mp,jsx as He,jsxs as Jt}from"react/jsx-runtime";function Fp(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 Vi({className:e}){let{customers:t,total:a,isLoading:s,error:n,page:r,pageSize:i,hasNextPage:l,hasPreviousPage:u,setPage:c,setPageSize:o,email:f,setEmail:b,refetch:g}=$i(),{api:m}=H(),v=ar.useCallback(()=>m.exportCustomersCsv(),[m]),[d,p]=ar.useState("list"),[x,S]=ar.useState(null),[k,h]=ar.useState(""),N=I=>{S(I),p("detail")},R=()=>{p("list"),S(null),g()};if(d==="detail"&&x)return He("div",{className:e,children:He(Ui,{customer:x,onBack:R})});let C=Jt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[He(ae,{type:"email",value:k,onChange:I=>h(I.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),b(k.trim()))}}),Jt(y,{type:"button",variant:"outline",size:"sm",onClick:()=>b(k.trim()),children:[He(Lp,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),f&&He(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),b("")},children:"Clear"}),He(wa,{fetchCsv:v,filename:"customers",className:"af-ml-auto"})]});if(s)return Jt("div",{className:e,children:[C,He("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:He("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return Jt("div",{className:e,children:[C,He("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Jt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&r===0)return Jt("div",{className:e,children:[f&&C,Jt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[He(Bp,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),He("p",{className:"af-text-muted-foreground af-text-center",children:f?"No customers match that email.":Jt(Mp,{children:["No customers yet.",He("br",{}),"Customers appear here after their first purchase."]})})]})]});let w=r*i+1,P=Math.min((r+1)*i,a);return Jt("div",{className:e,children:[C,Jt(ct,{children:[He(dt,{children:Jt(Ie,{children:[He(Z,{children:"Email"}),He(Z,{children:"Name"}),He(Z,{children:"Phone"}),He(Z,{children:"Customer since"}),He(Z,{className:"af-text-right",children:"Actions"})]})}),He(ut,{children:t.map(I=>Jt(Ie,{children:[He(Y,{className:"af-font-medium",children:I.email}),He(Y,{children:I.name||He("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),He(Y,{children:I.phone||He("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),He(Y,{className:"af-text-muted-foreground",children:Fp(I.created_at)}),He(Y,{className:"af-text-right",children:He(y,{variant:"ghost",size:"icon",onClick:()=>N(I),title:"View customer",children:He(Op,{className:"af-h-4 af-w-4"})})})]},I.id))})]}),Jt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Jt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Jt("span",{children:["Showing ",w,"-",P," of ",a]}),Jt(fn,{value:String(i),onValueChange:I=>o(Number(I)),children:[He(Qa,{className:"af-w-[70px] af-h-8",children:He(mn,{})}),Jt(en,{children:[He(St,{value:"10",children:"10"}),He(St,{value:"25",children:"25"}),He(St,{value:"50",children:"50"}),He(St,{value:"100",children:"100"})]})]}),He("span",{children:"per page"})]}),Jt("div",{className:"af-flex af-items-center af-gap-2",children:[Jt(y,{variant:"outline",size:"sm",onClick:()=>c(r-1),disabled:!u,children:[He(Ap,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Jt(y,{variant:"outline",size:"sm",onClick:()=>c(r+1),disabled:!l,children:["Next",He(Dp,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as je from"react";import{ArrowLeft as $p,ChevronLeft as Up,ChevronRight as Xc,Copy as Vp,Download as Hp,ExternalLink as zp,FileText as td,Loader2 as jp,Search as qp}from"lucide-react";import*as Xt from"react";function nr({initialPageSize:e=25,refreshKey:t,includeAggregates:a=!1}={}){let{api:s}=H(),[n,r]=Xt.useState([]),[i,l]=Xt.useState(0),[u,c]=Xt.useState(null),[o,f]=Xt.useState(!0),[b,g]=Xt.useState(null),[m,v]=Xt.useState(0),[d,p]=Xt.useState(e),[x,S]=Xt.useState(void 0),[k,h]=Xt.useState(""),[N,R]=Xt.useState(""),[C,w]=Xt.useState(""),[P,I]=Xt.useState(""),[_,q]=Xt.useState(""),j=x?x.join(","):"",U=Xt.useRef(0),te=Xt.useCallback(async()=>{let me=++U.current;f(!0),g(null);try{let T={labels:j?j.split(","):void 0,customerEmail:k||void 0,q:N||void 0,from:C||void 0,to:P||void 0,retainerId:_||void 0,includeAggregates:a,limit:d,offset:m*d},V=await s.getInvoices(T);if(me!==U.current)return;if(m>0&&m*d>=V.total){v(Math.max(0,Math.ceil(V.total/d)-1));return}r(V.invoices),l(V.total),a&&c(V.aggregates??null)}catch(T){if(me!==U.current)return;g(T instanceof Error?T:new Error("Failed to fetch invoices"))}finally{me===U.current&&f(!1)}},[s,j,k,N,C,P,_,m,d,a]);Xt.useEffect(()=>{te()},[te,t]);let ce=me=>T=>{v(0),me(T)};return{invoices:n,total:i,aggregates:u,isLoading:o,error:b,page:m,pageSize:d,hasNextPage:(m+1)*d<i,hasPreviousPage:m>0,setPage:v,setPageSize:ce(p),labels:x,setLabels:ce(S),customerEmail:k,setCustomerEmail:ce(h),q:N,setQ:ce(R),from:C,setFrom:ce(w),to:P,setTo:ce(I),retainerId:_,setRetainerId:ce(q),clearFilters:()=>{v(0),S(void 0),h(""),R(""),w(""),I(""),q("")},refetch:te}}import{Fragment as Xp,jsx as B,jsxs as oe}from"react/jsx-runtime";var Wp={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 el(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Wp[e.label]??e.label}function Gp(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 Qo={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Kp={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Or({invoice:e,className:t}){return oe("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[B(ee,{variant:Gp(e.label),className:t,children:el(e)}),e.collection_method==="charge_automatically"&&B(ee,{variant:"secondary",children:"Managed in Stripe"})]})}function ji({delivery:e,className:t}){if(!e)return null;let a=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return B(ee,{variant:a,className:t,children:Qo[e.state]??e.state})}function sr(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function yn(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t);return Number.isNaN(a.getTime())?e:a.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Qc={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Hi={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},Jo=100,Xo=5e3;async function Zp(e,t){let a=[],s=0;for(let n=0;n<Xo;n+=Jo){let r=await e.getInvoices({...t,limit:Jo,offset:n});if(s=r.total,a.push(...r.invoices),r.invoices.length<Jo||a.length>=s)break}return{invoices:a.slice(0,Xo),total:s,truncated:s>a.length||s>Xo}}function ad(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],a=e.map(s=>[s.id,sr(s),el(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),Q(s.amount_subtotal,s.currency),Q(s.tax_total,s.currency),Q(s.amount_total,s.currency),s.amount_due===null?"":Q(s.amount_due,s.currency),s.amount_paid===null?"":Q(s.amount_paid,s.currency),Q(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?"":Q(s.discount_total,s.currency),s.collection_method??""]);return[t,...a].map(s=>s.map(_c).join(",")).join(`
5
+ `)}function Yp(e){hi(new Blob([ad(e)],{type:"text/csv;charset=utf-8"}),bi("invoices"))}function Jp({className:e,refreshKey:t,initialInvoiceId:a,onDetailOpenChange:s,onConnectStripe:n,onUpgradePlan:r,needsPaidPlan:i=!1,retainerFilter:l=null,onClearRetainerFilter:u,maxRows:c,onViewAll:o}){let f=typeof c=="number",{api:b}=H(),{invoices:g,total:m,isLoading:v,error:d,page:p,pageSize:x,hasNextPage:S,hasPreviousPage:k,setPage:h,labels:N,setLabels:R,customerEmail:C,setCustomerEmail:w,q:P,setQ:I,from:_,setFrom:q,to:j,setTo:U,retainerId:te,setRetainerId:ce,refetch:me}=nr({refreshKey:t}),[T,V]=je.useState(typeof c=="number"?"all":"open"),[A,ne]=je.useState(""),[re,Me]=je.useState(null),Se=je.useRef(0),Ee=!f||!!o,Ye=je.useCallback($=>{if(f){o?.();return}Se.current++,nt(!1),Me($)},[f,o]),[ke,nt]=je.useState(!1),[E,M]=je.useState(0),[L,pe]=je.useState(null),[J,se]=je.useState(!1),[Fe,Qe]=je.useState(0);je.useEffect(()=>{Me($=>{if(!$)return $;let Pe=g.find(jt=>jt.id===$.id);return Pe&&Pe!==$?Pe:$})},[g]);let[Xe,It]=je.useState(!1),[he,$e]=je.useState(null),yt=async()=>{if(!Xe){It(!0),$e(null);try{let{invoices:$,total:Pe,truncated:jt}=await Zp(b,{labels:N,customerEmail:C,q:P,from:_,to:j,retainerId:te});Yp($),$e(jt?`Exported the first ${$.length.toLocaleString()} of ${Pe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{$e("Couldn't export \u2014 try again.")}finally{It(!1)}}},At=!C&&!P&&!_&&!j&&!te,[Mt,et]=je.useState(null);je.useEffect(()=>{if(v||m>0||!At||T!=="open")return;let $=!1;return b.getInvoices({limit:1}).then(Pe=>{$||et(Pe.total>0)}).catch(()=>{$||et(!0)}),()=>{$=!0}},[b,v,m,At,T,t]),je.useEffect(()=>{R(f?Hi.all:Hi.open)},[]),je.useEffect(()=>{let $=l?.id??"";$!==te&&(ce($),$&&(V("all"),R(Hi.all),w(""),I(""),ne(""),q(""),U("")))},[l?.id]),je.useEffect(()=>{let $=!1;return se(!1),b.getInvoiceSettings().then(Pe=>{$||pe({payments_active:Pe.payments_active,blocked:Pe.blocked})}).catch(()=>{$||se(!0)}),()=>{$=!0}},[b,t,Fe]),je.useEffect(()=>{if(!a||f)return;let $=!1,Pe=Se.current;return nt(!1),b.getInvoice(a).then(jt=>{!$&&Pe===Se.current&&Me(jt)}).catch(()=>{!$&&Pe===Se.current&&nt(!0)}),()=>{$=!0}},[b,a,E,f]),je.useEffect(()=>{s?.(re!==null)},[re,s]);let ta=$=>{V($),R(Hi[$])},Je=$=>{let Pe=$.trim();if(!Pe){P&&I(""),C&&w("");return}if(Pe.includes("@")){P&&I(""),w(Pe);return}C&&w(""),I(Pe.replace(/^#/,""))},wt=g,Xa=f?wt.slice(0,c):wt,Mn=ke&&oe("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. ",B(y,{type:"button",variant:"link",size:"sm",onClick:()=>M($=>$+1),children:"Retry opening invoice"})]});if(re)return oe("div",{className:e,children:[Mn,B(tl,{invoice:re,refreshKey:t,onBack:()=>{Ye(null),me()}},re.id)]});let ye=oe("div",{className:"af-mb-4 af-space-y-3",children:[J&&oe("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",B(y,{type:"button",variant:"link",size:"sm",onClick:()=>Qe($=>$+1),children:"Retry setup check"})]}),Mn,L?.blocked&&oe("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",L.blocked.reason?`: ${L.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),l&&oe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[oe(ee,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",l.label]}),u&&B(y,{type:"button",variant:"link",size:"sm",onClick:u,children:"Clear schedule filter"})]}),oe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[B("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(Qc).map($=>B("button",{type:"button","aria-pressed":T===$,onClick:()=>ta($),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",T===$?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Qc[$]},$))}),oe("div",{className:"af-relative af-w-full af-max-w-xs",children:[B(qp,{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"}),B(ae,{type:"text",value:A,onChange:$=>ne($.target.value),onBlur:()=>Je(A),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),Je(A))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),oe("div",{className:"af-flex af-items-center af-gap-2",children:[B(Oe,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),B(ae,{id:"invoices-from",type:"date",value:_,max:j||void 0,onChange:$=>q($.target.value),className:"af-invoice-date af-w-[150px]"})]}),oe("div",{className:"af-flex af-items-center af-gap-2",children:[B(Oe,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),B(ae,{id:"invoices-to",type:"date",value:j,min:_||void 0,onChange:$=>U($.target.value),className:"af-invoice-date af-w-[150px]"})]}),oe(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void yt(),disabled:Xe||v||!!d||m===0,"aria-busy":Xe,children:[B(Hp,{className:"af-h-4 af-w-4 af-mr-1"}),Xe?"Exporting\u2026":"Export CSV (all matching)"]})]}),he&&B("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:he})]});return v?oe("div",{className:e,children:[f?null:ye,B("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map($=>oe("div",{className:"af-rounded-md af-border af-p-3",children:[oe("div",{className:"af-flex af-items-center af-justify-between",children:[B(G,{className:"af-h-4 af-w-20"}),B(G,{className:"af-h-4 af-w-16"})]}),B(G,{className:"af-mt-2 af-h-3 af-w-40"})]},$))})]}):d?oe("div",{className:e,children:[f?null:ye,oe("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",B(y,{type:"button",variant:"link",size:"sm",onClick:()=>void me(),children:"Retry"})]})]}):m===0&&At&&(T==="all"||Mt===!1)&&(T==="open"||T==="all")?L?.blocked?oe("div",{className:e,children:[f?null:ye,B(zi,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):i?oe("div",{className:e,children:[f?null:ye,B(zi,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):L&&!L.payments_active?oe("div",{className:e,children:[f?null:ye,B(zi,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):oe("div",{className:e,children:[f?null:ye,B(zi,{heading:"No invoices yet",body:!L||J?"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."})]}):oe("div",{className:e,children:[f?null:ye,Xa.length===0?B("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."}):oe(Xp,{children:[B("div",{className:"af-space-y-3 lg:af-hidden",children:Xa.map($=>oe("button",{type:"button",onClick:()=>Ye($),disabled:!Ee,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ee?" hover:af-bg-muted/50":""}`,children:[oe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[B("span",{className:"af-font-medium",children:sr($)}),B(Or,{invoice:$})]}),B("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:$.customer_name??$.customer_email??"\u2014"}),$.delivery&&B("div",{className:"af-mt-1",children:B(ji,{delivery:$.delivery})}),oe("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[B("span",{children:$.collection_method==="charge_automatically"?"Automatic collection":$.due_at?`Due ${yn($.due_at)}`:"Due on receipt"}),B("span",{className:"af-font-medium af-tabular-nums",children:Q($.amount_due??$.amount_total,$.currency)})]})]},$.id))}),B("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(ct,{children:[B(dt,{children:oe(Ie,{children:[B(Z,{children:"Invoice"}),B(Z,{children:"Created"}),B(Z,{children:"Customer"}),B(Z,{children:"Due"}),B(Z,{className:"af-text-right",children:"Amount"}),B(Z,{children:"Status"}),B(Z,{children:"Delivery"}),B(Z,{className:"af-w-8"})]})}),B(ut,{children:Xa.map($=>oe(Ie,{className:Ee?"af-cursor-pointer":void 0,onClick:Ee?()=>Ye($):void 0,children:[B(Y,{className:"af-font-medium",children:B("button",{type:"button",disabled:!Ee,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ee?" hover:af-underline":""}`,onClick:Pe=>{Pe.stopPropagation(),Ye($)},"aria-label":`Open invoice ${sr($)}`,children:sr($)})}),B(Y,{children:yn($.created_at)}),oe(Y,{children:[B("div",{children:$.customer_name??"\u2014"}),B("div",{className:"af-text-xs af-text-muted-foreground",children:$.customer_email})]}),B(Y,{children:$.collection_method==="charge_automatically"?"Automatic":$.due_at?yn($.due_at):"On receipt"}),B(Y,{className:"af-text-right af-tabular-nums",children:Q($.amount_due??$.amount_total,$.currency)}),B(Y,{children:B(Or,{invoice:$})}),B(Y,{children:B(ji,{delivery:$.delivery})}),B(Y,{children:B(Xc,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},$.id))})]})}),f?null:oe("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[oe("span",{children:[m," invoice",m===1?"":"s"]}),oe("div",{className:"af-flex af-items-center af-gap-1",children:[B(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(p-1),disabled:!k,"aria-label":"Previous page",children:B(Up,{className:"af-h-4 af-w-4"})}),oe("span",{className:"af-tabular-nums",children:[p*x+1,"\u2013",Math.min((p+1)*x,m)]}),B(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(p+1),disabled:!S,"aria-label":"Next page",children:B(Xc,{className:"af-h-4 af-w-4"})})]})]})]})]})}function zi({heading:e,body:t,action:a}){return B(tr,{icon:td,heading:e,body:t,action:a})}function ys(e){return B(Jp,{...e},e.maxRows==null?"full":"compact")}var ls="af-text-xs af-text-muted-foreground";function ed(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function tl({invoice:e,onBack:t,refreshKey:a,className:s}){let{api:n}=H(),r=je.useRef(null);je.useEffect(()=>{r.current?.focus()},[e.id]);let[i,l]=je.useState(!1),[u,c]=je.useState(null),[o,f]=je.useState(!1),[b,g]=je.useState(!1),m=je.useRef(0),[v,d]=je.useState(null),[p,x]=je.useState(!1),[S,k]=je.useState(0);je.useEffect(()=>{let _=!1;return x(!1),n.getInvoice(e.id).then(q=>{_||d({source:e,value:q})}).catch(()=>{_||x(!0)}),()=>{_=!0}},[n,e,a,S]);let h=v?.source===e?v.value:e,N=h.collection_method==="charge_automatically";je.useEffect(()=>(m.current++,c(null),f(!1),g(!1),l(!1),()=>{m.current++}),[n,h,a]);let R=_=>_==null?"\u2014":Q(_,h.currency),C=async()=>{if(!(!h.pay_url||!ed()))try{await navigator.clipboard.writeText(h.pay_url),l(!0),setTimeout(()=>l(!1),1500)}catch{}},w=async()=>{if(u){c(null);return}let _=++m.current;g(!1),f(!0);try{let q=await n.getInvoicePreview(h.id);_===m.current&&c(q)}catch{_===m.current&&g(!0)}finally{_===m.current&&f(!1)}},P=h.bill_to,I=P?[P.company,P.name,P.address?.line1,P.address?.line2,[P.address?.city,P.address?.state,P.address?.postal_code].filter(Boolean).join(", "),P.address?.country,P.tax_id?`${P.tax_id.value}`:null,P.po_number?`PO ${P.po_number}`:null,P.service_period?`Service period: ${P.service_period}`:null].filter(_=>!!_&&_.length>0):[];return oe("div",{className:s,children:[oe("div",{className:"af-mb-4",children:[oe(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[B($p,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),oe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[oe("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",sr(h)]}),B(Or,{invoice:h}),B(ji,{delivery:h.delivery})]}),oe("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[h.customer_name??h.customer_email,h.customer_name&&h.customer_email?` \xB7 ${h.customer_email}`:""]})]}),p&&oe("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. ",B(y,{type:"button",variant:"link",size:"sm",onClick:()=>k(_=>_+1),children:"Retry details"})]}),h.label==="failed"&&B("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),h.label==="creating"&&B("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."}),oe("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[oe("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[oe("section",{className:"af-rounded-md af-border af-p-4",children:[oe(ct,{children:[B(dt,{children:oe(Ie,{children:[B(Z,{children:"Description"}),B(Z,{className:"af-text-right",children:"Qty"}),B(Z,{className:"af-text-right",children:"Amount"})]})}),B(ut,{children:h.line_items.map((_,q)=>oe(Ie,{children:[B(Y,{style:{overflowWrap:"anywhere"},children:_.description}),B(Y,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_.quantity}),B(Y,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:R(_.amount)})]},q))})]}),oe("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[B(hs,{label:"Subtotal",value:R(h.amount_subtotal)}),(h.discount_total??0)>0&&B(hs,{label:"Discount",value:`-${R(h.discount_total)}`}),h.tax_total>0&&B(hs,{label:h.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:R(h.tax_total)}),B(hs,{label:"Total",value:R(h.amount_total),strong:!0}),h.credit_applied>0&&B(hs,{label:"Credit applied",value:`-${R(h.credit_applied)}`}),h.amount_due!==null&&h.amount_due!==h.amount_total&&B(hs,{label:"Amount due",value:R(h.amount_due),strong:!0}),h.amount_paid!==null&&h.amount_paid>0&&B(hs,{label:"Amount paid",value:R(h.amount_paid)}),h.amount_refunded>0&&B(hs,{label:"Refunded",value:R(h.amount_refunded)})]}),h.credit_notes?.length>0&&oe("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[B("div",{className:ls,children:"Credit notes"}),h.credit_notes.map(_=>oe("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[oe("span",{className:"af-text-muted-foreground",children:[yn(_.created_at)," \xB7 ",_.origin==="dashboard"?"issued in Stripe":"refund",_.stripe_credit_note_id?"":" \xB7 being created"]}),oe("span",{className:"af-tabular-nums",children:["-",Q(_.amount,_.currency)]})]},_.id))]})]}),(h.note||h.footer)&&oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[h.note&&oe("div",{children:[B("div",{className:ls,children:"Note"}),B("div",{className:"af-whitespace-pre-wrap af-break-words",children:h.note})]}),h.footer&&oe("div",{children:[B("div",{className:ls,children:"Footer"}),B("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:h.footer})]})]}),u&&!N&&oe("section",{className:"af-rounded-md af-border af-p-4",children:[oe("div",{className:W(ls,"af-break-words"),children:["Email preview \u2014 ",u.subject]}),B("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),B("iframe",{title:"Invoice email preview",srcDoc:u.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),oe("div",{className:"af-min-w-0 af-space-y-4",children:[oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[B(hn,{label:"Created",value:yn(h.created_at)}),B(hn,{label:"Due",value:h.collection_method==="charge_automatically"?"Managed in Stripe":h.due_at?yn(h.due_at):"On receipt"}),h.paid_at&&B(hn,{label:"Paid",value:yn(h.paid_at)}),h.payment_method&&B(hn,{label:"Paid by",value:h.paid_out_of_band?`${h.payment_method} (recorded outside Stripe)`:h.payment_method}),h.payment_state!=="none"&&B(hn,{label:"Payment",value:h.payment_state==="processing"?"Processing":h.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),h.delivery&&B(hn,{label:"Delivery",value:`${Qo[h.delivery.state]} \xB7 ${h.delivery.recipient}`}),h.marked_uncollectible_at&&B(hn,{label:"Written off",value:yn(h.marked_uncollectible_at)}),h.correction_reason&&B(hn,{label:"Correction",value:h.correction_reason}),h.replaced_by_order_id&&B(hn,{label:"Replaced by",value:h.replaced_by_order_id}),h.collection_method==="charge_automatically"?B(hn,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):h.retainer_id&&B(hn,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),h.replaces_order_id&&B(hn,{label:"Replaces",value:h.replaces_order_id})]}),oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[B("div",{className:ls,children:"Reminders"}),N?B("div",{children:"View automatic payment reminders in Stripe."}):h.reminders.disabled?B("div",{children:"Off for this invoice."}):h.reminders.paused_until?oe("div",{children:["Paused until ",yn(h.reminders.paused_until),"."]}):h.reminders.next_at?oe("div",{children:["Next on ",yn(h.reminders.next_at),"."]}):h.reminders.final_sent_at?oe("div",{children:["Final reminder sent ",yn(h.reminders.final_sent_at),"."]}):B("div",{children:"None scheduled."}),!N&&oe("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",h.reminders.schedule.length===0?"none":h.reminders.schedule.map(_=>_<0?`${-_}d before`:_===0?"due day":`${_}d after`).join(", ")]})]}),h.communications&&h.communications.length>0&&oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[B("div",{className:ls,children:"Email delivery history"}),h.communications.map(_=>oe("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[oe("span",{className:"af-min-w-0 af-break-words",children:[Kp[_.kind]??_.kind,_.kind==="reminder"&&_.slot!==null?` #${_.slot}`:"",oe("span",{className:"af-text-muted-foreground",children:[" \xB7 ",_.recipient]})]}),oe("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Qo[_.state]??_.state," \xB7 ",yn(_.state_at??_.created_at)]})]},_.id))]}),I.length>0&&oe("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[B("div",{className:ls,children:"Bill to"}),I.map((_,q)=>B("div",{className:"af-break-words",children:_},q))]}),oe("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[h.pay_url&&oe(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void C(),disabled:!ed(),children:[B(Vp,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Copied":N?"Copy invoice link":"Copy pay link"]}),h.pdf_url&&B(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:oe("a",{href:h.pdf_url,target:"_blank",rel:"noreferrer",children:[B(zp,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!N&&oe(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void w(),disabled:o,children:[o?B(jp,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):B(td,{className:"af-h-4 af-w-4 af-mr-1"}),u?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!N&&B("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),h.pay_url&&B("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:h.pay_url}),B("p",{className:"af-text-xs af-text-muted-foreground",children:N?"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 hn({label:e,value:t}){return oe("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[B("span",{className:W(ls,"af-shrink-0"),children:e}),B("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function hs({label:e,value:t,strong:a}){return oe("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[B("dt",{className:W(ls,a&&"af-font-medium af-text-foreground"),children:e}),B("dd",{className:W("af-tabular-nums",a&&"af-font-semibold"),children:t})]})}import{Repeat as Qp}from"lucide-react";import{jsx as Gt,jsxs as In}from"react/jsx-runtime";var eg={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},nd={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function tg(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 sd(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>nd[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>nd[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":eg[e.status]}function rd(e){let t=e.interval==="year"?"every year":"every month";return`${Q(e.amount,e.currency)} ${t}`}function ag(e){return e.status==="canceled"?`Ended ${qi(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${qi(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 ${qi(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${qi(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function qi(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),a=new Date(t);return Number.isNaN(a.getTime())?e.slice(0,10):a.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function al({retainer:e,className:t}){return Gt(ee,{variant:tg(e.status),className:W("af-max-w-full af-whitespace-normal af-break-words",t),children:sd(e)})}function rr({retainers:e,isLoading:t,error:a,onRetry:s,onShowCycles:n,activeRetainerId:r,total:i,endedTotal:l=0,isLoadingMore:u=!1,onLoadMore:c,includeEnded:o=!1,onIncludeEndedChange:f,exportCsv:b,className:g}){let m=!!f;if(!t&&!a&&e.length===0&&!(m&&(o||l>0)))return null;let v=i!==void 0?Math.max(0,i-e.length):0;return In("section",{className:W("af-mb-6",g),"aria-label":"Recurring invoices",children:[In("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[Gt(Qp,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),Gt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),Gt("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),m&&Gt(y,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":o,onClick:()=>f?.(!o),children:o?"Hide ended recurring invoices":l>0&&e.length===0?`Show ended recurring invoices (${l})`:"Show ended recurring invoices"}),b&&Gt(wa,{fetchCsv:b,filename:"retainers",className:m?void 0:"af-ml-auto"})]}),a?In("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",Gt(y,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?Gt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(d=>In("div",{className:"af-rounded-md af-border af-p-3",children:[Gt(G,{className:"af-h-4 af-w-48"}),Gt(G,{className:"af-mt-2 af-h-3 af-w-32"})]},d))}):e.length===0?Gt("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:o?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):Gt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(d=>{let p=r===d.id;return In("li",{className:W("af-rounded-md af-border af-p-3",p&&"af-border-primary af-bg-muted/40"),children:[In("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[In("div",{className:"af-min-w-0",children:[Gt("div",{className:"af-truncate af-font-medium",children:d.customer_name??d.customer_email??"\u2014"}),Gt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:d.description})]}),Gt(al,{retainer:d})]}),d.collection_method==="charge_automatically"?In("div",{className:"af-mt-2 af-space-y-1",children:[Gt(ee,{variant:"secondary",children:"Managed in Stripe"}),Gt("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."})]}):Gt("div",{className:"af-mt-2 af-text-sm",children:rd(d)}),In("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:[In("span",{children:[ag(d)," \xB7 ",d.cycles.count===0?"no invoices yet":`${d.cycles.paid} paid${d.cycles.open>0?`, ${d.cycles.open} open`:""}`]}),d.cycles.count>0&&Gt(y,{type:"button",variant:p?"secondary":"ghost",size:"sm",onClick:()=>n(d),"aria-pressed":p,children:p?"Showing invoices":"View invoices"})]}),d.status==="failed"&&d.operation?.last_error&&In("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",d.operation.last_error,". Ask in the chat to try again."]})]},d.id)})}),!t&&!a&&v>0&&c&&Gt("div",{className:"af-mt-2",children:Gt(y,{type:"button",variant:"outline",size:"sm",onClick:c,disabled:u,children:u?"Loading\u2026":`Load more (${v} more)`})})]})}import*as od from"react";import{AlertTriangle as id,CheckCircle2 as ng,CreditCard as nl,Loader2 as sg,RefreshCw as rg}from"lucide-react";import{jsx as kt,jsxs as da}from"react/jsx-runtime";function ir({onConnectStripe:e,onUpgradePlan:t,whenActive:a,className:s}){let{status:n,isLoading:r,error:i,refetch:l}=gs(),[u,c]=od.useState(!1),o=async()=>{c(!0);try{await l()}finally{c(!1)}};return r&&!n?kt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:kt("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!n?kt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:da("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):n.status==="active"?a!==void 0?kt("div",{className:s,children:a}):kt("div",{className:s,children:da("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:[kt(ng,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),da("div",{children:[kt("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),da("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",n.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):da("div",{className:`af-space-y-4 ${s||""}`,children:[n.reason==="needs_stripe"&&da("div",{className:"af-space-y-3",children:[da("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[kt(nl,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),da("div",{children:[kt("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),kt("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?da(y,{onClick:e,children:[kt(nl,{className:"af-h-4 af-w-4 af-mr-1"}),n.stripe_account_connected?"Finish setting up":"Set up payments"]}):kt("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),n.reason==="needs_paid_plan"&&da("div",{className:"af-space-y-3",children:[da("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[kt(id,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),da("div",{children:[kt("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),kt("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?kt(y,{onClick:t,children:"Upgrade plan"}):kt("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),n.reason==="account_disabled"&&da("div",{className:"af-space-y-3",children:[da("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:[kt(id,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),da("div",{children:[kt("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),n.stripe_account_connected?kt("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."}):kt("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."})]})]}),da("div",{className:"af-flex af-gap-2",children:[e&&n.stripe_account_connected&&da(y,{onClick:e,children:[kt(nl,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),da(y,{variant:"outline",onClick:o,disabled:u,children:[u?kt(sg,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):kt(rg,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as Ea from"react";function sl(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function or({includeStats:e=!1,refreshKey:t}={}){let{api:a}=H(),[s,n]=Ea.useState([]),[r,i]=Ea.useState(!0),[l,u]=Ea.useState(null),c=Ea.useRef(0),o=Ea.useCallback(async()=>{let d=++c.current;try{i(!0),u(null);let p=await a.getProducts(e?{include:"stats"}:{});if(d!==c.current)return;n(p)}catch(p){if(d!==c.current)return;u(p instanceof Error?p:new Error("Failed to fetch products"))}finally{d===c.current&&i(!1)}},[a,e,t]);Ea.useEffect(()=>{o()},[o]);let f=Ea.useCallback(async d=>{let p=await a.createProduct(d);return n(x=>[p,...x]),p},[a]),b=Ea.useCallback(async(d,p)=>{let x=await a.updateProduct(d,p);return n(S=>sl(S,d,x)),x},[a]),g=Ea.useCallback(async d=>{await a.deleteProduct(d),n(p=>p.filter(x=>x.id!==d))},[a]),m=Ea.useCallback(async(d,p)=>{let x=await a.attachProductFile(d,p);return n(S=>sl(S,d,x)),x},[a]),v=Ea.useCallback(async(d,p)=>{let x=await a.attachProductFileFromUrl(d,p);return n(S=>sl(S,d,x)),x},[a]);return{products:s,isLoading:r,error:l,refetch:o,createProduct:f,updateProduct:b,deleteProduct:g,attachProductFile:m,attachProductFileFromUrl:v}}import*as Ia from"react";var rl=["creating","active","paused","canceling"],ig=["canceled","failed"],og={statuses:rl},lg={};function lr({refreshKey:e,includeEnded:t=!1,limit:a=50}={}){let{api:s}=H(),[n,r]=Ia.useState([]),[i,l]=Ia.useState(0),[u,c]=Ia.useState(0),[o,f]=Ia.useState(!0),[b,g]=Ia.useState(!1),[m,v]=Ia.useState(null),[d,p]=Ia.useState(t),x=Ia.useRef(0),S=Ia.useCallback(async()=>{let h=++x.current;f(!0),g(!1),v(null);try{let N=await s.getRetainers({statuses:d?void 0:rl,limit:a,offset:0});if(h!==x.current)return;if(r(N.retainers),l(N.total),!d&&N.total===0){let R=await s.getRetainers({statuses:ig,limit:1,offset:0});if(h!==x.current)return;c(R.total)}else c(0)}catch(N){if(h!==x.current)return;v(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{h===x.current&&f(!1)}},[s,d,a]);Ia.useEffect(()=>{S()},[S,e]);let k=Ia.useCallback(async()=>{if(o||b||n.length>=i)return;let h=x.current;g(!0);try{let N=await s.getRetainers({statuses:d?void 0:rl,limit:a,offset:n.length});if(h!==x.current)return;r(R=>{let C=new Set(R.map(w=>w.id));return[...R,...N.retainers.filter(w=>!C.has(w.id))]}),l(N.total)}catch(N){if(h!==x.current)return;v(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{h===x.current&&g(!1)}},[s,d,a,o,b,n.length,i]);return{retainers:n,total:i,endedTotal:u,hasMore:n.length<i,isLoading:o,isLoadingMore:b,error:m,includeEnded:d,setIncludeEnded:p,loadMore:k,refetch:S,filters:d?lg:og}}import{Fragment as vg,jsx as gt,jsxs as Ha}from"react/jsx-runtime";function ld({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:n}){let[r,i]=cr.useState(t),[l,u]=cr.useState("list"),[c,o]=cr.useState(null),f=or(),{status:b,error:g}=gs(),m=b?.currency,v=S=>{o(S),u("edit")},d=()=>{o(null),u("create")},p=()=>{u("list"),o(null)},x=S=>{o(S),u("edit")};return Ha("div",{className:e,children:[Ha("div",{className:"af-mb-6",children:[gt("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),gt("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Ha(di,{value:r,onValueChange:S=>i(S),children:[Ha(Pr,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Ha(Pn,{value:"products",className:"af-gap-2",children:[gt(ug,{className:"af-h-4 af-w-4"}),"Products"]}),Ha(Pn,{value:"orders",className:"af-gap-2",children:[gt(fg,{className:"af-h-4 af-w-4"}),"Orders"]}),Ha(Pn,{value:"invoices",className:"af-gap-2",children:[gt(dg,{className:"af-h-4 af-w-4"}),"Invoices"]}),Ha(Pn,{value:"customers",className:"af-gap-2",children:[gt(pg,{className:"af-h-4 af-w-4"}),"Customers"]}),gt(Pn,{value:"promos",children:"Promo codes"}),Ha(Pn,{value:"setup",className:"af-gap-2",children:[gt(mg,{className:"af-h-4 af-w-4"}),"Setup"]})]}),gt(Cn,{value:"products",children:l==="list"?gt(Pi,{productsState:f,onSelectProduct:v,onCreateProduct:d}):Ha("div",{children:[Ha("div",{className:"af-mb-6",children:[Ha(y,{variant:"ghost",size:"sm",onClick:p,className:"af-mb-2 af--ml-2",children:[gt(cg,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),gt("h3",{className:"af-text-lg af-font-semibold",children:l==="create"?"New Product":c?.name})]}),l==="create"&&!m?gt("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?Ha("div",{className:"af-text-destructive",children:["Error: ",g.message]}):gt("div",{className:"af-text-muted-foreground",children:"Loading..."})}):gt(Ti,{productsState:f,product:l==="edit"?c:null,currency:m??"usd",onSaved:x},l==="edit"?c?.id??"edit":"new")]})}),gt(Cn,{value:"orders",children:gt(bs,{onRefund:s})}),gt(Cn,{value:"invoices",children:gt(gg,{onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),gt(Cn,{value:"customers",children:gt(Vi,{})}),gt(Cn,{value:"promos",children:gt(Qs,{})}),gt(Cn,{value:"setup",children:gt(ir,{onConnectStripe:a,onUpgradePlan:n})})]})]})}function gg({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a}){let s=lr(),[n,r]=cr.useState(null),[i,l]=cr.useState(!1);return Ha(vg,{children:[!i&&gt(rr,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:n?.id??null,onShowCycles:u=>r(c=>c?.id===u.id?null:u),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),gt(ys,{onDetailOpenChange:l,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}import*as dd from"react";import*as jn from"react";function dr({refreshKey:e}={}){let{api:t}=H(),[a,s]=jn.useState(null),[n,r]=jn.useState(!0),[i,l]=jn.useState(null),u=jn.useRef(0),c=jn.useCallback(async()=>{let o=++u.current;try{r(!0),l(null);let f=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(o!==u.current)return;s(f)}catch(f){if(o!==u.current)return;l(f instanceof Error?f:new Error("Failed to fetch summary"))}finally{o===u.current&&r(!1)}},[t,e]);return jn.useEffect(()=>{c()},[c]),{summary:a,isLoading:n,error:i,refetch:c}}import{Fragment as il,jsx as ua,jsxs as ol}from"react/jsx-runtime";function cd(e,t){if(e.settled.complete)return{headline:Q(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:Q(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${Q(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:Q(0,t),extra:[]}}function ud({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:n,className:r}){let{summary:i,isLoading:l,error:u,refetch:c}=dr({refreshKey:e}),[o,f]=dd.useState(!1),b=ua("div",{className:"af-mb-6",children:u&&!i?ua(xt,{message:"Couldn't load your revenue summary.",onRetry:()=>c()}):ua("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:l||!i?ol(il,{children:[ua(pt,{label:"This week",children:ua(G,{className:"af-h-6 af-w-24"})}),ua(pt,{label:"Today",children:ua(G,{className:"af-h-6 af-w-24"})}),ua(pt,{label:"Needs attention",children:ua(G,{className:"af-h-6 af-w-10"})})]}):ua(il,{children:(()=>{let g=cd(i.revenue.d7,i.currency),m=cd(i.revenue.today,i.currency);return ol(il,{children:[ua(pt,{label:"This week",detail:g.extra.length>0?ua("div",{children:g.extra.map(v=>ua("div",{children:v},v))}):void 0,children:g.headline}),ua(pt,{label:"Today",detail:m.extra.length>0?ua("div",{children:m.extra.map(v=>ua("div",{children:v},v))}):void 0,children:m.headline}),ua(pt,{label:"Needs attention",valueClassName:i.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:i.needs_attention.count===0?"All clear":i.needs_attention.items[0]?.title??void 0,children:i.needs_attention.count})]})})()})})});return ol(Ut,{title:"Orders",onBackToWebsite:n,hideBackButton:o,className:r,children:[b,ua(bs,{refreshKey:e,initialOrderId:t,onDetailOpenChange:f,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as xn from"react";import{ImageOff as wg,Package as Sg,Search as Ng}from"lucide-react";import*as qn from"react";import{ArrowLeft as yg,ImageOff as xg}from"lucide-react";import{jsx as An,jsxs as Lr}from"react/jsx-runtime";var fd="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",xs="af-text-xs af-text-muted-foreground",Wi="af-text-sm af-font-medium af-tabular-nums",bg=3;function hg(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let u=e.min_amount??t?.min_amount??null,c=e.max_amount??t?.max_amount??null;return u!==null&&c!==null?{text:`Buyer chooses (${Q(u,a)} \u2013 ${Q(c,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(n===null||r===null)return{text:"Varies by variant",compareAt:null};let i=n===r?Q(n,a):`${Q(n,a)} \u2013 ${Q(r,a)}`,l=t?.compare_at_amount??null;return{text:i,compareAt:l!==null&&l>r?Q(l,a):null}}function Gi({product:e,className:t}){let a=hg(e);return Lr("div",{className:t,children:[An("span",{className:Wi,children:a.text}),a.compareAt&&An("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function Ki({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?An(ee,{variant:"destructive",children:"Out of stock"}):t.low_stock?Lr(ee,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?An(ee,{variant:"secondary",children:"Backorder"}):t.available===null?null:Lr(ee,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?An(ee,{variant:"warning",children:"Low stock"}):null}function Zi(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Yi(e){return e.map(t=>Q(t.amount,t.currency)).join(" + ")}function md(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${Q(e.min_amount,e.currency)} \u2013 ${Q(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":Q(e.unit_amount,e.currency)}function pd({variant:e}){let t=e.inventory;if(!t||!t.tracked)return An("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?Lr("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[An("span",{className:"af-tabular-nums",children:Math.max(0,a)}),An(ee,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?An(ee,{variant:"destructive",children:"Out of stock"}):Lr("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[An("span",{className:"af-tabular-nums",children:a}),a<=bg&&An(ee,{variant:"warning",children:"Low"})]})}import{jsx as we,jsxs as Pt}from"react/jsx-runtime";function Br({title:e,children:t,className:a}){return Pt("section",{className:W("af-rounded-lg af-border af-p-4",a),children:[we("h4",{className:fd,children:e}),we("div",{className:"af-mt-3",children:t})]})}function gd({src:e,className:t}){let[a,s]=qn.useState(!1);return qn.useEffect(()=>s(!1),[e]),!e||a?we("div",{"aria-hidden":"true",className:W("af-flex af-items-center af-justify-center af-bg-muted",t),children:we(xg,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):we("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:W("af-object-cover",t)})}function vd({product:e,showStats:t=!1,onBack:a}){let{api:s}=H(),[n,r]=qn.useState(null),[i,l]=qn.useState(!0),[u,c]=qn.useState(null),[o,f]=qn.useState(0),[b,g]=qn.useState(0);qn.useEffect(()=>{let h=!1;return l(!0),c(null),s.getProduct(e.id).then(N=>{h||r(N)}).catch(N=>{h||c(N instanceof Error?N:new Error("Failed to load product"))}).finally(()=>{h||l(!1)}),()=>{h=!0}},[s,e.id,o]);let m=n?{...e,...n}:e,v=m.images.length>0?m.images:e.images,d=v[b]??v[0],p=Zi(m),x=t?m.stats:void 0,S=n?.variants??[],k=S.length>1;return Pt("div",{children:[Pt("div",{className:"af-mb-6",children:[Pt(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[we(yg,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),Pt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[we("h3",{className:"af-text-xl af-font-semibold af-break-words",children:m.name}),we(ee,{variant:m.active?"success":"secondary",children:m.active?"Active":"Draft"}),we(Ki,{product:m})]}),we(Gi,{product:m,className:"af-mt-1"}),!m.active&&we("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),Pt("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[Pt("div",{className:"af-space-y-2",children:[we(gd,{src:d,className:"af-h-48 af-w-full af-rounded-md af-border"}),v.length>1&&we("div",{className:"af-flex af-flex-wrap af-gap-2",children:v.map((h,N)=>we("button",{type:"button",onClick:()=>g(N),"aria-label":`Show photo ${N+1} of ${v.length}`,"aria-pressed":N===b,className:W("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",N===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:we(gd,{src:h,className:"af-h-12 af-w-12 af-rounded-md"})},`${h}-${N}`))})]}),Pt("div",{className:"af-space-y-6",children:[m.description&&we(Br,{title:"Description",children:we("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:m.description})}),i?Pt(Br,{title:"Variants",children:[we("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(h=>Pt("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[we(G,{className:"af-h-4 af-w-28"}),we(G,{className:"af-h-4 af-w-20"}),we(G,{className:"af-h-4 af-w-16"})]},h))}),we("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):u?we(xt,{message:"Couldn't load this product's variants.",onRetry:()=>f(h=>h+1)}):k?we(Br,{title:`Variants \xB7 ${S.length}`,children:we("div",{className:"af-overflow-x-auto",children:Pt(ct,{children:[we(dt,{children:Pt(Ie,{children:[we(Z,{children:"Variant"}),we(Z,{children:"SKU"}),we(Z,{className:"af-text-right",children:"Price"}),we(Z,{children:"Stock"})]})}),we(ut,{children:S.map(h=>Pt(Ie,{children:[Pt(Y,{className:"af-font-medium",children:[h.title||h.option_values.map(N=>N.value).join(" / ")||"\u2014",!h.active&&we(ee,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),we(Y,{className:"af-text-muted-foreground",children:h.sku?we("code",{className:"af-font-mono af-text-xs af-break-all",children:h.sku}):"\u2014"}),Pt(Y,{className:"af-whitespace-nowrap af-text-right",children:[we("div",{className:Wi,children:md(h)}),h.compare_at_amount!==null&&h.unit_amount!==null&&h.compare_at_amount>h.unit_amount&&we("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:Q(h.compare_at_amount,h.currency)})]}),we(Y,{className:"af-text-sm",children:we(pd,{variant:h})})]},h.id))})]})})}):null,we(Br,{title:"Details",children:Pt("dl",{className:"af-space-y-2",children:[Pt("div",{children:[we("dt",{className:xs,children:"Delivery"}),we("dd",{className:"af-text-sm",children:p==="Digital download"?m.fulfillment.filename??"Digital download":p??"Nothing to deliver"})]}),m.fulfillment.type==="redirect"&&m.fulfillment.url&&Pt("div",{children:[we("dt",{className:xs,children:"Sends buyers to"}),we("dd",{className:"af-break-all af-text-sm",children:m.fulfillment.url})]}),Pt("div",{children:[we("dt",{className:xs,children:"Shipping address"}),we("dd",{className:"af-text-sm",children:m.collect_shipping_address?"Collected at checkout":"Not collected"})]}),Pt("div",{children:[we("dt",{className:xs,children:"Most one buyer can order"}),we("dd",{className:"af-text-sm af-tabular-nums",children:m.max_quantity})]})]})}),x&&we(Br,{title:"Last 30 days",children:Pt("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[Pt("div",{children:[we("dt",{className:xs,children:"Units sold"}),we("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),Pt("div",{children:[we("dt",{className:xs,children:"Orders"}),we("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),Pt("div",{children:[we("dt",{className:xs,children:"Gross"}),we("dd",{className:Wi,children:x.gross.length>0?Yi(x.gross):"\u2014"})]})]})}),we("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}import{Fragment as ws,jsx as ve,jsxs as Ct}from"react/jsx-runtime";var Rg={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},_g=["all","active","draft","low_stock","out_of_stock"];function bd(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function hd(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function kg(e){return e.inventory?.out_of_stock??!1}function Pg(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return hd(e);case"out_of_stock":return kg(e);default:return!0}}function Cg({product:e,showStats:t,onOpen:a}){let s=e.images[0],n=t?e.stats:void 0,r=Zi(e),i=e.variant_count??0;return Ct("button",{type:"button",onClick:a,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?ve("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):ve("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:ve(wg,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Ct("div",{className:"af-space-y-2 af-p-3",children:[Ct("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ct("div",{className:"af-min-w-0",children:[ve("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),ve(Gi,{product:e,className:"af-mt-0.5"})]}),!e.active&&ve(ee,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Ct("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ve(Ki,{product:e}),i>1&&Ct(ee,{variant:"outline",children:[i," variants"]}),r&&ve(ee,{variant:"outline",children:r})]}),n&&Ct("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Yi(n.gross)}`:""," ",ve("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Tg(){return ve("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=>Ct("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[ve("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),Ct("div",{className:"af-space-y-2 af-p-3",children:[ve(G,{className:"af-w-32"}),ve(G,{className:"af-w-16"}),ve(G,{className:"af-h-5 af-w-24"})]})]},e))})}function yd({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:n,isLoading:r,error:i,refetch:l}=or({includeStats:t,refreshKey:e}),[u,c]=xn.useState(!1),[o,f]=xn.useState(null),[b,g]=xn.useState("all"),{api:m}=H(),v=xn.useCallback(()=>m.exportProductsCsv(),[m]),[d,p]=xn.useState(""),[x,S]=xn.useState("newest"),k=xn.useMemo(()=>{if(!t)return null;let j=null;for(let U of n)!U.stats||U.stats.units_sold===0||(!j||U.stats.units_sold>(j.stats?.units_sold??0))&&(j=U);return j},[n,t]),h=xn.useMemo(()=>n.filter(hd).length,[n]),N=d.trim().toLowerCase(),R=xn.useMemo(()=>{let U=[...n.filter(te=>Pg(te,b)&&(!N||te.name.toLowerCase().includes(N)))];return x==="name"?U.sort((te,ce)=>te.name.localeCompare(ce.name)):x==="best_selling"?U.sort((te,ce)=>(ce.stats?.units_sold??0)-(te.stats?.units_sold??0)):U.sort((te,ce)=>bd(ce.created_at)-bd(te.created_at)),U},[n,b,N,x]),C=b!=="all"||!!N,w=()=>{g("all"),p("")},P=r||i!==null&&n.length===0,I=ve("div",{className:"af-mb-6",children:ve("div",{className:W("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:P?Ct(ws,{children:[ve(pt,{label:"Products",children:ve(G,{className:"af-h-6 af-w-10"})}),t?Ct(ws,{children:[ve(pt,{label:"Best seller",children:ve(G,{className:"af-h-6 af-w-28"})}),ve(pt,{label:"Low stock",children:ve(G,{className:"af-h-6 af-w-10"})})]}):ve(pt,{label:"Active",children:ve(G,{className:"af-h-6 af-w-10"})})]}):Ct(ws,{children:[ve(pt,{label:"Products",children:n.length}),t?Ct(ws,{children:[ve(pt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:k?`${k.stats?.units_sold??0} sold, last 30 days`:void 0,children:k?ve("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:k.name}):ve("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),ve(pt,{label:"Low stock",children:h})]}):ve(pt,{label:"Active",children:n.filter(j=>j.active).length})]})})}),_=Ct("div",{className:"af-mb-4 af-space-y-3",children:[Ct("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ve("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:_g.map(j=>ve("button",{type:"button","aria-pressed":b===j,onClick:()=>g(j),className:W("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:Rg[j]},j))}),Ct("div",{className:"af-relative af-w-full af-max-w-xs",children:[ve(Ng,{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"}),ve(ae,{type:"text",value:d,onChange:j=>p(j.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Ct(fn,{value:x,onValueChange:j=>S(j),children:[ve(Qa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:ve(mn,{})}),Ct(en,{children:[ve(St,{value:"newest",children:"Newest"}),ve(St,{value:"name",children:"Name A\u2013Z"}),t&&ve(St,{value:"best_selling",children:"Best selling"})]})]}),C&&ve(y,{type:"button",variant:"ghost",size:"sm",onClick:w,children:"Clear filters"}),ve(wa,{fetchCsv:v,filename:"products",label:C?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&n.length===0?ve(G,{className:"af-h-4 af-w-28"}):ve("p",{className:"af-text-sm af-text-muted-foreground",children:C?`${R.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),q;return o?q=ve(vd,{product:o,showStats:t,onBack:()=>{f(null),l()}},o.id):r&&n.length===0?q=Ct(ws,{children:[_,ve(Tg,{}),ve("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):i&&n.length===0?q=ve("div",{className:"af-flex af-justify-center af-py-8",children:ve(xt,{message:"Couldn't load your products.",onRetry:()=>l()})}):n.length===0?q=Ct(ca,{icon:ve(Sg,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",ve("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):q=Ct(ws,{children:[_,i&&ve("div",{className:"af-mb-4",children:ve(xt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>l()})}),R.length===0?Ct(ca,{children:["No products match these filters.",ve("br",{}),ve(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:w,children:"Show all products"})]}):ve("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:R.map(j=>ve(Cg,{product:j,showStats:t,onOpen:()=>f(j)},j.id))})]}),ve(Ut,{title:"Products",onBackToWebsite:a,hideBackButton:!!o,className:s,children:u?Ct(ws,{children:[ve(y,{variant:"ghost",onClick:()=>c(!1),children:"Back to products"}),ve(Qs,{})]}):Ct(ws,{children:[!o&&ve("div",{className:"af-mb-4 af-flex af-justify-end",children:ve(y,{variant:"outline",onClick:()=>c(!0),children:"Promo codes"})}),!o&&I,q]})})}import*as ja from"react";import{ArrowLeft as _d,Check as Eg,ChevronLeft as xd,ChevronRight as wd,ClipboardCopy as Ig,Mail as cl,Search as Ag,Users as Dg}from"lucide-react";import*as za from"react";function Ji({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=za.useState([]),[r,i]=za.useState(!0),[l,u]=za.useState(null),[c,o]=za.useState(0),[f]=za.useState(e),[b,g]=za.useState(""),[m,v]=za.useState(void 0),d=za.useRef(0),p=za.useCallback(async({afterRemoval:x=!1}={})=>{let S=++d.current;try{i(!0),u(null);let k={limit:f,offset:c*f};b.trim()&&(k.q=b.trim()),m&&(k.source=m);let h=await a.getPeople(k);if(S!==d.current)return;if(x&&h.people.length===0&&c>0){o(c-1);return}n(h.people)}catch(k){if(S!==d.current)return;u(k instanceof Error?k:new Error("Failed to fetch people"))}finally{S===d.current&&i(!1)}},[a,c,f,b,m,t]);return za.useEffect(()=>{p()},[p]),{people:s,isLoading:r,error:l,page:c,pageSize:f,hasNextPage:s.length===f,hasPreviousPage:c>0,setPage:o,q:b,setQ:x=>{g(x),o(0)},source:m,setSource:x=>{v(x),o(0)},refetch:()=>p(),refetchAfterRemoval:()=>p({afterRemoval:!0})}}import*as Wn from"react";function Xi(e,{refreshKey:t}={}){let{api:a}=H(),[s,n]=Wn.useState(null),[r,i]=Wn.useState(e!==null),[l,u]=Wn.useState(null),c=Wn.useRef(0),o=Wn.useCallback(async()=>{if(e===null){n(null),i(!1),u(null);return}let f=++c.current;try{i(!0),u(null);let b=await a.getPerson(e);if(f!==c.current)return;n(b)}catch(b){if(f!==c.current)return;u(b instanceof Error?b:new Error("Failed to fetch person"))}finally{f===c.current&&i(!1)}},[a,e,t]);return Wn.useEffect(()=>{o()},[o]),{person:s,isLoading:r,error:l,refetch:o}}import{jsx as D,jsxs as xe}from"react/jsx-runtime";var ll="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Og="af-text-xs af-text-muted-foreground";function ur(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 dl(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function Lg(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Bg({value:e,label:t}){let[a,s]=ja.useState(!1);return Lg()?xe(y,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[a?D(Eg,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):D(Ig,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function Sd(e){return xe("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&xe(ee,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&D(ee,{variant:"secondary",children:"Contact form"})]})}function Nd(e){return e.name?e.name:e.email?e.email:D("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Fg=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Mg=40;function $g(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),s=t.find(([n,r])=>Fg.test(n)&&typeof r=="string"&&r.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=Mg).sort((n,r)=>String(r[1]).trim().length-String(n[1]).trim().length)[0];return s?{message:String(s[1]),rest:t.filter(([n])=>n!==s[0])}:{message:null,rest:t}}function Ug(e){return e.replace(/_/g," ")}function Vg(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Hg({data:e}){let{message:t,rest:a}=$g(e);return t===null&&a.length===0?D("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):xe("div",{className:"af-space-y-3",children:[t!==null&&D("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),a.length>0&&D("dl",{className:"af-space-y-1",children:a.map(([s,n])=>xe("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[D("dt",{className:W(Og,"af-w-28 af-shrink-0 af-capitalize"),children:Ug(s)}),D("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Vg(n)})]},s))})]})}function kd({formName:e,createdAt:t,data:a,onDelete:s}){return xe("div",{className:"af-rounded-md af-border af-p-3",children:[xe("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[D(ee,{variant:"outline",children:"Form submission (unverified)"}),e&&D("span",{className:"af-text-xs af-text-muted-foreground",children:e}),D("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:ur(t)}),D(Xs,{iconOnly:!0,onDelete:s})]}),D(Hg,{data:a})]})}function zg(e){return e.charged_total??e.amount_total}function jg({email:e,refreshKey:t,onBack:a,onRemoved:s}){let{api:n}=H(),{person:r,isLoading:i,error:l,refetch:u}=Xi(e,{refreshKey:t}),c=async f=>{await n.deleteSubmission(f),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?u():a()},o=dl(e,r?.submissions[0]?.form_name);return xe("div",{children:[xe("div",{className:"af-mb-6",children:[xe(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[D(_d,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),xe("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[xe("div",{className:"af-min-w-0",children:[i?D(G,{className:"af-h-7 af-w-48"}):D("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),xe("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[D("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),D(Bg,{value:e,label:"Copy email address"})]})]}),D(y,{asChild:!0,children:xe("a",{href:o,children:[D(cl,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),i?xe("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(f=>xe("div",{className:"af-rounded-md af-border af-p-3",children:[D(G,{className:"af-w-40"}),D(G,{className:"af-mt-2 af-w-64"})]},f)),D("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):l||!r?D("div",{className:"af-flex af-justify-center af-py-8",children:D(xt,{message:"Couldn't load this person.",onRetry:()=>u()})}):xe("div",{className:"af-space-y-6",children:[r.customer&&xe("div",{children:[D("h4",{className:W(ll,"af-mb-3"),children:"Customer"}),xe("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&xe("div",{className:"af-flex af-gap-2",children:[D("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),D("dd",{children:r.customer.name})]}),r.customer.phone&&xe("div",{className:"af-flex af-gap-2",children:[D("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),D("dd",{children:r.customer.phone})]}),xe("div",{className:"af-flex af-gap-2",children:[D("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),D("dd",{children:ur(r.customer.created_at)})]})]})]}),r.orders.length>0&&xe("div",{children:[D("h4",{className:W(ll,"af-mb-3"),children:"Purchases"}),D("div",{className:"af-overflow-x-auto",children:xe(ct,{children:[D(dt,{children:xe(Ie,{children:[D(Z,{children:"Order"}),D(Z,{children:"Date"}),D(Z,{className:"af-text-right",children:"Total"}),D(Z,{children:"Status"})]})}),D(ut,{children:r.orders.map(f=>xe(Ie,{children:[D(Y,{className:"af-whitespace-nowrap af-font-medium",children:os(f)}),D(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ur(f.created_at)}),D(Y,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:Q(zg(f),f.currency)}),D(Y,{children:D(Ds,{status:f.status})})]},f.id))})]})}),D("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&&xe("div",{children:[D("h4",{className:W(ll,"af-mb-3"),children:"Messages"}),D("div",{className:"af-space-y-3",children:r.submissions.map(f=>D(kd,{formName:f.form_name,createdAt:f.created_at,data:f.data,onDelete:()=>c(f.id)},f.id))})]})]})]})}function qg({submissionId:e,onBack:t,onRemoved:a}){let{api:s}=H(),[n,r]=ja.useState(null),[i,l]=ja.useState(!0),[u,c]=ja.useState(null),[o,f]=ja.useState(0);return ja.useEffect(()=>{let b=!1;return l(!0),c(null),s.getSubmission(e).then(g=>{b||r(g)}).catch(g=>{b||c(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{b||l(!1)}),()=>{b=!0}},[s,e,o]),xe("div",{children:[xe("div",{className:"af-mb-6",children:[xe(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[D(_d,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),D("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?D(G,{className:"af-mt-1 af-h-4 af-w-32"}):n&&D("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:ur(n.metadata.submitted_at)})]}),i?xe("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[D(G,{className:"af-w-40"}),D(G,{className:"af-mt-2 af-w-64"}),D(G,{className:"af-mt-2 af-w-52"}),D("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):u||!n?D("div",{className:"af-flex af-justify-center af-py-8",children:D(xt,{message:"Couldn't load this submission.",onRetry:()=>f(b=>b+1)})}):xe("div",{className:"af-space-y-3",children:[D(kd,{formName:null,createdAt:n.metadata.submitted_at,data:n.data,onDelete:async()=>{await s.deleteSubmission(e),a(),t()}}),D("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 Wg={all:"All",customers:"Customers",leads:"Leads"},Gg=["all","customers","leads"],Rd={all:void 0,customers:"customer",leads:"lead"};function Kg({refreshKey:e,onBackToWebsite:t,className:a,maxRows:s,onViewAll:n}){let r=typeof s=="number",{people:i,isLoading:l,error:u,page:c,pageSize:o,hasNextPage:f,hasPreviousPage:b,setPage:g,q:m,setQ:v,source:d,setSource:p,refetch:x,refetchAfterRemoval:S}=Ji({refreshKey:e}),[k,h]=ja.useState({kind:"list"}),[N,R]=ja.useState(""),C=d==="customer"?"customers":d==="lead"?"leads":"all",w=V=>{Rd[V]!==d&&p(Rd[V])},{api:P}=H(),I=ja.useCallback(()=>P.exportPeopleCsv({...m?{q:m}:{},...d?{source:d}:{}}),[P,m,d]),_=!r||!!n,q=V=>{if(r){n?.();return}V.email?h({kind:"person",email:V.email}):V.submission_id&&h({kind:"submission",submissionId:V.submission_id})},j=ja.useRef(!1),U=()=>{j.current=!0},te=()=>{h({kind:"list"}),j.current?(j.current=!1,S()):x()},ce=V=>{let A=V.trim();A!==m&&v(A)},me=r?i.slice(0,s):i,T;if(k.kind==="person")T=D(jg,{email:k.email,refreshKey:e,onBack:te,onRemoved:U});else if(k.kind==="submission")T=D(qg,{submissionId:k.submissionId,onBack:te,onRemoved:U});else{let V=xe("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[D("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:Gg.map(A=>D("button",{type:"button","aria-pressed":C===A,onClick:()=>w(A),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",C===A?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Wg[A]},A))}),xe("div",{className:"af-relative af-w-full af-max-w-xs",children:[D(Ag,{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"}),D(ae,{type:"text",value:N,onChange:A=>R(A.target.value),onBlur:()=>ce(N),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),ce(N))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),m&&D(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{R(""),v("")},children:"Clear search"}),D(wa,{fetchCsv:I,filename:"people",className:"af-ml-auto"})]});if(l)T=xe("div",{children:[r?null:V,D("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(A=>xe("div",{className:"af-rounded-md af-border af-p-3",children:[xe("div",{className:"af-flex af-items-center af-justify-between",children:[D(G,{className:"af-h-4 af-w-32"}),D(G,{className:"af-h-4 af-w-16"})]}),D(G,{className:"af-mt-2 af-h-5 af-w-28"}),D(G,{className:"af-mt-2 af-h-3 af-w-56"})]},A))}),D("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:xe(ct,{children:[D(dt,{children:xe(Ie,{children:[D(Z,{children:"Person"}),D(Z,{children:"Came from"}),D(Z,{children:"Latest message"}),D(Z,{children:"Last activity"}),D(Z,{className:"af-w-8"}),D(Z,{className:"af-w-8"})]})}),D(ut,{"aria-hidden":"true",children:[0,1,2,3,4].map(A=>xe(Ie,{children:[D(Y,{children:D(G,{className:"af-h-4 af-w-40"})}),D(Y,{children:D(G,{className:"af-h-5 af-w-24"})}),D(Y,{children:D(G,{className:"af-h-4 af-w-56"})}),D(Y,{children:D(G,{className:"af-h-4 af-w-24"})}),D(Y,{}),D(Y,{})]},A))})]})}),D("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(u)T=xe("div",{children:[r?null:V,D("div",{className:"af-flex af-justify-center af-py-8",children:D(xt,{message:"Couldn't load your leads.",onRetry:()=>x()})})]});else if(me.length===0&&c===0){let A=!!m||C!=="all";T=xe("div",{children:[A&&V,A?D(ca,{children:m?"Nobody matches that search.":C==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):D(tr,{icon:Dg,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(i.length===0)T=xe("div",{children:[r?null:V,D(ca,{children:"No more results."}),D("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:xe(y,{variant:"outline",size:"sm",onClick:()=>g(c-1),children:[D(xd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let A=c*o+1,ne=c*o+i.length;T=xe("div",{children:[r?null:V,D("div",{className:"af-space-y-3 lg:af-hidden",children:me.map((re,Me)=>xe("div",{onClick:_?()=>q(re):void 0,className:`af-rounded-md af-border af-p-3${_?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[xe("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[xe("div",{className:"af-min-w-0",children:[D("button",{type:"button",onClick:Se=>{Se.stopPropagation(),q(re)},disabled:!_,"aria-label":`Open ${re.name||re.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:Nd(re)}),re.name&&re.email&&D("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:re.email})]}),xe("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[D("span",{className:"af-text-xs af-text-muted-foreground",children:ur(re.last_activity_at)}),re.email&&D(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:D("a",{href:dl(re.email),onClick:Se=>Se.stopPropagation(),"aria-label":`Email ${re.email}`,children:D(cl,{className:"af-h-4 af-w-4"})})})]})]}),D("div",{className:"af-mt-2",children:Sd(re)}),re.latest_message_excerpt&&D("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:re.latest_message_excerpt})]},re.email??re.submission_id??Me))}),D("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:xe(ct,{children:[D(dt,{children:xe(Ie,{children:[D(Z,{children:"Person"}),D(Z,{children:"Came from"}),D(Z,{children:"Latest message"}),D(Z,{children:"Last activity"}),D(Z,{className:"af-w-8",children:D("span",{className:"af-sr-only",children:"Reply"})}),D(Z,{className:"af-w-8"})]})}),D(ut,{children:me.map((re,Me)=>xe(Ie,{onClick:_?()=>q(re):void 0,className:_?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[xe(Y,{className:"af-max-w-[260px] af-font-medium",children:[D("button",{type:"button",onClick:Se=>{Se.stopPropagation(),q(re)},disabled:!_,"aria-label":`Open ${re.name||re.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:Nd(re)}),re.name&&re.email&&D("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:re.email})]}),D(Y,{children:Sd(re)}),D(Y,{className:"af-max-w-[320px]",children:re.latest_message_excerpt?D("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:re.latest_message_excerpt}):D("span",{className:"af-text-muted-foreground",children:"\u2014"})}),D(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ur(re.last_activity_at)}),D(Y,{className:"af-w-8",children:re.email&&D(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:D("a",{href:dl(re.email),onClick:Se=>Se.stopPropagation(),"aria-label":`Email ${re.email}`,children:D(cl,{className:"af-h-4 af-w-4"})})})}),D(Y,{className:"af-w-8 af-text-right",children:D(wd,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},re.email??re.submission_id??Me))})]})}),!r&&xe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[D("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${A}-${ne}`}),xe("div",{className:"af-flex af-items-center af-gap-2",children:[xe(y,{variant:"outline",size:"sm",onClick:()=>g(c-1),disabled:!b,children:[D(xd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),xe(y,{variant:"outline",size:"sm",onClick:()=>g(c+1),disabled:!f,children:["Next",D(wd,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?D("div",{className:a,children:T}):D(Ut,{title:"Leads",onBackToWebsite:t,hideBackButton:k.kind!=="list",className:a,children:T})}function Qi(e){return D(Kg,{...e},e.maxRows==null?"full":"compact")}import*as Ad from"react";import{ChevronLeft as Pd,ChevronRight as Zg,Repeat as Yg}from"lucide-react";import*as qa from"react";function eo({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=qa.useState([]),[r,i]=qa.useState(0),[l,u]=qa.useState(!0),[c,o]=qa.useState(null),[f,b]=qa.useState(0),[g,m]=qa.useState(e),[v,d]=qa.useState(void 0),p=qa.useRef(0),x=qa.useCallback(async()=>{let k=++p.current;try{u(!0),o(null);let h={limit:g,offset:f*g};v&&(h.status=v);let N=await a.getSubscriptions(h);if(k!==p.current)return;n(N.subscriptions),i(N.total)}catch(h){if(k!==p.current)return;o(h instanceof Error?h:new Error("Failed to fetch subscriptions"))}finally{k===p.current&&u(!1)}},[a,f,g,v,t]);qa.useEffect(()=>{x()},[x]);let S=Math.ceil(r/g);return{subscriptions:s,total:r,isLoading:l,error:c,page:f,pageSize:g,hasNextPage:f<S-1,hasPreviousPage:f>0,setPage:b,setPageSize:k=>{m(k),b(0)},status:v,setStatus:k=>{d(k),b(0)},refetch:x}}import{jsx as de,jsxs as Tt}from"react/jsx-runtime";function Cd(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 Td({sub:e}){return e.status==="canceled"?de(ee,{variant:"outline",children:"Canceled"}):e.status==="past_due"?de(ee,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?de(ee,{variant:"warning",children:"Scheduled to cancel"}):de(ee,{variant:"success",children:"Active"}):de(ee,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Jg(e,t){let a=Q(t,e.currency);return e.plan_interval_count===1?`${a} / ${e.plan_interval}`:`${a} every ${e.plan_interval_count} ${e.plan_interval}s`}function Ed({sub:e}){let t=e.current_amount!==e.plan_amount;return Tt("div",{children:[de("div",{className:"af-font-medium af-tabular-nums",children:Jg(e,e.current_amount)}),t&&Tt("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",Q(e.plan_amount,e.currency)]})]})}function Id(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Cd(e.current_period_end)}`:"Ends at period end":e.current_period_end?Cd(e.current_period_end):"\u2014"}function Dd({refreshKey:e,onBackToWebsite:t,className:a}){let{subscriptions:s,total:n,isLoading:r,error:i,page:l,pageSize:u,hasNextPage:c,hasPreviousPage:o,setPage:f,status:b,refetch:g}=eo({refreshKey:e}),{api:m}=H(),v=Ad.useCallback(()=>m.exportSubscriptionsCsv(b?{status:b}:{}),[m,b]),d;if(r)d=Tt("div",{children:[de("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(p=>Tt("div",{className:"af-rounded-md af-border af-p-3",children:[Tt("div",{className:"af-flex af-items-center af-justify-between",children:[de(G,{className:"af-h-4 af-w-40"}),de(G,{className:"af-h-4 af-w-20"})]}),de(G,{className:"af-mt-2 af-h-3 af-w-32"}),de(G,{className:"af-mt-2 af-h-5 af-w-24"})]},p))}),de("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Tt(ct,{children:[de(dt,{children:Tt(Ie,{children:[de(Z,{children:"Subscriber"}),de(Z,{children:"Plan"}),de(Z,{className:"af-text-right",children:"Amount"}),de(Z,{children:"Renews"}),de(Z,{children:"Status"})]})}),de(ut,{"aria-hidden":"true",children:[0,1,2,3,4].map(p=>Tt(Ie,{children:[de(Y,{children:de(G,{className:"af-h-4 af-w-44"})}),de(Y,{children:de(G,{className:"af-h-4 af-w-32"})}),de(Y,{className:"af-text-right",children:de(G,{className:"af-ml-auto af-h-4 af-w-24"})}),de(Y,{children:de(G,{className:"af-h-4 af-w-24"})}),de(Y,{children:de(G,{className:"af-h-5 af-w-20"})})]},p))})]})}),de("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(i)d=de("div",{className:"af-flex af-justify-center af-py-8",children:de(xt,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(s.length===0&&l===0)d=de(ca,{icon:de(Yg,{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)d=Tt("div",{children:[de(ca,{children:"No more results."}),de("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Tt(y,{variant:"outline",size:"sm",onClick:()=>f(l-1),children:[de(Pd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let p=l*u+1,x=l*u+s.length;d=Tt("div",{children:[de("div",{className:"af-mb-3 af-flex af-justify-end",children:de(wa,{fetchCsv:v,filename:"subscriptions"})}),de("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(S=>Tt("div",{className:"af-rounded-md af-border af-p-3",children:[Tt("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Tt("div",{className:"af-min-w-0",children:[de("div",{className:"af-truncate af-text-sm af-font-medium",children:S.customer_email||de("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),de("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:S.plan_title||"Untitled plan"})]}),de("div",{className:"af-shrink-0 af-text-right",children:de(Ed,{sub:S})})]}),Tt("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[de(Td,{sub:S}),S.is_test&&de(ee,{variant:"outline",children:"Test"}),de("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Id(S)})]}),de($n,{deliveries:S.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},S.id))}),de("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Tt(ct,{children:[de(dt,{children:Tt(Ie,{children:[de(Z,{children:"Subscriber"}),de(Z,{children:"Plan"}),de(Z,{className:"af-text-right",children:"Amount"}),de(Z,{children:"Renews"}),de(Z,{children:"Status"})]})}),de(ut,{children:s.map(S=>Tt(Ie,{children:[de(Y,{className:"af-max-w-[240px]",children:de("div",{className:"af-truncate af-font-medium",children:S.customer_email||de("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),de(Y,{className:"af-max-w-[220px]",children:de("div",{className:"af-truncate",children:S.plan_title||de("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),de(Y,{className:"af-whitespace-nowrap af-text-right",children:de(Ed,{sub:S})}),de(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Id(S)}),Tt(Y,{children:[Tt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[de(Td,{sub:S}),S.is_test&&de(ee,{variant:"outline",children:"Test"})]}),de($n,{deliveries:S.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},S.id))})]})}),Tt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[de("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${p}-${x} of ${n}`}),Tt("div",{className:"af-flex af-items-center af-gap-2",children:[Tt(y,{variant:"outline",size:"sm",onClick:()=>f(l-1),disabled:!o,children:[de(Pd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Tt(y,{variant:"outline",size:"sm",onClick:()=>f(l+1),disabled:!c,children:["Next",de(Zg,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return de(Ut,{title:"Subscriptions",onBackToWebsite:t,className:a,children:d})}import*as Zn from"react";import{Loader2 as ov}from"lucide-react";import*as Na from"react";import*as to from"react";var Bs=typeof window>"u"?to.useEffect:to.useLayoutEffect;var ao=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},Xg=(e,t)=>e instanceof Error?e:new Error(t);function Qg(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 Od(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function Ss({siteId:e,refreshKey:t,onSaveInvoiceSettings:a}){let{api:s}=H(),[n,r]=Na.useState(null),[i,l]=Na.useState(!0),[u,c]=Na.useState(null),o=Na.useRef(null),[f,b]=Na.useState(()=>Od(s,e)),g=f.api!==s||f.siteId!==e,m=f;g&&(m=Od(s,e),b(m),r(null),l(!0),c(null));let v=Na.useRef(m);Bs(()=>{v.current!==m&&(v.current=m,o.current=null)},[m]);let d=(w,P)=>v.current===w&&P>w.applied,p=(w,P,I)=>d(w,P)?(w.applied=P,o.current=I,r(I),l(!1),!0):!1,x=async w=>{for(;w.writing;)await w.idle;let P=++w.seq;try{let I=await w.api.getSite(w.siteId);return p(w,P,I)&&c(null),{seq:P,error:null}}catch(I){return{seq:P,error:Xg(I,"Failed to load store settings")}}},S=(w,P)=>{let I=async()=>{if(v.current!==w)throw new Error("Not saved: the store switched to another site first.");w.writing=!0,w.idle=new Promise(q=>{w.markIdle=q});try{return await P(++w.seq)}finally{w.writing=!1,w.markIdle()}},_=w.queue.then(I,I);return w.queue=_.catch(()=>{}),_},k=Na.useCallback(async()=>{let w=await x(m);w.error&&d(m,w.seq)&&(c(w.error),l(!1))},[m]);Na.useEffect(()=>{k()},[k,t]);let h=Na.useCallback(w=>S(m,async P=>{let I=await m.api.updateSite(m.siteId,w),{currency_restatement:_,...q}=I;return p(m,P,q)&&c(j=>j instanceof ao?j:null),I}),[m]),N=Na.useRef(a);Bs(()=>{N.current=a});let R=Na.useCallback(async(w,P)=>{await S(m,()=>w());let I=await x(m);return I.error&&d(m,I.seq)&&o.current&&(p(m,I.seq,{...o.current,...P}),c(new ao(`Saved, but couldn't refresh settings: ${I.error.message}`))),v.current===m?o.current:null},[m]),C=Na.useCallback(w=>{let P=N.current;return R(()=>P(w),Qg(w))},[R]);return{site:g?null:n,isLoading:g||i,error:g?null:u,refetch:k,updateSite:h,saveInvoiceSettings:a?C:null}}import*as ra from"react";import{Loader2 as Ld}from"lucide-react";import{jsx as wn,jsxs as Gn}from"react/jsx-runtime";function no(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var Dn="af-grid af-gap-1 af-text-sm",Bd="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",Fd="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 Wa({children:e}){return wn("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Fr({children:e}){return wn("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var Kn=ra.forwardRef(function({id:t,title:a,description:s,children:n},r){let i=`af-store-${t}-title`;return Gn("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":i,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[Gn("div",{className:"af-space-y-1",children:[wn("h3",{id:i,className:"af-text-sm af-font-semibold",children:a}),s&&wn(Wa,{children:s})]}),n]})});function so({label:e,description:t,checked:a,onSave:s,disabled:n=!1,disabledReason:r}){let[i,l]=ra.useState(null),[u,c]=ra.useState(null),o=i??a,f=async b=>{l(b),c(null);try{await s(b)}catch(g){c(no(g))}finally{l(null)}};return Gn("div",{className:"af-space-y-1",children:[Gn("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[wn("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":o,checked:o,disabled:n||i!==null,onChange:b=>void f(b.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),Gn("span",{className:"af-space-y-0.5",children:[Gn("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,i!==null&&wn(Ld,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&wn(Wa,{children:t})]})]}),(n&&r||u)&&Gn("div",{className:"af-space-y-1 af-pl-6",children:[n&&r&&wn(Wa,{children:r}),u&&wn(Fr,{children:u})]})]})}var fl=(e,t)=>JSON.stringify(e)===JSON.stringify(t),ul=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ev(e,t,a,s=[]){if(!ul(e)||!ul(t)||!ul(a))return{draft:fl(e,t)?a:e,dropped:[]};let n=[],r={...a};for(let i of Object.keys(a))fl(e[i],t[i])||(s.includes(i)?n.push(i):r[i]=e[i]);return{draft:r,dropped:n}}function fr(e,t){let a=JSON.stringify(e),[s,n]=ra.useState(e),[r,i]=ra.useState([]),l=ra.useRef(e),u=ra.useRef(e),c=ra.useRef(s);Bs(()=>{u.current=e,c.current=s});let o=ra.useRef(t?.when);ra.useEffect(()=>{let b=Object.is(o.current,t?.when)?[]:t?.fields??[];if(o.current=t?.when,fl(l.current,u.current)&&b.length===0)return;let g=ev(c.current,l.current,u.current,b);l.current=u.current,n(g.draft),g.dropped.length&&i(g.dropped)},[a,t?.when]);let f=ra.useCallback(b=>{n(b??u.current),i([])},[]);return{draft:s,setDraft:n,dirty:JSON.stringify(s)!==a,reset:f,dropped:r}}function mr({dirty:e,saving:t,error:a,onSave:s,onDiscard:n}){return e?Gn("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[Gn(y,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&wn(Ld,{className:"af-animate-spin"}),"Save"]}),wn(y,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:n,children:"Discard"}),a&&wn("p",{role:"alert",className:W("af-text-sm af-text-destructive"),children:a})]}):null}function pr(){let[e,t]=ra.useState(!1),[a,s]=ra.useState(null),n=ra.useCallback(async r=>{t(!0),s(null);try{await r()}catch(i){s(no(i))}finally{t(!1)}},[]);return{saving:e,error:a,setError:s,run:n}}function Md({what:e}){return Gn(Wa,{children:["Only the site owner can change ",e,"."]})}import*as Sn from"react";import{ExternalLink as tv,Plus as av,X as Hd}from"lucide-react";import{Fragment as iv,jsx as Ne,jsxs as De}from"react/jsx-runtime";var pl=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function zd({site:e,updateSite:t}){return De("div",{className:"af-space-y-4",children:[Ne(so,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:a=>t({collect_phone_at_checkout:a})}),e.checkout_marketing_consent!==void 0&&Ne(so,{label:"Ask buyers for marketing consent at checkout",description:"Adds Stripe's consent checkbox to your checkout. Buyers who tick it join your email list, and buyers who leave without paying can get your abandoned-cart recovery emails.",checked:e.checkout_marketing_consent&&e.stripe_account_country==="US",disabled:e.stripe_account_country!=="US",disabledReason:e.stripe_account_country?'Only available for US stores: Stripe offers its consent checkbox to US businesses only. Your checkout shows an "Email me" box instead.':"Available once your Stripe account is connected and its country has synced.",onSave:a=>t({checkout_marketing_consent:a})})]})}function $d(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(Ot(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(Ot(e.free_shipping_over,e.currency))}}function jd({site:e,updateSite:t,refetch:a,providerSlot:s,currencyChanging:n=!1}){let{draft:r,setDraft:i,dirty:l,reset:u,dropped:c}=fr($d(e),{when:e.currency,fields:["rates","threshold"]}),{saving:o,error:f,setError:b,run:g}=pr(),m=e.currency.toUpperCase(),v=()=>g(async()=>{let p={},x=[...new Set(r.countries.split(/[\s,]+/).map(w=>w.trim().toUpperCase()).filter(Boolean))],S=x.find(w=>!/^[A-Z]{2}$/.test(w));if(S)throw new Error(`"${S}" isn't a two-letter country code (e.g. US, CA).`);let k=x.length?x:null;pl(k,e.shipping_countries)||(p.shipping_countries=k);let h=[];for(let w of r.rates){let P=w.label.trim(),I=va(w.amount,e.currency);if(!P)throw new Error("Every rate needs a name.");if(w.amount.trim()===""||I===null)throw new Error(`Enter a price for "${P}" (0 for free).`);h.push({label:P,amount:I})}let N=h.length?h:null;pl(N,e.shipping_rates)||(p.shipping_rates=N);let R=null;if(r.threshold.trim()!==""&&(R=va(r.threshold,e.currency),R===null||R===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(R!==e.free_shipping_over&&(p.free_shipping_over=R),Object.keys(p).length===0){u();return}("shipping_rates"in p||"free_shipping_over"in p)&&(p.expected_currency=e.currency);let C;try{C=await t(p)}catch(w){throw w instanceof aa&&w.details?.code==="currency_changed"&&await a?.(),w}u($d(C))}),d=(p,x)=>i({...r,rates:r.rates.map((S,k)=>k===p?{...S,...x}:S)});return De("fieldset",{disabled:o||n,className:"af-space-y-4",children:[De("label",{className:Dn,children:["Countries you ship to",Ne(ae,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:p=>i({...r,countries:p.target.value})}),Ne(Wa,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),De("div",{className:"af-space-y-2",children:[De("p",{className:"af-text-sm",children:["Flat shipping rates (",m,")"]}),r.rates.length===0&&Ne(Wa,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((p,x)=>De("div",{className:"af-flex af-items-center af-gap-2",children:[Ne(ae,{"aria-label":`Rate ${x+1} name`,value:p.label,placeholder:"Standard",onChange:S=>d(x,{label:S.target.value})}),Ne(ae,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:p.amount,placeholder:"0",className:"af-w-32",onChange:S=>d(x,{amount:S.target.value})}),Ne(y,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${x+1}`,onClick:()=>i({...r,rates:r.rates.filter((S,k)=>k!==x)}),children:Ne(Hd,{})})]},x)),De(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[Ne(av,{})," Add rate"]}),Ne(Wa,{children:"Buyers pick one at checkout. The first is preselected."})]}),De("label",{className:Dn,children:["Free shipping over (",m,")",Ne(ae,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:p=>i({...r,threshold:p.target.value})}),Ne(Wa,{children:"Orders at or above this get the cheapest rate free."})]}),c.length>0&&De("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",m,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),Ne(mr,{dirty:l,saving:o,error:f,onSave:()=>void v(),onDiscard:()=>{b(null),u()}}),s]})}var ml="exclusive",nv=[{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 sv({href:e,children:t}){return De("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,Ne(tv,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function qd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=fr(e.tax_behavior??ml),{saving:i,error:l,setError:u,run:c}=pr(),[o,f]=Sn.useState(!1),b=e.stripe_tax_enabled,g=b||o,m=()=>c(async()=>{let p=a;if(p===e.tax_behavior){r();return}let x={tax_behavior:p};p!=="inclusive"&&e.tax_rate_bps!=null&&(x.tax_rate_bps=null);let S=await t(x);r(S.tax_behavior??ml)}),v=()=>c(async()=>{let p={stripe_tax_enabled:!0,tax_behavior:a};a!=="inclusive"&&e.tax_rate_bps!=null&&(p.tax_rate_bps=null);let x=await t(p);r(x.tax_behavior??ml),f(!1)}),d=(n||o)&&a!=="inclusive"&&e.tax_rate_bps!=null;return De("div",{className:"af-space-y-5",children:[De("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[Ne("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."}),Ne("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."}),Ne("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:nv.map(p=>Ne("li",{children:Ne(sv,{href:p.href,children:p.label})},p.href))})]}),Ne(so,{label:"Stripe automatic tax",description:b?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:g,onSave:async p=>{if(o){f(!1),u(null),r();return}if(p&&!e.tax_behavior){f(!0);return}return t({stripe_tax_enabled:p})}}),g&&De("fieldset",{disabled:i,className:"af-space-y-4 af-pl-6",children:[De("label",{className:Dn,children:["Do your prices already include tax?",De("select",{"aria-label":"Your prices",className:Bd,value:a,onChange:p=>s(p.target.value),children:[Ne("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),Ne("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),Ne(Wa,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),d&&De(Wa,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),o?De("div",{className:"af-space-y-2",children:[De("div",{className:"af-flex af-gap-2",children:[Ne(y,{type:"button",size:"sm",disabled:i,onClick:()=>void v(),children:"Turn on"}),Ne(y,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>{f(!1),u(null),r()},children:"Cancel"})]}),l&&Ne(Fr,{children:l})]}):Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void m(),onDiscard:()=>{u(null),r()}})]})]})}function Ud(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function Wd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=fr(Ud(e)),{saving:i,error:l,setError:u,run:c}=pr(),o=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),f=()=>c(async()=>{let b={},g=null;if(o&&a.rate.trim()!==""){let p=Number(a.rate);if(!Number.isFinite(p)||p<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(p*100)}o&&g!==e.tax_rate_bps&&(b.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let m=a.taxId.trim()||null;m!==e.tax_id&&(b.tax_id=m);let v=a.label.trim()||null;if(v!==e.tax_label&&(b.tax_label=v),Object.keys(b).length===0){r();return}let d=await t(b);r(Ud(d))});return De("fieldset",{disabled:i,className:"af-space-y-4",children:[De("label",{className:Dn,children:["Tax rate (%)",Ne(ae,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!o,value:o?a.rate:"",onChange:b=>s({...a,rate:b.target.value})}),Ne(Wa,{children:o?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),De("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[De("label",{className:Dn,children:["Tax ID",Ne(ae,{"aria-label":"Tax ID",value:a.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...a,taxId:b.target.value})})]}),De("label",{className:Dn,children:["Tax label",Ne(ae,{"aria-label":"Tax label",value:a.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...a,label:b.target.value})})]})]}),Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void f(),onDiscard:()=>{u(null),r()}})]})}function Gd({site:e,updateSite:t,onChangeStart:a}){let[s,n]=Sn.useState(e.currency.toUpperCase()),[r,i]=Sn.useState(!1),[l,u]=Sn.useState(!1),[c,o]=Sn.useState(null),f=e.currency.toUpperCase(),b=Sn.useRef(f);Sn.useEffect(()=>{b.current!==f&&(n(p=>p===b.current?f:p),b.current=f)},[f]);let g=s.trim().toUpperCase(),m=g!==f,v=/^[A-Z]{3}$/.test(g),d=async()=>{u(!0);let p=a?.(),x=!1;o(null);try{let S=await t({currency:g.toLowerCase()});x=!0;let k=S.currency_restatement;k&&!k.applied?o(k.reason?`Not changed: ${k.reason}.`:"The currency was not changed."):(n(S.currency.toUpperCase()),b.current=S.currency.toUpperCase()),i(!1)}catch(S){o(no(S))}finally{u(!1),p?.(x)}};return De("div",{className:"af-space-y-3",children:[De("div",{className:"af-flex af-items-end af-gap-2",children:[De("label",{className:Dn,children:["Store currency",Ne(ae,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:l||r,onChange:p=>{n(p.target.value),o(null)}})]}),m&&!r&&De(iv,{children:[Ne(y,{type:"button",size:"sm",disabled:!v,onClick:()=>i(!0),children:"Change currency"}),Ne(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>{n(f),o(null)},children:"Discard"})]})]}),Ne(Wa,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&De("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[De("p",{className:"af-text-sm",children:["Change the store currency from ",f," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",Q(2e3,f)," becomes ",Q(2e3,g),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),De("div",{className:"af-flex af-gap-2",children:[Ne(y,{type:"button",size:"sm",disabled:l,onClick:()=>void d(),children:"Confirm change"}),Ne(y,{type:"button",size:"sm",variant:"ghost",disabled:l,onClick:()=>i(!1),children:"Cancel"})]})]}),c&&Ne(Fr,{children:c})]})}function Vd(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function rv(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 Kd({site:e,save:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=fr(Vd(e)),{saving:i,error:l,setError:u,run:c}=pr();if(!t)return De("div",{className:"af-space-y-2 af-text-sm",children:[De("p",{children:["Due ",e.invoice_due_days," days after sending"]}),De("p",{children:["Reminders: ",rv(e.invoice_reminder_schedule)]}),De("p",{children:["Footer: ",e.invoice_footer||"None"]}),Ne(Md,{what:"invoice defaults"})]});let o=()=>c(async()=>{let f={},b=Number(a.dueDays);if(a.dueDays.trim()===""||!Number.isInteger(b)||b<0||b>90)throw new Error("Due days must be a whole number from 0 to 90.");b!==e.invoice_due_days&&(f.due_days=b);let m=a.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(m.some(x=>!Number.isInteger(x)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let v=[...new Set(m)].sort((x,S)=>x-S);pl(v,e.invoice_reminder_schedule)||(f.reminder_schedule=v);let d=a.footer.trim()||null;if(d!==e.invoice_footer&&(f.footer=d),Object.keys(f).length===0){r();return}let p=await t(f);r(p?Vd(p):void 0)});return De("fieldset",{disabled:i,className:"af-space-y-4",children:[De("label",{className:Dn,children:["Days until due",Ne(ae,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:a.dueDays,onChange:f=>s({...a,dueDays:f.target.value})})]}),De("label",{className:Dn,children:["Reminder schedule",Ne(ae,{"aria-label":"Reminder schedule",value:a.reminders,placeholder:"Off",onChange:f=>s({...a,reminders:f.target.value})}),Ne(Wa,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),De("label",{className:Dn,children:["Invoice footer",Ne("textarea",{"aria-label":"Invoice footer",className:Fd,maxLength:300,value:a.footer,onChange:f=>s({...a,footer:f.target.value})})]}),Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void o(),onDiscard:()=>{u(null),r()}})]})}function Zd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=fr(e.default_email_recipients),{saving:i,error:l,setError:u,run:c}=pr(),[o,f]=Sn.useState(""),[b,g]=Sn.useState(null),m=()=>{let d=o.trim().toLowerCase();if(d){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d)){g("Enter a valid email address.");return}if(a.some(p=>p.toLowerCase()===d)){g("Already added.");return}s([...a,d]),f(""),g(null)}},v=()=>c(async()=>{let d=await t({default_email_recipients:a});r(d.default_email_recipients)});return De("fieldset",{disabled:i,className:"af-space-y-3",children:[De("div",{className:"af-flex af-flex-wrap af-gap-2",children:[a.map(d=>De(ee,{variant:"secondary",className:"af-gap-1",children:[d,Ne("button",{type:"button","aria-label":`Remove ${d}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(a.filter(p=>p!==d)),children:Ne(Hd,{className:"af-h-3 af-w-3"})})]},d)),a.length===0&&Ne("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),De("div",{className:"af-flex af-gap-2",children:[Ne(ae,{"aria-label":"Add notification email",type:"email",value:o,placeholder:"Add email address",onChange:d=>{f(d.target.value),g(null)},onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),m())}}),Ne(y,{type:"button",variant:"outline",disabled:!o.trim(),onClick:m,children:"Add"})]}),b&&Ne(Fr,{children:b}),Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void v(),onDiscard:()=>{u(null),r()}})]})}import{jsx as cn,jsxs as Yd}from"react/jsx-runtime";function Jd({siteId:e,refreshKey:t,section:a,shippingProviderSlot:s,onConnectStripe:n,onUpgradePlan:r,className:i}){let{site:l,isLoading:u,error:c,refetch:o,updateSite:f}=Ss({siteId:e,refreshKey:t}),b=Zn.useRef(o),g=Zn.useRef(e);Bs(()=>{b.current=o,g.current=e});let m=Zn.useRef({}),[v,d]=Zn.useState([]),p=v.some(N=>N.siteId===e),x=Zn.useCallback(()=>{let N={siteId:e},R=b.current;return d(C=>[...C,N]),C=>{let w=()=>d(I=>I.filter(_=>_!==N));!(g.current===N.siteId)||C&&b.current===R?w():b.current().finally(w)}},[e]),S=N=>R=>{m.current[N]=R},k=l!==null&&l.payments_active;if(Zn.useEffect(()=>{if(!k||!a)return;let N=m.current[a];N&&(N.scrollIntoView?.({behavior:"smooth",block:"start"}),N.focus({preventScroll:!0}))},[k,a]),u)return Yd("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[cn(ov,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!l)return cn("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c?.message??"Could not load store settings."});if(!l.payments_active)return cn(ir,{className:i,onConnectStripe:n,onUpgradePlan:r,whenActive:cn("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let h={site:l,updateSite:f,refetch:o};return Yd("div",{className:`af-space-y-6 ${i??""}`,children:[c&&cn("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c.message}),cn(Kn,{ref:S("checkout"),id:"checkout",title:"Checkout",children:cn(zd,{...h})}),cn(Kn,{ref:S("shipping"),id:"shipping",title:"Shipping",children:cn(jd,{...h,providerSlot:s,currencyChanging:p})}),cn(Kn,{ref:S("tax"),id:"tax",title:"Tax",children:cn(qd,{...h})}),cn(Kn,{ref:S("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:cn(Gd,{...h,onChangeStart:x})})]},e)}import{Loader2 as lv}from"lucide-react";import{jsx as Fs,jsxs as Xd}from"react/jsx-runtime";function ro({siteId:e,refreshKey:t,onSaveInvoiceSettings:a,className:s}){let{site:n,isLoading:r,error:i,updateSite:l,refetch:u,saveInvoiceSettings:c}=Ss({siteId:e,refreshKey:t,onSaveInvoiceSettings:a});return r?Xd("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Fs(lv,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):n?Xd("div",{className:`af-space-y-6 ${s??""}`,children:[i&&Fs("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i.message}),Fs(Kn,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:Fs(Kd,{site:n,save:c})}),Fs(Kn,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:Fs(Wd,{site:n,updateSite:l,refetch:u})})]},e):Fs("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i?.message??"Could not load invoice settings."})}import{Loader2 as cv}from"lucide-react";import{jsx as Mr,jsxs as Qd}from"react/jsx-runtime";function eu({siteId:e,refreshKey:t,className:a}){let{site:s,isLoading:n,error:r,updateSite:i,refetch:l}=Ss({siteId:e,refreshKey:t});return n?Qd("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Mr(cv,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?Qd("div",{className:`af-space-y-3 ${a??""}`,children:[r&&Mr("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}),Mr(Kn,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:Mr(Zd,{site:s,updateSite:i,refetch:l})})]},e):Mr("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."})}import*as gr from"react";import{Fragment as tu,jsx as Ra,jsxs as $r}from"react/jsx-runtime";function au({refreshKey:e,initialInvoiceId:t,onBackToWebsite:a,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,siteId:i,onSaveInvoiceSettings:l,className:u}){let{aggregates:c,isLoading:o,error:f,refetch:b}=nr({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=lr({refreshKey:e}),{api:m}=H(),v=g.filters,d=gr.useCallback(()=>m.exportRetainersCsv(v),[m,v]),[p,x]=gr.useState(!1),[S,k]=gr.useState(null),[h,N]=gr.useState(!1),R=Ra("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:f||!o&&!c?$r("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. ",Ra(y,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):o||!c?$r(tu,{children:[Ra(pt,{label:"Outstanding",children:Ra(G,{className:"af-h-6 af-w-24"})}),Ra(pt,{label:"Overdue",children:Ra(G,{className:"af-h-6 af-w-24"})}),Ra(pt,{label:"Paid this month",children:Ra(G,{className:"af-h-6 af-w-24"})})]}):$r(tu,{children:[Ra(pt,{label:"Outstanding",detail:`${c.outstanding.count} open`,children:Q(c.outstanding.amount,c.currency)}),Ra(pt,{label:"Overdue",detail:c.overdue.count===0?"Nothing overdue":`${c.overdue.count} overdue`,valueClassName:c.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:Q(c.overdue.amount,c.currency)}),Ra(pt,{label:"Paid this month",detail:`${c.paid_this_month.count} paid`,children:Q(c.paid_this_month.amount,c.currency)})]})});return $r(Ut,{title:"Invoices",onBackToWebsite:a,hideBackButton:p,className:u,children:[R,i&&!p&&$r("div",{className:"af-mb-6",children:[Ra(y,{type:"button",variant:"outline",size:"sm","aria-expanded":h,"aria-controls":"af-invoice-settings",onClick:()=>N(C=>!C),children:"Invoice settings"}),h&&Ra("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:Ra(ro,{siteId:i,refreshKey:e,onSaveInvoiceSettings:l})})]}),!p&&Ra(rr,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:S?.id??null,onShowCycles:C=>k(w=>w?.id===C.id?null:C),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded,exportCsv:d}),Ra(ys,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:x,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,retainerFilter:S?{id:S.id,label:`${S.customer_name??S.customer_email??"Recurring invoices"} \u2014 ${S.description}`}:null,onClearRetainerFilter:()=>k(null)})]})}import*as ea from"react";import*as Nn from"react";function Bt(e,t,a){let[s,n]=Nn.useState(null),[r,i]=Nn.useState(!0),[l,u]=Nn.useState(null),c=Nn.useRef(0),o=Nn.useRef(e);o.current=e;let f=Nn.useRef(a);f.current=a;let b=Nn.useCallback(async()=>{let m=++c.current,v=f.current;i(!0),u(null);try{let d=await o.current();m===c.current&&n({scope:v,value:d})}catch(d){m===c.current&&u(d instanceof Error?d:new Error("Request failed"))}finally{m===c.current&&i(!1)}},[]);Nn.useEffect(()=>{b()},[b,t]);let g=s!==null&&s.scope===a;return{data:g?s.value:null,isLoading:r||!g&&l===null,error:l,refetch:b}}var gl={commitBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts"},cancelBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts/{sendId}/cancel",params:["sendId"]},createDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts"},updateDraft:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},deleteDraft:{method:"DELETE",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},testSendDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/test",params:["draftId"]},setDraftTemplate:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}/template",params:["draftId"]},duplicateDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/duplicate",params:["draftId"]},copyEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/copy",params:["templateId"]},archiveEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/archive",params:["templateId"]},unarchiveEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/unarchive",params:["templateId"]},deleteEmailTemplate:{method:"DELETE",path:"/sites/{siteId}/marketing/templates/{templateId}",params:["templateId"]},updateAutomation:{method:"PUT",path:"/sites/{siteId}/marketing/automations/{automationId}",params:["automationId"]},addSuggestedAutomation:{method:"POST",path:"/sites/{siteId}/marketing/automation-suggestions"},turnOnAutomation:{method:"POST",path:"/sites/{siteId}/marketing/automations/{automationId}/turn-on",params:["automationId"]},turnOffAutomation:{method:"POST",path:"/sites/{siteId}/marketing/automations/{automationId}/turn-off",params:["automationId"]},deleteAutomation:{method:"DELETE",path:"/sites/{siteId}/marketing/automations/{automationId}",params:["automationId"]},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"]}};function dv(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(gl,e)}function uv(e,t,a){let s=gl[e],n="params"in s?s.params:[],r={...a};delete r.siteId;let i=s.path.replace("{siteId}",encodeURIComponent(t));for(let u of n){let c=r[u];if(typeof c!="string"&&typeof c!="number")throw new Error(`${e} needs ${u}`);i=i.replace(`{${u}}`,encodeURIComponent(String(c))),delete r[u]}let l=s.method==="GET"||s.method==="DELETE"?void 0:r;return{method:s.method,path:i,body:l}}var nu={marketing_disabled:"Email marketing is not available yet.",site_deleted:"This site has been deleted.",sending_not_enabled:"Email isn't turned on for this site yet.",sending_paused:"Sending is paused while we review this site.",domain_not_verified:"Verify your sending domain before you can send.",dmarc_missing:"Your domain needs a DMARC record before you can send.",postal_address_missing:"Add your business postal address before you can send. Every email has to show it.",allowance_exhausted:"You've used this month's email allowance. Sending resumes next month or when you upgrade.",ramp_limit:"Today's sending limit for a new domain is used up. Sending continues tomorrow.",sample_failed:"Too many emails in the first batch bounced, so the rest of this send was stopped."},Ur=new Set(["sending_not_enabled","domain_not_verified","dmarc_missing","postal_address_missing"]);function Ns(e){return e?nu[e]??"Sending is not available right now.":null}import*as Yn from"react";var vr=50;function io({siteId:e,q:t="",offset:a=0,refreshKey:s=0}){let{api:n}=H(),r=Bt(()=>n.getMarketingContacts(e,{q:t||void 0,limit:vr,offset:a}),`${e}|${t}|${a}|${s}`,e),i=Bt(()=>n.getMarketingContactStats(e),`${e}|${s}`,e),l=Bt(()=>n.getMarketingTags(e),`${e}|${s}`,e);return{contacts:r,stats:i,tags:l,refetchAll:async()=>{await Promise.all([r.refetch(),i.refetch(),l.refetch()])}}}import*as $s from"react";import*as On from"react";import{Fragment as fv,jsx as Vr,jsxs as ru}from"react/jsx-runtime";var Hr=e=>`af-email-settings-${e}`,vl=On.createContext(null);function Ke(){let e=On.useContext(vl);if(!e)throw new Error("Email panels render inside EmailView");return e}function su(e){let{setInlineEditOpen:t}=Ke();On.useEffect(()=>(t(e),()=>t(!1)),[e,t])}function bl(e){return e.status==="sending"||e.status==="sent"||(e.status==="cancelled"||e.status==="failed")&&e.recipients.consumed>0}function oo(e,t){return new Set([...e.filter(a=>a.sent).map(a=>a.id),...t.filter(bl).flatMap(a=>a.draft_id?[a.draft_id]:[])])}function fa({onClick:e,children:t}){return Vr("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function br({reason:e}){let{openSetup:t,onOpenStoreSettings:a}=Ke(),s=e&&Ur.has(e)?Vr(fa,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&a?Vr(fa,{onClick:a,children:"Open Store settings"}):null;return s&&ru(fv,{children:[" ",s]})}function Rs(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 Ga(e,t){return Rs(e)===t?!0:e instanceof Error&&e.message.includes(t)}function hr(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function vt(){let{onOrgAction:e}=Ke(),[t,a]=On.useState(!1),[s,n]=On.useState(null),r=On.useCallback(async(i,l={})=>{a(!0),n(null);try{return{ok:!0,result:await e(i,l)}}catch(u){return n(hr(u)),{ok:!1,error:u}}finally{a(!1)}},[e]);return{busy:t,error:s,setError:n,run:r}}function fe({tone:e="info",children:t,className:a}){return Vr("div",{role:e==="error"?"alert":"status",className:W("af-rounded-md af-border af-px-3 af-py-2 af-text-sm",e==="warning"&&"af-border-yellow-300 af-bg-yellow-50 af-text-yellow-900",e==="error"&&"af-border-destructive af-bg-destructive/10 af-text-destructive",e==="success"&&"af-border-green-300 af-bg-green-50 af-text-green-900",a),children:t})}function _a({children:e,action:t,id:a}){return ru("div",{id:a,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[Vr("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function Ae(e){return e.toLocaleString("en-US")}function Ms(e,t){return`${e} ${t}${e===1?"":"s"}`}import{jsx as Aa,jsxs as cs}from"react/jsx-runtime";var hl="I confirm that everyone in this file agreed to receive marketing email from my business.",mv={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 lo({onImported:e}){let{canWrite:t}=Ke(),[a,s]=$s.useState(""),[n,r]=$s.useState(null),[i,l]=$s.useState(""),[u,c]=$s.useState(!1),[o,f]=$s.useState(!1),[b,g]=$s.useState(null),m=vt(),v=async()=>{if(!u||!a.trim())return;let d=i.split(",").map(x=>x.trim()).filter(Boolean),p=await m.run("importContacts",{csv:a,attested:!0,...d.length?{tags:d}:{},...o?{enroll_automations:!0}:{}});if(p.ok){let x=p.result;g(x),e?.(x)}};if(b){let d=new Map;for(let p of b.skipped_rows)d.set(p.reason,(d.get(p.reason)??0)+1);return cs("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[Aa("div",{className:"af-font-medium",children:"Import finished"}),cs("p",{className:"af-text-sm",children:[Ae(b.rows)," rows: ",Ae(b.created)," new, ",Ae(b.updated)," updated, ",Ae(b.skipped)," skipped."]}),d.size>0&&Aa("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...d].map(([p,x])=>cs("li",{children:[Ae(x)," ",mv[p]??p]},p))}),Aa("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),Aa(y,{type:"button",size:"sm",variant:"outline",onClick:()=>{g(null),s(""),r(null),c(!1)},children:"Import another file"})]})}return cs("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:d=>{d.preventDefault(),v()},children:[cs("label",{className:"af-block af-space-y-1",children:[Aa("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),Aa("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async d=>{let p=d.target.files?.[0];p&&(r(p.name),s(await p.text()))}}),Aa("span",{className:"af-block af-text-xs af-text-muted-foreground",children:'Needs an "email" column. Tags in a "tags" column are applied too.'}),n&&Aa("span",{className:"af-block af-text-xs",children:n})]}),cs("label",{className:"af-block af-space-y-1",children:[Aa("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),Aa(ae,{"aria-label":"Tags for imported contacts",value:i,onChange:d=>l(d.target.value)})]}),cs("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[Aa("input",{"aria-label":"Send these contacts into matching automations",type:"checkbox",className:"af-mt-1",checked:o,onChange:d=>f(d.target.checked)}),Aa("span",{children:"Send these contacts into matching automations. Leave this off when they were already welcomed on another platform."})]}),cs("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[Aa("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:u,onChange:d=>c(d.target.checked)}),cs("span",{children:[hl," Importing people who didn't agree can get your sending paused."]})]}),m.error&&Aa(fe,{tone:"error",children:m.error}),Aa(y,{type:"submit",size:"sm",disabled:!t||!u||!a.trim()||m.busy,children:m.busy?"Importing\u2026":"Import contacts"})]})}import{Fragment as ou,jsx as Le,jsxs as Vt}from"react/jsx-runtime";var pv={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function iu(){let{siteId:e,canWrite:t,refreshKey:a}=Ke(),[s,n]=Yn.useState(""),[r,i]=Yn.useState(""),[l,u]=Yn.useState(0),[c,o]=Yn.useState(0),[f,b]=Yn.useState(new Set),[g,m]=Yn.useState(!1),v=io({siteId:e,q:r,offset:l,refreshKey:c+a}),d=vt(),p=()=>o(R=>R+1),x=v.stats.data,S=v.contacts.data,k=v.tags.data??[],h=x?x.growth.slice(-4).reduce((R,C)=>R+C.new_subscribers,0):null,N=async()=>{let R=await d.run("exportContacts",{});if(!R.ok||typeof R.result!="string"||typeof document>"u")return;let C=URL.createObjectURL(new Blob([R.result],{type:"text/csv;charset=utf-8"})),w=document.createElement("a");w.href=C,w.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(C)};return Vt("div",{children:[Vt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[Le(pt,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:x?Ae(x.total):Le(G,{className:"af-h-6 af-w-16"})}),Le(pt,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:x?Ae(x.mailable):Le(G,{className:"af-h-6 af-w-16"})}),Le(pt,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:h!==null?Ae(h):Le(G,{className:"af-h-6 af-w-16"})})]}),Vt("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[Vt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:R=>{R.preventDefault(),u(0),i(s.trim())},children:[Le(ae,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:s,onChange:R=>n(R.target.value)}),Le(y,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),Le(y,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>m(R=>!R),children:g?"Close import":"Import"}),Le(y,{type:"button",variant:"outline",size:"sm",disabled:!t||d.busy,onClick:()=>void N(),children:"Export"})]}),g&&Le("div",{className:"af-mt-3",children:Le(lo,{onImported:p})}),d.error&&Le(fe,{tone:"error",className:"af-mt-2",children:d.error}),t&&f.size>0&&Le(vv,{tags:k.filter(R=>!R.system),count:f.size,busy:d.busy,onApply:async(R,C)=>{(await d.run("bulkTagContacts",{action:R,tag_id:C,contact_ids:[...f]})).ok&&(b(new Set),p())}}),Le("div",{className:"af-mt-3",children:v.contacts.error?Le(xt,{message:"Couldn't load contacts.",onRetry:()=>void v.contacts.refetch()}):S?S.contacts.length===0?Le(ca,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):Vt(ou,{children:[Le("ul",{className:"af-divide-y af-rounded-md af-border",children:S.contacts.map(R=>Le(gv,{contact:R,canWrite:t,busy:d.busy,selected:f.has(R.id),onSelect:C=>b(w=>{let P=new Set(w);return C?P.add(R.id):P.delete(R.id),P}),onUnsubscribe:async()=>{(await d.run("unsubscribeContact",{contactId:R.id})).ok&&p()}},R.id))}),Vt("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[Vt("span",{children:[Ae(l+1),"\u2013",Ae(l+S.contacts.length)," of ",Ae(S.total)]}),Vt("div",{className:"af-flex af-gap-2",children:[Le(y,{type:"button",variant:"ghost",size:"sm",disabled:l===0,onClick:()=>u(Math.max(0,l-vr)),children:"Previous"}),Le(y,{type:"button",variant:"ghost",size:"sm",disabled:l+S.contacts.length>=S.total,onClick:()=>u(l+vr),children:"Next"})]})]})]}):Le(G,{className:"af-h-24 af-w-full"})}),Le(bv,{tags:k,canWrite:t,onChanged:p})]})}function gv({contact:e,canWrite:t,busy:a,selected:s,onSelect:n,onUnsubscribe:r}){return Vt("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&Le("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:s,onChange:i=>n(i.target.checked)}),Vt("div",{className:"af-min-w-0 af-flex-1",children:[Vt("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?Vt("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),Vt("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[Le(ee,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":pv[e.status]}),e.tags.map(i=>Le(ee,{variant:"outline",children:i.label},i.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&Le(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:r,children:"Unsubscribe"})]})}function vv({tags:e,count:t,busy:a,onApply:s}){let[n,r]=Yn.useState("");return Vt("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:[Vt("span",{children:[Ae(t)," selected"]}),Vt("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:n,onChange:i=>r(i.target.value),children:[Le("option",{value:"",children:"Choose a tag\u2026"}),e.map(i=>Le("option",{value:i.id,children:i.label},i.id))]}),Le(y,{type:"button",size:"sm",variant:"outline",disabled:!n||a,onClick:()=>s("add",n),children:"Add tag"}),Le(y,{type:"button",size:"sm",variant:"ghost",disabled:!n||a,onClick:()=>s("remove",n),children:"Remove tag"})]})}function bv({tags:e,canWrite:t,onChanged:a}){let[s,n]=Yn.useState(""),[r,i]=Yn.useState(null),l=vt();return Vt("div",{children:[Le(_a,{children:"Tags"}),e.length===0?Le("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."}):Le("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(u=>Le("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:r?.id===u.id?Vt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async c=>{c.preventDefault(),(await l.run("updateTag",{tagId:u.id,label:r.label.trim()})).ok&&(i(null),a())},children:[Le(ae,{"aria-label":`New name for ${u.label}`,value:r.label,onChange:c=>i({id:u.id,label:c.target.value})}),Le(y,{type:"submit",size:"sm",disabled:!r.label.trim()||l.busy,children:"Save"})]}):Vt(ou,{children:[Vt("span",{children:[u.label," ",Vt("span",{className:"af-text-muted-foreground",children:["\xB7 ",Ae(u.total)," contacts, ",Ae(u.mailable)," can be emailed"]})]}),t&&!u.system&&Le(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>i({id:u.id,label:u.label}),children:"Rename"})]})},u.id))}),t&&Vt("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async u=>{u.preventDefault(),(await l.run("createTag",{label:s.trim()})).ok&&(n(""),a())},children:[Le(ae,{"aria-label":"New tag",placeholder:"New tag",value:s,maxLength:100,onChange:u=>n(u.target.value)}),Le(y,{type:"submit",size:"sm",variant:"outline",disabled:!s.trim()||l.busy,children:"Add tag"})]}),l.error&&Le(fe,{tone:"error",className:"af-mt-2",children:l.error})]})}import*as Nt from"react";import{ArrowLeft as Cv,Sparkles as Tv}from"lucide-react";function yr({siteId:e,refreshKey:t=0}){let{api:a}=H();return Bt(()=>a.getBroadcasts(e),`${e}|${t}`,e)}function xr({siteId:e,kind:t,refreshKey:a=0}){let{api:s}=H();return Bt(()=>s.getEmailDrafts(e,t),`${e}|${t??""}|${a}`,`${e}|${t??""}`)}import*as We from"react";var zr=e=>typeof e=="number"&&Number.isFinite(e);function yl(e){if(!e||typeof e!="object")return null;let t=e;return zr(t.x)&&zr(t.y)&&zr(t.width)&&zr(t.height)?{x:t.x,y:t.y,width:t.width,height:t.height}:null}var xl=(e,t)=>Number.isInteger(e)&&e>=0&&e<t;function lu(e,t,a){if(!t||e.source!==t)return null;let s=e.data;if(!s||typeof s!="object"||s.af!=="email-editor")return null;switch(s.type){case"hover":{if(s.section===null)return{type:"hover",section:null,rect:null};let n=yl(s.rect);return xl(s.section,a)&&n?{type:"hover",section:s.section,rect:n}:null}case"focus":case"open":{let n=yl(s.rect);return xl(s.section,a)&&n?{type:s.type,section:s.section,rect:n}:null}case"layout":{if(!zr(s.height)||!Array.isArray(s.sections))return null;let n=s.sections.flatMap(r=>{let i=r,l=i?yl(i.rect):null;return i&&xl(i.section,a)&&l?[{section:i.section,rect:l}]:[]});return{type:"layout",height:s.height,sections:n}}case"template":return s.region==="header"||s.region==="footer"?{type:"template",region:s.region}:null;default:return null}}var jr=(e,t,a)=>Math.min(Math.max(e,t),Math.max(t,a));function wl(e,t){let a=jr(e.x,0,t.width),s=jr(e.y,0,t.height);return{x:a,y:s,width:jr(e.width,0,t.width-a),height:jr(e.height,0,t.height-s)}}var qr={min:240,max:6e3,initial:480},cu=e=>jr(Math.ceil(e),qr.min,qr.max);import*as Us from"react";import{jsx as ka,jsxs as Ln}from"react/jsx-runtime";var Sl={heading:"Heading",text:"Text",button:"Button",image:"Image",cart:"Cart"};function uu(e){switch(e){case"heading":case"text":return{type:e,text:""};case"button":return{type:e,label:"",url:"https://"};case"image":return{type:e,url:"",alt:""};case"cart":return{type:e,label:"Return to your cart"}}}function Nl(e){switch(e.type){case"heading":case"text":return e.text;case"button":return`${e.label}
6
6
  ${e.url}`;case"image":return[e.url,e.alt].filter(Boolean).join(`
7
- `);case"cart":return e.label}}function du(e){switch(e.type){case"heading":case"text":return e.text.trim()!=="";case"button":return e.label.trim()!==""&&e.url.trim()!==""&&e.url.trim()!=="https://";case"image":return e.url.trim()!=="";case"cart":return e.label.trim()!==""}}var hv={...Nl,text:"Markdown: **bold**, *italic*, [link](https://\u2026), blank line = new paragraph"};function fu({block:e,isNew:t,busy:a,error:s,onPickImage:n,onDone:r,onRemove:i,onCancel:l,style:u,className:c}){let[o,f]=Us.useState(e),[b,g]=Us.useState(!1),m=p=>f(x=>({...x,...p})),v=Us.useRef(null);Us.useEffect(()=>v.current?.focus(),[]);let d=p=>{p&&!v.current&&(v.current=p)};return ka("form",{"data-testid":"section-editor",style:u,className:c,onSubmit:p=>{p.preventDefault(),du(o)&&r(o)},onKeyDown:p=>{p.key==="Escape"&&!a&&l()},children:On("div",{className:"af-space-y-2",children:[o.type==="heading"&&ka(ae,{ref:d,"aria-label":"Heading",value:o.text,maxLength:200,onChange:p=>m({text:p.target.value})}),o.type==="text"&&ka("textarea",{ref:d,"aria-label":"Text",className:"af-min-h-[120px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-font-mono af-text-sm",value:o.text,maxLength:5e3,onChange:p=>m({text:p.target.value})}),o.type==="button"&&On("div",{className:"af-grid af-gap-2 sm:af-grid-cols-2",children:[On("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",ka(ae,{ref:d,"aria-label":"Button label",value:o.label,maxLength:80,onChange:p=>m({label:p.target.value})})]}),On("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Opens",ka(ae,{"aria-label":"Button link",type:"url",value:o.url,onChange:p=>m({url:p.target.value})})]})]}),o.type==="image"&&On("div",{className:"af-space-y-2",children:[n?On("div",{className:"af-flex af-items-center af-gap-2",children:[o.url&&ka("img",{src:o.url,alt:"",className:"af-h-12 af-w-12 af-rounded af-object-cover"}),ka(y,{ref:d,type:"button",variant:"outline",size:"sm",disabled:b,onClick:async()=>{g(!0);try{let p=await n();p&&f(x=>({...x,url:p.url,alt:p.alt??(x.type==="image"?x.alt:"")}))}finally{g(!1)}},children:"Choose from your site's images\u2026"})]}):On("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Image address (https://\u2026)",ka(ae,{ref:d,"aria-label":"Image URL",type:"url",value:o.url,onChange:p=>m({url:p.target.value})})]}),On("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Describe the image (for people who can't see it)",ka(ae,{"aria-label":"Image description",value:o.alt??"",maxLength:200,onChange:p=>m({alt:p.target.value})})]})]}),o.type==="cart"&&On("div",{className:"af-space-y-2",children:[ka("p",{className:"af-text-sm af-text-muted-foreground",children:"Each shopper sees their own cart here. There's nothing to write but the button."}),On("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",ka(ae,{ref:d,"aria-label":"Cart button label",value:o.label,maxLength:80,onChange:p=>m({label:p.target.value})})]})]}),s&&ka(ue,{tone:"error",children:s}),On("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ka("span",{className:"af-grow af-text-xs af-text-muted-foreground",children:hv[o.type]}),!t&&ka(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:i,children:"Remove"}),ka(y,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:l,children:"Cancel"}),ka(y,{type:"submit",size:"sm",disabled:a||!du(o),children:"Done"})]})]})})}import*as mu from"react";import{ArrowLeft as yv}from"lucide-react";import{Fragment as _l,jsx as Ze,jsxs as ha}from"react/jsx-runtime";var Jn="standard",co={create:"Create an email template that ",copyStandard:"Create an email template based on Standard that ",update:e=>`Update the "${e}" template to be `};function kl({template:e}){return e?e.status==="archived"?Ze(ee,{variant:"secondary",children:"Archived"}):e.locked?Ze(ee,{variant:"secondary",children:"In use"}):null:Ze(ee,{variant:"secondary",children:"Built in"})}function Pl(e){return e>0?`Used by ${e} draft${e===1?"":"s"}`:null}function pu(e,t){let{api:a}=H(),{siteId:s,refreshKey:n,settings:r}=Ke(),i=JSON.stringify([r?.business_name,r?.postal_address,r?.brand]);return Lt(()=>a.previewEmailTemplate(s,e),`${s}|${e}|${t}|${n}|${i}`,`${s}|${e}|${t}`)}function uo({templateId:e,version:t,className:a,frame:s}){let n=pu(e,t);return Ze("div",{"aria-hidden":!0,className:`af-pointer-events-none af-overflow-hidden af-bg-white ${a}`,children:n.data&&Ze("div",{"data-testid":"template-thumbnail-frame",className:"af-mx-auto af-overflow-hidden",style:{width:s.width*s.scale,height:s.height*s.scale},children:Ze("iframe",{title:"",tabIndex:-1,sandbox:"",srcDoc:n.data.html,style:{width:s.width,height:s.height,border:0,transform:`scale(${s.scale})`,transformOrigin:"top left"}})})})}function gu({template:e,onBack:t,onOpenTemplate:a,onOpenDraft:s,onAskAssistant:n,reload:r,refreshKey:i}){let l=pu(e?.id??Jn,e?.updated_at??"builtin");return ha("div",{className:"af-space-y-4",children:[ha(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[Ze(yv,{className:"af-mr-1 af-h-4 af-w-4"}),"All templates"]}),ha("div",{className:"af-grid af-gap-4 md:af-grid-cols-[minmax(0,1fr)_280px]",children:[ha("div",{children:[l.data?Ze("iframe",{title:"Template preview",sandbox:"",srcDoc:l.data.html,className:"af-h-[520px] af-w-full af-rounded-md af-border af-bg-white"}):l.error?ha(ue,{tone:"warning",children:[Rs(l.error)==="postal_address_missing"?"Add your business postal address to preview your emails.":"Couldn't load this preview.",Ze(br,{reason:Rs(l.error)})]}):Ze(G,{className:"af-h-[520px] af-w-full"}),Ze("p",{className:"af-mt-2 af-text-center af-text-xs af-text-muted-foreground",children:"Shown with a sample email"})]}),ha("div",{className:"af-space-y-3",children:[Ze(xv,{template:e,onOpenTemplate:a,onAskAssistant:n,reload:r}),Ze(wv,{templateId:e?.id??null,onOpenDraft:s,refreshKey:i})]})]})]})}function xv({template:e,onOpenTemplate:t,onAskAssistant:a,reload:s}){let{canWrite:n}=Ke(),r=vt(),[i,l]=mu.useState(null),u=e?.name??"Standard",c=async(d,p)=>{let x=await r.run(d,p);l(null),x.ok&&d==="deleteEmailTemplate"&&t(null),!x.ok&&Ga(x.error,"template_in_use")&&r.setError("Emails use this template now."),s()},o=async d=>{let p=await r.run("copyEmailTemplate",{templateId:d.id});p.ok&&(t(p.result.id),s())},f=d=>Ze(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:r.busy,onClick:()=>void o(d),children:"Make a copy"}),b=Ze(y,{type:"button",variant:"ghost",size:"sm",disabled:r.busy,onClick:()=>l("delete"),children:"Delete"}),g=Ze(y,{type:"button",variant:"outline",size:"sm",disabled:r.busy,onClick:()=>l("archive"),children:"Archive"}),m=null;if(!n)m=null;else if(i&&e){let[d,p,x]=i==="delete"?["Delete this template?","Delete",()=>c("deleteEmailTemplate",{templateId:e.id})]:["Archive this template?","Archive",()=>c("archiveEmailTemplate",{templateId:e.id})];m=ha(_l,{children:[Ze("p",{className:"af-text-sm",children:d}),ha("div",{className:"af-flex af-gap-2",children:[Ze(y,{type:"button",variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),Ze(y,{type:"button",size:"sm",variant:i==="delete"?"destructive":"default",className:"af-ml-auto",disabled:r.busy,onClick:()=>void x(),children:p})]})]})}else e?e.status==="archived"?m=ha("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ze(y,{type:"button",variant:"outline",size:"sm",disabled:r.busy,onClick:()=>void c("unarchiveEmailTemplate",{templateId:e.id}),children:"Unarchive"}),f(e)]}):e.locked?m=ha("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_archive&&g,f(e)]}):m=ha(_l,{children:[a&&Ze(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>a(co.update(e.name)),children:"\u2728 Change this template with the editor"}),(e.can_delete||e.can_archive)&&ha("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_delete&&b,e.can_archive&&g]})]}):m=a&&Ze(y,{type:"button",size:"sm",onClick:()=>a(co.copyStandard),children:"Make a copy"});let v=e&&e.status==="active"&&!e.locked?Pl(e.usage.drafts):null;return ha("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[ha("div",{className:"af-flex af-items-center af-gap-2",children:[Ze("h3",{"data-testid":"template-title",className:"af-grow af-truncate af-text-sm af-font-semibold",children:u}),Ze(kl,{template:e})]}),v&&Ze("p",{className:"af-text-xs af-text-muted-foreground",children:v}),r.error&&Ze(ue,{tone:"error",children:r.error}),m]})}function wv({templateId:e,onOpenDraft:t,refreshKey:a}){let{siteId:s}=Ke(),n=xr({siteId:s,kind:"broadcast",refreshKey:a}),r=yr({siteId:s,refreshKey:a}),i=n.data?.filter(f=>(f.template?.id??null)===e)??null,l=r.data??[],u=oo(n.data??[],l),c=new Set(l.flatMap(f=>f.draft_id&&f.status==="scheduled"?[f.draft_id]:[])),o=f=>u.has(f)?"Sent":c.has(f)?"Scheduled":"Draft";return ha("div",{"data-testid":"template-usage",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[Ze("h3",{className:"af-text-sm af-font-semibold",children:"Emails using it"}),n.error||r.error?Ze(xt,{message:"Couldn't load the emails.",onRetry:()=>{n.refetch(),r.refetch()}}):!i||!r.data?Ze(G,{className:"af-h-10 af-w-full"}):i.length===0?Ze("p",{className:"af-text-sm af-text-muted-foreground",children:"No emails use it."}):Ze("ul",{className:"af-space-y-1",children:i.map(f=>{let b=o(f.id),g=ha(_l,{children:[Ze("span",{className:"af-block af-truncate af-text-sm",children:f.subject||"(no subject)"}),ha("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["Broadcast \xB7 ",b]})]});return Ze("li",{children:b==="Sent"?Ze("div",{className:"af-rounded-md af-px-2 af-py-1",children:g}):Ze("button",{type:"button",onClick:()=>t(f.id),className:"af-w-full af-rounded-md af-px-2 af-py-1 af-text-left hover:af-bg-muted",children:g})},f.id)})})]})}import{jsx as Vs,jsxs as fo}from"react/jsx-runtime";function vu({draft:e,disabled:t,onChanged:a}){let{api:s}=H(),{siteId:n,refreshKey:r}=Ke(),i=Lt(()=>s.getEmailTemplates(n),`${n}|${r}`,n),l=vt(),u=e.template?.id??Jn,c=u===Jn,o=(i.data??[]).filter(v=>v.status==="active"),f=o.find(v=>v.id===u),b=c?"Standard":e.template?.name??f?.name??"",g=c?"builtin":f?.updated_at??"current",m=async v=>{if(v===u)return;let d=await l.run("setDraftTemplate",{draftId:e.id,template_id:v===Jn?null:v,expected_version:e.version});d.ok?await a():Ga(d.error,"template_missing_cart")?l.setError("This email shows the shopper's cart, and that template has no cart section. Pick another template, or keep this one."):Ga(d.error,"version_conflict")?(l.setError("This email changed meanwhile. We've loaded the latest version; switch again if you still want to."),await a()):Ga(d.error,"template_archived")&&(l.setError("That template is archived."),await i.refetch())};return fo("div",{"data-testid":"template-card",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[Vs("div",{className:"af-text-sm af-font-semibold",children:"Template"}),fo("div",{className:"af-flex af-items-center af-gap-3",children:[Vs(uo,{templateId:u,version:g,className:"af-h-20 af-w-[72px] af-shrink-0 af-rounded af-border",frame:{width:600,height:670,scale:.12}}),Vs("div",{className:"af-min-w-0 af-grow af-truncate af-text-sm af-font-medium",children:b})]}),fo("label",{className:"af-grid af-gap-1 af-text-xs af-text-muted-foreground",children:["Switch to",fo("select",{"aria-label":"Switch to",value:u,disabled:t||l.busy,onChange:v=>void m(v.target.value),className:"af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-text-sm af-text-foreground",children:[Vs("option",{value:Jn,children:"Standard"}),o.map(v=>Vs("option",{value:v.id,children:v.name},v.id)),!c&&!f&&Vs("option",{value:u,disabled:!0,children:b})]})]}),l.error&&Vs(ue,{tone:"error",children:l.error})]})}import{jsx as mo,jsxs as bu}from"react/jsx-runtime";function hu({live:e,joinsOnSave:t,notice:a,onBackToCanvas:s}){return bu("div",{"data-testid":"automation-step-panel",className:"af-space-y-2",children:[e?bu(ue,{tone:"success",children:[mo("span",{className:"af-font-medium",children:"Live."})," Saved changes send to the next people who reach this step."]}):t?mo(ue,{children:"This email joins the automation when you save it with a subject and some content."}):null,a,mo("p",{className:"af-text-sm",children:mo(fa,{onClick:s,children:"Back to the automation"})})]})}import{Fragment as Cl,jsx as qe,jsxs as Qt}from"react/jsx-runtime";var Sv={heading:"Click to edit heading",text:"Click to edit text",button:"Click to edit button",image:"Click to replace image",cart:"The shopper's cart"},Nv=320,Rv=600,_v=e=>({top:Math.max(0,e.y-24),left:e.x});function kv(e,t){let a=Object.keys(e);return a.length!==Object.keys(t).length?!1:a.every(s=>{let n=e[Number(s)],r=t[Number(s)];return r!==void 0&&n.x===r.x&&n.y===r.y&&n.width===r.width&&n.height===r.height})}function po({draftId:e,renderCommit:t,automationStep:a,allowCart:s,onSaved:n,scheduled:r,onAskAssistant:i,onPickImage:l}){let{api:u}=H(),{siteId:c,canWrite:o,refreshKey:f,openSettings:b}=Ke(),g=o&&!r,m=We.useRef(g);m.current=g;let[v,d]=We.useState(null),[p,x]=We.useState(null),[S,k]=We.useState(null),[h,N]=We.useState(null),[R,C]=We.useState(null),[w,P]=We.useState(null),[I,_]=We.useState(null),[q,j]=We.useState(null),[U,te]=We.useState(null),[ce,me]=We.useState({}),[T,V]=We.useState(qr.initial),[A,ne]=We.useState(!1),re=vt(),Me=vt(),Se=We.useRef(null),Ee=We.useRef(null),Ye=We.useRef(0),ke=We.useRef(!1),nt=We.useRef(!1),E=We.useCallback(ye=>{ke.current=ye!==null,P(ye)},[]);su(w!==null);let M=We.useRef(v);M.current=v;let L=We.useRef(0),pe=We.useCallback(async(ye={})=>{let Rt=++L.current,$=m.current,Pe=()=>$?u.previewEmailDraft(c,e,{editable:!0}):u.previewEmailDraft(c,e),[zt,Rn]=await Promise.allSettled([u.getEmailDraft(c,e),Pe()]),X=Rn,la=()=>zt.status==="fulfilled"&&X.status==="fulfilled"&&X.value.version!==zt.value.version;if(la()&&Rt===L.current&&([X]=await Promise.allSettled([Pe()])),Rt===L.current){if(ye.background&&ke.current){nt.current=!0;return}if(N(null),k(null),zt.status==="rejected"){N(hr(zt.reason));return}d(zt.value),X.status==="fulfilled"?x({...X.value,editable:$&&!la()}):(x(null),k(Ga(X.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:hr(X.reason),code:null}))}},[u,c,e]);We.useEffect(()=>{d(null),x(null),pe()},[pe]);let J=We.useRef(g);We.useEffect(()=>{J.current!==g&&(J.current=g,g||E(null),pe())},[g,pe,E]);let se=We.useRef(f);We.useEffect(()=>{if(f!==se.current){if(se.current=f,ke.current){nt.current=!0;return}pe({background:!0})}},[f,pe]);let Fe=()=>{E(null),re.setError(null),nt.current&&(nt.current=!1,pe())},Qe=async(ye,Rt,$)=>{let Pe=await re.run("updateDraft",{draftId:e,expected_version:ye.version,...Rt});Pe.ok?(_(null),Ee.current=null,nt.current=!1,E(null),await pe(),n?.()):Ga(Pe.error,"version_conflict")&&(re.setError(null),_($),nt.current=!1,E(null),await pe())},Xe=We.useRef({frame:null,html:null,count:0}),[Et,be]=We.useState(null),$e=(ye,Rt)=>{let $=Xe.current;$.frame!==ye.currentTarget||$.html!==Rt?Xe.current={frame:ye.currentTarget,html:Rt,count:1}:++$.count>1&&be(Rt)},yt=p!==null&&Et===p.html,It=g&&p?.editable===!0&&!yt;if(We.useEffect(()=>{if(!It)return;let ye=Rt=>{let $=M.current;if(!$)return;let Pe=lu(Rt,Se.current?.contentWindow,$.blocks.length);if(Pe)switch(Pe.type){case"hover":te(Pe.section===null?null:{section:Pe.section,rect:Pe.rect});return;case"focus":Ee.current=Pe.section;return;case"open":if(Ee.current=Pe.section,ke.current)return;j(null),ne(!1),E({kind:"section",base:$,index:Pe.section,block:$.blocks[Pe.section],isNew:!1,anchor:Pe.rect,key:++Ye.current});return;case"layout":V(cu(Pe.height));{let zt=Object.fromEntries(Pe.sections.map(Rn=>[Rn.section,Rn.rect]));me(Rn=>kv(Rn,zt)?Rn:zt)}return;case"template":ke.current||j(Pe.region);return}};return window.addEventListener("message",ye),()=>window.removeEventListener("message",ye)},[It,E]),h)return Qt(ue,{tone:"error",children:["Couldn't load this email. ",h]});if(!v)return qe(G,{className:"af-h-40 af-w-full"});let Mt={width:Se.current?.clientWidth||Rv,height:It?T:qr.initial},et=w?.kind==="section"?w:null,ta=(()=>{if(!et)return null;if(!et.isNew)return ce[et.index]??et.anchor;let ye=ce[et.index-1];return ye?{x:ye.x,y:ye.y+ye.height,width:ye.width,height:0}:null})(),Je=ta?Sl(ta,Mt):null,wt=s??v.kind==="recovery",Xa=v.template?.name??"Standard",Mn=et&&qe(fu,{block:et.block,isNew:et.isNew,busy:re.busy,error:re.error,onPickImage:l,onCancel:Fe,onRemove:()=>{let{base:ye}=et;Qe(ye,{subject:ye.subject,preheader:ye.preheader,blocks:ye.blocks.filter((Rt,$)=>$!==et.index)},Rl(et.block))},onDone:ye=>{let{base:Rt}=et,$=et.isNew?[...Rt.blocks.slice(0,et.index),ye,...Rt.blocks.slice(et.index)]:Rt.blocks.map((Pe,zt)=>zt===et.index?ye:Pe);Qe(Rt,{subject:Rt.subject,preheader:Rt.preheader,blocks:$},Rl(ye))},className:Je?"af-absolute af-z-10 af-rounded-md af-border af-bg-background af-p-3 af-shadow-lg":"af-rounded-md af-border af-bg-background af-p-3 af-shadow-sm",style:Je?{top:Je.y,left:Je.x,width:Math.min(Math.max(Je.width,Nv),Mt.width)}:void 0},et.key);return Qt("div",{className:"af-grid af-gap-4 lg:af-grid-cols-[minmax(0,1fr)_300px]",children:[Qt("div",{className:"af-min-w-0 af-space-y-3",children:[w?.kind==="subject"?qe(Pv,{draft:w.base,busy:re.busy,error:re.error,onCancel:Fe,onDone:ye=>void Qe(w.base,{...ye,blocks:w.base.blocks},[ye.subject,ye.preheader??""].join(`
8
- `))}):It?qe("button",{type:"button","data-testid":"subject-line",onClick:()=>{ke.current||(j(null),E({kind:"subject",base:v}))},className:"af-block af-w-full af-rounded-md af-border af-border-dashed af-px-3 af-py-2 af-text-left hover:af-border-primary",children:qe(yu,{draft:v})}):qe("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:qe(yu,{draft:v})}),r&&Qt(ue,{tone:"info",children:[Qt("p",{children:["This email is scheduled",r.sendsAt?` to send ${new Date(r.sendsAt).toLocaleString()}`:"",", so it can't change. Unschedule it to edit, then schedule it again."]}),qe(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:!o||r.busy,onClick:()=>void r.onUnschedule(),children:"Unschedule to edit"}),r.error&&qe("p",{className:"af-mt-1 af-text-destructive",children:r.error})]}),I!==null&&Qt(ue,{tone:"warning",children:[qe("p",{children:"This email changed while you were editing, so your change wasn't saved. Here is the latest version; your text is below to apply again."}),qe("textarea",{readOnly:!0,"aria-label":"Your unsaved text",value:I,className:"af-mt-2 af-min-h-[72px] af-w-full af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-font-mono af-text-xs af-text-foreground"}),qe(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>_(null),children:"Dismiss"})]}),q&&qe("div",{"data-testid":"template-hint",children:qe(ue,{children:q==="header"?Qt(Cl,{children:['The header is part of the "',Xa,'" template. Switch templates on the right.']}):Qt(Cl,{children:["Every email ends with this footer. Your business name and address come from"," ",qe(fa,{onClick:()=>b("sender"),children:"Settings"}),"."]})})}),yt&&g&&qe(ue,{tone:"warning",children:"This template tried to open another page in the preview, so the preview can't be edited here."}),p?Qt("div",{className:"af-relative",children:[qe("iframe",{ref:Se,title:"Email preview",sandbox:It?"allow-scripts":"",srcDoc:p.html,onLoad:It?ye=>$e(ye,p.html):void 0,style:{height:Mt.height},className:"af-block af-w-full af-rounded-md af-border af-bg-white"},It?"editable":"read-only"),It&&U&&!w&&qe("div",{"aria-hidden":!0,className:"af-pointer-events-none af-absolute af-rounded af-bg-primary af-px-2 af-py-0.5 af-text-xs af-text-primary-foreground",style:_v(Sl(U.rect,Mt)),children:Sv[v.blocks[U.section]?.type??"text"]}),Je&&Mn]}):S?Qt(ue,{tone:"warning",children:[S.text,qe(br,{reason:S.code})]}):qe(G,{className:"af-h-40 af-w-full"}),!Je&&Mn,It&&!w&&Qt("div",{className:"af-space-y-2",children:[qe(y,{type:"button",variant:"outline",size:"sm",onClick:()=>ne(ye=>!ye),"aria-expanded":A,children:"+ Add a section"}),A&&qe("div",{"data-testid":"add-section-menu",className:"af-flex af-flex-wrap af-gap-2",children:["text","heading","button","image",...wt?["cart"]:[]].map(ye=>qe(y,{type:"button",size:"sm",variant:"secondary",onClick:()=>{let Rt=Ee.current!==null?Ee.current+1:v.blocks.length;ne(!1),j(null),E({kind:"section",base:v,index:Rt,block:uu(ye),isNew:!0,anchor:null,key:++Ye.current})},children:Nl[ye]},ye))})]}),qe("p",{className:"af-text-center af-text-xs af-text-muted-foreground",children:"Header and footer come from your template."})]}),Qt("div",{className:"af-space-y-3",children:[Qt("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[qe(y,{type:"button",variant:"outline",size:"sm",disabled:!o||Me.busy,onClick:async()=>{C(null);let ye=await Me.run("testSendDraft",{draftId:e});ye.ok&&C(ye.result?.sent_to??"your email")},children:"Send a test to me"}),R&&Qt(ue,{tone:"success",children:["Test sent to ",R,"."]}),Me.error&&qe(ue,{tone:"error",children:Me.error}),p&&!r&&t?.({draft:v,preview:p,reload:()=>pe()}),a&&qe(hu,{...a})]}),qe(vu,{draft:v,disabled:!g||w!==null,onChanged:async()=>{await pe(),n?.()}}),i&&o&&qe(y,{type:"button",variant:"outline",className:"af-w-full",onClick:()=>i(`Update the "${v.subject}" email to `),children:"\u2728 Change this email with the editor"})]})]})}function yu({draft:e}){return Qt(Cl,{children:[qe("span",{className:"af-text-xs af-text-muted-foreground",children:"Subject "}),qe("span",{className:"af-font-medium",children:e.subject||"(no subject)"}),e.preheader&&Qt("span",{className:"af-text-sm af-text-muted-foreground",children:[" \u2014 ",e.preheader]})]})}function Pv({draft:e,busy:t,error:a,onDone:s,onCancel:n}){let[r,i]=We.useState(e.subject),[l,u]=We.useState(e.preheader??"");return Qt("form",{className:"af-space-y-2 af-rounded-md af-border af-p-3",onSubmit:c=>{c.preventDefault(),s({subject:r,preheader:l.trim()||null})},children:[Qt("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Subject",qe(ae,{"aria-label":"Subject",value:r,maxLength:200,autoFocus:!0,onChange:c=>i(c.target.value)})]}),Qt("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Preview text (the grey line after the subject in the inbox)",qe(ae,{"aria-label":"Preview text",value:l,maxLength:200,onChange:c=>u(c.target.value)})]}),a&&qe(ue,{tone:"error",children:a}),Qt("div",{className:"af-flex af-justify-end af-gap-2",children:[qe(y,{type:"button",variant:"outline",size:"sm",disabled:t,onClick:n,children:"Cancel"}),qe(y,{type:"submit",size:"sm",disabled:t,children:"Done"})]})]})}import{jsx as Re,jsxs as Bt}from"react/jsx-runtime";var Tv={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function wu({openDraftId:e,onOpenDraft:t,onAskAssistant:a,onPickImage:s}){let{siteId:n,canWrite:r,refreshKey:i}=Ke(),[l,u]=Nt.useState(0),c=l+i,o=xr({siteId:n,kind:"broadcast",refreshKey:c}),f=yr({siteId:n,refreshKey:c}),b=vt(),g=vt(),m=oo(o.data??[],f.data??[]),v=o.data?.filter(d=>!m.has(d.id))??null;if(e){let d=f.data?.find(p=>p.draft_id===e&&p.status==="scheduled");return Bt("div",{className:"af-space-y-4",children:[Bt(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>t(null),children:[Re(Cv,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),!f.data&&!f.error||!o.data&&!o.error?Re(G,{className:"af-h-40 af-w-full"}):m.has(e)?Re(ue,{children:"This email has been sent, so it can't change. Duplicate it from the list to send it again."}):Re(po,{draftId:e,onSaved:()=>u(p=>p+1),renderCommit:p=>Re(Dv,{...p,onCommitted:()=>u(x=>x+1)}),scheduled:d?{sendsAt:d.scheduled_at,busy:b.busy,error:b.error,onUnschedule:async()=>{(await b.run("cancelBroadcast",{sendId:d.id})).ok&&u(x=>x+1)}}:void 0,onAskAssistant:a,onPickImage:s})]})}return Bt("div",{children:[Re(_a,{children:"Drafts"}),o.error?Re(xt,{message:"Couldn't load drafts.",onRetry:()=>void o.refetch()}):v?v.length===0?Re(ca,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):Re("ul",{"data-testid":"drafts",className:"af-divide-y af-rounded-md af-border",children:v.map(d=>Bt("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[Re("span",{className:"af-truncate af-text-sm",children:d.subject||"(no subject)"}),Re(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(d.id),children:"Review"})]},d.id))}):Re(G,{className:"af-h-10 af-w-full"}),Re(_a,{children:"Sent and scheduled"}),b.error&&Re(ue,{tone:"error",children:b.error}),g.error&&Re(ue,{tone:"error",children:g.error}),f.error?Re(xt,{message:"Couldn't load broadcasts.",onRetry:()=>void f.refetch()}):f.data?f.data.length===0?Re(ca,{children:"Nothing sent yet."}):Re("ul",{className:"af-divide-y af-rounded-md af-border",children:f.data.map(d=>Re(Ev,{broadcast:d,canCancel:r&&(d.status==="scheduled"||d.status==="unscheduled"||d.status==="sending"),busy:b.busy||g.busy,onCancel:async()=>{(await b.run("cancelBroadcast",{sendId:d.id})).ok&&u(x=>x+1)},onDuplicate:r&&d.draft_id&&hl(d)?async()=>{let p=await g.run("duplicateDraft",{draftId:d.draft_id});p.ok&&(u(x=>x+1),t(p.result.id))}:void 0},d.id))}):Re(G,{className:"af-h-10 af-w-full"})]})}function Ev({broadcast:e,canCancel:t,busy:a,onCancel:s,onDuplicate:n}){return Bt("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[Bt("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[Re("span",{className:"af-truncate af-text-sm af-font-medium",children:e.subject}),Bt("div",{className:"af-flex af-items-center af-gap-2",children:[Re(ee,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Tv[e.status]}),t&&Re(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:s,children:"Cancel"}),n&&Re(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:n,children:"Duplicate"})]})]}),Bt("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",Ae(e.recipients.planned)," recipients \xB7 ",Ae(e.stats.delivered)," delivered \xB7 ",Ae(e.stats.opened)," opened \xB7"," ",Ae(e.stats.clicked)," clicked \xB7 ",Ae(e.stats.bounced)," bounced \xB7 ",Ae(e.stats.complained)," complaints \xB7"," ",Ae(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&Re("div",{className:"af-text-xs af-text-muted-foreground",children:Ns(e.status_reason)})]})}var Su=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function xu(e){let t=e.targeting??null,a=e.proposed_send_at?new Date(e.proposed_send_at):null,s=a!==null&&a.getTime()>Date.now();return{key:Su(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:s?Iv(a):"",suggested:t!==null||a!==null,timePassed:a!==null&&!s}}function Iv(e){let t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}var Av=(e,t)=>e.match===t.match&&e.scheduleAt===t.scheduleAt&&e.tagIds.length===t.tagIds.length&&e.tagIds.every(a=>t.tagIds.includes(a));function Dv({draft:e,preview:t,reload:a,onCommitted:s}){let{api:n}=H(),{siteId:r,canWrite:i,settings:l,refreshKey:u}=Ke(),[c,o]=Nt.useState(null),[f,b]=Nt.useState(!1),[g,m]=Nt.useState(null),[v,d]=Nt.useState(()=>xu(e)),[p,x]=Nt.useState(v.tagIds),[S,k]=Nt.useState(v.match),[h,N]=Nt.useState(v.scheduleAt),[R,C]=Nt.useState(0),w=!Av({tagIds:p,match:S,scheduleAt:h},v),P=Su(e);Nt.useEffect(()=>{if(P===v.key||e.id===v.draftId&&w)return;let J=xu(e);d(J),x(J.tagIds),k(J.match),N(J.scheduleAt),C(0)},[P,e,v,w]);let I=Nt.useMemo(()=>c?new Set(c.map(J=>J.id)):null,[c]),_=I!==null&&p.every(J=>I.has(J));Nt.useEffect(()=>{if(!I||p.every(se=>I.has(se)))return;let J=se=>se.filter(Fe=>I.has(Fe));C(se=>se+p.length-J(p).length),x(J(p)),d(se=>({...se,tagIds:J(se.tagIds)}))},[I,p]);let[q,j]=Nt.useState(null),[U,te]=Nt.useState(null),[ce,me]=Nt.useState(null),T=vt();Nt.useEffect(()=>{n.getMarketingTags(r).then(J=>{o(J),b(!1)},()=>{o(null),b(!0)}),n.getMarketingContactStats(r).then(m,()=>m(null))},[n,r,u]);let V=h?new Date(h).toISOString():null,A=JSON.stringify([p,S,V]),ne=q?.plan??null,re=q!==null&&q.key===A,Me=Nt.useRef(0),Se=Nt.useCallback(async()=>{let J=++Me.current;te(null);try{let se=await n.estimateBroadcast(r,{targeting:{tag_ids:p,match:S},scheduled_at:V});J===Me.current&&j({key:A,plan:se})}catch(se){if(J!==Me.current)return;j(null),te(hr(se))}},[n,r,p,S,V,A,u]),Ee=Nt.useRef(!1);Nt.useEffect(()=>{if(!_&&p.length>0)return;if(!Ee.current){Ee.current=!0,Se();return}let J=setTimeout(()=>void Se(),300);return()=>clearTimeout(J)},[Se,_,p.length]);let Ye=l&&!l.readiness.can_send?Ns(l.readiness.reason):null,ke=ne!==null&&!ne.fits,nt=g?Math.max(0,g.by_status.subscribed-g.mailable):null,E=g&&ne&&nt!==null?Math.max(0,g.total-ne.recipients-nt):null,M=!i||T.busy||!ne||!re||ke||ne.recipients===0||Ye!==null||f&&p.length>0,L=async()=>{me(null);let J=await T.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:p,match:S},scheduled_at:V});if(J.ok){me({tone:"success",text:V?"Scheduled.":"Sending now."}),s();return}Ga(J.error,"version_conflict")?(T.setError(null),await a(),me({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):Ga(J.error,"over_allowance")&&await Se()},pe=J=>x(se=>se.includes(J)?se.filter(Fe=>Fe!==J):[...se,J]);return Bt("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[v.suggested&&!w&&Re(ue,{children:"Suggested by your assistant \u2014 review before sending."}),Re(_a,{children:"Who gets it"}),f&&Re(ue,{tone:"warning",children:p.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."}),R>0&&Re(ue,{tone:"warning",children:R===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),c&&c.length>0?Bt("div",{className:"af-space-y-2",children:[Re("div",{className:"af-flex af-flex-wrap af-gap-2",children:c.map(J=>Bt("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[Re("input",{type:"checkbox",checked:p.includes(J.id),onChange:()=>pe(J.id)}),J.label]},J.id))}),p.length>1&&Bt("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",Bt("select",{"aria-label":"Tag match",value:S,onChange:J=>k(J.target.value),className:"af-rounded-md af-border af-px-2 af-py-1",children:[Re("option",{value:"any",children:"any of these tags"}),Re("option",{value:"all",children:"all of these tags"})]})]}),p.length===0&&Re("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):Re("p",{className:"af-text-sm af-text-muted-foreground",children:"Everyone who can be emailed."}),Bt("label",{className:"af-block af-space-y-1",children:[Re("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),Re(ae,{"aria-label":"Schedule time",type:"datetime-local",value:h,onChange:J=>N(J.target.value)})]}),v.timePassed&&!h&&Re(ue,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),U?Bt(ue,{tone:"error",children:["Couldn't work out the audience. ",U]}):ne?Bt("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[Bt("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[Re(Tl,{label:"Will receive it",value:ne.recipients}),Re(Tl,{label:"Suppressed (bounced or complained)",value:nt}),Re(Tl,{label:"Not included",value:E})]}),Bt("p",{className:"af-text-muted-foreground",children:[Ae(ne.allowance.remaining)," of ",Ae(ne.allowance.monthly)," emails left this month."]}),ne.sample_size!==null&&Bt(ue,{children:["We'll send to ",Ae(ne.sample_size)," people first and check for bounces before sending the rest."]}),ne.ramp_days.length>1&&Bt(ue,{children:["Your domain is new, so this goes out over ",ne.ramp_days.length," days:"," ",ne.ramp_days.map(J=>`${Ae(J.recipients)} on ${J.date}`).join(", "),"."]})]}):Re(G,{className:"af-h-12 af-w-full"}),ke&&ne&&Bt(ue,{tone:"warning",children:["This send needs ",Ae(ne.recipients)," emails, but only ",Ae(ne.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),Ye&&Bt(ue,{tone:"warning",children:[Ye,Re(br,{reason:l?.readiness.reason})]}),ce&&Re(ue,{tone:ce.tone,children:ce.text}),T.error&&Re(ue,{tone:"error",children:T.error}),Re(y,{type:"button",disabled:M,onClick:()=>void L(),children:V?"Schedule":"Send now"})]})}function Tl({label:e,value:t}){return Bt("div",{className:"af-rounded-md af-border af-px-2 af-py-1",children:[Re("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Re("div",{className:"af-font-semibold",children:t===null?"\u2014":Ae(t)})]})}import*as Ka from"react";import{Check as ku,FileText as Zv,ShieldCheck as Cu}from"lucide-react";import*as Hs from"react";import{ArrowRight as Ov,Check as Nu,ChevronDown as Lv,Globe as Bv,Lock as Fv,Mail as vo,PenLine as Mv,Sparkles as $v}from"lucide-react";import{Fragment as go,jsx as Y,jsxs as he}from"react/jsx-runtime";var Uv=[{title:"Own your audience",body:"Your list is yours. Reaching it doesn't depend on a social feed or an ad budget."},{title:"Bring people back",body:"Most visitors leave and never return. Email gets them back when you have news, a sale or something new."},{title:"Look like you",body:"Emails come from your own domain, with your logo and colors."}],Vv="hello";function Il(e){return`${Vv}@${e}`}function Ru({onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,onTurnOn:s,siteDomain:n,businessName:r,dnsManaged:i,renderSendingRecords:l}){let{api:u}=H(),{siteId:c,settings:o,canWrite:f,refreshKey:b,refetchSettings:g}=Ke(),m=Lt(()=>u.getMarketingContactStats(c),`${c}|${b}`,c),[v,d]=Hs.useState(!1),[p,x]=Hs.useState(null);if(!o)return null;let S=m.data?.by_status.subscribed??0,k={siteDomain:n,businessName:r};return Hv(o)?Y(Al,{settings:o,site:k,waiting:S,children:f?s&&he("div",{className:"af-space-y-2",children:[he(y,{disabled:v,onClick:async()=>{d(!0),x(null);try{await s(),await g()}catch(h){x(h instanceof Error?h.message:"Couldn't turn on email. Try again.")}finally{d(!1)}},children:["Get started ",Y(Ov,{className:"af-ml-2 af-h-4 af-w-4","aria-hidden":!0})]}),p&&Y(ue,{tone:"error",children:p})]}):Y("p",{className:"af-text-sm af-text-muted-foreground",children:"Only the site owner can set up email."})}):Y(zv,{settings:o,site:k,waiting:S,onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,dnsManaged:i,renderSendingRecords:l})}function Hv(e){return e.readiness.reason==="sending_not_enabled"}function Al({settings:e,site:t,waiting:a=0,children:s}){return Y("div",{className:"af-mx-auto af-max-w-3xl af-px-2 af-py-8",children:he("div",{className:"af-grid af-items-center af-gap-10 md:af-grid-cols-[1fr_18rem]",children:[he("div",{children:[he("div",{className:"af-mb-3 af-inline-flex af-items-center af-gap-1.5 af-rounded-full af-bg-muted af-px-2.5 af-py-1 af-text-xs af-font-medium",children:[Y(vo,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0})," Email marketing"]}),Y("h3",{className:"af-text-2xl af-font-semibold af-tracking-tight",children:"Turn visitors into regulars"}),Y("p",{className:"af-mt-2 af-text-muted-foreground",children:"Build an email list from your website and reach those people directly, whenever you have something worth telling them."}),Y("ol",{className:"af-mt-6 af-space-y-3",children:Uv.map((n,r)=>he("li",{className:"af-flex af-gap-3",children:[Y("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-border af-text-xs af-font-semibold",children:r+1}),he("p",{className:"af-text-sm",children:[he("span",{className:"af-font-medium",children:[n.title,"."]})," ",Y("span",{className:"af-text-muted-foreground",children:n.body})]})]},n.title))}),a>0&&he("p",{className:"af-mt-5 af-rounded-md af-bg-amber-50 af-px-3 af-py-2 af-text-sm af-text-amber-900",children:[he("span",{className:"af-font-semibold",children:[Ae(a)," ",a===1?"person has":"people have"]})," ","already signed up and ",a===1?"is":"are"," waiting for your first email."]}),Y("div",{className:"af-mt-6",children:s})]}),Y(bo,{settings:e,site:t,className:"af-rotate-1"})]})})}function _u({onUpgradePlan:e}){return he("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-border-violet-200 af-bg-gradient-to-r af-from-violet-50 af-to-white af-p-4",children:[Y(Fv,{className:"af-h-5 af-w-5 af-shrink-0 af-text-violet-700","aria-hidden":!0}),he("div",{className:"af-flex-1",children:[Y("div",{className:"af-text-sm af-font-semibold af-text-violet-900",children:"Email marketing is part of Pro"}),Y("div",{className:"af-text-sm af-text-violet-900/80",children:"Collect subscribers and send newsletters from your own domain."})]}),e&&Y(y,{size:"sm",onClick:e,children:"Upgrade to Pro"})]})}function zv({settings:e,site:t,waiting:a,onStartDomainSetup:s,onConnectDomain:n,onAskAssistant:r,dnsManaged:i,renderSendingRecords:l}){let{refetchSettings:u,canWrite:c}=Ke(),[o,f]=Hs.useState(null),b=p=>f(x=>x===p?null:p),{siteDomain:g}=t,m=Wr(e),v=g===null&&!e.domain.sending_domain,d=!!e.postal_address;return he("div",{className:"af-mx-auto af-max-w-4xl af-py-4",children:[he("div",{className:"af-mb-6 af-flex af-items-start af-justify-between af-gap-6",children:[he("div",{children:[Y("h3",{className:"af-text-xl af-font-semibold",children:"Set up email"}),he("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Newsletters to your subscribers, sent from ",g??"your own domain","."]})]}),a>0&&he("div",{className:"af-text-right",children:[Y("div",{className:"af-text-2xl af-font-semibold",children:Ae(a)}),he("div",{className:"af-text-xs af-text-muted-foreground",children:[a===1?"subscriber":"subscribers"," waiting"]})]})]}),!c&&Y(ue,{className:"af-mb-4",children:"Only the site owner can finish setup."}),he("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_16rem]",children:[he("div",{className:"af-space-y-4",children:[he(El,{title:g??"Your domain",sub:"One domain for your website and your email.",children:[g&&Y(Bn,{icon:Bv,label:"Website",value:g,status:Y(Ln,{tone:"green",children:"Live"})}),v?Y(Bn,{icon:vo,label:"Email sending",value:"Needs a custom domain",status:Y(Ln,{tone:"gray",children:"Not available"}),action:n&&c?{label:"Connect domain",onClick:n}:void 0}):he(Bn,{icon:vo,label:"Email sending",value:e.domain.sending_domain??(g?`news.${g}`:"news.yourdomain.com"),status:Dl(e),action:!m&&c?{label:e.domain.sending_domain?"Details":"Set up",onClick:()=>b("sending")}:void 0,expanded:o==="sending",children:[!e.domain.sending_domain&&he("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."," ",i?"We manage your domain's DNS, so we add the records for you. Nothing to copy.":i===!1?"You'll get a few records to copy into your DNS provider.":"If we manage your domain's DNS we add the records; otherwise you'll get a few to copy into your DNS provider."]}),Y(Ol,{settings:e,canWrite:c,onStartDomainSetup:s,onChanged:u,dnsManaged:i,renderSendingRecords:l})]})]}),Y(El,{title:"Sender",sub:"Who your emails are from. The mailing address is legally required in every email.",children:Y(Bn,{icon:Mv,label:d?e.business_name??"Sender":"Not set",value:e.postal_address??"Name, mailing address and reply-to",status:d?Y(Ln,{tone:"green",children:"Done"}):Y(Ln,{tone:"gray",children:"Needed"}),action:c?{label:d?"Edit":"Add",onClick:()=>b("sender")}:void 0,expanded:o==="sender",children:Y(jv,{settings:e,businessName:t.businessName,onSaved:async()=>{await u(),f(null)}})})}),Y(El,{title:"How people join your list",sub:"Only people who asked to hear from you get your emails.",children:Y(Kv,{onAskAssistant:c?r:void 0})})]}),he("aside",{className:"af-space-y-3",children:[Y("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails will look like"}),Y(bo,{settings:e,site:t})]})]})]})}function El({title:e,sub:t,children:a}){return he("section",{className:"af-rounded-xl af-border af-bg-background",children:[he("div",{className:"af-px-5 af-pb-3 af-pt-4",children:[Y("h4",{className:"af-text-sm af-font-semibold",children:e}),Y("p",{className:"af-text-xs af-text-muted-foreground",children:t})]}),Y("div",{className:"af-space-y-2 af-px-3 af-pb-3",children:a})]})}function Bn({icon:e,marker:t,markerSpace:a=!1,label:s,value:n,mono:r=!0,hint:i,status:l,action:u,expanded:c=!1,children:o}){return he("div",{className:"af-rounded-lg af-border af-bg-muted/30",children:[he("div",{className:"af-flex af-items-center af-gap-3 af-p-3",children:[t?he("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-xs af-font-semibold af-text-background",children:[Y("span",{"aria-hidden":!0,children:t}),he("span",{className:"af-sr-only",children:["Shown at ",t," in the preview"]})]}):a?Y("span",{className:"af-h-6 af-w-6 af-shrink-0","aria-hidden":!0}):e&&Y("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-background",children:Y(e,{className:"af-h-4 af-w-4","aria-hidden":!0})}),he("div",{className:"af-min-w-0 af-flex-1",children:[Y("div",{className:"af-text-xs af-text-muted-foreground",children:s}),Y("div",{className:W("af-truncate af-text-sm",r&&"af-font-mono"),children:n}),i&&Y("div",{className:"af-text-xs af-text-muted-foreground",children:i})]}),l,u&&he(y,{size:"sm",variant:c?"secondary":"outline","aria-expanded":o?c:void 0,onClick:u.onClick,children:[u.label,o&&Y(Lv,{className:W("af-ml-1 af-h-3.5 af-w-3.5 af-transition-transform",c&&"af-rotate-180"),"aria-hidden":!0})]})]}),c&&o&&Y("div",{className:"af-border-t af-bg-background af-p-4",children:o})]})}function Ln({tone:e,children:t}){return Y("span",{className:W("af-inline-flex af-shrink-0 af-items-center af-rounded-full af-px-2 af-py-0.5 af-text-xs af-font-medium",e==="green"&&"af-bg-green-100 af-text-green-800",e==="amber"&&"af-bg-amber-100 af-text-amber-900",e==="gray"&&"af-bg-muted af-text-muted-foreground",e==="red"&&"af-bg-red-100 af-text-red-800"),children:t})}function Wr(e){return e.domain.status==="verified"&&e.domain.dmarc_status==="ok"}function Dl(e){let{sending_domain:t,status:a}=e.domain;return!t||a==="none"?Y(Ln,{tone:"gray",children:"Not set up"}):a==="verified"?Wr(e)?Y(Ln,{tone:"green",children:"Live"}):Y(Ln,{tone:"amber",children:"DMARC record missing"}):a==="failed"?Y(Ln,{tone:"red",children:"Records not found"}):Y(Ln,{tone:"amber",children:"Waiting for DNS"})}function jv({settings:e,businessName:t,onSaved:a}){let{canWrite:s}=Ke(),[n,r]=Hs.useState(e.business_name??t??""),[i,l]=Hs.useState(e.postal_address??""),[u,c]=Hs.useState(e.reply_to??""),o=vt();return he("form",{className:"af-space-y-3",onSubmit:async f=>{f.preventDefault(),(await o.run("updateSettings",{business_name:n.trim()||null,postal_address:i.trim()||null,reply_to:u.trim()||null,double_opt_in:e.double_opt_in})).ok&&await a()},children:[Y(qv,{name:n,address:i}),he("label",{className:"af-block af-space-y-1",children:[Y("span",{className:"af-text-sm af-font-medium",children:"Sender name"}),Y(ae,{"aria-label":"Business name",value:n,disabled:!s,onChange:f=>r(f.target.value)})]}),he("label",{className:"af-block af-space-y-1",children:[Y("span",{className:"af-text-sm af-font-medium",children:"Mailing address"}),Y("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:i,disabled:!s,onChange:f=>l(f.target.value)}),Y("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Anti-spam law requires it at the bottom of every email. A PO box works."})]}),he("label",{className:"af-block af-space-y-1",children:[Y("span",{className:"af-text-sm af-font-medium",children:"Replies go to (optional)"}),Y(ae,{"aria-label":"Reply-to email",type:"email",value:u,disabled:!s,onChange:f=>c(f.target.value)}),Y("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Your account email or an address on your domain."})]}),o.error&&Y(ue,{tone:"error",children:o.error}),s&&Y(y,{type:"submit",size:"sm",disabled:o.busy||!i.trim(),children:"Save sender details"})]})}function qv({name:e,address:t}){return he("div",{className:"af-rounded-lg af-bg-muted/50 af-px-4 af-py-4 af-text-center af-text-xs af-leading-relaxed af-text-muted-foreground",children:[Y("div",{className:"af-mb-1 af-text-[10px] af-uppercase af-tracking-wide",children:"Footer of every email"}),he("div",{children:["\xA9 ",new Date().getFullYear()," ",Y("span",{className:"af-font-medium af-text-foreground",children:e.trim()||"Your business"})]}),Y("div",{className:W(!t.trim()&&"af-italic af-text-amber-700"),children:t.trim()||"No mailing address yet"}),he("div",{children:[Y("span",{className:"af-underline",children:"Manage preferences"})," | ",Y("span",{className:"af-underline",children:"Unsubscribe"})]})]})}var Wv={1:"From",2:"Subject and body",3:"Footer"};function bo({settings:e,site:t,className:a,numbered:s=!1,highlight:n=null,postalAddress:r}){let i=e?.business_name||t.businessName||"Your business",l=e?.domain.sending_domain??(t.siteDomain?`news.${t.siteDomain}`:"news.yourdomain.com"),u={backgroundColor:e?.brand.color??"hsl(var(--primary))"},c=r!==void 0?r.trim()||null:e?.postal_address,o=(f,b,g)=>s?he("div",{"data-preview-region":f,"data-highlighted":n===f,className:W("af-relative af-rounded-md af-pl-7 af-transition-shadow",n===f&&"af-ring-2 af-ring-primary af-ring-offset-2",b),children:[he("span",{className:"af-absolute af-left-0 af-top-0 af-flex af-h-5 af-w-5 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-[10px] af-font-semibold af-text-background",children:[Y("span",{"aria-hidden":!0,children:f}),he("span",{className:"af-sr-only",children:[f,". ",Wv[f],":"]})]}),g]}):Y("div",{className:b,children:g});return he("div",{className:W("af-rounded-lg af-border af-bg-background af-p-4 af-shadow-sm",a),"aria-hidden":s?void 0:!0,"aria-label":s?"Email preview":void 0,role:s?"group":void 0,children:[o(1,"af-flex af-items-start af-gap-3",he(go,{children:[Y("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-sm af-font-semibold af-text-white",style:u,children:i.slice(0,1).toUpperCase()}),he("div",{className:"af-min-w-0",children:[Y("div",{className:"af-truncate af-text-sm af-font-semibold",children:i}),he("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:["<",Il(l),">"]}),Y("div",{className:"af-text-xs af-text-muted-foreground",children:"to me"})]})]})),o(2,"af-mt-4 af-space-y-2",he(go,{children:[Y("div",{className:"af-text-sm af-font-medium",children:"What's new this month"}),Y("div",{className:"af-h-2 af-w-full af-rounded af-bg-muted"}),Y("div",{className:"af-h-2 af-w-5/6 af-rounded af-bg-muted"}),Y("div",{className:"af-h-2 af-w-2/3 af-rounded af-bg-muted"})]})),o(3,"af-mt-4 af-border-t af-pt-2 af-text-center af-text-[10px] af-leading-snug af-text-muted-foreground",he(go,{children:[Y("div",{children:c??Y("span",{className:"af-italic af-text-amber-700",children:"Mailing address goes here"})}),Y("div",{className:"af-underline",children:"Unsubscribe"})]}))]})}var Gv="Add a newsletter signup to my footer";function Kv({onAskAssistant:e}){let t=Ll();if(!t.data)return null;let{signups:a,optIns:s,others:n}=Bl(t.data);return he("div",{className:"af-space-y-3",children:[a.length===0?he("div",{className:"af-flex af-flex-col af-items-center af-gap-2 af-rounded-lg af-border af-border-dashed af-px-6 af-py-6 af-text-center",children:[Y("div",{className:"af-flex af-h-10 af-w-10 af-items-center af-justify-center af-rounded-full af-bg-muted",children:Y(vo,{className:"af-h-5 af-w-5","aria-hidden":!0})}),Y("div",{className:"af-text-sm af-font-medium",children:"Add a signup form to your site"}),Y("p",{className:"af-max-w-sm af-text-xs af-text-muted-foreground",children:`A short "Get our news" form, usually in the footer. It's how most of your list will find you.`}),e&&he(y,{type:"button",size:"sm",className:"af-mt-1",onClick:()=>e(Gv),children:[Y($v,{className:"af-mr-1.5 af-h-3.5 af-w-3.5","aria-hidden":!0}),"Add signup form"]})]}):he("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[Y(Nu,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),he("div",{className:"af-min-w-0 af-flex-1",children:[Y("span",{className:"af-font-medium",children:"Signup form is live"}),he("span",{className:"af-text-muted-foreground",children:[" \xB7 ",a.map(r=>r.name).join(", ")]})]})]}),s.length>0&&he("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[Y(Nu,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),he("div",{className:"af-min-w-0 af-flex-1",children:[Y("span",{className:"af-font-medium",children:"Opt-in checkbox"}),he("span",{className:"af-text-muted-foreground",children:[" \xB7 ",s.map(r=>r.name).join(", ")]})]})]}),a.length===0&&n.length>0&&he("p",{className:"af-px-2 af-text-xs af-text-muted-foreground",children:["Your ",n.length===1?"form":"forms"," ",n.map(r=>`"${r.name}"`).join(", "),' can also add people, with a "Send me news" checkbox.',e&&he(go,{children:[" ",Y("button",{type:"button",className:"af-font-medium af-text-foreground af-underline af-underline-offset-2",onClick:()=>e(Fl(n)),children:"Add the checkbox"})]})]})]})}import{Fragment as sb,jsx as fe,jsxs as Gt}from"react/jsx-runtime";var ho="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 Yv(e){let{status:t,dmarc_status:a,sending_domain:s}=e.domain;return!s||t==="none"?"No sending domain yet.":t==="verified"?a==="ok"?`Verified. Emails send from ${s}.`:`${s} is verified, but your domain still needs a DMARC record.`:t==="failed"?`${s} couldn't be verified. Check the DNS records below.`:`Waiting for the DNS records on ${s} to take effect. This can take a few hours.`}function Ml({onStartDomainSetup:e,onAskAssistant:t,dnsManaged:a,renderSendingRecords:s}){let{settings:n,refetchSettings:r,canWrite:i,settingsSection:l,onOpenBrandSettings:u}=Ke(),[c,o]=Ka.useState(null),[f,b]=Ka.useState(null),[g,m]=Ka.useState(""),v=n!==null;if(Ka.useEffect(()=>{v&&l&&document.getElementById(Hr(l))?.scrollIntoView?.({block:"start"})},[v,l]),!n)return fe(G,{className:"af-h-40 af-w-full"});let d=C=>b(w=>w===C?null:C),p=()=>b(null),x=async()=>{await r(),p()},S=(C,w,P)=>({id:P,"data-settings-row":C,onMouseEnter:()=>o(w),onMouseLeave:()=>o(null),onFocus:()=>o(w),onBlur:()=>o(null)}),k=Wr(n),{sending_domain:h,status:N}=n.domain,R=C=>i?{expanded:f===C}:{};return fe("div",{className:"af-@container",children:Gt("div",{className:"af-grid af-items-start af-gap-6 @2xl:af-grid-cols-[minmax(0,17rem)_minmax(0,1fr)]",children:[Gt("aside",{className:"af-space-y-3 af-pl-3",children:[fe("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails look like this"}),fe(bo,{settings:n,site:{},numbered:!0,highlight:c,postalAddress:f==="address"?g:void 0}),fe(ab,{settings:n})]}),Gt("div",{children:[fe(_a,{children:"From"}),Gt("div",{className:"af-space-y-2",children:[fe("div",{...S("Sending domain",1,Hr("domain")),children:fe(Bn,{markerSpace:!0,label:"Sending from",value:h?Il(h):"No sending domain yet",status:Dl(n),action:!k&&i?{label:h?N==="verified"||N==="failed"?"Fix":"Details":"Set up",onClick:()=>d("domain")}:void 0,...R("domain"),children:fe(Ol,{settings:n,canWrite:i,onStartDomainSetup:e,onChanged:r,dnsManaged:a,renderSendingRecords:s})})}),fe("div",{...S("Sender name and replies",1),children:fe(Bn,{marker:1,label:"Sender name and replies",mono:!1,value:`${n.business_name??"No sender name"} \xB7 replies to ${n.reply_to??"your account email"}`,action:i?{label:"Edit",onClick:()=>d("sender")}:void 0,...R("sender"),children:fe(Jv,{settings:n,onSaved:x,onCancel:p})})})]}),fe(_a,{children:"Brand"}),fe("div",{...S("Logo",2),children:fe(Bn,{marker:2,label:"Logo",mono:!1,value:n.brand.logo_url?"Your logo, from Brand settings":"No logo yet",hint:"Emails use your site's logo. Colors come from the email's template.",action:u?{label:"Brand settings",onClick:u}:void 0})}),fe(_a,{children:"Footer"}),fe("div",{...S("Mailing address",3,Hr("sender")),children:fe(Bn,{marker:3,label:"Mailing address",mono:!1,value:n.postal_address??"Not set",hint:"Anti-spam law requires it at the bottom of every email. A PO box works.",status:n.postal_address?void 0:fe(Ln,{tone:"amber",children:"Needed"}),action:i?{label:n.postal_address?"Edit":"Add",onClick:()=>{m(n.postal_address??""),d("address")}}:void 0,...R("address"),children:fe(Xv,{settings:n,draft:g,onDraft:m,onSaved:x,onCancel:p})})}),Gt("div",{id:Hr("signups"),children:[fe(_a,{children:"Who gets it"}),Gt("div",{className:"af-space-y-2",children:[fe("div",{...S("Double opt-in",null),children:fe(Qv,{settings:n,canWrite:i,onSaved:r})}),fe(nb,{onAskAssistant:i?t:void 0})]})]})]})]})})}function $l(e,t){return{business_name:e.business_name,postal_address:e.postal_address,reply_to:e.reply_to,double_opt_in:e.double_opt_in,...t}}function Tu({busy:e,error:t,canSave:a=!0,onSave:s,onCancel:n,children:r}){return Gt("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),await s()},children:[r,t&&fe(ue,{tone:"error",children:t}),Gt("div",{className:"af-flex af-gap-2",children:[fe(y,{type:"submit",size:"sm",disabled:e||!a,children:"Save"}),fe(y,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Cancel"})]})]})}function Jv({settings:e,onSaved:t,onCancel:a}){let[s,n]=Ka.useState(e.business_name??""),[r,i]=Ka.useState(e.reply_to??""),l=vt();return Gt(Tu,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",$l(e,{business_name:s.trim()||null,reply_to:r.trim()||null}))).ok&&await t()},children:[fe(Pu,{label:"Sender name",children:fe(ae,{"aria-label":"Business name",value:s,onChange:u=>n(u.target.value)})}),fe(Pu,{label:"Replies go to (your account email or an address on your domain)",children:fe(ae,{"aria-label":"Reply-to email",type:"email",value:r,onChange:u=>i(u.target.value)})})]})}function Xv({settings:e,draft:t,onDraft:a,onSaved:s,onCancel:n}){let r=vt();return fe(Tu,{busy:r.busy,error:r.error,canSave:!!t.trim(),onCancel:n,onSave:async()=>{(await r.run("updateSettings",$l(e,{postal_address:t.trim()}))).ok&&await s()},children:fe("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:t,onChange:i=>a(i.target.value)})})}function Qv({settings:e,canWrite:t,onSaved:a}){let[s,n]=Ka.useState(null),[r,i]=Ka.useState(!1),l=vt(),u=s??e.double_opt_in;return Gt("div",{className:"af-space-y-2",children:[fe(Bn,{icon:Cu,label:"Double opt-in",mono:!1,value:u?"New subscribers confirm by email first":"New subscribers join straight away",status:Gt("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[fe("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:ho,className:"af-inline-flex af-h-4 af-w-4 af-cursor-help af-items-center af-justify-center af-rounded-full af-border af-text-[10px]",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:"?"}),fe("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!r,className:"af-absolute af-right-0 af-top-6 af-z-10 af-w-72 af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:ho}),fe("input",{"aria-label":"Double opt-in",type:"checkbox",role:"switch",checked:u,disabled:!t||l.busy,onChange:async c=>{let o=c.target.checked;n(o),(await l.run("updateSettings",$l(e,{double_opt_in:o}))).ok&&await a(),n(null)}})]})}),l.error&&fe(ue,{tone:"error",children:l.error})]})}function Ol({settings:e,canWrite:t,onStartDomainSetup:a,onChanged:s,dnsManaged:n,renderSendingRecords:r}){let[i,l]=Ka.useState(null),[u,c]=Ka.useState(!1),[o,f]=Ka.useState(null),[b,g]=Ka.useState(0),m=Wr(e),{sending_domain:v,status:d}=e.domain,x=i?.status==="managed"||i?.status==="external"?i?.status==="managed":!!n,S=i?.records??[],k=x&&v&&!m&&d!=="verified"?fe(eb,{failed:d==="failed"}):null;return Gt("div",{children:[k??fe("p",{className:"af-text-sm",children:Yv(e)}),!m&&a&&fe(y,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||u,onClick:async()=>{c(!0),f(null);try{l(await a()),g(h=>h+1),await s()}catch(h){f(h instanceof Error?h.message:"Couldn't start domain setup.")}finally{c(!1)}},children:v?"Check domain setup":"Set up sending domain"}),o&&fe(ue,{tone:"error",className:"af-mt-2",children:o}),r?(v||i)&&fe("div",{className:"af-mt-3",children:r()},b):S.length>0&&Gt("div",{className:"af-mt-3 af-space-y-1",children:[fe("p",{className:"af-text-sm",children:x?"The records we added to your DNS:":"Add these records at your domain provider:"}),Gt("table",{className:"af-w-full af-text-left af-text-xs",children:[fe("thead",{children:Gt("tr",{children:[fe("th",{className:"af-py-1 af-pr-2",children:"Type"}),fe("th",{className:"af-py-1 af-pr-2",children:"Name"}),fe("th",{className:"af-py-1 af-pr-2",children:"Value"}),fe("th",{className:"af-py-1",children:"Priority"})]})}),fe("tbody",{children:S.map((h,N)=>Gt("tr",{className:"af-border-t af-align-top",children:[fe("td",{className:"af-py-1 af-pr-2",children:h.type}),fe("td",{className:"af-break-all af-py-1 af-pr-2",children:h.name}),fe("td",{className:"af-break-all af-py-1 af-pr-2",children:h.value}),fe("td",{className:"af-py-1",children:h.priority??""})]},N))})]})]}),i&&!k&&fe(tb,{result:i})]})}function eb({failed:e}){return e?Gt(ue,{tone:"warning",children:[fe("div",{className:"af-font-medium",children:"Verification is taking longer than usual. Nothing for you to change."}),fe("div",{children:"We added the records and will keep checking. If it isn't live within a day, contact support and we'll sort it out."})]}):fe(ue,{tone:"success",children:Gt("div",{className:"af-flex af-gap-2",children:[fe(Cu,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0","aria-hidden":!0}),Gt("div",{children:[fe("div",{className:"af-font-medium",children:"We added these records to your DNS for you. Nothing to do."}),fe("div",{children:"Verification usually finishes within a few hours."})]})]})})}function tb({result:e}){return e.status==="no_domain"?fe(ue,{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"?fe(ue,{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:fe("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 ab({settings:e}){let{monthly:t,sent:a,reserved:s}=e.allowance,n=a+s;return Gt("p",{className:"af-text-xs af-text-muted-foreground",children:[Ae(n)," of ",Ae(t)," emails used this month (",Ae(Math.max(0,t-n))," left). Receipts and form notifications don't count."]})}function Ll(){let{api:e}=H(),{siteId:t,refreshKey:a}=Ke();return Lt(async()=>Promise.all((await e.getForms()).map(s=>e.getForm(s.id))),`${t}|${a}`,t)}function Bl(e){return{signups:e.filter(t=>t.purpose==="newsletter"),optIns:e.filter(t=>t.purpose==="opt_in"),others:e.filter(t=>t.purpose!=="newsletter"&&t.purpose!=="opt_in")}}function Fl(e){let t=e.length===1;return`Add a "Send me news" opt-in checkbox to ${t?"the":"these"} ${e.map(a=>a.name).join(" and ")} form${t?"":"s"}`}function nb({onAskAssistant:e}){let t=Ll();if(!t.data||t.data.length===0)return null;let{signups:a,optIns:s,others:n}=Bl(t.data),r=[{id:"signup",label:"Signup forms",note:"Submitting one subscribes the visitor.",forms:a,icon:ku},{id:"opt_in",label:'Forms with a "Send me news" checkbox',note:"Visitors who tick the box join your list.",forms:s,icon:ku},{id:"other",label:"Other forms",note:"These don't add anyone to your list.",forms:n,icon:Zv,action:a.length===0&&e?{label:"Add the checkbox",onClick:()=>e(Fl(n))}:void 0}];return fe(sb,{children:r.filter(i=>i.forms.length>0).map(i=>fe("div",{"data-form-group":i.id,children:fe(Bn,{icon:i.icon,label:i.label,mono:!1,value:i.forms.map(l=>l.name).join(", "),hint:i.note,action:i.action})},i.id))})}function Pu({label:e,children:t}){return Gt("label",{className:"af-block af-space-y-1",children:[fe("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}import*as yo from"react";import{jsx as ma,jsxs as zs}from"react/jsx-runtime";function Iu({templateId:e,onOpenTemplate:t,onOpenDraft:a,onAskAssistant:s}){let{api:n}=H(),{siteId:r,canWrite:i,refreshKey:l}=Ke(),[u,c]=yo.useState(0),o=u+l,f=Lt(()=>n.getEmailTemplates(r),`${r}|${o}`,r),b=yo.useCallback(()=>c(d=>d+1),[]),g=i?s:void 0;if(e){let d=e===Jn?null:f.data?.find(p=>p.id===e);if(d!==void 0)return ma(gu,{template:d,onBack:()=>t(null),onOpenTemplate:t,onOpenDraft:a,onAskAssistant:g,reload:b,refreshKey:o},e);if(f.isLoading)return ma(G,{className:"af-h-96 af-w-full"})}let m=f.data?.filter(d=>d.status!=="archived")??[],v=f.data?.filter(d=>d.status==="archived")??[];return zs("div",{children:[zs("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[ma("h3",{className:"af-text-sm af-font-semibold",children:"Templates"}),g&&ma(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(co.create),children:"\u2728 New template with the editor"})]}),zs(Eu,{children:[ma(Ul,{template:null,onOpen:()=>t(Jn)}),m.map(d=>ma(Ul,{template:d,onOpen:()=>t(d.id)},d.id))]}),f.error&&!f.data?ma("div",{className:"af-mt-3",children:ma(xt,{message:"Couldn't load your templates.",onRetry:()=>void f.refetch()})}):!f.data&&ma(G,{className:"af-mt-3 af-h-10 af-w-full"}),v.length>0&&zs("div",{"data-testid":"archived-templates",children:[ma(_a,{children:"Archived"}),ma(Eu,{children:v.map(d=>ma(Ul,{template:d,onOpen:()=>t(d.id)},d.id))})]})]})}function Eu({children:e}){return ma("ul",{className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:e})}function rb(e){let t=[Pl(e.usage.drafts),e.usage.scheduled>0&&`${e.usage.scheduled} scheduled`,e.usage.sent>0&&`${e.usage.sent} sent`].filter(Boolean);return t.length>0?t.join(" \xB7 "):null}function Ul({template:e,onOpen:t}){let a=e?.name??"Standard",s=e&&rb(e);return zs("li",{"data-testid":"template-card",className:"af-relative af-overflow-hidden af-rounded-md af-border hover:af-border-primary",children:[ma(uo,{templateId:e?.id??Jn,version:e?.updated_at??"builtin",className:"af-h-40 af-border-b",frame:{width:600,height:400,scale:.4}}),zs("div",{className:"af-space-y-1 af-p-2",children:[zs("div",{className:"af-flex af-items-center af-gap-2",children:[ma("span",{"data-testid":"template-name",className:"af-grow af-truncate af-text-sm af-font-medium",children:a}),ma(kl,{template:e})]}),s&&ma("p",{className:"af-text-xs af-text-muted-foreground",children:s})]}),ma("button",{type:"button","aria-label":`Open ${a}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}import*as dn from"react";import{ChevronRight as jl}from"lucide-react";import*as Za from"react";import{ArrowDown as ib,ArrowUp as ob,Clock as Ou,Mail as Lu,Plus as lb,Trash2 as cb,Zap as db}from"lucide-react";import{Fragment as zl,jsx as _e,jsxs as Ht}from"react/jsx-runtime";var ub=365*24,fb=[1,24,48,72,168];function wo(e){return e.map(t=>t.type==="send"?{type:"send",draft_id:t.draft_id}:{type:"wait",wait_hours:t.wait_hours})}function _s(e){return e%168===0?Ms(e/168,"week"):e%24===0?Ms(e/24,"day"):Ms(e,"hour")}var Kr={joined_list:{title:"Someone joins your list",phrase:"joins your list"},purchase_made:{title:"Someone buys from your store",phrase:"buys from your store"},abandoned_checkout:{title:"Someone leaves checkout without paying",phrase:"leaves checkout without paying"}};function Zr(e,t){return e.slice(0,t+1).filter(a=>a.type==="send").length}var xo=300,Au=64,mb=24,Gr={trigger:72,send:104,wait:64,waitEditing:196,exit:44};function pb(e,t){let a=[],s=0,n=r=>{a.push({...r,y:s}),s+=r.height+Au};return n({id:"trigger",kind:"trigger",height:Gr.trigger}),e.forEach((r,i)=>n({id:r.step_key,kind:r.type,index:i,height:r.type==="send"?Gr.send:r.step_key===t?Gr.waitEditing:Gr.wait})),n({id:"exit",kind:"exit",height:Gr.exit}),{nodes:a,height:s-Au}}var Bu=Za.createContext(null);function Yr(){let e=Za.useContext(Bu);if(!e)throw new Error("Canvas nodes render inside AutomationCanvas");return e}function Vl(e,t){let a=e[t];return a.type==="send"?`email ${Zr(e,t)}`:`the ${_s(a.wait_hours)} wait`}function Fu(e){let{automation:t,onChangeSteps:a}=e,s=t.steps,[n,r]=Za.useState(null),[i,l]=Za.useState(null),[u,c]=Za.useState(null),o=(m,v)=>{c(null),r(null),l(null),a(m,v)},f=wo(s),b={...e,insertAt:n,setInsertAt:m=>{c(null),r(m)},editingWait:i,setEditingWait:l,insertWait:m=>{if(!f.slice(m).some(v=>v.type==="send")){r(null),c("A wait after the last email does nothing, so it wasn't added.");return}o([...f.slice(0,m),{type:"wait",wait_hours:24},...f.slice(m)],"Add a 1 day wait")},setWait:(m,v)=>o(f.map((d,p)=>p===m?{type:"wait",wait_hours:v}:d),`Change ${Vl(s,m)} to ${_s(v)}`),move:(m,v)=>{let d=[...f];[d[m],d[m+v]]=[d[m+v],d[m]],o(d,`Move ${Vl(s,m)} ${v<0?"up":"down"}`)},remove:m=>o(f.filter((v,d)=>d!==m),`Remove ${Vl(s,m)}`)},g=pb(s,i);return Ht(Bu.Provider,{value:b,children:[u&&_e(ue,{className:"af-mb-2",children:u}),_e("div",{"data-testid":"automation-canvas",className:"af-rounded-md af-border af-bg-muted/40",style:{height:g.height+2*mb},children:_e(Za.Suspense,{fallback:_e(G,{className:"af-h-full af-w-full"}),children:_e(gb,{layout:g,steps:s})})})]})}var gb=Za.lazy(async()=>({default:vb(await import("@xyflow/react"))}));function vb(e){let t=l=>[{type:"target",position:e.Position.Top,x:xo/2,y:0,width:1,height:1},{type:"source",position:e.Position.Bottom,x:xo/2,y:l,width:1,height:1}],a=()=>Ht(zl,{children:[_e(e.Handle,{type:"target",position:e.Position.Top,isConnectable:!1,className:"!af-opacity-0"}),_e(e.Handle,{type:"source",position:e.Position.Bottom,isConnectable:!1,className:"!af-opacity-0"})]}),s=l=>Ht(zl,{children:[l,_e(a,{})]}),n={trigger:()=>s(_e(Du,{kind:"trigger"})),send:({data:l})=>s(_e(bb,{index:l.index,step:l.step})),wait:({data:l})=>s(_e(hb,{index:l.index,step:l.step})),exit:()=>s(_e(Du,{kind:"exit"}))};function r({id:l,sourceX:u,sourceY:c,targetX:o,targetY:f,data:b}){let[g,m,v]=e.getStraightPath({sourceX:u,sourceY:c,targetX:o,targetY:f});return Ht(zl,{children:[_e(e.BaseEdge,{id:l,path:g}),_e(e.EdgeLabelRenderer,{children:_e("div",{className:"nodrag nopan af-pointer-events-auto af-absolute",style:{transform:`translate(-50%, -50%) translate(${m}px, ${v}px)`},children:_e(xb,{index:b.insertAt})})})]})}let i={insert:r};return function({layout:u,steps:c}){let o=u.nodes.map(b=>({id:b.id,type:b.kind,position:{x:0,y:b.y},width:xo,height:b.height,style:{width:xo,height:b.height,pointerEvents:"all"},handles:t(b.height),data:"index"in b?{index:b.index,step:c[b.index]}:{index:-1,step:null},draggable:!1,selectable:!1,connectable:!1,focusable:!1})),f=u.nodes.slice(1).map((b,g)=>({id:`${u.nodes[g].id}->${b.id}`,source:u.nodes[g].id,target:b.id,type:"insert",data:{insertAt:g},selectable:!1,focusable:!1}));return _e(e.ReactFlow,{nodes:o,edges:f,nodeTypes:n,edgeTypes:i,proOptions:{hideAttribution:!0},fitView:!0,fitViewOptions:{padding:.05,maxZoom:1,minZoom:.5},minZoom:.5,maxZoom:1,nodesDraggable:!1,nodesConnectable:!1,nodesFocusable:!1,edgesFocusable:!1,elementsSelectable:!1,panOnDrag:!1,panOnScroll:!1,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,preventScrolling:!1,deleteKeyCode:null,selectionKeyCode:null,multiSelectionKeyCode:null})}}function Du({kind:e}){let{automation:t}=Yr();return e==="exit"?_e("div",{"data-testid":"canvas-exit",className:"af-flex af-h-full af-items-center af-justify-center af-rounded-full af-border af-bg-background af-text-xs af-text-muted-foreground",children:"Exit: they leave the automation"}):Ht("div",{"data-testid":"canvas-trigger",className:"af-flex af-h-full af-items-center af-gap-3 af-rounded-md af-border af-border-primary/40 af-bg-background af-px-3",children:[_e(db,{className:"af-h-4 af-w-4 af-shrink-0"}),Ht("div",{className:"af-min-w-0",children:[_e("div",{className:"af-text-xs af-text-muted-foreground",children:"Trigger"}),_e("div",{className:"af-truncate af-text-sm af-font-medium",children:Kr[t.trigger_type].title})]})]})}function Mu({index:e,label:t}){let{automation:a,editable:s,move:n,remove:r}=Yr();if(!s)return null;let i=a.steps.length-1;return Ht("div",{className:"af-flex af-shrink-0 af-gap-0.5",children:[_e(Hl,{label:`Move ${t} up`,disabled:e===0,onClick:()=>n(e,-1),children:_e(ob,{})}),_e(Hl,{label:`Move ${t} down`,disabled:e===i,onClick:()=>n(e,1),children:_e(ib,{})}),_e(Hl,{label:`Remove ${t}`,onClick:()=>r(e),children:_e(cb,{})})]})}function Hl({label:e,disabled:t,onClick:a,children:s}){return _e(y,{type:"button",variant:"ghost",size:"icon",className:"nodrag af-h-7 af-w-7","aria-label":e,title:e,disabled:t,onClick:a,children:s})}function bb({index:e,step:t}){let{automation:a,statsByStep:s,onOpenEmail:n}=Yr(),r=Zr(a.steps,e),i=s[t.step_key];return Ht("div",{"data-testid":"canvas-email",className:"af-flex af-h-full af-flex-col af-justify-between af-rounded-md af-border af-bg-background af-p-3",children:[Ht("div",{className:"af-flex af-items-start af-gap-2",children:[_e(Lu,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0"}),Ht("button",{type:"button",className:"nodrag af-min-w-0 af-grow af-text-left hover:af-underline","aria-label":`Open email ${r}`,onClick:()=>n(t.draft_id),children:[Ht("div",{className:"af-text-xs af-text-muted-foreground",children:["Email ",r]}),_e("div",{className:"af-truncate af-text-sm af-font-medium",children:t.subject||"(no subject)"})]}),a.status==="on"&&t.live&&_e(ee,{variant:"success",children:"Live"}),_e(Mu,{index:e,label:`email ${r}`})]}),_e("p",{"data-testid":"canvas-email-stats",className:"af-text-xs af-text-muted-foreground",children:i?`Sent ${Ae(i.sent)} \xB7 Opened ${Ae(i.opened)} \xB7 Clicked ${Ae(i.clicked)}`:"Not sent yet"})]})}function hb({index:e,step:t}){let{editable:a,editingWait:s,setEditingWait:n,setWait:r}=Yr(),i=`the ${_s(t.wait_hours)} wait`,l=a&&s===t.step_key;return Ht("div",{"data-testid":"canvas-wait",className:"af-flex af-h-full af-flex-col af-gap-2 af-rounded-md af-border af-border-dashed af-bg-background af-px-3 af-py-2",children:[Ht("div",{className:"af-flex af-items-center af-gap-2",children:[_e(Ou,{className:"af-h-4 af-w-4 af-shrink-0"}),a?Ht("button",{type:"button",className:"nodrag af-grow af-text-left af-text-sm hover:af-underline","aria-expanded":l,onClick:()=>n(l?null:t.step_key),children:["Wait ",_s(t.wait_hours)]}):Ht("span",{className:"af-grow af-text-sm",children:["Wait ",_s(t.wait_hours)]}),_e(Mu,{index:e,label:i})]}),l&&_e(yb,{hours:t.wait_hours,onSave:u=>r(e,u),onCancel:()=>n(null)})]})}function yb({hours:e,onSave:t,onCancel:a}){let s=e%24===0,[n,r]=Za.useState(String(s?e/24:e)),[i,l]=Za.useState(s?"days":"hours"),u=Number(n)*(i==="days"?24:1),c=Number.isInteger(u)&&u>=1&&u<=ub;return Ht("div",{"data-testid":"wait-editor",className:"nodrag af-space-y-2",children:[_e("div",{className:"af-flex af-flex-wrap af-gap-1",children:fb.map(o=>_e(y,{type:"button",size:"sm",variant:o===e?"default":"outline",className:"af-h-7 af-px-2",onClick:()=>t(o),children:_s(o)},o))}),Ht("form",{className:"af-flex af-items-center af-gap-1",onSubmit:o=>{o.preventDefault(),c&&t(u)},children:[_e(ae,{"aria-label":"Custom wait",type:"number",min:1,value:n,onChange:o=>r(o.target.value),className:"af-h-7 af-w-20"}),Ht("select",{"aria-label":"Wait unit",value:i,onChange:o=>l(o.target.value),className:"af-h-7 af-rounded-md af-border af-bg-background af-px-1 af-text-sm",children:[_e("option",{value:"hours",children:"hours"}),_e("option",{value:"days",children:"days"})]}),_e(y,{type:"submit",size:"sm",className:"af-h-7 af-px-2",disabled:!c,children:"Save"}),_e(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:a,children:"Cancel"})]}),!c&&_e("p",{className:"af-text-xs af-text-destructive",children:"A wait is 1 hour to 365 days."})]})}function xb({index:e}){let{editable:t,insertAt:a,setInsertAt:s,insertWait:n,onInsertEmail:r}=Yr();if(!t)return null;let i=a===e;return Ht("div",{className:"af-flex af-items-center af-gap-1",children:[_e("button",{type:"button","aria-label":e===0?"Add a step after the trigger":`Add a step after step ${e}`,"aria-expanded":i,onClick:()=>s(i?null:e),className:W("af-flex af-h-6 af-w-6 af-items-center af-justify-center af-rounded-full af-border af-bg-background af-shadow-sm hover:af-border-primary",i&&"af-border-primary"),children:_e(lb,{className:"af-h-3.5 af-w-3.5"})}),i&&Ht("div",{"data-testid":"insert-menu",className:"af-flex af-gap-1 af-rounded-md af-border af-bg-background af-p-1 af-shadow-md",children:[Ht(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:()=>n(e),children:[_e(Ou,{})," Wait"]}),Ht(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:()=>{s(null),r(e)},children:[_e(Lu,{})," Email"]})]})]})}import{Fragment as js,jsx as ge,jsxs as at}from"react/jsx-runtime";var wb="Create an automation that ",Sb={welcome:{title:"Welcome email",trigger:"joined_list",description:"Greets each new subscriber as soon as they join your list.",emails:1},post_purchase:{title:"Thank you for your order",trigger:"purchase_made",description:"Thanks each buyer a day after their order.",emails:1},recovery:{title:"Abandoned cart recovery",trigger:"abandoned_checkout",description:"Reminds shoppers who left checkout, an hour later and again a day later, with their cart.",emails:2}};function $u({automation:e}){let[t,a]=e.status==="on"?e.available?["success","On"]:["warning","Unavailable"]:["secondary",e.status==="draft"?"Draft":"Off"];return ge(ee,{"data-testid":"automation-state",variant:t,children:a})}function Nb(e,t,a){switch(e){case"trigger_unavailable":return"This site can't use this trigger any more.";case"checkout_consent_off":return"Abandoned checkout needs the marketing consent box at checkout, which is off.";case"no_send_steps":return"Add an email before turning this automation on.";case"email_empty":{let s=t&&a?t.steps.findIndex(n=>n.step_key===a):-1;return s>=0?`Email ${Zr(t.steps,s)} needs a subject and some content.`:"Every email needs a subject and some content."}case"postal_address_missing":return"Add your business postal address before an automation can send.";case"version_conflict":return"This automation changed since you loaded it. Here is the latest version; check it, then try again.";default:return Ns(e)??"Something went wrong. Try again."}}function ql(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.step_key=="string"?t.step_key:typeof t.details?.step_key=="string"?t.details.step_key:null}function Jr({code:e,automation:t,stepKey:a,onOpenEmail:s}){let{openSettings:n,openSetup:r,onOpenStoreSettings:i}=Ke(),l=t&&a?t.steps.find(c=>c.step_key===a):void 0,u=null;return e==="postal_address_missing"?u=ge(fa,{onClick:()=>n("sender"),children:"Add it in Settings"}):e==="checkout_consent_off"&&i?u=ge(fa,{onClick:i,children:"Open Store settings"}):e==="email_empty"&&l?.type==="send"&&s?u=ge(fa,{onClick:()=>s(l.draft_id),children:"Open the email"}):e==="domain_not_verified"||e==="dmarc_missing"?u=ge(fa,{onClick:()=>n("domain"),children:"Fix in Settings"}):e==="sending_not_enabled"&&(u=ge(fa,{onClick:r,children:"Finish setup"})),at(js,{children:[Nb(e,t,a),u&&at(js,{children:[" ",u]})]})}function Uu({automationId:e,onOpenAutomation:t,list:a,onAskAssistant:s,onPickImage:n}){let{canWrite:r}=Ke(),i=r?s:void 0;if(e){let l=a.data?.automations.find(u=>u.id===e);if(l)return ge(kb,{automation:l,reload:a.refetch,onBack:()=>t(null),onAskAssistant:i,onPickImage:n},l.id);if(!a.data&&!a.error)return ge(G,{className:"af-h-96 af-w-full"})}return at("div",{children:[at("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[ge("h3",{className:"af-text-sm af-font-semibold",children:"Automations"}),i&&ge(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i(wb),children:"\u2728 New automation with the editor"})]}),a.error&&!a.data?ge(xt,{message:"Couldn't load your automations.",onRetry:()=>void a.refetch()}):a.data?at(js,{children:[a.data.capabilities.suggestions.length>0&&at(js,{children:[ge(_a,{children:"Suggested"}),ge("ul",{"data-testid":"automation-suggestions",className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:a.data.capabilities.suggestions.map(l=>ge(_b,{suggestion:l,list:a.data,reload:a.refetch,onOpenAutomation:t},l))})]}),ge(_a,{children:"Your automations"}),a.data.automations.length===0?ge(ca,{children:"No automations yet. Turn on a suggestion above, or ask the editor to build one."}):ge("ul",{"data-testid":"automations",className:"af-divide-y af-rounded-md af-border",children:a.data.automations.map(l=>ge(Rb,{automation:l,onOpen:()=>t(l.id)},l.id))})]}):ge(G,{className:"af-h-24 af-w-full"})]})}function Vu(e){return[Kr[e.trigger_type].title,...e.steps.map(t=>t.type==="send"?"Email":`Wait ${_s(t.wait_hours)}`)].join(" \u2192 ")}function Hu(e){let{api:t}=H(),{siteId:a,refreshKey:s}=Ke(),n=e.status==="draft",r=Lt(()=>n?Promise.resolve([]):t.getAutomationStats(a,e.id),`${a}|${e.id}|${e.version}|${e.status}|${s}`,`${a}|${e.id}`);return dn.useMemo(()=>Object.fromEntries((r.data??[]).map(i=>[i.step_key,i])),[r.data])}function Rb({automation:e,onOpen:t}){let a=Object.values(Hu(e)),s=n=>Ae(a.reduce((r,i)=>r+i[n],0));return at("li",{"data-testid":"automation-row",className:"af-relative af-flex af-items-center af-gap-3 af-px-3 af-py-2 hover:af-bg-muted/40",children:[at("div",{className:"af-min-w-0 af-grow af-space-y-0.5",children:[at("div",{className:"af-flex af-items-center af-gap-2",children:[ge("span",{className:"af-truncate af-text-sm af-font-medium",children:e.name}),ge($u,{automation:e})]}),ge("p",{"data-testid":"automation-chain",className:"af-truncate af-text-xs af-text-muted-foreground",children:Vu(e)}),a.length>0&&at("p",{"data-testid":"automation-stats",className:"af-text-xs af-text-muted-foreground",children:["Sent ",s("sent")," \xB7 Opened ",s("opened")," \xB7 Clicked ",s("clicked")]})]}),ge(jl,{className:"af-h-4 af-w-4 af-shrink-0 af-text-muted-foreground"}),ge("button",{type:"button","aria-label":`Open ${e.name}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}function _b({suggestion:e,list:t,reload:a,onOpenAutomation:s}){let{api:n}=H(),{siteId:r,canWrite:i,onOpenStoreSettings:l}=Ke(),u=vt(),[c,o]=dn.useState(!1),[f,b]=dn.useState(null),g=Sb[e],m=t.automations.find(x=>x.trigger_type===g.trigger&&x.list_tag_id===null),v=e==="recovery"&&t.capabilities.checkout_consent==="off_available",d=async()=>{o(!1),b(null);let x=await u.run("addSuggestedAutomation",{key:e}),S=x.ok?x.result:null;if(!x.ok){let h=Ga(x.error,"automation_exists")?x.error:null,N=h?.automation_id??h?.details?.automation_id;if(!N)return;if(u.setError(null),S=await n.getAutomation(r,N).catch(()=>null),!S)return void a()}let k=await u.run("turnOnAutomation",{automationId:S.id,expected_version:S.version});k.ok||(u.setError(null),b({code:Rs(k.error),stepKey:ql(k.error)})),await a()},p=()=>m?ge("p",{className:"af-text-sm",children:ge(fa,{onClick:()=>s(m.id),children:"Open the automation"})}):i?c?at("div",{className:"af-space-y-2",children:[at("p",{className:"af-text-sm",children:['Turn on "',g.title,'"? It sends ',Ms(g.emails,"email")," to each person who ",Kr[g.trigger].phrase,"."]}),at("div",{className:"af-flex af-gap-2",children:[ge(y,{type:"button",variant:"outline",size:"sm",onClick:()=>o(!1),children:"Cancel"}),ge(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:u.busy,onClick:()=>void d(),children:"Turn on"})]})]}):v?at("div",{className:"af-space-y-1",children:[ge("p",{className:"af-text-xs af-text-muted-foreground",children:"Needs the marketing consent box at checkout, in Store settings."}),ge(y,{type:"button",size:"sm",disabled:!l,onClick:()=>l?.(),children:"Turn on"})]}):ge("div",{children:ge(y,{type:"button",size:"sm",disabled:u.busy,onClick:()=>o(!0),children:"Turn on"})}):null;return at("li",{"data-testid":"suggestion-card",className:"af-flex af-flex-col af-gap-2 af-rounded-md af-border af-p-3",children:[at("div",{className:"af-flex af-items-center af-gap-2",children:[ge("span",{"data-testid":"suggestion-title",className:"af-grow af-text-sm af-font-medium",children:g.title}),m&&ge(ee,{variant:"secondary",children:"Added"})]}),ge("p",{className:"af-text-xs af-text-muted-foreground",children:g.description}),f&&at(ue,{tone:"warning",children:["Not turned on. ",ge(Jr,{code:f.code,automation:m,stepKey:f.stepKey})]}),u.error&&ge(ue,{tone:"error",children:u.error}),p()]})}var So={on:{message:(e,t)=>`Turn on "${e.name}"? It sends ${Ms(t,"email")} to each person who ${Kr[e.trigger_type].phrase}. Changes you save after this go out to the next people who reach each step.`,action:"turnOnAutomation",label:"Turn on",variant:"default"},off:{message:e=>`Turn off "${e.name}"? Nobody new enters it and no new emails start. Emails already queued still go out.`,action:"turnOffAutomation",label:"Turn off",variant:"default"},delete:{message:e=>`Delete "${e.name}" and its emails?`,action:"deleteAutomation",label:"Delete",variant:"destructive"}};function kb({automation:e,reload:t,onBack:a,onAskAssistant:s,onPickImage:n}){let{api:r}=H(),{siteId:i,canWrite:l}=Ke(),u=Hu(e),c=vt(),o=vt(),f=vt(),[b,g]=dn.useState(null),[m,v]=dn.useState(null),[d,p]=dn.useState(null),[x,S]=dn.useState(null),[k,h]=dn.useState(null),[N,R]=dn.useState(!1),C=e.status==="on",w=e.steps.filter(T=>T.type==="send").length,P=async T=>{R(!0);try{await T()}finally{R(!1)}},I=(T,V)=>P(async()=>{p(null),S(null);let A=await c.run("updateAutomation",{automationId:e.id,expected_version:e.version,steps:T});if(!A.ok){let ne=Rs(A.error);ne==="version_conflict"?(c.setError(null),p(V)):(ne==="email_empty"||ne==="postal_address_missing")&&(c.setError(null),S({code:ne,stepKey:ql(A.error)}))}await t()}),_=T=>P(async()=>{let V=await c.run("createDraft",{kind:"automation",automation_id:e.id,subject:"",blocks:[]});if(!V.ok)return;let A=V.result.id;if(C)return h({draftId:A,joinAt:T});let ne=wo(e.steps);await I([...ne.slice(0,T),{type:"send",draft_id:A},...ne.slice(T)],"Add an email")}),q=dn.useRef(Promise.resolve()),j=T=>{let V=q.current.then(async()=>{let A=await r.getEmailDraft(i,T.draftId).catch(()=>null);if(!A||!A.subject.trim()||A.blocks.length===0)return;let ne=await r.getAutomation(i,e.id).catch(()=>null);if(!ne)return;if(ne.steps.some(Ee=>Ee.type==="send"&&Ee.draft_id===T.draftId))return h({draftId:T.draftId});let re=wo(ne.steps),Me=Math.min(T.joinAt,re.length);(await f.run("updateAutomation",{automationId:e.id,expected_version:ne.version,steps:[...re.slice(0,Me),{type:"send",draft_id:T.draftId},...re.slice(Me)]})).ok&&h({draftId:T.draftId}),await t()});return q.current=V.catch(()=>{}),V},U=async T=>{g(null),v(null);let V=T==="turnOnAutomation"?{automationId:e.id,expected_version:e.version}:{automationId:e.id},A=await o.run(T,V);!A.ok&&T==="turnOnAutomation"&&(o.setError(null),v({code:Rs(A.error),stepKey:ql(A.error)})),A.ok&&T==="deleteAutomation"&&a(),await t()},te=T=>at("nav",{"aria-label":"Breadcrumb",className:"af-mb-3 af-flex af-flex-wrap af-items-center af-gap-1.5 af-text-sm af-text-muted-foreground",children:[ge(fa,{onClick:a,children:"Automations"}),ge(jl,{className:"af-h-3.5 af-w-3.5"}),T===void 0?ge("span",{className:"af-font-medium af-text-foreground",children:e.name}):at(js,{children:[ge(fa,{onClick:()=>h(null),children:e.name}),ge(jl,{className:"af-h-3.5 af-w-3.5"}),ge("span",{className:"af-font-medium af-text-foreground",children:T})]})]});if(k){let T=e.steps.findIndex(A=>A.type==="send"&&A.draft_id===k.draftId),V=k.joinAt!==void 0;return at("div",{children:[te(T>=0?`Email ${Zr(e.steps,T)}`:"New email"),ge(po,{draftId:k.draftId,allowCart:e.trigger_type==="abandoned_checkout",automationStep:{live:C&&!V,joinsOnSave:C&&V,notice:f.error&&at(ue,{tone:"error",children:["Couldn't add this email to the automation. ",f.error]}),onBackToCanvas:()=>h(null)},onSaved:()=>{k.joinAt!==void 0?j({draftId:k.draftId,joinAt:k.joinAt}):t()},onAskAssistant:s,onPickImage:n},k.draftId)]})}let ce=e.blocked_by[0]??null,me=C&&!e.available;return at("div",{className:"af-space-y-3",children:[te(),at("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ge("h3",{"data-testid":"automation-title",className:"af-grow af-truncate af-text-base af-font-semibold",children:e.name}),ge($u,{automation:e}),l&&!b&&ge(js,{children:C?ge(y,{type:"button",variant:"outline",size:"sm",disabled:o.busy,onClick:()=>g("off"),children:"Turn off"}):at(js,{children:[ge(y,{type:"button",variant:"ghost",size:"sm",disabled:o.busy,onClick:()=>g("delete"),children:"Delete"}),ge(y,{type:"button",size:"sm",disabled:o.busy,onClick:()=>g("on"),children:"Turn on"})]})})]}),ge("p",{className:"af-text-xs af-text-muted-foreground",children:Vu(e)}),b&&at("div",{"data-testid":"automation-confirm",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[ge("p",{className:"af-text-sm",children:So[b].message(e,w)}),at("div",{className:"af-flex af-gap-2",children:[ge(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(null),children:"Cancel"}),ge(y,{type:"button",size:"sm",variant:So[b].variant,className:"af-ml-auto",disabled:o.busy,onClick:()=>void U(So[b].action),children:So[b].label})]})]}),m&&at(ue,{tone:"warning",children:[ge("span",{className:"af-font-medium",children:"Not turned on."})," ",ge(Jr,{code:m.code,automation:e,stepKey:m.stepKey,onOpenEmail:T=>h({draftId:T})})]}),o.error&&ge(ue,{tone:"error",children:o.error}),me?at(ue,{tone:"warning",children:[ge("span",{className:"af-font-medium",children:"Unavailable."})," ",ge(Jr,{code:ce??"trigger_unavailable",automation:e})," Nobody new enters it; people already in it still get their remaining emails."]}):ce&&!m&&at(ue,{tone:"warning",children:[C?"Not sending right now.":"Won't send yet."," ",ge(Jr,{code:ce,automation:e})]}),C&&!me&&at(ue,{tone:"success",children:[ge("span",{className:"af-font-medium",children:"Live."})," Changes you make here, and saves to its emails, go out to the next people who reach each step."]}),d&&at(ue,{tone:"warning",children:["This automation changed while you were editing, so your change wasn't saved: ",ge("span",{className:"af-font-medium",children:d}),". Here is the latest version; make the change again if you still want it."]}),x&&at(ue,{tone:"warning",children:["Not saved. ",ge(Jr,{code:x.code,automation:e,stepKey:x.stepKey,onOpenEmail:T=>h({draftId:T})})]}),c.error&&ge(ue,{tone:"error",children:c.error}),ge(Fu,{automation:e,statsByStep:u,editable:l&&!c.busy&&!N,onChangeSteps:(T,V)=>void I(T,V),onInsertEmail:T=>void _(T),onOpenEmail:T=>h({draftId:T})})]})}import{Fragment as Ob,jsx as bt,jsxs as Xr}from"react/jsx-runtime";var Pb=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"automations",label:"Automations"},{id:"templates",label:"Templates"},{id:"settings",label:"Settings"}];function Xn(e,t={}){return{tab:e,draftId:null,templateId:null,automationId:null,...t}}var zu=e=>!!(e.tab||e.draftId||e.templateId||e.automationId);function ju(e){return e.draftId?Xn("broadcasts"):e.templateId?Xn("templates",{templateId:e.templateId}):e.automationId?Xn("automations",{automationId:e.automationId}):Xn(e.tab==="template"?"templates":e.tab??"audience")}var Cb={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function qu(e){return bt(Tb,{...e},e.siteId)}function Tb({siteId:e,isOwnerSide:t,needsPaidPlan:a,initialDraftId:s,initialTab:n,initialAutomationId:r,templateId:i,showViewNonce:l,onOrgAction:u,onRequestReview:c,onStartDomainSetup:o,dnsManaged:f,renderSendingRecords:b,onBackToWebsite:g,onUpgradePlan:m,onConnectDomain:v,onAskAssistant:d,onPickImage:p,onTurnOn:x,siteDomain:S,businessName:k,onOpenStoreSettings:h,onOpenBrandSettings:N,refreshKey:R=0,className:C}){let{api:w}=H(),P=Lt(()=>w.getMarketingSettings(e),`${e}|${R}`,e),I=Lt(()=>w.getAutomations(e),`${e}|${R}`,e),_={tab:n,draftId:s,templateId:i,automationId:r},[q,j]=ea.useState(()=>ju(_)),[U,te]=ea.useState(s??null),[ce,me]=ea.useState(zu(_)),[T,V]=ea.useState(null),[A,ne]=ea.useState(!1),re=ea.useCallback(()=>me(!1),[]),Me=ea.useCallback(se=>{j(Xn("settings")),V(se??null)},[]),Se=se=>{j(Xn(se)),V(null)},Ee=ea.useCallback(se=>j(Xn("broadcasts",{draftId:se})),[]),Ye=ea.useCallback(se=>j(Xn("templates",{templateId:se})),[]),ke=ea.useCallback(se=>j(Xn("automations",{automationId:se})),[]),nt=!ce&&P.data!==null&&Eb(P.data),E=q.tab,M=P.data&&!P.error?Ib(P.data):null,L=JSON.stringify([l??null,n??null,s??null,i??null,r??null]),pe=ea.useRef(L);ea.useEffect(()=>{if(L===pe.current||A)return;pe.current=L;let se={tab:n,draftId:s,templateId:i,automationId:r};zu(se)&&(j(ju(se)),te(se.draftId??null),V(null),me(!0))},[L,A,n,s,i,r]),ea.useEffect(()=>{if(!U||a)return;let se=!0,Fe=Qe=>{se&&(j(Xn("broadcasts",{draftId:Qe})),te(null))};return w.getEmailDraft(e,U).then(Qe=>Fe(Qe.kind==="broadcast"?Qe.id:null),()=>Fe(null)),()=>{se=!1}},[w,e,U,a]);let J=ea.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:u,settings:P.data,refetchSettings:P.refetch,refreshKey:R,openSetup:re,openSettings:Me,settingsSection:T,onOpenStoreSettings:h,onOpenBrandSettings:N,setInlineEditOpen:ne}),[e,t,u,P.data,P.refetch,R,re,Me,T,h,N]);return a?bt(Ut,{title:"Email Marketing",onBackToWebsite:g,className:C,children:bt(Al,{settings:P.data,site:{siteDomain:S,businessName:k},children:bt(_u,{onUpgradePlan:m})})}):bt(Ut,{title:"Email Marketing",onBackToWebsite:g,className:C,children:bt(bl.Provider,{value:J,children:nt?bt(Ru,{onStartDomainSetup:o,dnsManaged:f,renderSendingRecords:b,onConnectDomain:v,onAskAssistant:d,onTurnOn:x,siteDomain:S,businessName:k}):Xr(Ob,{children:[P.error&&!P.data&&bt(xt,{message:"Couldn't load email settings.",onRetry:()=>void P.refetch()}),M&&bt(Db,{reason:M,pauseReason:P.data?.paused.reason??null,onRequestReview:c}),!t&&bt(ue,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),bt("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:Pb.map(se=>Xr("button",{type:"button",role:"tab","aria-selected":E===se.id,onClick:()=>Se(se.id),className:W("af-border-b-2 af-px-3 af-py-2 af-text-sm",E===se.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:[se.label,se.id==="settings"&&M&&bt("span",{"data-testid":"settings-dot",role:"img","aria-label":"Sending is on hold",className:"af-ml-1.5 af-inline-block af-h-1.5 af-w-1.5 af-rounded-full af-bg-amber-600 af-align-middle"})]},se.id))}),bt("div",{role:"tabpanel",children:U?bt(G,{className:"af-h-24 af-w-full"}):E==="audience"?bt(iu,{}):E==="broadcasts"?bt(wu,{openDraftId:q.draftId,onOpenDraft:Ee,onAskAssistant:d,onPickImage:p}):E==="automations"?bt(Uu,{automationId:q.automationId,onOpenAutomation:ke,list:I,onAskAssistant:d,onPickImage:p}):E==="templates"?bt(Iu,{templateId:q.templateId,onOpenTemplate:Ye,onOpenDraft:Ee,onAskAssistant:d}):bt(Ml,{onStartDomainSetup:o,onAskAssistant:d,dnsManaged:f,renderSendingRecords:b})})]})})})}function Eb(e){return!e.paused.paused_at&&!e.readiness.can_send&&Ur.has(e.readiness.reason??"")}function Ib(e){if(e.paused.paused_at)return"paused";let t=e.readiness.reason;return!e.readiness.can_send&&t&&Ur.has(t)?t:null}var Ab={domain_not_verified:"domain",dmarc_missing:"domain",postal_address_missing:"sender"};function Db({reason:e,pauseReason:t,onRequestReview:a}){let{openSetup:s,openSettings:n}=Ke(),[r,i]=ea.useState("idle");if(e==="paused")return bt("div",{"data-testid":"email-hold",className:"af-mb-3",children:Xr(ue,{tone:"warning",children:[bt("div",{className:"af-font-medium",children:"Sending is paused."}),Xr("p",{children:[Cb[t??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),a&&(r==="sent"?bt("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):bt(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{i("sending");try{await a(),i("sent")}catch{i("failed")}},children:"Request review"})),r==="failed"&&bt("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]})});let l=Ab[e];return bt("div",{"data-testid":"email-hold",className:"af-mb-3",children:Xr(ue,{tone:"warning",children:["Sending is on hold. ",Ns(e)," ",l?bt(fa,{onClick:()=>n(l),children:"Fix in Settings"}):bt(fa,{onClick:s,children:"Finish setup"})]})})}import*as ia from"react";var Lb=2e3,ya=()=>({data:null,error:null,isLoading:!0});function wr(e,{refreshKey:t,breakdowns:a=[],filters:s=[]}={}){let{api:n}=H(),[r,i]=ia.useState(ya),[l,u]=ia.useState(ya),[c,o]=ia.useState(ya),[f,b]=ia.useState(ya),[g,m]=ia.useState(ya),v=T=>Object.fromEntries(T.map(V=>[V,ya()])),[d,p]=ia.useState(()=>v(a)),x=ia.useRef(0),S=ia.useRef(0),k=ia.useRef("idle"),h=a.join(","),N=us()??"",R=JSON.stringify(s),C=`${e}:${h}:${R}:${N}`,[w,P]=ia.useState({api:n,fetchIdentity:C});(w.api!==n||w.fetchIdentity!==C)&&(P({api:n,fetchIdentity:C}),x.current+=1,i(ya),u(ya),o(ya),b(ya),p(v(h?h.split(","):[])));let I=`${e}:${String(t??"")}:${N}`,[_,q]=ia.useState({api:n,conversionsIdentity:I});(_.api!==n||_.conversionsIdentity!==I)&&(q({api:n,conversionsIdentity:I}),S.current+=1,k.current="idle",m(ya));let j=ia.useCallback(async T=>{let V=++x.current,A=h?h.split(","):[];i(ya),u(ya),o(ya),b(ya),p(Object.fromEntries(A.map(E=>[E,ya()])));let ne=k.current!=="pending"&&(T?.force===!0||k.current==="idle"),re=(E,M)=>M.then(L=>{V===x.current&&E({data:L,error:null,isLoading:!1})},L=>{V===x.current&&E({data:null,error:L instanceof Error?L:new Error("Failed to fetch report"),isLoading:!1})}),Me=n.getAnalyticsStatus(),Se=re(i,Me),Ee=Symbol("status-timeout"),Ye,ke=await Promise.race([Me.then(E=>E,()=>null),new Promise(E=>{Ye=setTimeout(()=>E(Ee),Lb)})]);if(clearTimeout(Ye),V!==x.current)return;if(ke===Ee&&i({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),ke!==null&&ke!==Ee&&(ke.collecting!==!0||ke.first_seen===null&&!ke.first_seen_unavailable||ke.first_seen!==null&&ke.first_seen_in_reports===!1)){let E={data:null,error:null,isLoading:!1};u(E),o(E),b(E),p(Object.fromEntries(A.map(M=>[M,{...E}]))),ne&&(m(E),k.current="done"),await Se;return}await Promise.all([ke===Ee?Promise.resolve():Se,re(u,n.getAnalyticsSummary(e,s)),re(o,n.getAnalyticsTimeseries(e,s)),re(b,n.getAnalyticsChannels(e,s)),ne?(()=>{k.current="pending";let E=++S.current;return m(ya),n.getAnalyticsConversions(e).then(M=>{E===S.current&&(m({data:M,error:null,isLoading:!1}),k.current="done")},M=>{E===S.current&&(m({data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}),k.current="done")})})():Promise.resolve(),...A.map(E=>n.getAnalyticsBreakdown(E,e,s).then(M=>{V===x.current&&p(L=>({...L,[E]:{data:M,error:null,isLoading:!1}}))},M=>{V===x.current&&p(L=>({...L,[E]:{data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,R,I,N]),U=ia.useCallback(async()=>{let T=x.current;try{let V=await n.getAnalyticsStatus();if(T!==x.current)return;i({data:V,error:null,isLoading:!1})}catch(V){if(T!==x.current)return;i(A=>({data:A.data,error:V instanceof Error?V:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),te=ia.useCallback(()=>j({force:!0}),[j]);ia.useEffect(()=>{j()},[j,t]);let ce=r.isLoading||l.isLoading||c.isLoading||f.isLoading||g.isLoading||Object.values(d).some(T=>T.isLoading),me=[c,l,f,g,...Object.values(d)].map(T=>T.data?.status==="ok"?T.data.timezone:void 0).find(T=>T!==void 0);return{status:r,summary:l,timeseries:c,channels:f,conversions:g,breakdowns:d,reportedZone:me,isLoading:ce,refetch:te,refetchStatus:U}}import*as oa from"react";var Wl=3e4,Gl=3;function No(e={}){let t="collecting"in e,{collecting:a,statusFailed:s=!1,identity:n}=e,{api:r}=H(),[i,l]=oa.useState(null),[u,c]=oa.useState(null),[o,f]=oa.useState(!1),[b,g]=oa.useState(null),[m,v]=oa.useState(!1),[d,p]=oa.useState(!0),[x,S]=oa.useState(0),k=oa.useRef(0),h=oa.useRef(0),N=oa.useRef(void 0);a!==void 0&&(N.current=a);let R=t?N.current===!0||N.current===void 0&&s:!0,[C,w]=oa.useState({api:r,identity:n}),P=n!==void 0&&n!==C.identity;(C.api!==r||P)&&(N.current=void 0,w({api:r,identity:n}),h.current+=1,k.current=0,l(null),c(null),f(!1),g(null),v(!1),p(!0),S(0));let I=oa.useRef(()=>{}),_=oa.useRef(null),q=oa.useCallback(async()=>{if(_.current!==null&&_.current===h.current)return;let j=++h.current;_.current=j;try{let U=await r.getAnalyticsRealtime();if(j!==h.current)return;if(U.status==="unreachable"){v(!0),f(!0),p(!1),S(te=>te+1);return}k.current=0,v(!1),l(U.data.current_visitors),c(U.as_of),f(!1),g(null),p(!1),S(te=>te+1)}catch(U){if(j!==h.current)return;k.current+=1,p(!1),S(te=>te+1),f(!0),k.current>=Gl&&g(U instanceof Error?U:new Error("Realtime unavailable"))}finally{_.current===j&&(_.current=null)}},[r]);return I.current=()=>void q(),oa.useEffect(()=>{let j,U=()=>{j===void 0&&(j=setInterval(()=>I.current(),Wl))},te=()=>{j!==void 0&&(clearInterval(j),j=void 0)},ce=()=>{typeof document<"u"&&document.hidden?te():(I.current(),U())};return R?((typeof document>"u"||!document.hidden)&&(I.current(),U()),document?.addEventListener("visibilitychange",ce),()=>{te(),document?.removeEventListener("visibilitychange",ce),h.current+=1}):()=>{document?.removeEventListener("visibilitychange",ce)}},[C.api,C.identity,R]),{currentVisitors:i,asOf:u,isStale:o,error:b,isUnreachable:m,isInitialLoad:d,polls:x}}import*as Ft from"react";import*as Gu from"react";import{jsx as Kl,jsxs as Wu}from"react/jsx-runtime";function Bb(){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 Zl({value:e,chosen:t,onChange:a}){let s=Rr(),n=t===null&&s!==null&&e===s,r=Gu.useMemo(()=>{let i=Bb();return i.includes(e)?i:[e,...i]},[e]);return Wu("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[Kl("span",{className:"af-sr-only",children:"Reporting timezone"}),Wu("select",{value:n?"":e,onChange:i=>a(i.target.value===""?null:i.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[Kl("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(i=>Kl("option",{value:i,children:i.replace(/_/g," ")},i))]})]})}var Ro=(e,{published:t}={})=>{let a=t===!1,s=e!=null&&(!e.collecting||a&&e.first_seen===null&&!e.first_seen_unavailable),n=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,i=n||r;return{notCollecting:s,awaitingFirstVisit:n,firstVisitTooRecent:r,holdingForFirstData:i,nothingToReport:s||i}};import*as Qr from"react";var Fb=3e4;function _o({status:e,holdingForFirstData:t,refetchStatus:a,refetch:s}){Qr.useEffect(()=>{if(!t)return;let r,i=()=>{r===void 0&&(r=setInterval(()=>void a(),Fb))},l=()=>{r!==void 0&&(clearInterval(r),r=void 0)},u=()=>{typeof document<"u"&&document.hidden?l():(a(),i())};return(typeof document>"u"||!document.hidden)&&i(),document?.addEventListener("visibilitychange",u),()=>{l(),document?.removeEventListener("visibilitychange",u)}},[t,a]);let n=Qr.useRef(void 0);Qr.useEffect(()=>{if(!e){n.current=void 0;return}let r=n.current;n.current=t,r===!0&&!t&&s()},[e,t,s])}import*as Ws from"react";var Mb=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Aa(e){let t=Math.abs(e);if(t<1e3)return String(e);let a=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[s,n]of a)if(t>=s){let r=e/s,i=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(i)>=1e3&&s!==1e9?Aa(i*s):`${i}${n}`}return String(e)}function Sr(e){return`${(e*100).toFixed(1)}%`}function ei(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let a=Math.floor(t/60);return a<60?`${a}m ${t%60}s`:`${Math.floor(a/60)}h ${a%60}m`}function Zu(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`:ei(t)}function Yu(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Ju(e,t){if(!(!Number.isFinite(e)||e<=0))for(let a of t){let s=Math.ceil(e/a);if(s<=5)return Array.from({length:s+1},(n,r)=>Number((r*a).toPrecision(12)))}}function ti(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Xu(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 Yl(e){let t=Number(e.slice(5,7)),a=Number(e.slice(8,10));return`${Mb[t-1]} ${a}`}function Ku(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function $b(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Qu(e,t,a="UTC"){let s=new Map(t.map(i=>[i.date,i])),n=[],r=Ku(e.to,a);for(let i=Ku(e.from,a);i<r;i=$b(i))n.push(s.get(i)??{date:i,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function ef(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=new Date(`${e}T00:00:00Z`);if(Number.isNaN(s.getTime()))return e;let n=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${n} ${a[s.getUTCMonth()]}`}import{Fragment as Vb,jsx as ks,jsxs as Ub}from"react/jsx-runtime";function tf({what:e="This report",onRetry:t,collecting:a}){return Ub("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:[ks("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),ks("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:a===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),t?ks("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 ko({what:e="No data"}){return ks("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 ds({sourced:e,error:t,isLoading:a,what:s,onRetry:n,collecting:r,children:i}){return a?ks("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?ks(tf,{what:s,onRetry:n,collecting:r}):!e||e.status==="unreachable"?ks(tf,{what:s,onRetry:n,collecting:r}):ks(Vb,{children:i(e.data)})}import{Fragment as Hb,jsx as Ya,jsxs as qs}from"react/jsx-runtime";function Jl({rows:e,dimension:t,metric:a,metricLabel:s,secondary:n,emptyCopy:r="No data for this period",onFilter:i,canFilter:l,maxRows:u=9}){let[c,o]=Ws.useState(!1);if(e.length===0)return Ya(ko,{what:r});let f=e.reduce((m,v)=>Math.max(m,Number(v[a]??0)),0)||1,b=Math.max(0,e.length-u),g=c?e:e.slice(0,u);return qs(Hb,{children:[qs("table",{className:"af-w-full af-text-sm",children:[Ya("thead",{children:qs("tr",{className:"af-text-xs af-text-muted-foreground",children:[Ya("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),Ya("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),Ya("tbody",{children:g.map((m,v)=>{let d=Number(m[a]??0),p=m[t]??null,x=ti(p),S=n?m[n]:null,k=p!==null&&(l?l(p,S):!0);return qs("tr",{className:"af-border-t af-border-border",children:[qs("td",{className:"af-relative af-py-1.5 af-pr-2",children:[Ya("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,d/f*100)}%`}}),p!==null&&i&&k?Ya("button",{type:"button",onClick:()=>i(p,S),title:`Filter by ${x}`,"aria-label":`Filter by ${x}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:x}):Ya("span",{className:"af-relative af-break-words af-text-foreground",children:x}),S?Ya("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:S}):null]}),Ya("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Aa(d)})]},`${x}-${S??""}-${v}`)})})]}),b>0?Ya("button",{type:"button",onClick:()=>o(m=>!m),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:c?"Show fewer":`Show all ${e.length}`}):null]})}function ai({title:e,tabs:t,defaultTabId:a,headerRight:s}){let[n,r]=Ws.useState(a),i=t.find(g=>g.id===n)??t[0],l=Ws.useId(),u=g=>`${l}-tab-${g}`,c=g=>`${l}-panel-${g}`,o=Ws.useRef(null),f=(g,m)=>{g.preventDefault();let v=(m+t.length)%t.length;r(t[v].id),o.current?.querySelectorAll('[role="tab"]')?.[v]?.focus()};return qs("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[qs("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:[Ya("div",{ref:o,role:"tablist","aria-label":e,onKeyDown:g=>{let m=t.findIndex(v=>v.id===n);g.key==="ArrowRight"&&f(g,m+1),g.key==="ArrowLeft"&&f(g,m-1),g.key==="Home"&&f(g,0),g.key==="End"&&f(g,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(g=>Ya("button",{id:u(g.id),role:"tab",type:"button","aria-selected":g.id===n,"aria-controls":c(g.id),tabIndex:g.id===n?0:-1,onClick:()=>r(g.id),className:g.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:g.label},g.id))}),s]}),i?Ya("div",{id:c(i.id),role:"tabpanel","aria-labelledby":u(i.id),tabIndex:0,className:"af-px-3 af-py-2",children:i.render()},i.id):null]})}import*as Ja from"react";import*as Ps from"@radix-ui/react-popover";var Gs=3,Ks=100;import{jsx as Kt,jsxs as Qn}from"react/jsx-runtime";var ni={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"},zb=Object.keys(ni);function af(e){let t=ni[e.dimension],a=e.operator==="is_not"?"is not":"is",s=e.values.map(n=>ti(n)).join(" or ");return`${t} ${a} ${s}`}function Xl(e,t){let a=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));if(a>=0){let s=[...new Set([...e[a].values,...t.values])];return s.length>Ks||s.length===e[a].values.length?e:e.map((n,r)=>r===a?{...n,values:s}:n)}return t.values.length>Ks||e.length>=Gs?e:[...e,t]}function jb(e,t){let a={};for(let[s,n]of Object.entries(t)){let r=e.get(s)??new Set;for(let i of n)r.add(i);e.set(s,r),a[s]=[...r]}return a}function nf(e,t){let a=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));return a>=0?e.map((s,n)=>n===a?t:s):t.values.length>Ks||e.length>=Gs?e:[...e,t]}function qb(e){return{dimension:e,operator:"is",search:"",picked:[]}}function sf(e,t,a,s={}){if(e.api!==t.api||e.period!==t.period)return e.api=t.api,e.period=t.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=jb(e.byDimension,a);for(let[r,i]of Object.entries(s)){let l=e.foldsByLabel.get(r)??new Set;for(let u of i)l.add(u);e.foldsByLabel.set(r,l)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([r,i])=>[r,[...i]]))}}function rf(e){let{filters:t,onChange:a}=e,s=t.length>=Gs;return Ja.useEffect(()=>{if(t.length===0)return;let n=r=>{let i=r.target;i&&(i.tagName==="INPUT"||i.closest('[role="dialog"]'))||r.key==="Escape"&&a([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[t.length,a]),Qn("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,r)=>Qn("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:[Kt("span",{className:"af-text-foreground",children:af(n)}),Kt("button",{type:"button","aria-label":`Remove filter ${af(n)}`,onClick:()=>a(t.filter((i,l)=>l!==r)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),Kt(Wb,{...e,disabled:s}),t.length>0?Kt("button",{type:"button",onClick:()=>a([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Wb({filters:e,onChange:t,suggestions:a,resetKey:s,disabled:n,expandValues:r}){let[i,l]=Ja.useState(!1),u=Ja.useRef(null),[c,o]=Ja.useState(null);Ja.useEffect(()=>{o(u.current?.closest(".aifeatures-admin")??null)},[]);let[f,b]=Ja.useState(null),[g,m]=Ja.useState("is"),[v,d]=Ja.useState(""),[p,x]=Ja.useState([]);Ja.useEffect(()=>{i||(b(null),m("is"),d(""),x([]))},[i]);let S=Ja.useRef(s);S.current!==s&&(S.current=s,i&&l(!1),f!==null&&b(null),p.length>0&&x([]),v!==""&&d(""),g!=="is"&&m("is"));let k=P=>{let I=qb(P);b(I.dimension),x(I.picked),d(I.search),m(I.operator)},N=(f?a[f]??[]:[]).filter(P=>P.toLowerCase().includes(v.trim().toLowerCase())),R=f===null||p.length===0?null:Xl(e,{dimension:f,operator:g,values:r?r(f,p):p}),C=R!==null&&R!==e,w=()=>{let P=R;!P||P===e||(t(P),l(!1))};return Qn(Ps.Root,{open:i,onOpenChange:l,children:[Kt(Ps.Trigger,{asChild:!0,children:Kt("button",{ref:u,type:"button",disabled:!1,title:n?`At most ${Gs} 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"})}),Kt(Ps.Portal,{container:c,children:Kt(Ps.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:f===null?Qn("div",{children:[Kt("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),Kt("div",{className:"af-max-h-96 af-overflow-y-auto",children:zb.filter(P=>a[P]!==void 0).map(P=>{let I=a[P]?.length??0,_=!e.some(q=>q.dimension===P)&&e.length>=Gs;return Qn("button",{type:"button",onClick:()=>k(P),disabled:I===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:[Kt("span",{children:ni[P]}),Kt("span",{className:"af-text-muted-foreground",children:I===0?"no data":_?"no room":I})]},P)})})]}):Qn("div",{children:[Qn("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Kt("button",{type:"button",onClick:()=>k(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),Kt("span",{className:"af-text-xs af-font-medium af-text-foreground",children:ni[f]}),Qn("select",{"aria-label":"Operator",value:g,onChange:P=>m(P.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:[Kt("option",{value:"is",children:"is"}),Kt("option",{value:"is_not",children:"is not"})]})]}),Kt("input",{type:"text",value:v,onChange:P=>d(P.target.value),placeholder:"Search\u2026","aria-label":`Search ${ni[f]}`,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"}),Kt("div",{className:"af-max-h-48 af-overflow-y-auto",children:N.length===0?Qn("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",v,"\u201D."]}):N.map(P=>Qn("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:[Kt("input",{type:"checkbox",checked:p.includes(P),disabled:!p.includes(P)&&p.length>=Ks,onChange:I=>x(_=>I.target.checked?[..._,P]:_.filter(q=>q!==P))}),Kt("span",{className:"af-break-all",children:ti(P)})]},P))}),Kt("button",{type:"button",onClick:w,disabled:!C,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:p.length<=1?"Apply filter":p.length>=Ks?`Apply filter (${p.length} values \u2014 the maximum)`:`Apply filter (${p.length} values)`})]})})})]})}import{Fragment as Zb,jsx as Da,jsxs as Po}from"react/jsx-runtime";var Gb=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Aa,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Aa,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Aa,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:Sr,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:ei,chart:"visit_duration_seconds"}];function Kb({current:e,previous:t,downIsGood:a}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let n=s>0,r=a?!n:n,i=`${n?"+":""}${(s*100).toFixed(1)}%`;return Da("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:i})}function of({summary:e,selected:t,onSelect:a}){return Da("div",{className:"af-@container",children:Da("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Gb.map(s=>{let n=s.chart===t,r=a!==void 0,i=Po(Zb,{children:[Da("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),Po("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Da("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?Da(Kb,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?Da("button",{type:"button","aria-pressed":n,onClick:()=>a(s.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:i},s.key):Da("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:i},s.key)})})})}function Ql({currentVisitors:e,asOf:t,isStale:a,isUnreachable:s,isInitialLoad:n=!1,scopeIsSiteWide:r=!1}){if(n&&!s)return Po("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:[Da("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Da("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return Da("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let i=t?Xu(t):"freshness unknown",l=r?" across the whole site, not the current filter,":"",u=a?`${e} current visitors${l} ${i} (not updating)`:`${e} current visitors${l} ${i}`;return Po("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:u,children:[Da("span",{"aria-hidden":"true",className:a?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),Da("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Da("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),Da("span",{className:"af-sr-only",children:u})]})}import*as cf from"react";import{Star as Yb}from"lucide-react";import{Fragment as lf,jsx as pa,jsxs as Zs}from"react/jsx-runtime";function Co(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function To({rows:e,denominator:t,windowPrecedesCollection:a=!1,coverageUnknown:s=!1,emptyCopy:n="No conversions in this period",maxRows:r=9,primaryConversion:i}){let[l,u]=cf.useState(!1),c=e.filter(d=>!d.implicit||d.visitors>0||d.events>0||Co(d,i)),o=a?pa("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?pa("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(c.length===0)return Zs(lf,{children:[pa(ko,{what:n}),o]});let f=c.slice(0,r),b=i?c.find(d=>Co(d,i)):void 0,g=b&&!f.includes(b)?c.filter(d=>f.includes(d)||d===b).slice(0,Math.max(0,r-1)).concat(b):f,m=l?e:g,v=Math.max(0,e.length-g.length);return Zs(lf,{children:[Zs("table",{className:"af-w-full af-text-sm",children:[pa("thead",{children:Zs("tr",{className:"af-text-xs af-text-muted-foreground",children:[pa("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),pa("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),pa("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),pa("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),pa("tbody",{children:m.map((d,p)=>Zs("tr",{className:"af-border-t af-border-border","aria-current":Co(d,i)?"true":void 0,children:[pa("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Co(d,i)?Zs("span",{className:"af-flex af-items-center af-gap-1.5",children:[pa(Yb,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),pa("span",{className:"af-font-medium af-text-foreground",children:d.goal}),pa("span",{className:"af-sr-only",children:"(your main conversion)"})]}):d.goal}),pa("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Aa(d.visitors)}),pa("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Aa(d.events)}),pa("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:d.conversion_rate===null?pa("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Sr(d.conversion_rate)})]},`${d.goal}-${p}`))})]}),v>0?pa("button",{type:"button",onClick:()=>u(d=>!d),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length} goals`}):null,Zs("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Aa(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),o]})}import{Area as Jb,AreaChart as Xb,CartesianGrid as Qb,ResponsiveContainer as eh,Tooltip as th,XAxis as ah,YAxis as nh}from"recharts";import{jsx as Oa,jsxs as si}from"react/jsx-runtime";var Eo={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},tc={visitors:Aa,visits:Aa,pageviews:Aa,views_per_visit:e=>e.toFixed(2),bounce_rate:Sr,visit_duration_seconds:ei},sh=31,rh=new Set(["visitors","visits","pageviews"]),ih={...tc,bounce_rate:Yu,visit_duration_seconds:Zu},ec=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],oh=[5,10,15,30,60,120,300,600,900,1800,3600,7200],lh=[.01,.02,.05,.1,.2,.25,.5,1],ch=[.25,.5,1,2,5,10,25,50],dh={visitors:ec,visits:ec,pageviews:ec,views_per_visit:ch,bounce_rate:lh,visit_duration_seconds:oh};function uh({active:e,payload:t,label:a,metric:s}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return si("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:[Oa("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Eo[s]}),si("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[Oa("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),Oa("span",{className:"af-text-muted-foreground",children:ef(String(a))}),Oa("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:tc[s](Number(n[s]??0))})]})]})}function Io({rows:e,window:t,metric:a,timeZone:s="UTC",height:n=260}){let r=Qu(t,e,s),i=tc[a],l=ih[a],u=Ju(r.reduce((o,f)=>Math.max(o,Number(f[a]??0)),0),dh[a]),c=`${Eo[a]} by day: ${r.map(o=>`${Yl(o.date)}: ${i(Number(o[a]??0))}`).join("; ")}.`;return si("figure",{"aria-label":`${Eo[a]} over time`,className:"af-m-0",children:[Oa(eh,{width:"100%",height:n,children:si(Xb,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[Oa("defs",{children:si("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[Oa("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),Oa("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),Oa(Qb,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Oa(ah,{dataKey:"date",tickFormatter:Yl,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Oa(nh,{allowDecimals:!rh.has(a),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...u?{ticks:u,domain:[0,u[u.length-1]]}:{},tickFormatter:o=>l(o),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Oa(th,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Oa(uh,{metric:a})}),Oa(Jb,{type:"linear",dataKey:a,name:Eo[a],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=sh?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),Oa("figcaption",{className:"af-sr-only",children:c})]})}import{Fragment as ac,jsx as Be,jsxs as Pa}from"react/jsx-runtime";var fh="2026-08-13",mh=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],ph=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function gh({filters:e,onFiltersChange:t,refreshKey:a,onBackToWebsite:s,primaryConversion:n,className:r,published:i,lastPublishedAt:l}){let[u,c]=Ft.useState(30),[o,f]=Ft.useState(()=>Bo()),b=e!==void 0&&t!==void 0,[g,m]=Ft.useState(e??[]),{api:v}=H(),[d,p]=Ft.useState(v);d!==v&&(p(v),!b&&g.length>0&&m([]));let x=b?e:g,S=Ft.useCallback(L=>{t&&t(L),b||m(L)},[t,b]),k=Ft.useCallback((L,pe,J)=>{let se=Array.isArray(pe)?pe:[pe];if(se.length===0)return null;let Fe=Xl(x,{dimension:L,operator:"is",values:se});if(J&&(!J.value||(Fe=nf(Fe,{dimension:J.dimension,operator:"is",values:[J.value]}),!Fe.find(Et=>Et.dimension===J.dimension&&Et.operator!=="is_not")?.values.includes(J.value))))return null;let Qe=Fe.find(Xe=>Xe.dimension===L&&Xe.operator!=="is_not");return se.every(Xe=>Qe?.values.includes(Xe))?JSON.stringify(Fe)===JSON.stringify(x)?null:Fe:null},[x]),h=Ft.useCallback((L,pe,J)=>k(L,pe,J)!==null,[k]),N=Ft.useCallback((L,pe,J)=>{let se=k(L,pe,J);se&&S(se)},[k,S]),[R,C]=Ft.useState("visitors"),w=wr(u,{refreshKey:a,breakdowns:ph,filters:x}),P=w.status.data,I=w.reportedZone??P?.timezone,_=I??o??Rr()??"UTC",{notCollecting:q,awaitingFirstVisit:j,firstVisitTooRecent:U,holdingForFirstData:te}=Ro(P,{published:i}),ce=i===!1,me=No({collecting:j||q?!1:P?.collecting,statusFailed:w.status.error!=null,identity:P?.analytics_id}),T=Ft.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),V=Ft.useMemo(()=>{let L=w.breakdowns.sources?.data,pe={};if(!L||L.status!=="ok")return pe;for(let J of L.data){let se=J.source,Fe=J.sources;typeof se=="string"&&Array.isArray(Fe)&&Fe.length>0&&(pe[se]=Fe)}return pe},[w.breakdowns.sources?.data]),A=Ft.useMemo(()=>{let L=(se,Fe)=>{let Qe=w.breakdowns[se]?.data;return!Qe||Qe.status!=="ok"?[]:[...new Set(Qe.data.map(Xe=>Xe[Fe]).filter(Xe=>typeof Xe=="string"&&Xe!==""))]};return{channel:w.channels.data?.status==="ok"?[...new Set(w.channels.data.data.map(se=>se.channel))]:[],source:L("sources","source"),campaign:L("utm/campaign","campaign"),page:L("pages","pathname"),entry_page:L("entry-pages","pathname"),exit_page:L("exit-pages","pathname"),country:L("countries","country"),browser:L("browsers","browser"),os:L("operating-systems","os"),device:L("devices","device")}},[w.breakdowns,w.channels.data]),[ne,re]=Ft.useState({}),Me=JSON.stringify(A),[Se,Ee]=Ft.useState(new Map),Ye=JSON.stringify(V);Ft.useEffect(()=>{let{suggestions:L,folds:pe}=sf(T.current,{api:v,period:u},JSON.parse(Me),JSON.parse(Ye));re(L),Ee(pe)},[Me,Ye,v,u]);let ke=Ft.useCallback((L,pe)=>L!=="source"?pe:[...new Set(pe.flatMap(J=>{let se=[...Se.get(J)??[],...V[J]??[]];return se.length>0?se:[J]}))],[Se,V]),nt=Ft.useMemo(()=>{let L=w.conversions.error;return L instanceof aa&&L.details?.code==="goals_exceed_report_budget"?L.message:null},[w.conversions.error]),E=Ft.useMemo(()=>{let L=[w.summary,w.timeseries,w.channels,...Object.values(w.breakdowns)];for(let pe of L){let J=pe?.error;if(J instanceof aa&&J.details?.code==="filter_unsupported")return J.message}return null},[w.summary,w.timeseries,w.channels,w.breakdowns]),M=(L,pe,J,se,Fe,Qe,Xe,Et,be)=>()=>{let $e=w.breakdowns[L];return Be(ds,{sourced:$e?.data??null,error:$e?.error,isLoading:$e?.isLoading,what:pe,collecting:P?.collecting,onRetry:w.refetch,children:yt=>{let It=Mt=>Et?ke(Et,[Mt]):Mt;return Be(Jl,{rows:yt,dimension:J,metric:se,metricLabel:Fe,secondary:Qe,emptyCopy:x.length>0?"No data for this filter":Xe,canFilter:Et?(Mt,et)=>h(Et,It(Mt),be?{dimension:be,value:et}:void 0):()=>!1,onFilter:Et?(Mt,et)=>N(Et,It(Mt),be?{dimension:be,value:et}:void 0):void 0})}})};if(_o({status:P,holdingForFirstData:te,refetchStatus:w.refetchStatus,refetch:w.refetch}),q){let L=!!l&&String(l).slice(0,10)<fh;return Be(Ut,{title:"Analytics",onBackToWebsite:s,className:r,children:Pa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),Be("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.":L?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return j?Be(Ut,{title:"Analytics",onBackToWebsite:s,className:r,children:Pa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),Be("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."})]})}):U?Pa(Ut,{title:"Analytics",onBackToWebsite:s,className:r,children:[Be("div",{className:"af-mb-3 af-flex af-justify-end",children:Be(Zl,{value:_,chosen:o,onChange:L=>{Fo(L),f(L)}})}),Pa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),Pa("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",P?.timezone?` ${P.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),Be("div",{className:"af-mt-4 af-flex af-justify-center",children:Be(Ql,{currentVisitors:me.currentVisitors,asOf:me.asOf,isStale:me.isStale,isUnreachable:me.isUnreachable||me.error!==null,isInitialLoad:me.isInitialLoad})})]})]}):Be(Ut,{title:"Analytics",onBackToWebsite:s,className:r,children:Pa("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Pa("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Be("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:mh.map(L=>Be("button",{type:"button","aria-pressed":L.value===u,onClick:()=>c(L.value),className:L.value===u?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:L.label},L.value))}),Be(Zl,{value:_,chosen:o,onChange:L=>{Fo(L),f(L)}}),Be(Ql,{currentVisitors:me.currentVisitors,asOf:me.asOf,isStale:me.isStale,isUnreachable:me.isUnreachable||me.error!==null,isInitialLoad:me.isInitialLoad,scopeIsSiteWide:x.length>0})]}),Be(rf,{filters:x,onChange:S,suggestions:ne,expandValues:ke,resetKey:v}),E?Pa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),Be("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:E}),Be("button",{type:"button",onClick:()=>S([]),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,!E&&P?.timezone_defaulted?Be("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,E?null:Pa(ac,{children:[Be(ds,{sourced:w.summary.data,error:w.summary.error,isLoading:w.summary.isLoading,what:"The traffic summary",collecting:P?.collecting,onRetry:w.refetch,children:L=>Pa(ac,{children:[Be(of,{summary:L,selected:R,onSelect:C}),L.previous_unavailable?Pa("p",{className:"af-text-xs af-text-muted-foreground",children:[L.previous_unavailable_reason==="filter"?"No comparison for this filter \u2014 the previous period has too many distinct traffic sources to resolve it. Try a shorter period, or filter by source instead.":"No comparison available right now \u2014 we couldn\u2019t check how far back this site\u2019s history goes. It should return on its own."," ","The numbers above are still for the period you selected."]}):null]})}),Be("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:Be(ds,{sourced:w.timeseries.data,error:w.timeseries.error,isLoading:w.timeseries.isLoading,what:"The visitors chart",collecting:P?.collecting,onRetry:w.refetch,children:L=>{let pe=w.timeseries.data?.status==="ok"?w.timeseries.data.window:{from:"",to:""};return Be(Io,{rows:L,window:pe,metric:R,timeZone:I??"UTC"})}})}),Pa("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[Be(ai,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>Be(ds,{sourced:w.channels.data,error:w.channels.error,isLoading:w.channels.isLoading,what:"Channels",collecting:P?.collecting,onRetry:w.refetch,children:L=>Be(Jl,{rows:L,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:pe=>h("channel",pe),onFilter:pe=>N("channel",pe)})})},{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")}]}),Be(ai,{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")}]}),Be(ai,{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")}]}),Be(ai,{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")}]})]}),Pa("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[Be("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:Be("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),Pa("div",{className:"af-px-3 af-py-2",children:[x.length>0?Pa("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",x.length===1?"filter":"filters"," above."]}):null,nt!==null?Pa("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:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),Be("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:nt})]}):Be(ds,{sourced:w.conversions.data,error:w.conversions.error,isLoading:w.conversions.isLoading,what:"Conversions",collecting:P?.collecting,onRetry:w.refetch,children:L=>{let pe=w.conversions.data?.status==="ok"?w.conversions.data:null;return Be(ac,{children:Be(To,{rows:L,primaryConversion:n,denominator:pe?.denominator??0,windowPrecedesCollection:pe?.window_precedes_collection??!1,coverageUnknown:pe?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import*as hf from"react";import{Phone as gf,Mail as sc,ShoppingBag as yh,ExternalLink as xh,MessageCircle as wh,Download as Sh,Target as yf}from"lucide-react";import*as Nn from"react";import{Check as nc,ChevronLeft as vh,Loader2 as df}from"lucide-react";import{jsx as ht,jsxs as ga}from"react/jsx-runtime";var uf=90,ff=100;function bh(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function mf(e){return!!e.label&&e.label!==e.target}function hh(e,t,a){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:s,with_a_value:n}=t;return s===0?e===0?"Nothing specific has converted here yet.":null:n===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":n<s?a?`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function ri(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function pf({current:e,onChange:t,onClose:a}){let{api:s}=H(),[n,r]=Nn.useState(null),[i,l]=Nn.useState(!1),[u,c]=Nn.useState({at:"goals"}),[o,f]=Nn.useState(null),[b,g]=Nn.useState(null),[m,v]=Nn.useState(!1),[d,p]=Nn.useState(null),x=Nn.useRef(0);Nn.useEffect(()=>{let N=!0;return r(null),l(!1),c({at:"goals"}),f(null),g(null),v(!1),p(null),x.current+=1,s.getAnalyticsConversions(uf).then(R=>{if(N){if(R.status!=="ok"){l(!0);return}r(R.data)}}).catch(()=>{N&&l(!0)}),()=>{N=!1}},[s]);let S=N=>{c({at:"targets",row:N}),f(null),g(null),v(!1),p(null);let R=++x.current;s.getAnalyticsGoalTargets(N.goal,uf,ff).then(C=>{if(R===x.current){if(C.status!=="ok"){g("failed");return}f(C.data),v(C.truncated===!0),p(C.coverage??null)}}).catch(C=>{if(R!==x.current)return;let w=C instanceof aa?C.details?.code:void 0;g(w==="goal_has_no_targets"?"no-values":"failed")})},k=N=>{t(N),a()};if(i)return ht("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return ga("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[ht(df,{className:"af-h-4 af-w-4 af-animate-spin"}),ht("span",{children:"Loading your conversions\u2026"})]});if(u.at==="targets"){let N=u.row,R=new Map;for(let C of o??[])R.set(C.label,(R.get(C.label)??0)+1);return ga("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:[ht("header",{className:"af-flex af-items-center af-gap-1",children:ga(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>c({at:"goals"}),children:[ht(vh,{className:"af-h-4 af-w-4"}),ht("span",{children:"All conversions"})]})}),ga("button",{type:"button","aria-current":e&&ri(N,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:()=>k({goal:N.goal,implicit:N.implicit}),children:[e&&ri(N,e)&&!e.target&&ht(nc,{className:"af-h-4 af-w-4 af-shrink-0"}),ga("span",{children:["Any ",N.goal.toLowerCase()]})]}),b==="no-values"&&ht("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"&&ga("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[ht("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),ht(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>S(N),children:"Try again"})]}),!o&&b===null&&ga("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:[ht(df,{className:"af-h-4 af-w-4 af-animate-spin"}),ht("span",{children:"Loading\u2026"})]}),o&&ht("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:hh(o.length,d,m)}),m&&ga("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",ff,". If what you want isn\u2019t here, pick the conversion itself instead."]}),o?.some(mf)&&ht("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),o?.map(C=>{let w=!!(e&&ri(N,e)&&e.target===C.target),P=R.get(C.label)>1;return mf(C)?ga("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:[ga("span",{className:"af-min-w-0",children:[ht("span",{className:"af-block af-truncate",children:C.label}),P&&ht("span",{className:"af-block af-truncate af-text-xs",children:C.target})]}),ht("span",{className:"af-shrink-0 af-text-xs",children:C.visitors.toLocaleString()})]},C.target):ga("button",{type:"button","aria-current":w?"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:()=>k({goal:N.goal,implicit:N.implicit,target:C.target,...C.label&&C.label!==C.target?{label:C.label}:{}}),children:[ga("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[w&&ht(nc,{className:"af-h-4 af-w-4 af-shrink-0"}),ga("span",{className:"af-min-w-0",children:[ht("span",{className:"af-block af-truncate",children:C.label}),P&&ht("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:C.target})]})]}),ht("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:C.visitors.toLocaleString()})]},C.target)})]})}let h=e?.goal&&!n.some(N=>ri(N,e));return ga("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[h&&ga("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&ht("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(N=>{let R=e?ri(N,e):!1;return ga("div",{className:"af-flex af-items-center af-gap-1",children:[ga("button",{type:"button","aria-current":R?"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:()=>k({goal:N.goal,implicit:N.implicit}),children:[ga("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[R&&ht(nc,{className:"af-h-4 af-w-4 af-shrink-0"}),ht("span",{className:"af-truncate",children:N.goal})]}),ht("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:N.visitors.toLocaleString()})]}),bh(N)&&ht(y,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${N.goal}`,onClick:()=>S(N),children:"Narrow"})]},N.goal)}),e?.goal&&ht("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:()=>k(null),children:"No main conversion"})]})}import{Fragment as kh,jsx as Ys,jsxs as bf}from"react/jsx-runtime";function Nh(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let a of t)try{let{hostname:s}=new URL(a);if(s)return s.toLowerCase().replace(/^www\./,"")}catch{}return null}function Rh(e){if(rc(e,"whatsapp"))return!0;let t=Nh(e);return t===null?!1:["wa.me","whatsapp.com"].some(a=>t===a||t.endsWith(`.${a}`))}function rc(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var vf=[{goal:"Contact",target:e=>rc(e,"tel"),icon:gf,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>rc(e,"mailto"),icon:sc,line:"This site is set up to get you emails."},{goal:"Contact",icon:gf,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Rh(e),icon:wh,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:xh,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:sc,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:sc,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:yh,line:"This site is set up to sell."},{goal:"File Download",icon:Sh,line:"This site is set up to get your file downloaded."}];function xf(e){let{goal:t,target:a}=e;return e.implicit!==!0?null:(a?vf.find(n=>n.goal===t&&n.target?.(a)):void 0)??vf.find(n=>n.goal===t&&!n.target)??null}function _h(e){return xf(e)?.icon??yf}function wf({primaryConversion:e,onChange:t}){let[a,s]=hf.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?xf(e):null,i=e?.label?.trim(),l=e?_h(e):yf,u=e?.goal?i?`Your main conversion is ${i}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",c=bf(kh,{children:[Ys(l,{className:"af-h-4 af-w-4 af-shrink-0"}),Ys("span",{children:u})]});return t?bf(Ii,{open:a,onOpenChange:s,children:[Ys(Ai,{asChild:!0,children:Ys("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:c})}),Ys(Dr,{align:"start",className:"af-w-80 af-p-1",children:a&&Ys(pf,{current:e,onChange:t,onClose:()=>s(!1)})})]}):Ys("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:c})}import{Fragment as Ph,jsx as Cs,jsxs as Ao}from"react/jsx-runtime";function Sf({refreshKey:e,onViewAll:t,primaryConversion:a}){let s=wr(7,{refreshKey:e,breakdowns:[]}),n=s.status.data??void 0,{nothingToReport:r,notCollecting:i,holdingForFirstData:l}=Ro(n);return _o({status:n,holdingForFirstData:l,refetchStatus:s.refetchStatus,refetch:s.refetch}),Ao("section",{className:"af-rounded-md af-border af-p-3",children:[Ao("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Cs("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&Cs(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?Cs("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:i?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):Ao(Ph,{children:[Cs(ds,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let c=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return Cs(Io,{rows:u,window:c?.window??{from:"",to:""},metric:"visitors",timeZone:c?.timezone,height:140})}}),Ao("div",{className:"af-mt-3",children:[Cs("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),Cs(ds,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let c=s.conversions.data?.status==="ok"?s.conversions.data:null;return Cs(To,{rows:u,primaryConversion:a,denominator:c?.denominator??0,windowPrecedesCollection:c?.window_precedes_collection??!1,coverageUnknown:c?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as Fn,jsxs as ii}from"react/jsx-runtime";var ic=5;function oc({title:e,viewAllLabel:t,onViewAll:a}){return ii("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Fn("h3",{className:"af-text-sm af-font-medium",children:e}),a&&Fn(y,{type:"button",variant:"ghost",size:"sm",onClick:a,children:t})]})}function Ch({refreshKey:e,onBackToWebsite:t,primaryConversion:a,onChangePrimaryConversion:s,onOpenSurface:n,needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l}){let u=dr({refreshKey:e}),c=(u.summary?.products.count??0)>0||(u.summary?.commerce?.storefront_orders??!1),o=c||(u.summary?.commerce?.invoicing??!1);return Fn(Ut,{title:"Dashboard",onBackToWebsite:t,children:ii("div",{className:"af-flex af-flex-col af-gap-4",children:[Fn(wf,{primaryConversion:a,onChange:s}),Fn(Sf,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:a}),ii("section",{className:"af-rounded-md af-border af-p-3",children:[Fn(oc,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),Fn(Qi,{refreshKey:e,maxRows:ic,onViewAll:n&&(()=>n("leads"))})]}),c&&ii("section",{className:"af-rounded-md af-border af-p-3",children:[Fn(oc,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),Fn(bs,{refreshKey:e,maxRows:ic,onViewAll:n&&(()=>n("orders"))})]}),o&&ii("section",{className:"af-rounded-md af-border af-p-3",children:[Fn(oc,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),Fn(ys,{refreshKey:e,maxRows:ic,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l})]})]})})}export{vr as AUDIENCE_PAGE_SIZE,aa as AifeaturesApiError,_f as AifeaturesProvider,gh as AnalyticsView,lo as ContactImport,Ui as CustomerDetail,Vi as CustomersList,ho as DOUBLE_OPT_IN_HELP,Ch as DashboardView,vl as EMAIL_ORG_ACTIONS,nu as EMAIL_READINESS_TEXT,qu as EmailView,wa as ExportCsvButton,Ri as FormSettings,xi as FormSubmissions,Ic as FormsDashboard,ui as FormsList,yl as IMPORT_ATTESTATION,al as InvoiceDetail,Or as InvoiceLabelBadge,ro as InvoiceSettingsPanel,ys as InvoicesList,au as InvoicesView,Qi as LeadsView,Gs as MAX_ANALYTICS_FILTERS,Ks as MAX_ANALYTICS_FILTER_VALUES,eu as NotificationRecipientsSettings,Bi as OrderDetail,Ds as OrderStatusBadge,bs as OrdersList,ud as OrdersView,ld as PaymentsDashboard,ir as PaymentsSetup,Ti as ProductSettings,Pi as ProductsList,yd as ProductsView,Qs as PromosPanel,Gl as REALTIME_FAILURES_BEFORE_ERROR,Wl as REALTIME_POLL_MS,nl as RetainerStatusBadge,rr as RetainersPanel,Jd as StoreSettings,vi as SubmissionDetail,Dd as SubscriptionsView,Ci as VariantsEditor,Ut as ViewShell,Si as WebhookDeliveries,Ni as WebhookSettings,uv as buildEmailOrgRequest,is as chargedTotal,Mo as createApiClient,Ns as emailReadinessText,Q as formatPrice,dv as isEmailOrgAction,vn as isZeroDecimalCurrency,Dt as toMajorUnits,va as toMinorUnits,H as useAifeatures,H as useAifeaturesContext,wr as useAnalytics,io as useAudience,yr as useBroadcasts,dr as useBusinessSummary,yi as useCsvExport,$i as useCustomers,xr as useEmailDrafts,wi as useEventDestinations,Js as useForms,nr as useInvoices,Ei as useOrders,gs as usePaymentsStatus,Ji as usePeople,Xi as usePerson,or as useProducts,No as useRealtimeVisitors,lr as useRetainers,Ss as useSiteSettings,pi as useSubmissions,eo as useSubscriptions};
7
+ `);case"cart":return e.label}}function du(e){switch(e.type){case"heading":case"text":return e.text.trim()!=="";case"button":return e.label.trim()!==""&&e.url.trim()!==""&&e.url.trim()!=="https://";case"image":return e.url.trim()!=="";case"cart":return e.label.trim()!==""}}var hv={...Sl,text:"Markdown: **bold**, *italic*, [link](https://\u2026), blank line = new paragraph"};function fu({block:e,isNew:t,busy:a,error:s,onPickImage:n,onDone:r,onRemove:i,onCancel:l,style:u,className:c}){let[o,f]=Us.useState(e),[b,g]=Us.useState(!1),m=p=>f(x=>({...x,...p})),v=Us.useRef(null);Us.useEffect(()=>v.current?.focus(),[]);let d=p=>{p&&!v.current&&(v.current=p)};return ka("form",{"data-testid":"section-editor",style:u,className:c,onSubmit:p=>{p.preventDefault(),du(o)&&r(o)},onKeyDown:p=>{p.key==="Escape"&&!a&&l()},children:Ln("div",{className:"af-space-y-2",children:[o.type==="heading"&&ka(ae,{ref:d,"aria-label":"Heading",value:o.text,maxLength:200,onChange:p=>m({text:p.target.value})}),o.type==="text"&&ka("textarea",{ref:d,"aria-label":"Text",className:"af-min-h-[120px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-font-mono af-text-sm",value:o.text,maxLength:5e3,onChange:p=>m({text:p.target.value})}),o.type==="button"&&Ln("div",{className:"af-grid af-gap-2 sm:af-grid-cols-2",children:[Ln("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",ka(ae,{ref:d,"aria-label":"Button label",value:o.label,maxLength:80,onChange:p=>m({label:p.target.value})})]}),Ln("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Opens",ka(ae,{"aria-label":"Button link",type:"url",value:o.url,onChange:p=>m({url:p.target.value})})]})]}),o.type==="image"&&Ln("div",{className:"af-space-y-2",children:[n?Ln("div",{className:"af-flex af-items-center af-gap-2",children:[o.url&&ka("img",{src:o.url,alt:"",className:"af-h-12 af-w-12 af-rounded af-object-cover"}),ka(y,{ref:d,type:"button",variant:"outline",size:"sm",disabled:b,onClick:async()=>{g(!0);try{let p=await n();p&&f(x=>({...x,url:p.url,alt:p.alt??(x.type==="image"?x.alt:"")}))}finally{g(!1)}},children:"Choose from your site's images\u2026"})]}):Ln("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Image address (https://\u2026)",ka(ae,{ref:d,"aria-label":"Image URL",type:"url",value:o.url,onChange:p=>m({url:p.target.value})})]}),Ln("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Describe the image (for people who can't see it)",ka(ae,{"aria-label":"Image description",value:o.alt??"",maxLength:200,onChange:p=>m({alt:p.target.value})})]})]}),o.type==="cart"&&Ln("div",{className:"af-space-y-2",children:[ka("p",{className:"af-text-sm af-text-muted-foreground",children:"Each shopper sees their own cart here. There's nothing to write but the button."}),Ln("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",ka(ae,{ref:d,"aria-label":"Cart button label",value:o.label,maxLength:80,onChange:p=>m({label:p.target.value})})]})]}),s&&ka(fe,{tone:"error",children:s}),Ln("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ka("span",{className:"af-grow af-text-xs af-text-muted-foreground",children:hv[o.type]}),!t&&ka(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:i,children:"Remove"}),ka(y,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:l,children:"Cancel"}),ka(y,{type:"submit",size:"sm",disabled:a||!du(o),children:"Done"})]})]})})}import*as mu from"react";import{ArrowLeft as yv}from"lucide-react";import{Fragment as Rl,jsx as Ze,jsxs as ha}from"react/jsx-runtime";var Jn="standard",co={create:"Create an email template that ",copyStandard:"Create an email template based on Standard that ",update:e=>`Update the "${e}" template to be `};function _l({template:e}){return e?e.status==="archived"?Ze(ee,{variant:"secondary",children:"Archived"}):e.locked?Ze(ee,{variant:"secondary",children:"In use"}):null:Ze(ee,{variant:"secondary",children:"Built in"})}function kl(e){return e>0?`Used by ${e} draft${e===1?"":"s"}`:null}function pu(e,t){let{api:a}=H(),{siteId:s,refreshKey:n,settings:r}=Ke(),i=JSON.stringify([r?.business_name,r?.postal_address,r?.brand]);return Bt(()=>a.previewEmailTemplate(s,e),`${s}|${e}|${t}|${n}|${i}`,`${s}|${e}|${t}`)}function uo({templateId:e,version:t,className:a,frame:s}){let n=pu(e,t);return Ze("div",{"aria-hidden":!0,className:`af-pointer-events-none af-overflow-hidden af-bg-white ${a}`,children:n.data&&Ze("div",{"data-testid":"template-thumbnail-frame",className:"af-mx-auto af-overflow-hidden",style:{width:s.width*s.scale,height:s.height*s.scale},children:Ze("iframe",{title:"",tabIndex:-1,sandbox:"",srcDoc:n.data.html,style:{width:s.width,height:s.height,border:0,transform:`scale(${s.scale})`,transformOrigin:"top left"}})})})}function gu({template:e,onBack:t,onOpenTemplate:a,onOpenDraft:s,onAskAssistant:n,reload:r,refreshKey:i}){let l=pu(e?.id??Jn,e?.updated_at??"builtin");return ha("div",{className:"af-space-y-4",children:[ha(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[Ze(yv,{className:"af-mr-1 af-h-4 af-w-4"}),"All templates"]}),ha("div",{className:"af-grid af-gap-4 md:af-grid-cols-[minmax(0,1fr)_280px]",children:[ha("div",{children:[l.data?Ze("iframe",{title:"Template preview",sandbox:"",srcDoc:l.data.html,className:"af-h-[520px] af-w-full af-rounded-md af-border af-bg-white"}):l.error?ha(fe,{tone:"warning",children:[Rs(l.error)==="postal_address_missing"?"Add your business postal address to preview your emails.":"Couldn't load this preview.",Ze(br,{reason:Rs(l.error)})]}):Ze(G,{className:"af-h-[520px] af-w-full"}),Ze("p",{className:"af-mt-2 af-text-center af-text-xs af-text-muted-foreground",children:"Shown with a sample email"})]}),ha("div",{className:"af-space-y-3",children:[Ze(xv,{template:e,onOpenTemplate:a,onAskAssistant:n,reload:r}),Ze(wv,{templateId:e?.id??null,onOpenDraft:s,refreshKey:i})]})]})]})}function xv({template:e,onOpenTemplate:t,onAskAssistant:a,reload:s}){let{canWrite:n}=Ke(),r=vt(),[i,l]=mu.useState(null),u=e?.name??"Standard",c=async(d,p)=>{let x=await r.run(d,p);l(null),x.ok&&d==="deleteEmailTemplate"&&t(null),!x.ok&&Ga(x.error,"template_in_use")&&r.setError("Emails use this template now."),s()},o=async d=>{let p=await r.run("copyEmailTemplate",{templateId:d.id});p.ok&&(t(p.result.id),s())},f=d=>Ze(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:r.busy,onClick:()=>void o(d),children:"Make a copy"}),b=Ze(y,{type:"button",variant:"ghost",size:"sm",disabled:r.busy,onClick:()=>l("delete"),children:"Delete"}),g=Ze(y,{type:"button",variant:"outline",size:"sm",disabled:r.busy,onClick:()=>l("archive"),children:"Archive"}),m=null;if(!n)m=null;else if(i&&e){let[d,p,x]=i==="delete"?["Delete this template?","Delete",()=>c("deleteEmailTemplate",{templateId:e.id})]:["Archive this template?","Archive",()=>c("archiveEmailTemplate",{templateId:e.id})];m=ha(Rl,{children:[Ze("p",{className:"af-text-sm",children:d}),ha("div",{className:"af-flex af-gap-2",children:[Ze(y,{type:"button",variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),Ze(y,{type:"button",size:"sm",variant:i==="delete"?"destructive":"default",className:"af-ml-auto",disabled:r.busy,onClick:()=>void x(),children:p})]})]})}else e?e.status==="archived"?m=ha("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ze(y,{type:"button",variant:"outline",size:"sm",disabled:r.busy,onClick:()=>void c("unarchiveEmailTemplate",{templateId:e.id}),children:"Unarchive"}),f(e)]}):e.locked?m=ha("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_archive&&g,f(e)]}):m=ha(Rl,{children:[a&&Ze(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>a(co.update(e.name)),children:"\u2728 Change this template with the editor"}),(e.can_delete||e.can_archive)&&ha("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_delete&&b,e.can_archive&&g]})]}):m=a&&Ze(y,{type:"button",size:"sm",onClick:()=>a(co.copyStandard),children:"Make a copy"});let v=e&&e.status==="active"&&!e.locked?kl(e.usage.drafts):null;return ha("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[ha("div",{className:"af-flex af-items-center af-gap-2",children:[Ze("h3",{"data-testid":"template-title",className:"af-grow af-truncate af-text-sm af-font-semibold",children:u}),Ze(_l,{template:e})]}),v&&Ze("p",{className:"af-text-xs af-text-muted-foreground",children:v}),r.error&&Ze(fe,{tone:"error",children:r.error}),m]})}function wv({templateId:e,onOpenDraft:t,refreshKey:a}){let{siteId:s}=Ke(),n=xr({siteId:s,kind:"broadcast",refreshKey:a}),r=yr({siteId:s,refreshKey:a}),i=n.data?.filter(f=>(f.template?.id??null)===e)??null,l=r.data??[],u=oo(n.data??[],l),c=new Set(l.flatMap(f=>f.draft_id&&f.status==="scheduled"?[f.draft_id]:[])),o=f=>u.has(f)?"Sent":c.has(f)?"Scheduled":"Draft";return ha("div",{"data-testid":"template-usage",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[Ze("h3",{className:"af-text-sm af-font-semibold",children:"Emails using it"}),n.error||r.error?Ze(xt,{message:"Couldn't load the emails.",onRetry:()=>{n.refetch(),r.refetch()}}):!i||!r.data?Ze(G,{className:"af-h-10 af-w-full"}):i.length===0?Ze("p",{className:"af-text-sm af-text-muted-foreground",children:"No emails use it."}):Ze("ul",{className:"af-space-y-1",children:i.map(f=>{let b=o(f.id),g=ha(Rl,{children:[Ze("span",{className:"af-block af-truncate af-text-sm",children:f.subject||"(no subject)"}),ha("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["Broadcast \xB7 ",b]})]});return Ze("li",{children:b==="Sent"?Ze("div",{className:"af-rounded-md af-px-2 af-py-1",children:g}):Ze("button",{type:"button",onClick:()=>t(f.id),className:"af-w-full af-rounded-md af-px-2 af-py-1 af-text-left hover:af-bg-muted",children:g})},f.id)})})]})}import{jsx as Vs,jsxs as fo}from"react/jsx-runtime";function vu({draft:e,disabled:t,onChanged:a}){let{api:s}=H(),{siteId:n,refreshKey:r}=Ke(),i=Bt(()=>s.getEmailTemplates(n),`${n}|${r}`,n),l=vt(),u=e.template?.id??Jn,c=u===Jn,o=(i.data??[]).filter(v=>v.status==="active"),f=o.find(v=>v.id===u),b=c?"Standard":e.template?.name??f?.name??"",g=c?"builtin":f?.updated_at??"current",m=async v=>{if(v===u)return;let d=await l.run("setDraftTemplate",{draftId:e.id,template_id:v===Jn?null:v,expected_version:e.version});d.ok?await a():Ga(d.error,"template_missing_cart")?l.setError("This email shows the shopper's cart, and that template has no cart section. Pick another template, or keep this one."):Ga(d.error,"version_conflict")?(l.setError("This email changed meanwhile. We've loaded the latest version; switch again if you still want to."),await a()):Ga(d.error,"template_archived")&&(l.setError("That template is archived."),await i.refetch())};return fo("div",{"data-testid":"template-card",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[Vs("div",{className:"af-text-sm af-font-semibold",children:"Template"}),fo("div",{className:"af-flex af-items-center af-gap-3",children:[Vs(uo,{templateId:u,version:g,className:"af-h-20 af-w-[72px] af-shrink-0 af-rounded af-border",frame:{width:600,height:670,scale:.12}}),Vs("div",{className:"af-min-w-0 af-grow af-truncate af-text-sm af-font-medium",children:b})]}),fo("label",{className:"af-grid af-gap-1 af-text-xs af-text-muted-foreground",children:["Switch to",fo("select",{"aria-label":"Switch to",value:u,disabled:t||l.busy,onChange:v=>void m(v.target.value),className:"af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-text-sm af-text-foreground",children:[Vs("option",{value:Jn,children:"Standard"}),o.map(v=>Vs("option",{value:v.id,children:v.name},v.id)),!c&&!f&&Vs("option",{value:u,disabled:!0,children:b})]})]}),l.error&&Vs(fe,{tone:"error",children:l.error})]})}import{jsx as mo,jsxs as bu}from"react/jsx-runtime";function hu({live:e,joinsOnSave:t,notice:a,onBackToCanvas:s}){return bu("div",{"data-testid":"automation-step-panel",className:"af-space-y-2",children:[e?bu(fe,{tone:"success",children:[mo("span",{className:"af-font-medium",children:"Live."})," Saved changes send to the next people who reach this step."]}):t?mo(fe,{children:"This email joins the automation when you save it with a subject and some content."}):null,a,mo("p",{className:"af-text-sm",children:mo(fa,{onClick:s,children:"Back to the automation"})})]})}import{Fragment as Pl,jsx as qe,jsxs as Qt}from"react/jsx-runtime";var Sv={heading:"Click to edit heading",text:"Click to edit text",button:"Click to edit button",image:"Click to replace image",cart:"The shopper's cart"},Nv=320,Rv=600,_v=e=>({top:Math.max(0,e.y-24),left:e.x});function kv(e,t){let a=Object.keys(e);return a.length!==Object.keys(t).length?!1:a.every(s=>{let n=e[Number(s)],r=t[Number(s)];return r!==void 0&&n.x===r.x&&n.y===r.y&&n.width===r.width&&n.height===r.height})}function po({draftId:e,renderCommit:t,automationStep:a,allowCart:s,onSaved:n,scheduled:r,onAskAssistant:i,onPickImage:l}){let{api:u}=H(),{siteId:c,canWrite:o,refreshKey:f,openSettings:b}=Ke(),g=o&&!r,m=We.useRef(g);m.current=g;let[v,d]=We.useState(null),[p,x]=We.useState(null),[S,k]=We.useState(null),[h,N]=We.useState(null),[R,C]=We.useState(null),[w,P]=We.useState(null),[I,_]=We.useState(null),[q,j]=We.useState(null),[U,te]=We.useState(null),[ce,me]=We.useState({}),[T,V]=We.useState(qr.initial),[A,ne]=We.useState(!1),re=vt(),Me=vt(),Se=We.useRef(null),Ee=We.useRef(null),Ye=We.useRef(0),ke=We.useRef(!1),nt=We.useRef(!1),E=We.useCallback(ye=>{ke.current=ye!==null,P(ye)},[]);su(w!==null);let M=We.useRef(v);M.current=v;let L=We.useRef(0),pe=We.useCallback(async(ye={})=>{let Rt=++L.current,$=m.current,Pe=()=>$?u.previewEmailDraft(c,e,{editable:!0}):u.previewEmailDraft(c,e),[jt,_n]=await Promise.allSettled([u.getEmailDraft(c,e),Pe()]),X=_n,la=()=>jt.status==="fulfilled"&&X.status==="fulfilled"&&X.value.version!==jt.value.version;if(la()&&Rt===L.current&&([X]=await Promise.allSettled([Pe()])),Rt===L.current){if(ye.background&&ke.current){nt.current=!0;return}if(N(null),k(null),jt.status==="rejected"){N(hr(jt.reason));return}d(jt.value),X.status==="fulfilled"?x({...X.value,editable:$&&!la()}):(x(null),k(Ga(X.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:hr(X.reason),code:null}))}},[u,c,e]);We.useEffect(()=>{d(null),x(null),pe()},[pe]);let J=We.useRef(g);We.useEffect(()=>{J.current!==g&&(J.current=g,g||E(null),pe())},[g,pe,E]);let se=We.useRef(f);We.useEffect(()=>{if(f!==se.current){if(se.current=f,ke.current){nt.current=!0;return}pe({background:!0})}},[f,pe]);let Fe=()=>{E(null),re.setError(null),nt.current&&(nt.current=!1,pe())},Qe=async(ye,Rt,$)=>{let Pe=await re.run("updateDraft",{draftId:e,expected_version:ye.version,...Rt});Pe.ok?(_(null),Ee.current=null,nt.current=!1,E(null),await pe(),n?.()):Ga(Pe.error,"version_conflict")&&(re.setError(null),_($),nt.current=!1,E(null),await pe())},Xe=We.useRef({frame:null,html:null,count:0}),[It,he]=We.useState(null),$e=(ye,Rt)=>{let $=Xe.current;$.frame!==ye.currentTarget||$.html!==Rt?Xe.current={frame:ye.currentTarget,html:Rt,count:1}:++$.count>1&&he(Rt)},yt=p!==null&&It===p.html,At=g&&p?.editable===!0&&!yt;if(We.useEffect(()=>{if(!At)return;let ye=Rt=>{let $=M.current;if(!$)return;let Pe=lu(Rt,Se.current?.contentWindow,$.blocks.length);if(Pe)switch(Pe.type){case"hover":te(Pe.section===null?null:{section:Pe.section,rect:Pe.rect});return;case"focus":Ee.current=Pe.section;return;case"open":if(Ee.current=Pe.section,ke.current)return;j(null),ne(!1),E({kind:"section",base:$,index:Pe.section,block:$.blocks[Pe.section],isNew:!1,anchor:Pe.rect,key:++Ye.current});return;case"layout":V(cu(Pe.height));{let jt=Object.fromEntries(Pe.sections.map(_n=>[_n.section,_n.rect]));me(_n=>kv(_n,jt)?_n:jt)}return;case"template":ke.current||j(Pe.region);return}};return window.addEventListener("message",ye),()=>window.removeEventListener("message",ye)},[At,E]),h)return Qt(fe,{tone:"error",children:["Couldn't load this email. ",h]});if(!v)return qe(G,{className:"af-h-40 af-w-full"});let Mt={width:Se.current?.clientWidth||Rv,height:At?T:qr.initial},et=w?.kind==="section"?w:null,ta=(()=>{if(!et)return null;if(!et.isNew)return ce[et.index]??et.anchor;let ye=ce[et.index-1];return ye?{x:ye.x,y:ye.y+ye.height,width:ye.width,height:0}:null})(),Je=ta?wl(ta,Mt):null,wt=s??v.kind==="recovery",Xa=v.template?.name??"Standard",Mn=et&&qe(fu,{block:et.block,isNew:et.isNew,busy:re.busy,error:re.error,onPickImage:l,onCancel:Fe,onRemove:()=>{let{base:ye}=et;Qe(ye,{subject:ye.subject,preheader:ye.preheader,blocks:ye.blocks.filter((Rt,$)=>$!==et.index)},Nl(et.block))},onDone:ye=>{let{base:Rt}=et,$=et.isNew?[...Rt.blocks.slice(0,et.index),ye,...Rt.blocks.slice(et.index)]:Rt.blocks.map((Pe,jt)=>jt===et.index?ye:Pe);Qe(Rt,{subject:Rt.subject,preheader:Rt.preheader,blocks:$},Nl(ye))},className:Je?"af-absolute af-z-10 af-rounded-md af-border af-bg-background af-p-3 af-shadow-lg":"af-rounded-md af-border af-bg-background af-p-3 af-shadow-sm",style:Je?{top:Je.y,left:Je.x,width:Math.min(Math.max(Je.width,Nv),Mt.width)}:void 0},et.key);return Qt("div",{className:"af-grid af-gap-4 lg:af-grid-cols-[minmax(0,1fr)_300px]",children:[Qt("div",{className:"af-min-w-0 af-space-y-3",children:[w?.kind==="subject"?qe(Pv,{draft:w.base,busy:re.busy,error:re.error,onCancel:Fe,onDone:ye=>void Qe(w.base,{...ye,blocks:w.base.blocks},[ye.subject,ye.preheader??""].join(`
8
+ `))}):At?qe("button",{type:"button","data-testid":"subject-line",onClick:()=>{ke.current||(j(null),E({kind:"subject",base:v}))},className:"af-block af-w-full af-rounded-md af-border af-border-dashed af-px-3 af-py-2 af-text-left hover:af-border-primary",children:qe(yu,{draft:v})}):qe("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:qe(yu,{draft:v})}),r&&Qt(fe,{tone:"info",children:[Qt("p",{children:["This email is scheduled",r.sendsAt?` to send ${new Date(r.sendsAt).toLocaleString()}`:"",", so it can't change. Unschedule it to edit, then schedule it again."]}),qe(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:!o||r.busy,onClick:()=>void r.onUnschedule(),children:"Unschedule to edit"}),r.error&&qe("p",{className:"af-mt-1 af-text-destructive",children:r.error})]}),I!==null&&Qt(fe,{tone:"warning",children:[qe("p",{children:"This email changed while you were editing, so your change wasn't saved. Here is the latest version; your text is below to apply again."}),qe("textarea",{readOnly:!0,"aria-label":"Your unsaved text",value:I,className:"af-mt-2 af-min-h-[72px] af-w-full af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-font-mono af-text-xs af-text-foreground"}),qe(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>_(null),children:"Dismiss"})]}),q&&qe("div",{"data-testid":"template-hint",children:qe(fe,{children:q==="header"?Qt(Pl,{children:['The header is part of the "',Xa,'" template. Switch templates on the right.']}):Qt(Pl,{children:["Every email ends with this footer. Your business name and address come from"," ",qe(fa,{onClick:()=>b("sender"),children:"Settings"}),"."]})})}),yt&&g&&qe(fe,{tone:"warning",children:"This template tried to open another page in the preview, so the preview can't be edited here."}),p?Qt("div",{className:"af-relative",children:[qe("iframe",{ref:Se,title:"Email preview",sandbox:At?"allow-scripts":"",srcDoc:p.html,onLoad:At?ye=>$e(ye,p.html):void 0,style:{height:Mt.height},className:"af-block af-w-full af-rounded-md af-border af-bg-white"},At?"editable":"read-only"),At&&U&&!w&&qe("div",{"aria-hidden":!0,className:"af-pointer-events-none af-absolute af-rounded af-bg-primary af-px-2 af-py-0.5 af-text-xs af-text-primary-foreground",style:_v(wl(U.rect,Mt)),children:Sv[v.blocks[U.section]?.type??"text"]}),Je&&Mn]}):S?Qt(fe,{tone:"warning",children:[S.text,qe(br,{reason:S.code})]}):qe(G,{className:"af-h-40 af-w-full"}),!Je&&Mn,At&&!w&&Qt("div",{className:"af-space-y-2",children:[qe(y,{type:"button",variant:"outline",size:"sm",onClick:()=>ne(ye=>!ye),"aria-expanded":A,children:"+ Add a section"}),A&&qe("div",{"data-testid":"add-section-menu",className:"af-flex af-flex-wrap af-gap-2",children:["text","heading","button","image",...wt?["cart"]:[]].map(ye=>qe(y,{type:"button",size:"sm",variant:"secondary",onClick:()=>{let Rt=Ee.current!==null?Ee.current+1:v.blocks.length;ne(!1),j(null),E({kind:"section",base:v,index:Rt,block:uu(ye),isNew:!0,anchor:null,key:++Ye.current})},children:Sl[ye]},ye))})]}),qe("p",{className:"af-text-center af-text-xs af-text-muted-foreground",children:"Header and footer come from your template."})]}),Qt("div",{className:"af-space-y-3",children:[Qt("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[qe(y,{type:"button",variant:"outline",size:"sm",disabled:!o||Me.busy,onClick:async()=>{C(null);let ye=await Me.run("testSendDraft",{draftId:e});ye.ok&&C(ye.result?.sent_to??"your email")},children:"Send a test to me"}),R&&Qt(fe,{tone:"success",children:["Test sent to ",R,"."]}),Me.error&&qe(fe,{tone:"error",children:Me.error}),p&&!r&&t?.({draft:v,preview:p,reload:()=>pe()}),a&&qe(hu,{...a})]}),qe(vu,{draft:v,disabled:!g||w!==null,onChanged:async()=>{await pe(),n?.()}}),i&&o&&qe(y,{type:"button",variant:"outline",className:"af-w-full",onClick:()=>i(`Update the "${v.subject}" email to `),children:"\u2728 Change this email with the editor"})]})]})}function yu({draft:e}){return Qt(Pl,{children:[qe("span",{className:"af-text-xs af-text-muted-foreground",children:"Subject "}),qe("span",{className:"af-font-medium",children:e.subject||"(no subject)"}),e.preheader&&Qt("span",{className:"af-text-sm af-text-muted-foreground",children:[" \u2014 ",e.preheader]})]})}function Pv({draft:e,busy:t,error:a,onDone:s,onCancel:n}){let[r,i]=We.useState(e.subject),[l,u]=We.useState(e.preheader??"");return Qt("form",{className:"af-space-y-2 af-rounded-md af-border af-p-3",onSubmit:c=>{c.preventDefault(),s({subject:r,preheader:l.trim()||null})},children:[Qt("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Subject",qe(ae,{"aria-label":"Subject",value:r,maxLength:200,autoFocus:!0,onChange:c=>i(c.target.value)})]}),Qt("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Preview text (the grey line after the subject in the inbox)",qe(ae,{"aria-label":"Preview text",value:l,maxLength:200,onChange:c=>u(c.target.value)})]}),a&&qe(fe,{tone:"error",children:a}),Qt("div",{className:"af-flex af-justify-end af-gap-2",children:[qe(y,{type:"button",variant:"outline",size:"sm",disabled:t,onClick:n,children:"Cancel"}),qe(y,{type:"submit",size:"sm",disabled:t,children:"Done"})]})]})}import{jsx as Re,jsxs as Et}from"react/jsx-runtime";var Ev="Write a newsletter for my subscribers",Iv={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function wu({openDraftId:e,onOpenDraft:t,onAskAssistant:a,onPickImage:s}){let{siteId:n,canWrite:r,refreshKey:i}=Ke(),[l,u]=Nt.useState(0),c=l+i,o=xr({siteId:n,kind:"broadcast",refreshKey:c}),f=yr({siteId:n,refreshKey:c}),b=vt(),g=vt(),m=oo(o.data??[],f.data??[]),v=o.data?.filter(d=>!m.has(d.id))??null;if(e){let d=f.data?.find(p=>p.draft_id===e&&p.status==="scheduled");return Et("div",{className:"af-space-y-4",children:[Et(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>t(null),children:[Re(Cv,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),!f.data&&!f.error||!o.data&&!o.error?Re(G,{className:"af-h-40 af-w-full"}):m.has(e)?Re(fe,{children:"This email has been sent, so it can't change. Duplicate it from the list to send it again."}):Re(po,{draftId:e,onSaved:()=>u(p=>p+1),renderCommit:p=>Re(Lv,{...p,onCommitted:()=>u(x=>x+1)}),scheduled:d?{sendsAt:d.scheduled_at,busy:b.busy,error:b.error,onUnschedule:async()=>{(await b.run("cancelBroadcast",{sendId:d.id})).ok&&u(x=>x+1)}}:void 0,onAskAssistant:a,onPickImage:s})]})}return Et("div",{children:[Re(_a,{children:"Drafts"}),o.error?Re(xt,{message:"Couldn't load drafts.",onRetry:()=>void o.refetch()}):v?v.length===0?Re(ca,{action:r&&a&&Et(y,{type:"button",size:"sm",onClick:()=>a(Ev),children:[Re(Tv,{className:"af-mr-1.5 af-h-3.5 af-w-3.5","aria-hidden":!0}),"Write a newsletter"]}),children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):Re("ul",{"data-testid":"drafts",className:"af-divide-y af-rounded-md af-border",children:v.map(d=>Et("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[Re("span",{className:"af-truncate af-text-sm",children:d.subject||"(no subject)"}),Re(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(d.id),children:"Review"})]},d.id))}):Re(G,{className:"af-h-10 af-w-full"}),Re(_a,{children:"Sent and scheduled"}),b.error&&Re(fe,{tone:"error",children:b.error}),g.error&&Re(fe,{tone:"error",children:g.error}),f.error?Re(xt,{message:"Couldn't load broadcasts.",onRetry:()=>void f.refetch()}):f.data?f.data.length===0?Re(ca,{children:"Nothing sent yet."}):Re("ul",{className:"af-divide-y af-rounded-md af-border",children:f.data.map(d=>Re(Av,{broadcast:d,canCancel:r&&(d.status==="scheduled"||d.status==="unscheduled"||d.status==="sending"),busy:b.busy||g.busy,onCancel:async()=>{(await b.run("cancelBroadcast",{sendId:d.id})).ok&&u(x=>x+1)},onDuplicate:r&&d.draft_id&&bl(d)?async()=>{let p=await g.run("duplicateDraft",{draftId:d.draft_id});p.ok&&(u(x=>x+1),t(p.result.id))}:void 0},d.id))}):Re(G,{className:"af-h-10 af-w-full"})]})}function Av({broadcast:e,canCancel:t,busy:a,onCancel:s,onDuplicate:n}){return Et("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[Et("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[Re("span",{className:"af-truncate af-text-sm af-font-medium",children:e.subject}),Et("div",{className:"af-flex af-items-center af-gap-2",children:[Re(ee,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Iv[e.status]}),t&&Re(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:s,children:"Cancel"}),n&&Re(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:n,children:"Duplicate"})]})]}),Et("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",Ae(e.recipients.planned)," recipients \xB7 ",Ae(e.stats.delivered)," delivered \xB7 ",Ae(e.stats.opened)," opened \xB7"," ",Ae(e.stats.clicked)," clicked \xB7 ",Ae(e.stats.bounced)," bounced \xB7 ",Ae(e.stats.complained)," complaints \xB7"," ",Ae(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&Re("div",{className:"af-text-xs af-text-muted-foreground",children:Ns(e.status_reason)})]})}var Su=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function xu(e){let t=e.targeting??null,a=e.proposed_send_at?new Date(e.proposed_send_at):null,s=a!==null&&a.getTime()>Date.now();return{key:Su(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:s?Dv(a):"",suggested:t!==null||a!==null,timePassed:a!==null&&!s}}function Dv(e){let t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}var Ov=(e,t)=>e.match===t.match&&e.scheduleAt===t.scheduleAt&&e.tagIds.length===t.tagIds.length&&e.tagIds.every(a=>t.tagIds.includes(a));function Lv({draft:e,preview:t,reload:a,onCommitted:s}){let{api:n}=H(),{siteId:r,canWrite:i,settings:l,refreshKey:u}=Ke(),[c,o]=Nt.useState(null),[f,b]=Nt.useState(!1),[g,m]=Nt.useState(null),[v,d]=Nt.useState(()=>xu(e)),[p,x]=Nt.useState(v.tagIds),[S,k]=Nt.useState(v.match),[h,N]=Nt.useState(v.scheduleAt),[R,C]=Nt.useState(0),w=!Ov({tagIds:p,match:S,scheduleAt:h},v),P=Su(e);Nt.useEffect(()=>{if(P===v.key||e.id===v.draftId&&w)return;let J=xu(e);d(J),x(J.tagIds),k(J.match),N(J.scheduleAt),C(0)},[P,e,v,w]);let I=Nt.useMemo(()=>c?new Set(c.map(J=>J.id)):null,[c]),_=I!==null&&p.every(J=>I.has(J));Nt.useEffect(()=>{if(!I||p.every(se=>I.has(se)))return;let J=se=>se.filter(Fe=>I.has(Fe));C(se=>se+p.length-J(p).length),x(J(p)),d(se=>({...se,tagIds:J(se.tagIds)}))},[I,p]);let[q,j]=Nt.useState(null),[U,te]=Nt.useState(null),[ce,me]=Nt.useState(null),T=vt();Nt.useEffect(()=>{n.getMarketingTags(r).then(J=>{o(J),b(!1)},()=>{o(null),b(!0)}),n.getMarketingContactStats(r).then(m,()=>m(null))},[n,r,u]);let V=h?new Date(h).toISOString():null,A=JSON.stringify([p,S,V]),ne=q?.plan??null,re=q!==null&&q.key===A,Me=Nt.useRef(0),Se=Nt.useCallback(async()=>{let J=++Me.current;te(null);try{let se=await n.estimateBroadcast(r,{targeting:{tag_ids:p,match:S},scheduled_at:V});J===Me.current&&j({key:A,plan:se})}catch(se){if(J!==Me.current)return;j(null),te(hr(se))}},[n,r,p,S,V,A,u]),Ee=Nt.useRef(!1);Nt.useEffect(()=>{if(!_&&p.length>0)return;if(!Ee.current){Ee.current=!0,Se();return}let J=setTimeout(()=>void Se(),300);return()=>clearTimeout(J)},[Se,_,p.length]);let Ye=l&&!l.readiness.can_send?Ns(l.readiness.reason):null,ke=ne!==null&&!ne.fits,nt=g?Math.max(0,g.by_status.subscribed-g.mailable):null,E=g&&ne&&nt!==null?Math.max(0,g.total-ne.recipients-nt):null,M=!i||T.busy||!ne||!re||ke||ne.recipients===0||Ye!==null||f&&p.length>0,L=async()=>{me(null);let J=await T.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:p,match:S},scheduled_at:V});if(J.ok){me({tone:"success",text:V?"Scheduled.":"Sending now."}),s();return}Ga(J.error,"version_conflict")?(T.setError(null),await a(),me({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):Ga(J.error,"over_allowance")&&await Se()},pe=J=>x(se=>se.includes(J)?se.filter(Fe=>Fe!==J):[...se,J]);return Et("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[v.suggested&&!w&&Re(fe,{children:"Suggested by your assistant \u2014 review before sending."}),Re(_a,{children:"Who gets it"}),f&&Re(fe,{tone:"warning",children:p.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."}),R>0&&Re(fe,{tone:"warning",children:R===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),c&&c.length>0?Et("div",{className:"af-space-y-2",children:[Re("div",{className:"af-flex af-flex-wrap af-gap-2",children:c.map(J=>Et("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[Re("input",{type:"checkbox",checked:p.includes(J.id),onChange:()=>pe(J.id)}),J.label]},J.id))}),p.length>1&&Et("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",Et("select",{"aria-label":"Tag match",value:S,onChange:J=>k(J.target.value),className:"af-rounded-md af-border af-px-2 af-py-1",children:[Re("option",{value:"any",children:"any of these tags"}),Re("option",{value:"all",children:"all of these tags"})]})]}),p.length===0&&Re("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):Re("p",{className:"af-text-sm af-text-muted-foreground",children:"Everyone who can be emailed."}),Et("label",{className:"af-block af-space-y-1",children:[Re("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),Re(ae,{"aria-label":"Schedule time",type:"datetime-local",value:h,onChange:J=>N(J.target.value)})]}),v.timePassed&&!h&&Re(fe,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),U?Et(fe,{tone:"error",children:["Couldn't work out the audience. ",U]}):ne?Et("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[Et("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[Re(Cl,{label:"Will receive it",value:ne.recipients}),Re(Cl,{label:"Suppressed (bounced or complained)",value:nt}),Re(Cl,{label:"Not included",value:E})]}),Et("p",{className:"af-text-muted-foreground",children:[Ae(ne.allowance.remaining)," of ",Ae(ne.allowance.monthly)," emails left this month."]}),ne.sample_size!==null&&Et(fe,{children:["We'll send to ",Ae(ne.sample_size)," people first and check for bounces before sending the rest."]}),ne.ramp_days.length>1&&Et(fe,{children:["Your domain is new, so this goes out over ",ne.ramp_days.length," days:"," ",ne.ramp_days.map(J=>`${Ae(J.recipients)} on ${J.date}`).join(", "),"."]})]}):Re(G,{className:"af-h-12 af-w-full"}),ke&&ne&&Et(fe,{tone:"warning",children:["This send needs ",Ae(ne.recipients)," emails, but only ",Ae(ne.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),Ye&&Et(fe,{tone:"warning",children:[Ye,Re(br,{reason:l?.readiness.reason})]}),ce&&Re(fe,{tone:ce.tone,children:ce.text}),T.error&&Re(fe,{tone:"error",children:T.error}),Re(y,{type:"button",disabled:M,onClick:()=>void L(),children:V?"Schedule":"Send now"})]})}function Cl({label:e,value:t}){return Et("div",{className:"af-rounded-md af-border af-px-2 af-py-1",children:[Re("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Re("div",{className:"af-font-semibold",children:t===null?"\u2014":Ae(t)})]})}import*as Ka from"react";import{Check as ku,FileText as Jv,ShieldCheck as Cu}from"lucide-react";import*as Hs from"react";import{ArrowRight as Bv,Check as Nu,ChevronDown as Fv,Globe as Mv,Lock as $v,Mail as go,PenLine as Uv,Sparkles as Vv}from"lucide-react";import{Fragment as El,jsx as K,jsxs as be}from"react/jsx-runtime";var Hv=[{title:"Own your audience",body:"Your list is yours. Reaching it doesn't depend on a social feed or an ad budget."},{title:"Bring people back",body:"Most visitors leave and never return. Email gets them back when you have news, a sale or something new."},{title:"Look like you",body:"Emails come from your own domain, with your logo and colors."}],zv="hello";function Il(e){return`${zv}@${e}`}function Ru({onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,onTurnOn:s,siteDomain:n,businessName:r,dnsManaged:i,renderSendingRecords:l}){let{api:u}=H(),{siteId:c,settings:o,canWrite:f,refreshKey:b,refetchSettings:g}=Ke(),m=Bt(()=>u.getMarketingContactStats(c),`${c}|${b}`,c),[v,d]=Hs.useState(!1),[p,x]=Hs.useState(null);if(!o)return null;let S=m.data?.by_status.subscribed??0,k={siteDomain:n,businessName:r};return jv(o)?K(Al,{settings:o,site:k,waiting:S,children:f?s&&be("div",{className:"af-space-y-2",children:[be(y,{disabled:v,onClick:async()=>{d(!0),x(null);try{await s(),await g()}catch(h){x(h instanceof Error?h.message:"Couldn't turn on email. Try again.")}finally{d(!1)}},children:["Get started ",K(Bv,{className:"af-ml-2 af-h-4 af-w-4","aria-hidden":!0})]}),p&&K(fe,{tone:"error",children:p})]}):K("p",{className:"af-text-sm af-text-muted-foreground",children:"Only the site owner can set up email."})}):K(qv,{settings:o,site:k,waiting:S,onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,dnsManaged:i,renderSendingRecords:l})}function jv(e){return e.readiness.reason==="sending_not_enabled"}function Al({settings:e,site:t,waiting:a=0,children:s}){return K("div",{className:"af-mx-auto af-max-w-3xl af-px-2 af-py-8",children:be("div",{className:"af-grid af-items-center af-gap-10 md:af-grid-cols-[1fr_18rem]",children:[be("div",{children:[be("div",{className:"af-mb-3 af-inline-flex af-items-center af-gap-1.5 af-rounded-full af-bg-muted af-px-2.5 af-py-1 af-text-xs af-font-medium",children:[K(go,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0})," Email marketing"]}),K("h3",{className:"af-text-2xl af-font-semibold af-tracking-tight",children:"Turn visitors into regulars"}),K("p",{className:"af-mt-2 af-text-muted-foreground",children:"Build an email list from your website and reach those people directly, whenever you have something worth telling them."}),K("ol",{className:"af-mt-6 af-space-y-3",children:Hv.map((n,r)=>be("li",{className:"af-flex af-gap-3",children:[K("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-border af-text-xs af-font-semibold",children:r+1}),be("p",{className:"af-text-sm",children:[be("span",{className:"af-font-medium",children:[n.title,"."]})," ",K("span",{className:"af-text-muted-foreground",children:n.body})]})]},n.title))}),a>0&&be("p",{className:"af-mt-5 af-rounded-md af-bg-amber-50 af-px-3 af-py-2 af-text-sm af-text-amber-900",children:[be("span",{className:"af-font-semibold",children:[Ae(a)," ",a===1?"person has":"people have"]})," ","already signed up and ",a===1?"is":"are"," waiting for your first email."]}),K("div",{className:"af-mt-6",children:s})]}),K(vo,{settings:e,site:t,className:"af-rotate-1"})]})})}function _u({onUpgradePlan:e}){return be("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-border-violet-200 af-bg-gradient-to-r af-from-violet-50 af-to-white af-p-4",children:[K($v,{className:"af-h-5 af-w-5 af-shrink-0 af-text-violet-700","aria-hidden":!0}),be("div",{className:"af-flex-1",children:[K("div",{className:"af-text-sm af-font-semibold af-text-violet-900",children:"Email marketing is part of Pro"}),K("div",{className:"af-text-sm af-text-violet-900/80",children:"Collect subscribers and send newsletters from your own domain."})]}),e&&K(y,{size:"sm",onClick:e,children:"Upgrade to Pro"})]})}function qv({settings:e,site:t,waiting:a,onStartDomainSetup:s,onConnectDomain:n,onAskAssistant:r,dnsManaged:i,renderSendingRecords:l}){let{refetchSettings:u,canWrite:c}=Ke(),[o,f]=Hs.useState(null),b=p=>f(x=>x===p?null:p),{siteDomain:g}=t,m=Wr(e),v=g===null&&!e.domain.sending_domain,d=!!e.postal_address;return be("div",{className:"af-mx-auto af-max-w-4xl af-py-4",children:[be("div",{className:"af-mb-6 af-flex af-items-start af-justify-between af-gap-6",children:[be("div",{children:[K("h3",{className:"af-text-xl af-font-semibold",children:"Set up email"}),be("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Newsletters to your subscribers, sent from ",g??"your own domain","."]})]}),a>0&&be("div",{className:"af-text-right",children:[K("div",{className:"af-text-2xl af-font-semibold",children:Ae(a)}),be("div",{className:"af-text-xs af-text-muted-foreground",children:[a===1?"subscriber":"subscribers"," waiting"]})]})]}),!c&&K(fe,{className:"af-mb-4",children:"Only the site owner can finish setup."}),be("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_16rem]",children:[be("div",{className:"af-space-y-4",children:[be(Tl,{title:g??"Your domain",sub:"One domain for your website and your email.",children:[g&&K(dn,{icon:Mv,label:"Website",value:g,status:K(Bn,{tone:"green",children:"Live"})}),v?K(dn,{icon:go,label:"Email sending",value:"Needs a custom domain",status:K(Bn,{tone:"gray",children:"Not available"}),action:n&&c?{label:"Connect domain",onClick:n}:void 0}):be(dn,{icon:go,label:"Email sending",value:e.domain.sending_domain??(g?`news.${g}`:"news.yourdomain.com"),status:Dl(e),action:!m&&c?{label:e.domain.sending_domain?"Details":"Set up",onClick:()=>b("sending")}:void 0,expanded:o==="sending",children:[!e.domain.sending_domain&&be("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."," ",i?"We manage your domain's DNS, so we add the records for you. Nothing to copy.":i===!1?"You'll get a few records to copy into your DNS provider.":"If we manage your domain's DNS we add the records; otherwise you'll get a few to copy into your DNS provider."]}),K(Ol,{settings:e,canWrite:c,onStartDomainSetup:s,onChanged:u,dnsManaged:i,renderSendingRecords:l})]})]}),K(Tl,{title:"Sender",sub:"Who your emails are from. The mailing address is legally required in every email.",children:K(dn,{icon:Uv,label:d?e.business_name??"Sender":"Not set",value:e.postal_address??"Name, mailing address and reply-to",status:d?K(Bn,{tone:"green",children:"Done"}):K(Bn,{tone:"gray",children:"Needed"}),action:c?{label:d?"Edit":"Add",onClick:()=>b("sender")}:void 0,expanded:o==="sender",children:K(Wv,{settings:e,businessName:t.businessName,onSaved:async()=>{await u(),f(null)}})})}),K(Tl,{title:"How people join your list",sub:"Only people who asked to hear from you get your emails.",children:K(Yv,{onAskAssistant:c?r:void 0})})]}),be("aside",{className:"af-space-y-3",children:[K("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails will look like"}),K(vo,{settings:e,site:t})]})]})]})}function Tl({title:e,sub:t,children:a}){return be("section",{className:"af-rounded-xl af-border af-bg-background",children:[be("div",{className:"af-px-5 af-pb-3 af-pt-4",children:[K("h4",{className:"af-text-sm af-font-semibold",children:e}),K("p",{className:"af-text-xs af-text-muted-foreground",children:t})]}),K("div",{className:"af-space-y-2 af-px-3 af-pb-3",children:a})]})}function dn({icon:e,marker:t,markerSpace:a=!1,label:s,value:n,mono:r=!0,hint:i,status:l,action:u,expanded:c=!1,children:o}){return be("div",{className:"af-rounded-lg af-border af-bg-muted/30",children:[be("div",{className:"af-flex af-items-center af-gap-3 af-p-3",children:[t?be("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-xs af-font-semibold af-text-background",children:[K("span",{"aria-hidden":!0,children:t}),be("span",{className:"af-sr-only",children:["Shown at ",t," in the preview"]})]}):a?K("span",{className:"af-h-6 af-w-6 af-shrink-0","aria-hidden":!0}):e&&K("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-background",children:K(e,{className:"af-h-4 af-w-4","aria-hidden":!0})}),be("div",{className:"af-min-w-0 af-flex-1",children:[K("div",{className:"af-text-xs af-text-muted-foreground",children:s}),K("div",{className:W("af-truncate af-text-sm",r&&"af-font-mono"),children:n}),i&&K("div",{className:"af-text-xs af-text-muted-foreground",children:i})]}),l,u&&be(y,{size:"sm",variant:c?"secondary":"outline","aria-expanded":o?c:void 0,onClick:u.onClick,children:[u.label,o&&K(Fv,{className:W("af-ml-1 af-h-3.5 af-w-3.5 af-transition-transform",c&&"af-rotate-180"),"aria-hidden":!0})]})]}),c&&o&&K("div",{className:"af-border-t af-bg-background af-p-4",children:o})]})}function Bn({tone:e,children:t}){return K("span",{className:W("af-inline-flex af-shrink-0 af-items-center af-rounded-full af-px-2 af-py-0.5 af-text-xs af-font-medium",e==="green"&&"af-bg-green-100 af-text-green-800",e==="amber"&&"af-bg-amber-100 af-text-amber-900",e==="gray"&&"af-bg-muted af-text-muted-foreground",e==="red"&&"af-bg-red-100 af-text-red-800"),children:t})}function Wr(e){return e.domain.status==="verified"&&e.domain.dmarc_status==="ok"}function Dl(e){let{sending_domain:t,status:a}=e.domain;return!t||a==="none"?K(Bn,{tone:"gray",children:"Not set up"}):a==="verified"?Wr(e)?K(Bn,{tone:"green",children:"Live"}):K(Bn,{tone:"amber",children:"DMARC record missing"}):a==="failed"?K(Bn,{tone:"red",children:"Records not found"}):K(Bn,{tone:"amber",children:"Waiting for DNS"})}function Wv({settings:e,businessName:t,onSaved:a}){let{canWrite:s}=Ke(),[n,r]=Hs.useState(e.business_name??t??""),[i,l]=Hs.useState(e.postal_address??""),[u,c]=Hs.useState(e.reply_to??""),o=vt();return be("form",{className:"af-space-y-3",onSubmit:async f=>{f.preventDefault(),(await o.run("updateSettings",{business_name:n.trim()||null,postal_address:i.trim()||null,reply_to:u.trim()||null,double_opt_in:e.double_opt_in})).ok&&await a()},children:[K(Gv,{name:n,address:i}),be("label",{className:"af-block af-space-y-1",children:[K("span",{className:"af-text-sm af-font-medium",children:"Sender name"}),K(ae,{"aria-label":"Business name",value:n,disabled:!s,onChange:f=>r(f.target.value)})]}),be("label",{className:"af-block af-space-y-1",children:[K("span",{className:"af-text-sm af-font-medium",children:"Mailing address"}),K("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:i,disabled:!s,onChange:f=>l(f.target.value)}),K("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Anti-spam law requires it at the bottom of every email. A PO box works."})]}),be("label",{className:"af-block af-space-y-1",children:[K("span",{className:"af-text-sm af-font-medium",children:"Replies go to (optional)"}),K(ae,{"aria-label":"Reply-to email",type:"email",value:u,disabled:!s,onChange:f=>c(f.target.value)}),K("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Your account email or an address on your domain."})]}),o.error&&K(fe,{tone:"error",children:o.error}),s&&K(y,{type:"submit",size:"sm",disabled:o.busy||!i.trim(),children:"Save sender details"})]})}function Gv({name:e,address:t}){return be("div",{className:"af-rounded-lg af-bg-muted/50 af-px-4 af-py-4 af-text-center af-text-xs af-leading-relaxed af-text-muted-foreground",children:[K("div",{className:"af-mb-1 af-text-[10px] af-uppercase af-tracking-wide",children:"Footer of every email"}),be("div",{children:["\xA9 ",new Date().getFullYear()," ",K("span",{className:"af-font-medium af-text-foreground",children:e.trim()||"Your business"})]}),K("div",{className:W(!t.trim()&&"af-italic af-text-amber-700"),children:t.trim()||"No mailing address yet"}),be("div",{children:[K("span",{className:"af-underline",children:"Manage preferences"})," | ",K("span",{className:"af-underline",children:"Unsubscribe"})]})]})}var Kv={1:"From",2:"Subject and body",3:"Footer"};function vo({settings:e,site:t,className:a,numbered:s=!1,highlight:n=null,postalAddress:r}){let i=e?.business_name||t.businessName||"Your business",l=e?.domain.sending_domain??(t.siteDomain?`news.${t.siteDomain}`:"news.yourdomain.com"),u={backgroundColor:e?.brand.color??"hsl(var(--primary))"},c=r!==void 0?r.trim()||null:e?.postal_address,o=(f,b,g)=>s?be("div",{"data-preview-region":f,"data-highlighted":n===f,className:W("af-relative af-rounded-md af-pl-7 af-transition-shadow",n===f&&"af-ring-2 af-ring-primary af-ring-offset-2",b),children:[be("span",{className:"af-absolute af-left-0 af-top-0 af-flex af-h-5 af-w-5 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-[10px] af-font-semibold af-text-background",children:[K("span",{"aria-hidden":!0,children:f}),be("span",{className:"af-sr-only",children:[f,". ",Kv[f],":"]})]}),g]}):K("div",{className:b,children:g});return be("div",{className:W("af-rounded-lg af-border af-bg-background af-p-4 af-shadow-sm",a),"aria-hidden":s?void 0:!0,"aria-label":s?"Email preview":void 0,role:s?"group":void 0,children:[o(1,"af-flex af-items-start af-gap-3",be(El,{children:[K("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-sm af-font-semibold af-text-white",style:u,children:i.slice(0,1).toUpperCase()}),be("div",{className:"af-min-w-0",children:[K("div",{className:"af-truncate af-text-sm af-font-semibold",children:i}),be("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:["<",Il(l),">"]}),K("div",{className:"af-text-xs af-text-muted-foreground",children:"to me"})]})]})),o(2,"af-mt-4 af-space-y-2",be(El,{children:[K("div",{className:"af-text-sm af-font-medium",children:"What's new this month"}),K("div",{className:"af-h-2 af-w-full af-rounded af-bg-muted"}),K("div",{className:"af-h-2 af-w-5/6 af-rounded af-bg-muted"}),K("div",{className:"af-h-2 af-w-2/3 af-rounded af-bg-muted"})]})),o(3,"af-mt-4 af-border-t af-pt-2 af-text-center af-text-[10px] af-leading-snug af-text-muted-foreground",be(El,{children:[K("div",{children:c??K("span",{className:"af-italic af-text-amber-700",children:"Mailing address goes here"})}),K("div",{className:"af-underline",children:"Unsubscribe"})]}))]})}var Zv="Add a newsletter signup to my footer";function Yv({onAskAssistant:e}){let t=Ll();if(!t.data)return null;let{signups:a,optIns:s,others:n}=Bl(t.data);return be("div",{className:"af-space-y-3",children:[a.length===0?be("div",{className:"af-flex af-flex-col af-items-center af-gap-2 af-rounded-lg af-border af-border-dashed af-px-6 af-py-6 af-text-center",children:[K("div",{className:"af-flex af-h-10 af-w-10 af-items-center af-justify-center af-rounded-full af-bg-muted",children:K(go,{className:"af-h-5 af-w-5","aria-hidden":!0})}),K("div",{className:"af-text-sm af-font-medium",children:"Add a signup form to your site"}),K("p",{className:"af-max-w-sm af-text-xs af-text-muted-foreground",children:`A short "Get our news" form, usually in the footer. It's how most of your list will find you.`}),e&&be(y,{type:"button",size:"sm",className:"af-mt-1",onClick:()=>e(Zv),children:[K(Vv,{className:"af-mr-1.5 af-h-3.5 af-w-3.5","aria-hidden":!0}),"Add signup form"]})]}):be("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[K(Nu,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),be("div",{className:"af-min-w-0 af-flex-1",children:[K("span",{className:"af-font-medium",children:"Signup form is live"}),be("span",{className:"af-text-muted-foreground",children:[" \xB7 ",a.map(r=>r.name).join(", ")]})]})]}),s.length>0&&be("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[K(Nu,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),be("div",{className:"af-min-w-0 af-flex-1",children:[K("span",{className:"af-font-medium",children:"Opt-in checkbox"}),be("span",{className:"af-text-muted-foreground",children:[" \xB7 ",s.map(r=>r.name).join(", ")]})]})]}),a.length===0&&n.length>0&&be("div",{className:"af-space-y-1 af-px-2 af-text-xs af-text-muted-foreground",children:[be("p",{children:[n.length===1?"This form":"These forms",' can also add people, with a "Send me news" checkbox:']}),K("ul",{className:"af-space-y-1",children:n.map(r=>be("li",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[K("span",{className:"af-truncate af-text-foreground",children:r.name}),e&&K("button",{type:"button",className:"af-shrink-0 af-font-medium af-text-foreground af-underline af-underline-offset-2",onClick:()=>e(Fl([r])),children:"Add the checkbox"})]},r.id))})]})]})}import{Fragment as ib,jsx as ue,jsxs as Ht}from"react/jsx-runtime";var bo="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 Xv(e){let{status:t,dmarc_status:a,sending_domain:s}=e.domain;return!s||t==="none"?"No sending domain yet.":t==="verified"?a==="ok"?`Verified. Emails send from ${s}.`:`${s} is verified, but your domain still needs a DMARC record.`:t==="failed"?`${s} couldn't be verified. Check the DNS records below.`:`Waiting for the DNS records on ${s} to take effect. This can take a few hours.`}function Ml({onStartDomainSetup:e,onAskAssistant:t,dnsManaged:a,renderSendingRecords:s}){let{settings:n,refetchSettings:r,canWrite:i,settingsSection:l,onOpenBrandSettings:u}=Ke(),[c,o]=Ka.useState(null),[f,b]=Ka.useState(null),[g,m]=Ka.useState(""),v=n!==null;if(Ka.useEffect(()=>{v&&l&&document.getElementById(Hr(l))?.scrollIntoView?.({block:"start"})},[v,l]),!n)return ue(G,{className:"af-h-40 af-w-full"});let d=C=>b(w=>w===C?null:C),p=()=>b(null),x=async()=>{await r(),p()},S=(C,w,P)=>({id:P,"data-settings-row":C,onMouseEnter:()=>o(w),onMouseLeave:()=>o(null),onFocus:()=>o(w),onBlur:()=>o(null)}),k=Wr(n),{sending_domain:h,status:N}=n.domain,R=C=>i?{expanded:f===C}:{};return ue("div",{className:"af-@container",children:Ht("div",{className:"af-grid af-items-start af-gap-6 @2xl:af-grid-cols-[minmax(0,17rem)_minmax(0,1fr)]",children:[Ht("aside",{className:"af-space-y-3 af-pl-3",children:[ue("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails look like this"}),ue(vo,{settings:n,site:{},numbered:!0,highlight:c,postalAddress:f==="address"?g:void 0}),ue(sb,{settings:n})]}),Ht("div",{children:[ue(_a,{children:"From"}),Ht("div",{className:"af-space-y-2",children:[ue("div",{...S("Sending domain",1,Hr("domain")),children:ue(dn,{markerSpace:!0,label:"Sending from",value:h?Il(h):"No sending domain yet",status:Dl(n),action:!k&&i?{label:h?N==="verified"||N==="failed"?"Fix":"Details":"Set up",onClick:()=>d("domain")}:void 0,...R("domain"),children:ue(Ol,{settings:n,canWrite:i,onStartDomainSetup:e,onChanged:r,dnsManaged:a,renderSendingRecords:s})})}),ue("div",{...S("Sender name and replies",1),children:ue(dn,{marker:1,label:"Sender name and replies",mono:!1,value:`${n.business_name??"No sender name"} \xB7 replies to ${n.reply_to??"your account email"}`,action:i?{label:"Edit",onClick:()=>d("sender")}:void 0,...R("sender"),children:ue(Qv,{settings:n,onSaved:x,onCancel:p})})})]}),ue(_a,{children:"Brand"}),ue("div",{...S("Logo",2),children:ue(dn,{marker:2,label:"Logo",mono:!1,value:n.brand.logo_url?"Your logo, from Brand settings":"No logo yet",hint:"Emails use your site's logo. Colors come from the email's template.",action:u?{label:"Brand settings",onClick:u}:void 0})}),ue(_a,{children:"Footer"}),ue("div",{...S("Mailing address",3,Hr("sender")),children:ue(dn,{marker:3,label:"Mailing address",mono:!1,value:n.postal_address??"Not set",hint:"Anti-spam law requires it at the bottom of every email. A PO box works.",status:n.postal_address?void 0:ue(Bn,{tone:"amber",children:"Needed"}),action:i?{label:n.postal_address?"Edit":"Add",onClick:()=>{m(n.postal_address??""),d("address")}}:void 0,...R("address"),children:ue(eb,{settings:n,draft:g,onDraft:m,onSaved:x,onCancel:p})})}),Ht("div",{id:Hr("signups"),className:"af-mt-6",children:[ue(_a,{children:"Signups"}),Ht("div",{className:"af-space-y-2",children:[ue("div",{...S("Double opt-in",null),children:ue(tb,{settings:n,canWrite:i,onSaved:r})}),ue(rb,{onAskAssistant:i?t:void 0})]})]})]})]})})}function $l(e,t){return{business_name:e.business_name,postal_address:e.postal_address,reply_to:e.reply_to,double_opt_in:e.double_opt_in,...t}}function Tu({busy:e,error:t,canSave:a=!0,onSave:s,onCancel:n,children:r}){return Ht("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),await s()},children:[r,t&&ue(fe,{tone:"error",children:t}),Ht("div",{className:"af-flex af-gap-2",children:[ue(y,{type:"submit",size:"sm",disabled:e||!a,children:"Save"}),ue(y,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Cancel"})]})]})}function Qv({settings:e,onSaved:t,onCancel:a}){let[s,n]=Ka.useState(e.business_name??""),[r,i]=Ka.useState(e.reply_to??""),l=vt();return Ht(Tu,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",$l(e,{business_name:s.trim()||null,reply_to:r.trim()||null}))).ok&&await t()},children:[ue(Pu,{label:"Sender name",children:ue(ae,{"aria-label":"Business name",value:s,onChange:u=>n(u.target.value)})}),ue(Pu,{label:"Replies go to (your account email or an address on your domain)",children:ue(ae,{"aria-label":"Reply-to email",type:"email",value:r,onChange:u=>i(u.target.value)})})]})}function eb({settings:e,draft:t,onDraft:a,onSaved:s,onCancel:n}){let r=vt();return ue(Tu,{busy:r.busy,error:r.error,canSave:!!t.trim(),onCancel:n,onSave:async()=>{(await r.run("updateSettings",$l(e,{postal_address:t.trim()}))).ok&&await s()},children:ue("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:t,onChange:i=>a(i.target.value)})})}function tb({settings:e,canWrite:t,onSaved:a}){let[s,n]=Ka.useState(null),[r,i]=Ka.useState(!1),l=vt(),u=s??e.double_opt_in;return Ht("div",{className:"af-space-y-2",children:[ue(dn,{icon:Cu,label:"Double opt-in",mono:!1,value:u?"New subscribers confirm by email first":"New subscribers join straight away",status:Ht("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[ue("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:bo,className:"af-inline-flex af-h-4 af-w-4 af-cursor-help af-items-center af-justify-center af-rounded-full af-border af-text-[10px]",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:"?"}),ue("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!r,className:"af-absolute af-right-0 af-top-6 af-z-10 af-w-72 af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:bo}),ue("input",{"aria-label":"Double opt-in",type:"checkbox",role:"switch",checked:u,disabled:!t||l.busy,onChange:async c=>{let o=c.target.checked;n(o),(await l.run("updateSettings",$l(e,{double_opt_in:o}))).ok&&await a(),n(null)}})]})}),l.error&&ue(fe,{tone:"error",children:l.error})]})}function Ol({settings:e,canWrite:t,onStartDomainSetup:a,onChanged:s,dnsManaged:n,renderSendingRecords:r}){let[i,l]=Ka.useState(null),[u,c]=Ka.useState(!1),[o,f]=Ka.useState(null),[b,g]=Ka.useState(0),m=Wr(e),{sending_domain:v,status:d}=e.domain,x=i?.status==="managed"||i?.status==="external"?i?.status==="managed":!!n,S=i?.records??[],k=x&&v&&!m&&d!=="verified"?ue(ab,{failed:d==="failed"}):null;return Ht("div",{children:[k??ue("p",{className:"af-text-sm",children:Xv(e)}),!m&&a&&ue(y,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||u,onClick:async()=>{c(!0),f(null);try{l(await a()),g(h=>h+1),await s()}catch(h){f(h instanceof Error?h.message:"Couldn't start domain setup.")}finally{c(!1)}},children:v?"Check domain setup":"Set up sending domain"}),o&&ue(fe,{tone:"error",className:"af-mt-2",children:o}),r?(v||i)&&ue("div",{className:"af-mt-3",children:r()},b):S.length>0&&Ht("div",{className:"af-mt-3 af-space-y-1",children:[ue("p",{className:"af-text-sm",children:x?"The records we added to your DNS:":"Add these records at your domain provider:"}),Ht("table",{className:"af-w-full af-text-left af-text-xs",children:[ue("thead",{children:Ht("tr",{children:[ue("th",{className:"af-py-1 af-pr-2",children:"Type"}),ue("th",{className:"af-py-1 af-pr-2",children:"Name"}),ue("th",{className:"af-py-1 af-pr-2",children:"Value"}),ue("th",{className:"af-py-1",children:"Priority"})]})}),ue("tbody",{children:S.map((h,N)=>Ht("tr",{className:"af-border-t af-align-top",children:[ue("td",{className:"af-py-1 af-pr-2",children:h.type}),ue("td",{className:"af-break-all af-py-1 af-pr-2",children:h.name}),ue("td",{className:"af-break-all af-py-1 af-pr-2",children:h.value}),ue("td",{className:"af-py-1",children:h.priority??""})]},N))})]})]}),i&&!k&&ue(nb,{result:i})]})}function ab({failed:e}){return e?Ht(fe,{tone:"warning",children:[ue("div",{className:"af-font-medium",children:"Verification is taking longer than usual. Nothing for you to change."}),ue("div",{children:"We added the records and will keep checking. If it isn't live within a day, contact support and we'll sort it out."})]}):ue(fe,{tone:"success",children:Ht("div",{className:"af-flex af-gap-2",children:[ue(Cu,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0","aria-hidden":!0}),Ht("div",{children:[ue("div",{className:"af-font-medium",children:"We added these records to your DNS for you. Nothing to do."}),ue("div",{children:"Verification usually finishes within a few hours."})]})]})})}function nb({result:e}){return e.status==="no_domain"?ue(fe,{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"?ue(fe,{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:ue("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 sb({settings:e}){let{monthly:t,sent:a,reserved:s}=e.allowance,n=a+s;return Ht("p",{className:"af-text-xs af-text-muted-foreground",children:[Ae(n)," of ",Ae(t)," emails used this month (",Ae(Math.max(0,t-n))," left). Receipts and form notifications don't count."]})}function Ll(){let{api:e}=H(),{siteId:t,refreshKey:a}=Ke();return Bt(async()=>Promise.all((await e.getForms()).map(s=>e.getForm(s.id))),`${t}|${a}`,t)}function Bl(e){return{signups:e.filter(t=>t.purpose==="newsletter"),optIns:e.filter(t=>t.purpose==="opt_in"),others:e.filter(t=>t.purpose!=="newsletter"&&t.purpose!=="opt_in")}}function Fl(e){let t=e.length===1;return`Add a "Send me news" opt-in checkbox to ${t?"the":"these"} ${e.map(a=>a.name).join(" and ")} form${t?"":"s"}`}function rb({onAskAssistant:e}){let t=Ll();if(!t.data||t.data.length===0)return null;let{signups:a,optIns:s,others:n}=Bl(t.data),r=a.length===0?e:void 0;return Ht(ib,{children:[a.length>0&&ue("div",{"data-form-group":"signup",children:ue(dn,{icon:ku,label:"Signup forms",mono:!1,value:a.map(i=>i.name).join(", "),hint:"Submitting one subscribes the visitor."})}),s.length>0&&ue("div",{"data-form-group":"opt_in",children:ue(dn,{icon:ku,label:'Forms with a "Send me news" checkbox',mono:!1,value:s.map(i=>i.name).join(", "),hint:"Visitors who tick the box join your list."})}),n.length>0&&ue("div",{"data-form-group":"other",className:"af-space-y-2",children:n.map(i=>ue("div",{"data-form-row":!0,children:ue(dn,{icon:Jv,label:"Other form",mono:!1,value:i.name,hint:"Doesn't add anyone to your list.",action:r?{label:"Add the checkbox",onClick:()=>r(Fl([i]))}:void 0})},i.id))})]})}function Pu({label:e,children:t}){return Ht("label",{className:"af-block af-space-y-1",children:[ue("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}import*as ho from"react";import{jsx as ma,jsxs as zs}from"react/jsx-runtime";function Iu({templateId:e,onOpenTemplate:t,onOpenDraft:a,onAskAssistant:s}){let{api:n}=H(),{siteId:r,canWrite:i,refreshKey:l}=Ke(),[u,c]=ho.useState(0),o=u+l,f=Bt(()=>n.getEmailTemplates(r),`${r}|${o}`,r),b=ho.useCallback(()=>c(d=>d+1),[]),g=i?s:void 0;if(e){let d=e===Jn?null:f.data?.find(p=>p.id===e);if(d!==void 0)return ma(gu,{template:d,onBack:()=>t(null),onOpenTemplate:t,onOpenDraft:a,onAskAssistant:g,reload:b,refreshKey:o},e);if(f.isLoading)return ma(G,{className:"af-h-96 af-w-full"})}let m=f.data?.filter(d=>d.status!=="archived")??[],v=f.data?.filter(d=>d.status==="archived")??[];return zs("div",{children:[zs("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[ma("h3",{className:"af-text-sm af-font-semibold",children:"Templates"}),g&&ma(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(co.create),children:"\u2728 New template with the editor"})]}),zs(Eu,{children:[ma(Ul,{template:null,onOpen:()=>t(Jn)}),m.map(d=>ma(Ul,{template:d,onOpen:()=>t(d.id)},d.id))]}),f.error&&!f.data?ma("div",{className:"af-mt-3",children:ma(xt,{message:"Couldn't load your templates.",onRetry:()=>void f.refetch()})}):!f.data&&ma(G,{className:"af-mt-3 af-h-10 af-w-full"}),v.length>0&&zs("div",{"data-testid":"archived-templates",children:[ma(_a,{children:"Archived"}),ma(Eu,{children:v.map(d=>ma(Ul,{template:d,onOpen:()=>t(d.id)},d.id))})]})]})}function Eu({children:e}){return ma("ul",{className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:e})}function ob(e){let t=[kl(e.usage.drafts),e.usage.scheduled>0&&`${e.usage.scheduled} scheduled`,e.usage.sent>0&&`${e.usage.sent} sent`].filter(Boolean);return t.length>0?t.join(" \xB7 "):null}function Ul({template:e,onOpen:t}){let a=e?.name??"Standard",s=e&&ob(e);return zs("li",{"data-testid":"template-card",className:"af-relative af-overflow-hidden af-rounded-md af-border hover:af-border-primary",children:[ma(uo,{templateId:e?.id??Jn,version:e?.updated_at??"builtin",className:"af-h-40 af-border-b",frame:{width:600,height:400,scale:.4}}),zs("div",{className:"af-space-y-1 af-p-2",children:[zs("div",{className:"af-flex af-items-center af-gap-2",children:[ma("span",{"data-testid":"template-name",className:"af-grow af-truncate af-text-sm af-font-medium",children:a}),ma(_l,{template:e})]}),s&&ma("p",{className:"af-text-xs af-text-muted-foreground",children:s})]}),ma("button",{type:"button","aria-label":`Open ${a}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}import*as un from"react";import{ChevronRight as jl}from"lucide-react";import*as Za from"react";import{ArrowDown as lb,ArrowUp as cb,Clock as Ou,Mail as Lu,Plus as db,Trash2 as ub,Zap as fb}from"lucide-react";import{Fragment as zl,jsx as _e,jsxs as zt}from"react/jsx-runtime";var mb=365*24,pb=[1,24,48,72,168];function xo(e){return e.map(t=>t.type==="send"?{type:"send",draft_id:t.draft_id}:{type:"wait",wait_hours:t.wait_hours})}function _s(e){return e%168===0?Ms(e/168,"week"):e%24===0?Ms(e/24,"day"):Ms(e,"hour")}var Kr={joined_list:{title:"Someone joins your list",phrase:"joins your list"},purchase_made:{title:"Someone buys from your store",phrase:"buys from your store"},abandoned_checkout:{title:"Someone leaves checkout without paying",phrase:"leaves checkout without paying"}};function Zr(e,t){return e.slice(0,t+1).filter(a=>a.type==="send").length}var yo=300,Au=64,gb=24,Gr={trigger:72,send:104,wait:64,waitEditing:196,exit:44};function vb(e,t){let a=[],s=0,n=r=>{a.push({...r,y:s}),s+=r.height+Au};return n({id:"trigger",kind:"trigger",height:Gr.trigger}),e.forEach((r,i)=>n({id:r.step_key,kind:r.type,index:i,height:r.type==="send"?Gr.send:r.step_key===t?Gr.waitEditing:Gr.wait})),n({id:"exit",kind:"exit",height:Gr.exit}),{nodes:a,height:s-Au}}var Bu=Za.createContext(null);function Yr(){let e=Za.useContext(Bu);if(!e)throw new Error("Canvas nodes render inside AutomationCanvas");return e}function Vl(e,t){let a=e[t];return a.type==="send"?`email ${Zr(e,t)}`:`the ${_s(a.wait_hours)} wait`}function Fu(e){let{automation:t,onChangeSteps:a}=e,s=t.steps,[n,r]=Za.useState(null),[i,l]=Za.useState(null),[u,c]=Za.useState(null),o=(m,v)=>{c(null),r(null),l(null),a(m,v)},f=xo(s),b={...e,insertAt:n,setInsertAt:m=>{c(null),r(m)},editingWait:i,setEditingWait:l,insertWait:m=>{if(!f.slice(m).some(v=>v.type==="send")){r(null),c("A wait after the last email does nothing, so it wasn't added.");return}o([...f.slice(0,m),{type:"wait",wait_hours:24},...f.slice(m)],"Add a 1 day wait")},setWait:(m,v)=>o(f.map((d,p)=>p===m?{type:"wait",wait_hours:v}:d),`Change ${Vl(s,m)} to ${_s(v)}`),move:(m,v)=>{let d=[...f];[d[m],d[m+v]]=[d[m+v],d[m]],o(d,`Move ${Vl(s,m)} ${v<0?"up":"down"}`)},remove:m=>o(f.filter((v,d)=>d!==m),`Remove ${Vl(s,m)}`)},g=vb(s,i);return zt(Bu.Provider,{value:b,children:[u&&_e(fe,{className:"af-mb-2",children:u}),_e("div",{"data-testid":"automation-canvas",className:"af-rounded-md af-border af-bg-muted/40",style:{height:g.height+2*gb},children:_e(Za.Suspense,{fallback:_e(G,{className:"af-h-full af-w-full"}),children:_e(bb,{layout:g,steps:s})})})]})}var bb=Za.lazy(async()=>({default:hb(await import("@xyflow/react"))}));function hb(e){let t=l=>[{type:"target",position:e.Position.Top,x:yo/2,y:0,width:1,height:1},{type:"source",position:e.Position.Bottom,x:yo/2,y:l,width:1,height:1}],a=()=>zt(zl,{children:[_e(e.Handle,{type:"target",position:e.Position.Top,isConnectable:!1,className:"!af-opacity-0"}),_e(e.Handle,{type:"source",position:e.Position.Bottom,isConnectable:!1,className:"!af-opacity-0"})]}),s=l=>zt(zl,{children:[l,_e(a,{})]}),n={trigger:()=>s(_e(Du,{kind:"trigger"})),send:({data:l})=>s(_e(yb,{index:l.index,step:l.step})),wait:({data:l})=>s(_e(xb,{index:l.index,step:l.step})),exit:()=>s(_e(Du,{kind:"exit"}))};function r({id:l,sourceX:u,sourceY:c,targetX:o,targetY:f,data:b}){let[g,m,v]=e.getStraightPath({sourceX:u,sourceY:c,targetX:o,targetY:f});return zt(zl,{children:[_e(e.BaseEdge,{id:l,path:g}),_e(e.EdgeLabelRenderer,{children:_e("div",{className:"nodrag nopan af-pointer-events-auto af-absolute",style:{transform:`translate(-50%, -50%) translate(${m}px, ${v}px)`},children:_e(Sb,{index:b.insertAt})})})]})}let i={insert:r};return function({layout:u,steps:c}){let o=u.nodes.map(b=>({id:b.id,type:b.kind,position:{x:0,y:b.y},width:yo,height:b.height,style:{width:yo,height:b.height,pointerEvents:"all"},handles:t(b.height),data:"index"in b?{index:b.index,step:c[b.index]}:{index:-1,step:null},draggable:!1,selectable:!1,connectable:!1,focusable:!1})),f=u.nodes.slice(1).map((b,g)=>({id:`${u.nodes[g].id}->${b.id}`,source:u.nodes[g].id,target:b.id,type:"insert",data:{insertAt:g},selectable:!1,focusable:!1}));return _e(e.ReactFlow,{nodes:o,edges:f,nodeTypes:n,edgeTypes:i,proOptions:{hideAttribution:!0},fitView:!0,fitViewOptions:{padding:.05,maxZoom:1,minZoom:.5},minZoom:.5,maxZoom:1,nodesDraggable:!1,nodesConnectable:!1,nodesFocusable:!1,edgesFocusable:!1,elementsSelectable:!1,panOnDrag:!1,panOnScroll:!1,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,preventScrolling:!1,deleteKeyCode:null,selectionKeyCode:null,multiSelectionKeyCode:null})}}function Du({kind:e}){let{automation:t}=Yr();return e==="exit"?_e("div",{"data-testid":"canvas-exit",className:"af-flex af-h-full af-items-center af-justify-center af-rounded-full af-border af-bg-background af-text-xs af-text-muted-foreground",children:"Exit: they leave the automation"}):zt("div",{"data-testid":"canvas-trigger",className:"af-flex af-h-full af-items-center af-gap-3 af-rounded-md af-border af-border-primary/40 af-bg-background af-px-3",children:[_e(fb,{className:"af-h-4 af-w-4 af-shrink-0"}),zt("div",{className:"af-min-w-0",children:[_e("div",{className:"af-text-xs af-text-muted-foreground",children:"Trigger"}),_e("div",{className:"af-truncate af-text-sm af-font-medium",children:Kr[t.trigger_type].title})]})]})}function Mu({index:e,label:t}){let{automation:a,editable:s,move:n,remove:r}=Yr();if(!s)return null;let i=a.steps.length-1;return zt("div",{className:"af-flex af-shrink-0 af-gap-0.5",children:[_e(Hl,{label:`Move ${t} up`,disabled:e===0,onClick:()=>n(e,-1),children:_e(cb,{})}),_e(Hl,{label:`Move ${t} down`,disabled:e===i,onClick:()=>n(e,1),children:_e(lb,{})}),_e(Hl,{label:`Remove ${t}`,onClick:()=>r(e),children:_e(ub,{})})]})}function Hl({label:e,disabled:t,onClick:a,children:s}){return _e(y,{type:"button",variant:"ghost",size:"icon",className:"nodrag af-h-7 af-w-7","aria-label":e,title:e,disabled:t,onClick:a,children:s})}function yb({index:e,step:t}){let{automation:a,statsByStep:s,onOpenEmail:n}=Yr(),r=Zr(a.steps,e),i=s[t.step_key];return zt("div",{"data-testid":"canvas-email",className:"af-flex af-h-full af-flex-col af-justify-between af-rounded-md af-border af-bg-background af-p-3",children:[zt("div",{className:"af-flex af-items-start af-gap-2",children:[_e(Lu,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0"}),zt("button",{type:"button",className:"nodrag af-min-w-0 af-grow af-text-left hover:af-underline","aria-label":`Open email ${r}`,onClick:()=>n(t.draft_id),children:[zt("div",{className:"af-text-xs af-text-muted-foreground",children:["Email ",r]}),_e("div",{className:"af-truncate af-text-sm af-font-medium",children:t.subject||"(no subject)"})]}),a.status==="on"&&t.live&&_e(ee,{variant:"success",children:"Live"}),_e(Mu,{index:e,label:`email ${r}`})]}),_e("p",{"data-testid":"canvas-email-stats",className:"af-text-xs af-text-muted-foreground",children:i?`Sent ${Ae(i.sent)} \xB7 Opened ${Ae(i.opened)} \xB7 Clicked ${Ae(i.clicked)}`:"Not sent yet"})]})}function xb({index:e,step:t}){let{editable:a,editingWait:s,setEditingWait:n,setWait:r}=Yr(),i=`the ${_s(t.wait_hours)} wait`,l=a&&s===t.step_key;return zt("div",{"data-testid":"canvas-wait",className:"af-flex af-h-full af-flex-col af-gap-2 af-rounded-md af-border af-border-dashed af-bg-background af-px-3 af-py-2",children:[zt("div",{className:"af-flex af-items-center af-gap-2",children:[_e(Ou,{className:"af-h-4 af-w-4 af-shrink-0"}),a?zt("button",{type:"button",className:"nodrag af-grow af-text-left af-text-sm hover:af-underline","aria-expanded":l,onClick:()=>n(l?null:t.step_key),children:["Wait ",_s(t.wait_hours)]}):zt("span",{className:"af-grow af-text-sm",children:["Wait ",_s(t.wait_hours)]}),_e(Mu,{index:e,label:i})]}),l&&_e(wb,{hours:t.wait_hours,onSave:u=>r(e,u),onCancel:()=>n(null)})]})}function wb({hours:e,onSave:t,onCancel:a}){let s=e%24===0,[n,r]=Za.useState(String(s?e/24:e)),[i,l]=Za.useState(s?"days":"hours"),u=Number(n)*(i==="days"?24:1),c=Number.isInteger(u)&&u>=1&&u<=mb;return zt("div",{"data-testid":"wait-editor",className:"nodrag af-space-y-2",children:[_e("div",{className:"af-flex af-flex-wrap af-gap-1",children:pb.map(o=>_e(y,{type:"button",size:"sm",variant:o===e?"default":"outline",className:"af-h-7 af-px-2",onClick:()=>t(o),children:_s(o)},o))}),zt("form",{className:"af-flex af-items-center af-gap-1",onSubmit:o=>{o.preventDefault(),c&&t(u)},children:[_e(ae,{"aria-label":"Custom wait",type:"number",min:1,value:n,onChange:o=>r(o.target.value),className:"af-h-7 af-w-20"}),zt("select",{"aria-label":"Wait unit",value:i,onChange:o=>l(o.target.value),className:"af-h-7 af-rounded-md af-border af-bg-background af-px-1 af-text-sm",children:[_e("option",{value:"hours",children:"hours"}),_e("option",{value:"days",children:"days"})]}),_e(y,{type:"submit",size:"sm",className:"af-h-7 af-px-2",disabled:!c,children:"Save"}),_e(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:a,children:"Cancel"})]}),!c&&_e("p",{className:"af-text-xs af-text-destructive",children:"A wait is 1 hour to 365 days."})]})}function Sb({index:e}){let{editable:t,insertAt:a,setInsertAt:s,insertWait:n,onInsertEmail:r}=Yr();if(!t)return null;let i=a===e;return zt("div",{className:"af-flex af-items-center af-gap-1",children:[_e("button",{type:"button","aria-label":e===0?"Add a step after the trigger":`Add a step after step ${e}`,"aria-expanded":i,onClick:()=>s(i?null:e),className:W("af-flex af-h-6 af-w-6 af-items-center af-justify-center af-rounded-full af-border af-bg-background af-shadow-sm hover:af-border-primary",i&&"af-border-primary"),children:_e(db,{className:"af-h-3.5 af-w-3.5"})}),i&&zt("div",{"data-testid":"insert-menu",className:"af-flex af-gap-1 af-rounded-md af-border af-bg-background af-p-1 af-shadow-md",children:[zt(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:()=>n(e),children:[_e(Ou,{})," Wait"]}),zt(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:()=>{s(null),r(e)},children:[_e(Lu,{})," Email"]})]})]})}import{Fragment as js,jsx as ge,jsxs as at}from"react/jsx-runtime";var Nb="Create an automation that ",Rb={welcome:{title:"Welcome email",trigger:"joined_list",description:"Greets each new subscriber as soon as they join your list.",emails:1},post_purchase:{title:"How's your order?",trigger:"purchase_made",description:"Checks in with each buyer 10 days after their order, once it has had time to arrive.",emails:1},recovery:{title:"Abandoned cart recovery",trigger:"abandoned_checkout",description:"Reminds shoppers who left checkout, an hour later and again a day later, with their cart.",emails:2}};function $u({automation:e}){let[t,a]=e.status==="on"?e.available?["success","On"]:["warning","Unavailable"]:["secondary",e.status==="draft"?"Draft":"Off"];return ge(ee,{"data-testid":"automation-state",variant:t,children:a})}function _b(e,t,a){switch(e){case"trigger_unavailable":return"This site can't use this trigger any more.";case"checkout_consent_off":return"Abandoned checkout needs the marketing consent box at checkout, which is off.";case"no_send_steps":return"Add an email before turning this automation on.";case"email_empty":{let s=t&&a?t.steps.findIndex(n=>n.step_key===a):-1;return s>=0?`Email ${Zr(t.steps,s)} needs a subject and some content.`:"Every email needs a subject and some content."}case"postal_address_missing":return"Add your business postal address before an automation can send.";case"version_conflict":return"This automation changed since you loaded it. Here is the latest version; check it, then try again.";default:return Ns(e)??"Something went wrong. Try again."}}function ql(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.step_key=="string"?t.step_key:typeof t.details?.step_key=="string"?t.details.step_key:null}function Jr({code:e,automation:t,stepKey:a,onOpenEmail:s}){let{openSettings:n,openSetup:r,onOpenStoreSettings:i}=Ke(),l=t&&a?t.steps.find(c=>c.step_key===a):void 0,u=null;return e==="postal_address_missing"?u=ge(fa,{onClick:()=>n("sender"),children:"Add it in Settings"}):e==="checkout_consent_off"&&i?u=ge(fa,{onClick:i,children:"Open Store settings"}):e==="email_empty"&&l?.type==="send"&&s?u=ge(fa,{onClick:()=>s(l.draft_id),children:"Open the email"}):e==="domain_not_verified"||e==="dmarc_missing"?u=ge(fa,{onClick:()=>n("domain"),children:"Fix in Settings"}):e==="sending_not_enabled"&&(u=ge(fa,{onClick:r,children:"Finish setup"})),at(js,{children:[_b(e,t,a),u&&at(js,{children:[" ",u]})]})}function Uu({automationId:e,onOpenAutomation:t,list:a,onAskAssistant:s,onPickImage:n}){let{canWrite:r}=Ke(),i=r?s:void 0;if(e){let l=a.data?.automations.find(u=>u.id===e);if(l)return ge(Cb,{automation:l,reload:a.refetch,onBack:()=>t(null),onAskAssistant:i,onPickImage:n},l.id);if(!a.data&&!a.error)return ge(G,{className:"af-h-96 af-w-full"})}return at("div",{children:[at("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[ge("h3",{className:"af-text-sm af-font-semibold",children:"Automations"}),i&&ge(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i(Nb),children:"\u2728 New automation with the editor"})]}),a.error&&!a.data?ge(xt,{message:"Couldn't load your automations.",onRetry:()=>void a.refetch()}):a.data?at(js,{children:[a.data.capabilities.suggestions.length>0&&at(js,{children:[ge(_a,{children:"Suggested"}),ge("ul",{"data-testid":"automation-suggestions",className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:a.data.capabilities.suggestions.map(l=>ge(Pb,{suggestion:l,list:a.data,reload:a.refetch,onOpenAutomation:t},l))})]}),ge(_a,{children:"Your automations"}),a.data.automations.length===0?ge(ca,{children:"No automations yet. Turn on a suggestion above, or ask the editor to build one."}):ge("ul",{"data-testid":"automations",className:"af-divide-y af-rounded-md af-border",children:a.data.automations.map(l=>ge(kb,{automation:l,onOpen:()=>t(l.id)},l.id))})]}):ge(G,{className:"af-h-24 af-w-full"})]})}function Vu(e){return[Kr[e.trigger_type].title,...e.steps.map(t=>t.type==="send"?"Email":`Wait ${_s(t.wait_hours)}`)].join(" \u2192 ")}function Hu(e){let{api:t}=H(),{siteId:a,refreshKey:s}=Ke(),n=e.status==="draft",r=Bt(()=>n?Promise.resolve([]):t.getAutomationStats(a,e.id),`${a}|${e.id}|${e.version}|${e.status}|${s}`,`${a}|${e.id}`);return un.useMemo(()=>Object.fromEntries((r.data??[]).map(i=>[i.step_key,i])),[r.data])}function kb({automation:e,onOpen:t}){let a=Object.values(Hu(e)),s=n=>Ae(a.reduce((r,i)=>r+i[n],0));return at("li",{"data-testid":"automation-row",className:"af-relative af-flex af-items-center af-gap-3 af-px-3 af-py-2 hover:af-bg-muted/40",children:[at("div",{className:"af-min-w-0 af-grow af-space-y-0.5",children:[at("div",{className:"af-flex af-items-center af-gap-2",children:[ge("span",{className:"af-truncate af-text-sm af-font-medium",children:e.name}),ge($u,{automation:e})]}),ge("p",{"data-testid":"automation-chain",className:"af-truncate af-text-xs af-text-muted-foreground",children:Vu(e)}),a.length>0&&at("p",{"data-testid":"automation-stats",className:"af-text-xs af-text-muted-foreground",children:["Sent ",s("sent")," \xB7 Opened ",s("opened")," \xB7 Clicked ",s("clicked")]})]}),ge(jl,{className:"af-h-4 af-w-4 af-shrink-0 af-text-muted-foreground"}),ge("button",{type:"button","aria-label":`Open ${e.name}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}function Pb({suggestion:e,list:t,reload:a,onOpenAutomation:s}){let{api:n}=H(),{siteId:r,canWrite:i,onOpenStoreSettings:l}=Ke(),u=vt(),[c,o]=un.useState(!1),[f,b]=un.useState(null),g=Rb[e],m=t.automations.find(x=>x.trigger_type===g.trigger&&x.list_tag_id===null),v=e==="recovery"&&t.capabilities.checkout_consent==="off_available",d=async()=>{o(!1),b(null);let x=await u.run("addSuggestedAutomation",{key:e}),S=x.ok?x.result:null;if(!x.ok){let h=Ga(x.error,"automation_exists")?x.error:null,N=h?.automation_id??h?.details?.automation_id;if(!N)return;if(u.setError(null),S=await n.getAutomation(r,N).catch(()=>null),!S)return void a()}let k=await u.run("turnOnAutomation",{automationId:S.id,expected_version:S.version});k.ok||(u.setError(null),b({code:Rs(k.error),stepKey:ql(k.error)})),await a()},p=()=>m?ge("p",{className:"af-text-sm",children:ge(fa,{onClick:()=>s(m.id),children:"Open the automation"})}):i?c?at("div",{className:"af-space-y-2",children:[at("p",{className:"af-text-sm",children:['Turn on "',g.title,'"? It sends ',Ms(g.emails,"email")," to each person who ",Kr[g.trigger].phrase,"."]}),at("div",{className:"af-flex af-gap-2",children:[ge(y,{type:"button",variant:"outline",size:"sm",onClick:()=>o(!1),children:"Cancel"}),ge(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:u.busy,onClick:()=>void d(),children:"Turn on"})]})]}):v?at("div",{className:"af-space-y-1",children:[ge("p",{className:"af-text-xs af-text-muted-foreground",children:"Needs the marketing consent box at checkout, in Store settings."}),ge(y,{type:"button",size:"sm",disabled:!l,onClick:()=>l?.(),children:"Turn on"})]}):ge("div",{children:ge(y,{type:"button",size:"sm",disabled:u.busy,onClick:()=>o(!0),children:"Turn on"})}):null;return at("li",{"data-testid":"suggestion-card",className:"af-flex af-flex-col af-gap-2 af-rounded-md af-border af-p-3",children:[at("div",{className:"af-flex af-items-center af-gap-2",children:[ge("span",{"data-testid":"suggestion-title",className:"af-grow af-text-sm af-font-medium",children:g.title}),m&&ge(ee,{variant:"secondary",children:"Added"})]}),ge("p",{className:"af-text-xs af-text-muted-foreground",children:g.description}),f&&at(fe,{tone:"warning",children:["Not turned on. ",ge(Jr,{code:f.code,automation:m,stepKey:f.stepKey})]}),u.error&&ge(fe,{tone:"error",children:u.error}),p()]})}var wo={on:{message:(e,t)=>`Turn on "${e.name}"? It sends ${Ms(t,"email")} to each person who ${Kr[e.trigger_type].phrase}. Changes you save after this go out to the next people who reach each step.`,action:"turnOnAutomation",label:"Turn on",variant:"default"},off:{message:e=>`Turn off "${e.name}"? Nobody new enters it and no new emails start. Emails already queued still go out.`,action:"turnOffAutomation",label:"Turn off",variant:"default"},delete:{message:e=>`Delete "${e.name}" and its emails?`,action:"deleteAutomation",label:"Delete",variant:"destructive"}};function Cb({automation:e,reload:t,onBack:a,onAskAssistant:s,onPickImage:n}){let{api:r}=H(),{siteId:i,canWrite:l}=Ke(),u=Hu(e),c=vt(),o=vt(),f=vt(),[b,g]=un.useState(null),[m,v]=un.useState(null),[d,p]=un.useState(null),[x,S]=un.useState(null),[k,h]=un.useState(null),[N,R]=un.useState(!1),C=e.status==="on",w=e.steps.filter(T=>T.type==="send").length,P=async T=>{R(!0);try{await T()}finally{R(!1)}},I=(T,V)=>P(async()=>{p(null),S(null);let A=await c.run("updateAutomation",{automationId:e.id,expected_version:e.version,steps:T});if(!A.ok){let ne=Rs(A.error);ne==="version_conflict"?(c.setError(null),p(V)):(ne==="email_empty"||ne==="postal_address_missing")&&(c.setError(null),S({code:ne,stepKey:ql(A.error)}))}await t()}),_=T=>P(async()=>{let V=await c.run("createDraft",{kind:"automation",automation_id:e.id,subject:"",blocks:[]});if(!V.ok)return;let A=V.result.id;if(C)return h({draftId:A,joinAt:T});let ne=xo(e.steps);await I([...ne.slice(0,T),{type:"send",draft_id:A},...ne.slice(T)],"Add an email")}),q=un.useRef(Promise.resolve()),j=T=>{let V=q.current.then(async()=>{let A=await r.getEmailDraft(i,T.draftId).catch(()=>null);if(!A||!A.subject.trim()||A.blocks.length===0)return;let ne=await r.getAutomation(i,e.id).catch(()=>null);if(!ne)return;if(ne.steps.some(Ee=>Ee.type==="send"&&Ee.draft_id===T.draftId))return h({draftId:T.draftId});let re=xo(ne.steps),Me=Math.min(T.joinAt,re.length);(await f.run("updateAutomation",{automationId:e.id,expected_version:ne.version,steps:[...re.slice(0,Me),{type:"send",draft_id:T.draftId},...re.slice(Me)]})).ok&&h({draftId:T.draftId}),await t()});return q.current=V.catch(()=>{}),V},U=async T=>{g(null),v(null);let V=T==="turnOnAutomation"?{automationId:e.id,expected_version:e.version}:{automationId:e.id},A=await o.run(T,V);!A.ok&&T==="turnOnAutomation"&&(o.setError(null),v({code:Rs(A.error),stepKey:ql(A.error)})),A.ok&&T==="deleteAutomation"&&a(),await t()},te=T=>at("nav",{"aria-label":"Breadcrumb",className:"af-mb-3 af-flex af-flex-wrap af-items-center af-gap-1.5 af-text-sm af-text-muted-foreground",children:[ge(fa,{onClick:a,children:"Automations"}),ge(jl,{className:"af-h-3.5 af-w-3.5"}),T===void 0?ge("span",{className:"af-font-medium af-text-foreground",children:e.name}):at(js,{children:[ge(fa,{onClick:()=>h(null),children:e.name}),ge(jl,{className:"af-h-3.5 af-w-3.5"}),ge("span",{className:"af-font-medium af-text-foreground",children:T})]})]});if(k){let T=e.steps.findIndex(A=>A.type==="send"&&A.draft_id===k.draftId),V=k.joinAt!==void 0;return at("div",{children:[te(T>=0?`Email ${Zr(e.steps,T)}`:"New email"),ge(po,{draftId:k.draftId,allowCart:e.trigger_type==="abandoned_checkout",automationStep:{live:C&&!V,joinsOnSave:C&&V,notice:f.error&&at(fe,{tone:"error",children:["Couldn't add this email to the automation. ",f.error]}),onBackToCanvas:()=>h(null)},onSaved:()=>{k.joinAt!==void 0?j({draftId:k.draftId,joinAt:k.joinAt}):t()},onAskAssistant:s,onPickImage:n},k.draftId)]})}let ce=e.blocked_by[0]??null,me=C&&!e.available;return at("div",{className:"af-space-y-3",children:[te(),at("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ge("h3",{"data-testid":"automation-title",className:"af-grow af-truncate af-text-base af-font-semibold",children:e.name}),ge($u,{automation:e}),l&&!b&&ge(js,{children:C?ge(y,{type:"button",variant:"outline",size:"sm",disabled:o.busy,onClick:()=>g("off"),children:"Turn off"}):at(js,{children:[ge(y,{type:"button",variant:"ghost",size:"sm",disabled:o.busy,onClick:()=>g("delete"),children:"Delete"}),ge(y,{type:"button",size:"sm",disabled:o.busy,onClick:()=>g("on"),children:"Turn on"})]})})]}),ge("p",{className:"af-text-xs af-text-muted-foreground",children:Vu(e)}),b&&at("div",{"data-testid":"automation-confirm",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[ge("p",{className:"af-text-sm",children:wo[b].message(e,w)}),at("div",{className:"af-flex af-gap-2",children:[ge(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(null),children:"Cancel"}),ge(y,{type:"button",size:"sm",variant:wo[b].variant,className:"af-ml-auto",disabled:o.busy,onClick:()=>void U(wo[b].action),children:wo[b].label})]})]}),m&&at(fe,{tone:"warning",children:[ge("span",{className:"af-font-medium",children:"Not turned on."})," ",ge(Jr,{code:m.code,automation:e,stepKey:m.stepKey,onOpenEmail:T=>h({draftId:T})})]}),o.error&&ge(fe,{tone:"error",children:o.error}),me?at(fe,{tone:"warning",children:[ge("span",{className:"af-font-medium",children:"Unavailable."})," ",ge(Jr,{code:ce??"trigger_unavailable",automation:e})," Nobody new enters it; people already in it still get their remaining emails."]}):ce&&!m&&at(fe,{tone:"warning",children:[C?"Not sending right now.":"Won't send yet."," ",ge(Jr,{code:ce,automation:e})]}),C&&!me&&at(fe,{tone:"success",children:[ge("span",{className:"af-font-medium",children:"Live."})," Changes you make here, and saves to its emails, go out to the next people who reach each step."]}),d&&at(fe,{tone:"warning",children:["This automation changed while you were editing, so your change wasn't saved: ",ge("span",{className:"af-font-medium",children:d}),". Here is the latest version; make the change again if you still want it."]}),x&&at(fe,{tone:"warning",children:["Not saved. ",ge(Jr,{code:x.code,automation:e,stepKey:x.stepKey,onOpenEmail:T=>h({draftId:T})})]}),c.error&&ge(fe,{tone:"error",children:c.error}),ge(Fu,{automation:e,statsByStep:u,editable:l&&!c.busy&&!N,onChangeSteps:(T,V)=>void I(T,V),onInsertEmail:T=>void _(T),onOpenEmail:T=>h({draftId:T})})]})}import{Fragment as Bb,jsx as bt,jsxs as Xr}from"react/jsx-runtime";var Tb=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"automations",label:"Automations"},{id:"templates",label:"Templates"},{id:"settings",label:"Settings"}];function Xn(e,t={}){return{tab:e,draftId:null,templateId:null,automationId:null,...t}}var zu=e=>!!(e.tab||e.draftId||e.templateId||e.automationId);function ju(e){return e.draftId?Xn("broadcasts"):e.templateId?Xn("templates",{templateId:e.templateId}):e.automationId?Xn("automations",{automationId:e.automationId}):Xn(e.tab==="template"?"templates":e.tab??"audience")}var Eb={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function qu(e){return bt(Ib,{...e},e.siteId)}function Ib({siteId:e,isOwnerSide:t,needsPaidPlan:a,initialDraftId:s,initialTab:n,initialAutomationId:r,templateId:i,showViewNonce:l,onOrgAction:u,onRequestReview:c,onStartDomainSetup:o,dnsManaged:f,renderSendingRecords:b,onBackToWebsite:g,onUpgradePlan:m,onConnectDomain:v,onAskAssistant:d,onPickImage:p,onTurnOn:x,siteDomain:S,businessName:k,onOpenStoreSettings:h,onOpenBrandSettings:N,refreshKey:R=0,className:C}){let{api:w}=H(),P=Bt(()=>w.getMarketingSettings(e),`${e}|${R}`,e),I=Bt(()=>w.getAutomations(e),`${e}|${R}`,e),_={tab:n,draftId:s,templateId:i,automationId:r},[q,j]=ea.useState(()=>ju(_)),[U,te]=ea.useState(s??null),[ce,me]=ea.useState(zu(_)),[T,V]=ea.useState(null),[A,ne]=ea.useState(!1),re=ea.useCallback(()=>me(!1),[]),Me=ea.useCallback(se=>{j(Xn("settings")),V(se??null)},[]),Se=se=>{j(Xn(se)),V(null)},Ee=ea.useCallback(se=>j(Xn("broadcasts",{draftId:se})),[]),Ye=ea.useCallback(se=>j(Xn("templates",{templateId:se})),[]),ke=ea.useCallback(se=>j(Xn("automations",{automationId:se})),[]),nt=!ce&&P.data!==null&&Ab(P.data),E=q.tab,M=P.data&&!P.error?Db(P.data):null,L=JSON.stringify([l??null,n??null,s??null,i??null,r??null]),pe=ea.useRef(L);ea.useEffect(()=>{if(L===pe.current||A)return;pe.current=L;let se={tab:n,draftId:s,templateId:i,automationId:r};zu(se)&&(j(ju(se)),te(se.draftId??null),V(null),me(!0))},[L,A,n,s,i,r]),ea.useEffect(()=>{if(!U||a)return;let se=!0,Fe=Qe=>{se&&(j(Xn("broadcasts",{draftId:Qe})),te(null))};return w.getEmailDraft(e,U).then(Qe=>Fe(Qe.kind==="broadcast"?Qe.id:null),()=>Fe(null)),()=>{se=!1}},[w,e,U,a]);let J=ea.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:u,settings:P.data,refetchSettings:P.refetch,refreshKey:R,openSetup:re,openSettings:Me,settingsSection:T,onOpenStoreSettings:h,onOpenBrandSettings:N,setInlineEditOpen:ne}),[e,t,u,P.data,P.refetch,R,re,Me,T,h,N]);return a?bt(Ut,{title:"Email Marketing",onBackToWebsite:g,className:C,children:bt(Al,{settings:P.data,site:{siteDomain:S,businessName:k},children:bt(_u,{onUpgradePlan:m})})}):bt(Ut,{title:"Email Marketing",onBackToWebsite:g,className:C,children:bt(vl.Provider,{value:J,children:nt?bt(Ru,{onStartDomainSetup:o,dnsManaged:f,renderSendingRecords:b,onConnectDomain:v,onAskAssistant:d,onTurnOn:x,siteDomain:S,businessName:k}):Xr(Bb,{children:[P.error&&!P.data&&bt(xt,{message:"Couldn't load email settings.",onRetry:()=>void P.refetch()}),M&&bt(Lb,{reason:M,pauseReason:P.data?.paused.reason??null,onRequestReview:c}),!t&&bt(fe,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),bt("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:Tb.map(se=>Xr("button",{type:"button",role:"tab","aria-selected":E===se.id,onClick:()=>Se(se.id),className:W("af-border-b-2 af-px-3 af-py-2 af-text-sm",E===se.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:[se.label,se.id==="settings"&&M&&bt("span",{"data-testid":"settings-dot",role:"img","aria-label":"Sending is on hold",className:"af-ml-1.5 af-inline-block af-h-1.5 af-w-1.5 af-rounded-full af-bg-amber-600 af-align-middle"})]},se.id))}),bt("div",{role:"tabpanel",children:U?bt(G,{className:"af-h-24 af-w-full"}):E==="audience"?bt(iu,{}):E==="broadcasts"?bt(wu,{openDraftId:q.draftId,onOpenDraft:Ee,onAskAssistant:d,onPickImage:p}):E==="automations"?bt(Uu,{automationId:q.automationId,onOpenAutomation:ke,list:I,onAskAssistant:d,onPickImage:p}):E==="templates"?bt(Iu,{templateId:q.templateId,onOpenTemplate:Ye,onOpenDraft:Ee,onAskAssistant:d}):bt(Ml,{onStartDomainSetup:o,onAskAssistant:d,dnsManaged:f,renderSendingRecords:b})})]})})})}function Ab(e){return!e.paused.paused_at&&!e.readiness.can_send&&Ur.has(e.readiness.reason??"")}function Db(e){if(e.paused.paused_at)return"paused";let t=e.readiness.reason;return!e.readiness.can_send&&t&&Ur.has(t)?t:null}var Ob={domain_not_verified:"domain",dmarc_missing:"domain",postal_address_missing:"sender"};function Lb({reason:e,pauseReason:t,onRequestReview:a}){let{openSetup:s,openSettings:n}=Ke(),[r,i]=ea.useState("idle");if(e==="paused")return bt("div",{"data-testid":"email-hold",className:"af-mb-3",children:Xr(fe,{tone:"warning",children:[bt("div",{className:"af-font-medium",children:"Sending is paused."}),Xr("p",{children:[Eb[t??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),a&&(r==="sent"?bt("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):bt(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{i("sending");try{await a(),i("sent")}catch{i("failed")}},children:"Request review"})),r==="failed"&&bt("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]})});let l=Ob[e];return bt("div",{"data-testid":"email-hold",className:"af-mb-3",children:Xr(fe,{tone:"warning",children:["Sending is on hold. ",Ns(e)," ",l?bt(fa,{onClick:()=>n(l),children:"Fix in Settings"}):bt(fa,{onClick:s,children:"Finish setup"})]})})}import*as ia from"react";var Fb=2e3,ya=()=>({data:null,error:null,isLoading:!0});function wr(e,{refreshKey:t,breakdowns:a=[],filters:s=[]}={}){let{api:n}=H(),[r,i]=ia.useState(ya),[l,u]=ia.useState(ya),[c,o]=ia.useState(ya),[f,b]=ia.useState(ya),[g,m]=ia.useState(ya),v=T=>Object.fromEntries(T.map(V=>[V,ya()])),[d,p]=ia.useState(()=>v(a)),x=ia.useRef(0),S=ia.useRef(0),k=ia.useRef("idle"),h=a.join(","),N=us()??"",R=JSON.stringify(s),C=`${e}:${h}:${R}:${N}`,[w,P]=ia.useState({api:n,fetchIdentity:C});(w.api!==n||w.fetchIdentity!==C)&&(P({api:n,fetchIdentity:C}),x.current+=1,i(ya),u(ya),o(ya),b(ya),p(v(h?h.split(","):[])));let I=`${e}:${String(t??"")}:${N}`,[_,q]=ia.useState({api:n,conversionsIdentity:I});(_.api!==n||_.conversionsIdentity!==I)&&(q({api:n,conversionsIdentity:I}),S.current+=1,k.current="idle",m(ya));let j=ia.useCallback(async T=>{let V=++x.current,A=h?h.split(","):[];i(ya),u(ya),o(ya),b(ya),p(Object.fromEntries(A.map(E=>[E,ya()])));let ne=k.current!=="pending"&&(T?.force===!0||k.current==="idle"),re=(E,M)=>M.then(L=>{V===x.current&&E({data:L,error:null,isLoading:!1})},L=>{V===x.current&&E({data:null,error:L instanceof Error?L:new Error("Failed to fetch report"),isLoading:!1})}),Me=n.getAnalyticsStatus(),Se=re(i,Me),Ee=Symbol("status-timeout"),Ye,ke=await Promise.race([Me.then(E=>E,()=>null),new Promise(E=>{Ye=setTimeout(()=>E(Ee),Fb)})]);if(clearTimeout(Ye),V!==x.current)return;if(ke===Ee&&i({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),ke!==null&&ke!==Ee&&(ke.collecting!==!0||ke.first_seen===null&&!ke.first_seen_unavailable||ke.first_seen!==null&&ke.first_seen_in_reports===!1)){let E={data:null,error:null,isLoading:!1};u(E),o(E),b(E),p(Object.fromEntries(A.map(M=>[M,{...E}]))),ne&&(m(E),k.current="done"),await Se;return}await Promise.all([ke===Ee?Promise.resolve():Se,re(u,n.getAnalyticsSummary(e,s)),re(o,n.getAnalyticsTimeseries(e,s)),re(b,n.getAnalyticsChannels(e,s)),ne?(()=>{k.current="pending";let E=++S.current;return m(ya),n.getAnalyticsConversions(e).then(M=>{E===S.current&&(m({data:M,error:null,isLoading:!1}),k.current="done")},M=>{E===S.current&&(m({data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}),k.current="done")})})():Promise.resolve(),...A.map(E=>n.getAnalyticsBreakdown(E,e,s).then(M=>{V===x.current&&p(L=>({...L,[E]:{data:M,error:null,isLoading:!1}}))},M=>{V===x.current&&p(L=>({...L,[E]:{data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,R,I,N]),U=ia.useCallback(async()=>{let T=x.current;try{let V=await n.getAnalyticsStatus();if(T!==x.current)return;i({data:V,error:null,isLoading:!1})}catch(V){if(T!==x.current)return;i(A=>({data:A.data,error:V instanceof Error?V:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),te=ia.useCallback(()=>j({force:!0}),[j]);ia.useEffect(()=>{j()},[j,t]);let ce=r.isLoading||l.isLoading||c.isLoading||f.isLoading||g.isLoading||Object.values(d).some(T=>T.isLoading),me=[c,l,f,g,...Object.values(d)].map(T=>T.data?.status==="ok"?T.data.timezone:void 0).find(T=>T!==void 0);return{status:r,summary:l,timeseries:c,channels:f,conversions:g,breakdowns:d,reportedZone:me,isLoading:ce,refetch:te,refetchStatus:U}}import*as oa from"react";var Wl=3e4,Gl=3;function So(e={}){let t="collecting"in e,{collecting:a,statusFailed:s=!1,identity:n}=e,{api:r}=H(),[i,l]=oa.useState(null),[u,c]=oa.useState(null),[o,f]=oa.useState(!1),[b,g]=oa.useState(null),[m,v]=oa.useState(!1),[d,p]=oa.useState(!0),[x,S]=oa.useState(0),k=oa.useRef(0),h=oa.useRef(0),N=oa.useRef(void 0);a!==void 0&&(N.current=a);let R=t?N.current===!0||N.current===void 0&&s:!0,[C,w]=oa.useState({api:r,identity:n}),P=n!==void 0&&n!==C.identity;(C.api!==r||P)&&(N.current=void 0,w({api:r,identity:n}),h.current+=1,k.current=0,l(null),c(null),f(!1),g(null),v(!1),p(!0),S(0));let I=oa.useRef(()=>{}),_=oa.useRef(null),q=oa.useCallback(async()=>{if(_.current!==null&&_.current===h.current)return;let j=++h.current;_.current=j;try{let U=await r.getAnalyticsRealtime();if(j!==h.current)return;if(U.status==="unreachable"){v(!0),f(!0),p(!1),S(te=>te+1);return}k.current=0,v(!1),l(U.data.current_visitors),c(U.as_of),f(!1),g(null),p(!1),S(te=>te+1)}catch(U){if(j!==h.current)return;k.current+=1,p(!1),S(te=>te+1),f(!0),k.current>=Gl&&g(U instanceof Error?U:new Error("Realtime unavailable"))}finally{_.current===j&&(_.current=null)}},[r]);return I.current=()=>void q(),oa.useEffect(()=>{let j,U=()=>{j===void 0&&(j=setInterval(()=>I.current(),Wl))},te=()=>{j!==void 0&&(clearInterval(j),j=void 0)},ce=()=>{typeof document<"u"&&document.hidden?te():(I.current(),U())};return R?((typeof document>"u"||!document.hidden)&&(I.current(),U()),document?.addEventListener("visibilitychange",ce),()=>{te(),document?.removeEventListener("visibilitychange",ce),h.current+=1}):()=>{document?.removeEventListener("visibilitychange",ce)}},[C.api,C.identity,R]),{currentVisitors:i,asOf:u,isStale:o,error:b,isUnreachable:m,isInitialLoad:d,polls:x}}import*as Ft from"react";import*as Gu from"react";import{jsx as Kl,jsxs as Wu}from"react/jsx-runtime";function Mb(){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 Zl({value:e,chosen:t,onChange:a}){let s=Rr(),n=t===null&&s!==null&&e===s,r=Gu.useMemo(()=>{let i=Mb();return i.includes(e)?i:[e,...i]},[e]);return Wu("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[Kl("span",{className:"af-sr-only",children:"Reporting timezone"}),Wu("select",{value:n?"":e,onChange:i=>a(i.target.value===""?null:i.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[Kl("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(i=>Kl("option",{value:i,children:i.replace(/_/g," ")},i))]})]})}var No=(e,{published:t}={})=>{let a=t===!1,s=e!=null&&(!e.collecting||a&&e.first_seen===null&&!e.first_seen_unavailable),n=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,i=n||r;return{notCollecting:s,awaitingFirstVisit:n,firstVisitTooRecent:r,holdingForFirstData:i,nothingToReport:s||i}};import*as Qr from"react";var $b=3e4;function Ro({status:e,holdingForFirstData:t,refetchStatus:a,refetch:s}){Qr.useEffect(()=>{if(!t)return;let r,i=()=>{r===void 0&&(r=setInterval(()=>void a(),$b))},l=()=>{r!==void 0&&(clearInterval(r),r=void 0)},u=()=>{typeof document<"u"&&document.hidden?l():(a(),i())};return(typeof document>"u"||!document.hidden)&&i(),document?.addEventListener("visibilitychange",u),()=>{l(),document?.removeEventListener("visibilitychange",u)}},[t,a]);let n=Qr.useRef(void 0);Qr.useEffect(()=>{if(!e){n.current=void 0;return}let r=n.current;n.current=t,r===!0&&!t&&s()},[e,t,s])}import*as Ws from"react";var Ub=["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 a=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[s,n]of a)if(t>=s){let r=e/s,i=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(i)>=1e3&&s!==1e9?Da(i*s):`${i}${n}`}return String(e)}function Sr(e){return`${(e*100).toFixed(1)}%`}function ei(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let a=Math.floor(t/60);return a<60?`${a}m ${t%60}s`:`${Math.floor(a/60)}h ${a%60}m`}function Zu(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`:ei(t)}function Yu(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Ju(e,t){if(!(!Number.isFinite(e)||e<=0))for(let a of t){let s=Math.ceil(e/a);if(s<=5)return Array.from({length:s+1},(n,r)=>Number((r*a).toPrecision(12)))}}function ti(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Xu(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 Yl(e){let t=Number(e.slice(5,7)),a=Number(e.slice(8,10));return`${Ub[t-1]} ${a}`}function Ku(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Vb(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Qu(e,t,a="UTC"){let s=new Map(t.map(i=>[i.date,i])),n=[],r=Ku(e.to,a);for(let i=Ku(e.from,a);i<r;i=Vb(i))n.push(s.get(i)??{date:i,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function ef(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=new Date(`${e}T00:00:00Z`);if(Number.isNaN(s.getTime()))return e;let n=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${n} ${a[s.getUTCMonth()]}`}import{Fragment as zb,jsx as ks,jsxs as Hb}from"react/jsx-runtime";function tf({what:e="This report",onRetry:t,collecting:a}){return Hb("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:[ks("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),ks("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:a===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),t?ks("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 _o({what:e="No data"}){return ks("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 ds({sourced:e,error:t,isLoading:a,what:s,onRetry:n,collecting:r,children:i}){return a?ks("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?ks(tf,{what:s,onRetry:n,collecting:r}):!e||e.status==="unreachable"?ks(tf,{what:s,onRetry:n,collecting:r}):ks(zb,{children:i(e.data)})}import{Fragment as jb,jsx as Ya,jsxs as qs}from"react/jsx-runtime";function Jl({rows:e,dimension:t,metric:a,metricLabel:s,secondary:n,emptyCopy:r="No data for this period",onFilter:i,canFilter:l,maxRows:u=9}){let[c,o]=Ws.useState(!1);if(e.length===0)return Ya(_o,{what:r});let f=e.reduce((m,v)=>Math.max(m,Number(v[a]??0)),0)||1,b=Math.max(0,e.length-u),g=c?e:e.slice(0,u);return qs(jb,{children:[qs("table",{className:"af-w-full af-text-sm",children:[Ya("thead",{children:qs("tr",{className:"af-text-xs af-text-muted-foreground",children:[Ya("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),Ya("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),Ya("tbody",{children:g.map((m,v)=>{let d=Number(m[a]??0),p=m[t]??null,x=ti(p),S=n?m[n]:null,k=p!==null&&(l?l(p,S):!0);return qs("tr",{className:"af-border-t af-border-border",children:[qs("td",{className:"af-relative af-py-1.5 af-pr-2",children:[Ya("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,d/f*100)}%`}}),p!==null&&i&&k?Ya("button",{type:"button",onClick:()=>i(p,S),title:`Filter by ${x}`,"aria-label":`Filter by ${x}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:x}):Ya("span",{className:"af-relative af-break-words af-text-foreground",children:x}),S?Ya("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:S}):null]}),Ya("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Da(d)})]},`${x}-${S??""}-${v}`)})})]}),b>0?Ya("button",{type:"button",onClick:()=>o(m=>!m),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:c?"Show fewer":`Show all ${e.length}`}):null]})}function ai({title:e,tabs:t,defaultTabId:a,headerRight:s}){let[n,r]=Ws.useState(a),i=t.find(g=>g.id===n)??t[0],l=Ws.useId(),u=g=>`${l}-tab-${g}`,c=g=>`${l}-panel-${g}`,o=Ws.useRef(null),f=(g,m)=>{g.preventDefault();let v=(m+t.length)%t.length;r(t[v].id),o.current?.querySelectorAll('[role="tab"]')?.[v]?.focus()};return qs("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[qs("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:[Ya("div",{ref:o,role:"tablist","aria-label":e,onKeyDown:g=>{let m=t.findIndex(v=>v.id===n);g.key==="ArrowRight"&&f(g,m+1),g.key==="ArrowLeft"&&f(g,m-1),g.key==="Home"&&f(g,0),g.key==="End"&&f(g,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(g=>Ya("button",{id:u(g.id),role:"tab",type:"button","aria-selected":g.id===n,"aria-controls":c(g.id),tabIndex:g.id===n?0:-1,onClick:()=>r(g.id),className:g.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:g.label},g.id))}),s]}),i?Ya("div",{id:c(i.id),role:"tabpanel","aria-labelledby":u(i.id),tabIndex:0,className:"af-px-3 af-py-2",children:i.render()},i.id):null]})}import*as Ja from"react";import*as Ps from"@radix-ui/react-popover";var Gs=3,Ks=100;import{jsx as Kt,jsxs as Qn}from"react/jsx-runtime";var ni={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"},qb=Object.keys(ni);function af(e){let t=ni[e.dimension],a=e.operator==="is_not"?"is not":"is",s=e.values.map(n=>ti(n)).join(" or ");return`${t} ${a} ${s}`}function Xl(e,t){let a=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));if(a>=0){let s=[...new Set([...e[a].values,...t.values])];return s.length>Ks||s.length===e[a].values.length?e:e.map((n,r)=>r===a?{...n,values:s}:n)}return t.values.length>Ks||e.length>=Gs?e:[...e,t]}function Wb(e,t){let a={};for(let[s,n]of Object.entries(t)){let r=e.get(s)??new Set;for(let i of n)r.add(i);e.set(s,r),a[s]=[...r]}return a}function nf(e,t){let a=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));return a>=0?e.map((s,n)=>n===a?t:s):t.values.length>Ks||e.length>=Gs?e:[...e,t]}function Gb(e){return{dimension:e,operator:"is",search:"",picked:[]}}function sf(e,t,a,s={}){if(e.api!==t.api||e.period!==t.period)return e.api=t.api,e.period=t.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=Wb(e.byDimension,a);for(let[r,i]of Object.entries(s)){let l=e.foldsByLabel.get(r)??new Set;for(let u of i)l.add(u);e.foldsByLabel.set(r,l)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([r,i])=>[r,[...i]]))}}function rf(e){let{filters:t,onChange:a}=e,s=t.length>=Gs;return Ja.useEffect(()=>{if(t.length===0)return;let n=r=>{let i=r.target;i&&(i.tagName==="INPUT"||i.closest('[role="dialog"]'))||r.key==="Escape"&&a([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[t.length,a]),Qn("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,r)=>Qn("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:[Kt("span",{className:"af-text-foreground",children:af(n)}),Kt("button",{type:"button","aria-label":`Remove filter ${af(n)}`,onClick:()=>a(t.filter((i,l)=>l!==r)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),Kt(Kb,{...e,disabled:s}),t.length>0?Kt("button",{type:"button",onClick:()=>a([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Kb({filters:e,onChange:t,suggestions:a,resetKey:s,disabled:n,expandValues:r}){let[i,l]=Ja.useState(!1),u=Ja.useRef(null),[c,o]=Ja.useState(null);Ja.useEffect(()=>{o(u.current?.closest(".aifeatures-admin")??null)},[]);let[f,b]=Ja.useState(null),[g,m]=Ja.useState("is"),[v,d]=Ja.useState(""),[p,x]=Ja.useState([]);Ja.useEffect(()=>{i||(b(null),m("is"),d(""),x([]))},[i]);let S=Ja.useRef(s);S.current!==s&&(S.current=s,i&&l(!1),f!==null&&b(null),p.length>0&&x([]),v!==""&&d(""),g!=="is"&&m("is"));let k=P=>{let I=Gb(P);b(I.dimension),x(I.picked),d(I.search),m(I.operator)},N=(f?a[f]??[]:[]).filter(P=>P.toLowerCase().includes(v.trim().toLowerCase())),R=f===null||p.length===0?null:Xl(e,{dimension:f,operator:g,values:r?r(f,p):p}),C=R!==null&&R!==e,w=()=>{let P=R;!P||P===e||(t(P),l(!1))};return Qn(Ps.Root,{open:i,onOpenChange:l,children:[Kt(Ps.Trigger,{asChild:!0,children:Kt("button",{ref:u,type:"button",disabled:!1,title:n?`At most ${Gs} 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"})}),Kt(Ps.Portal,{container:c,children:Kt(Ps.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:f===null?Qn("div",{children:[Kt("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),Kt("div",{className:"af-max-h-96 af-overflow-y-auto",children:qb.filter(P=>a[P]!==void 0).map(P=>{let I=a[P]?.length??0,_=!e.some(q=>q.dimension===P)&&e.length>=Gs;return Qn("button",{type:"button",onClick:()=>k(P),disabled:I===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:[Kt("span",{children:ni[P]}),Kt("span",{className:"af-text-muted-foreground",children:I===0?"no data":_?"no room":I})]},P)})})]}):Qn("div",{children:[Qn("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Kt("button",{type:"button",onClick:()=>k(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),Kt("span",{className:"af-text-xs af-font-medium af-text-foreground",children:ni[f]}),Qn("select",{"aria-label":"Operator",value:g,onChange:P=>m(P.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:[Kt("option",{value:"is",children:"is"}),Kt("option",{value:"is_not",children:"is not"})]})]}),Kt("input",{type:"text",value:v,onChange:P=>d(P.target.value),placeholder:"Search\u2026","aria-label":`Search ${ni[f]}`,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"}),Kt("div",{className:"af-max-h-48 af-overflow-y-auto",children:N.length===0?Qn("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",v,"\u201D."]}):N.map(P=>Qn("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:[Kt("input",{type:"checkbox",checked:p.includes(P),disabled:!p.includes(P)&&p.length>=Ks,onChange:I=>x(_=>I.target.checked?[..._,P]:_.filter(q=>q!==P))}),Kt("span",{className:"af-break-all",children:ti(P)})]},P))}),Kt("button",{type:"button",onClick:w,disabled:!C,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:p.length<=1?"Apply filter":p.length>=Ks?`Apply filter (${p.length} values \u2014 the maximum)`:`Apply filter (${p.length} values)`})]})})})]})}import{Fragment as Jb,jsx as Oa,jsxs as ko}from"react/jsx-runtime";var Zb=[{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:Sr,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:ei,chart:"visit_duration_seconds"}];function Yb({current:e,previous:t,downIsGood:a}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let n=s>0,r=a?!n:n,i=`${n?"+":""}${(s*100).toFixed(1)}%`;return Oa("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:i})}function of({summary:e,selected:t,onSelect:a}){return Oa("div",{className:"af-@container",children:Oa("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Zb.map(s=>{let n=s.chart===t,r=a!==void 0,i=ko(Jb,{children:[Oa("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),ko("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Oa("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?Oa(Yb,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?Oa("button",{type:"button","aria-pressed":n,onClick:()=>a(s.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:i},s.key):Oa("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:i},s.key)})})})}function Ql({currentVisitors:e,asOf:t,isStale:a,isUnreachable:s,isInitialLoad:n=!1,scopeIsSiteWide:r=!1}){if(n&&!s)return ko("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:[Oa("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Oa("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return Oa("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let i=t?Xu(t):"freshness unknown",l=r?" across the whole site, not the current filter,":"",u=a?`${e} current visitors${l} ${i} (not updating)`:`${e} current visitors${l} ${i}`;return ko("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:u,children:[Oa("span",{"aria-hidden":"true",className:a?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),Oa("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Oa("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),Oa("span",{className:"af-sr-only",children:u})]})}import*as cf from"react";import{Star as Xb}from"lucide-react";import{Fragment as lf,jsx as pa,jsxs as Zs}from"react/jsx-runtime";function Po(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Co({rows:e,denominator:t,windowPrecedesCollection:a=!1,coverageUnknown:s=!1,emptyCopy:n="No conversions in this period",maxRows:r=9,primaryConversion:i}){let[l,u]=cf.useState(!1),c=e.filter(d=>!d.implicit||d.visitors>0||d.events>0||Po(d,i)),o=a?pa("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?pa("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(c.length===0)return Zs(lf,{children:[pa(_o,{what:n}),o]});let f=c.slice(0,r),b=i?c.find(d=>Po(d,i)):void 0,g=b&&!f.includes(b)?c.filter(d=>f.includes(d)||d===b).slice(0,Math.max(0,r-1)).concat(b):f,m=l?e:g,v=Math.max(0,e.length-g.length);return Zs(lf,{children:[Zs("table",{className:"af-w-full af-text-sm",children:[pa("thead",{children:Zs("tr",{className:"af-text-xs af-text-muted-foreground",children:[pa("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),pa("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),pa("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),pa("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),pa("tbody",{children:m.map((d,p)=>Zs("tr",{className:"af-border-t af-border-border","aria-current":Po(d,i)?"true":void 0,children:[pa("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Po(d,i)?Zs("span",{className:"af-flex af-items-center af-gap-1.5",children:[pa(Xb,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),pa("span",{className:"af-font-medium af-text-foreground",children:d.goal}),pa("span",{className:"af-sr-only",children:"(your main conversion)"})]}):d.goal}),pa("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Da(d.visitors)}),pa("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Da(d.events)}),pa("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:d.conversion_rate===null?pa("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Sr(d.conversion_rate)})]},`${d.goal}-${p}`))})]}),v>0?pa("button",{type:"button",onClick:()=>u(d=>!d),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length} goals`}):null,Zs("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%."]}),o]})}import{Area as Qb,AreaChart as eh,CartesianGrid as th,ResponsiveContainer as ah,Tooltip as nh,XAxis as sh,YAxis as rh}from"recharts";import{jsx as La,jsxs as si}from"react/jsx-runtime";var To={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},tc={visitors:Da,visits:Da,pageviews:Da,views_per_visit:e=>e.toFixed(2),bounce_rate:Sr,visit_duration_seconds:ei},ih=31,oh=new Set(["visitors","visits","pageviews"]),lh={...tc,bounce_rate:Yu,visit_duration_seconds:Zu},ec=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],ch=[5,10,15,30,60,120,300,600,900,1800,3600,7200],dh=[.01,.02,.05,.1,.2,.25,.5,1],uh=[.25,.5,1,2,5,10,25,50],fh={visitors:ec,visits:ec,pageviews:ec,views_per_visit:uh,bounce_rate:dh,visit_duration_seconds:ch};function mh({active:e,payload:t,label:a,metric:s}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return si("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:[La("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:To[s]}),si("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[La("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),La("span",{className:"af-text-muted-foreground",children:ef(String(a))}),La("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:tc[s](Number(n[s]??0))})]})]})}function Eo({rows:e,window:t,metric:a,timeZone:s="UTC",height:n=260}){let r=Qu(t,e,s),i=tc[a],l=lh[a],u=Ju(r.reduce((o,f)=>Math.max(o,Number(f[a]??0)),0),fh[a]),c=`${To[a]} by day: ${r.map(o=>`${Yl(o.date)}: ${i(Number(o[a]??0))}`).join("; ")}.`;return si("figure",{"aria-label":`${To[a]} over time`,className:"af-m-0",children:[La(ah,{width:"100%",height:n,children:si(eh,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[La("defs",{children:si("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[La("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),La("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),La(th,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),La(sh,{dataKey:"date",tickFormatter:Yl,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),La(rh,{allowDecimals:!oh.has(a),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...u?{ticks:u,domain:[0,u[u.length-1]]}:{},tickFormatter:o=>l(o),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),La(nh,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:La(mh,{metric:a})}),La(Qb,{type:"linear",dataKey:a,name:To[a],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=ih?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),La("figcaption",{className:"af-sr-only",children:c})]})}import{Fragment as ac,jsx as Be,jsxs as Pa}from"react/jsx-runtime";var ph="2026-08-13",gh=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],vh=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function bh({filters:e,onFiltersChange:t,refreshKey:a,onBackToWebsite:s,primaryConversion:n,className:r,published:i,lastPublishedAt:l}){let[u,c]=Ft.useState(30),[o,f]=Ft.useState(()=>Lo()),b=e!==void 0&&t!==void 0,[g,m]=Ft.useState(e??[]),{api:v}=H(),[d,p]=Ft.useState(v);d!==v&&(p(v),!b&&g.length>0&&m([]));let x=b?e:g,S=Ft.useCallback(L=>{t&&t(L),b||m(L)},[t,b]),k=Ft.useCallback((L,pe,J)=>{let se=Array.isArray(pe)?pe:[pe];if(se.length===0)return null;let Fe=Xl(x,{dimension:L,operator:"is",values:se});if(J&&(!J.value||(Fe=nf(Fe,{dimension:J.dimension,operator:"is",values:[J.value]}),!Fe.find(It=>It.dimension===J.dimension&&It.operator!=="is_not")?.values.includes(J.value))))return null;let Qe=Fe.find(Xe=>Xe.dimension===L&&Xe.operator!=="is_not");return se.every(Xe=>Qe?.values.includes(Xe))?JSON.stringify(Fe)===JSON.stringify(x)?null:Fe:null},[x]),h=Ft.useCallback((L,pe,J)=>k(L,pe,J)!==null,[k]),N=Ft.useCallback((L,pe,J)=>{let se=k(L,pe,J);se&&S(se)},[k,S]),[R,C]=Ft.useState("visitors"),w=wr(u,{refreshKey:a,breakdowns:vh,filters:x}),P=w.status.data,I=w.reportedZone??P?.timezone,_=I??o??Rr()??"UTC",{notCollecting:q,awaitingFirstVisit:j,firstVisitTooRecent:U,holdingForFirstData:te}=No(P,{published:i}),ce=i===!1,me=So({collecting:j||q?!1:P?.collecting,statusFailed:w.status.error!=null,identity:P?.analytics_id}),T=Ft.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),V=Ft.useMemo(()=>{let L=w.breakdowns.sources?.data,pe={};if(!L||L.status!=="ok")return pe;for(let J of L.data){let se=J.source,Fe=J.sources;typeof se=="string"&&Array.isArray(Fe)&&Fe.length>0&&(pe[se]=Fe)}return pe},[w.breakdowns.sources?.data]),A=Ft.useMemo(()=>{let L=(se,Fe)=>{let Qe=w.breakdowns[se]?.data;return!Qe||Qe.status!=="ok"?[]:[...new Set(Qe.data.map(Xe=>Xe[Fe]).filter(Xe=>typeof Xe=="string"&&Xe!==""))]};return{channel:w.channels.data?.status==="ok"?[...new Set(w.channels.data.data.map(se=>se.channel))]:[],source:L("sources","source"),campaign:L("utm/campaign","campaign"),page:L("pages","pathname"),entry_page:L("entry-pages","pathname"),exit_page:L("exit-pages","pathname"),country:L("countries","country"),browser:L("browsers","browser"),os:L("operating-systems","os"),device:L("devices","device")}},[w.breakdowns,w.channels.data]),[ne,re]=Ft.useState({}),Me=JSON.stringify(A),[Se,Ee]=Ft.useState(new Map),Ye=JSON.stringify(V);Ft.useEffect(()=>{let{suggestions:L,folds:pe}=sf(T.current,{api:v,period:u},JSON.parse(Me),JSON.parse(Ye));re(L),Ee(pe)},[Me,Ye,v,u]);let ke=Ft.useCallback((L,pe)=>L!=="source"?pe:[...new Set(pe.flatMap(J=>{let se=[...Se.get(J)??[],...V[J]??[]];return se.length>0?se:[J]}))],[Se,V]),nt=Ft.useMemo(()=>{let L=w.conversions.error;return L instanceof aa&&L.details?.code==="goals_exceed_report_budget"?L.message:null},[w.conversions.error]),E=Ft.useMemo(()=>{let L=[w.summary,w.timeseries,w.channels,...Object.values(w.breakdowns)];for(let pe of L){let J=pe?.error;if(J instanceof aa&&J.details?.code==="filter_unsupported")return J.message}return null},[w.summary,w.timeseries,w.channels,w.breakdowns]),M=(L,pe,J,se,Fe,Qe,Xe,It,he)=>()=>{let $e=w.breakdowns[L];return Be(ds,{sourced:$e?.data??null,error:$e?.error,isLoading:$e?.isLoading,what:pe,collecting:P?.collecting,onRetry:w.refetch,children:yt=>{let At=Mt=>It?ke(It,[Mt]):Mt;return Be(Jl,{rows:yt,dimension:J,metric:se,metricLabel:Fe,secondary:Qe,emptyCopy:x.length>0?"No data for this filter":Xe,canFilter:It?(Mt,et)=>h(It,At(Mt),he?{dimension:he,value:et}:void 0):()=>!1,onFilter:It?(Mt,et)=>N(It,At(Mt),he?{dimension:he,value:et}:void 0):void 0})}})};if(Ro({status:P,holdingForFirstData:te,refetchStatus:w.refetchStatus,refetch:w.refetch}),q){let L=!!l&&String(l).slice(0,10)<ph;return Be(Ut,{title:"Analytics",onBackToWebsite:s,className:r,children:Pa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),Be("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.":L?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return j?Be(Ut,{title:"Analytics",onBackToWebsite:s,className:r,children:Pa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),Be("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."})]})}):U?Pa(Ut,{title:"Analytics",onBackToWebsite:s,className:r,children:[Be("div",{className:"af-mb-3 af-flex af-justify-end",children:Be(Zl,{value:_,chosen:o,onChange:L=>{Bo(L),f(L)}})}),Pa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),Pa("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",P?.timezone?` ${P.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),Be("div",{className:"af-mt-4 af-flex af-justify-center",children:Be(Ql,{currentVisitors:me.currentVisitors,asOf:me.asOf,isStale:me.isStale,isUnreachable:me.isUnreachable||me.error!==null,isInitialLoad:me.isInitialLoad})})]})]}):Be(Ut,{title:"Analytics",onBackToWebsite:s,className:r,children:Pa("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Pa("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Be("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:gh.map(L=>Be("button",{type:"button","aria-pressed":L.value===u,onClick:()=>c(L.value),className:L.value===u?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:L.label},L.value))}),Be(Zl,{value:_,chosen:o,onChange:L=>{Bo(L),f(L)}}),Be(Ql,{currentVisitors:me.currentVisitors,asOf:me.asOf,isStale:me.isStale,isUnreachable:me.isUnreachable||me.error!==null,isInitialLoad:me.isInitialLoad,scopeIsSiteWide:x.length>0})]}),Be(rf,{filters:x,onChange:S,suggestions:ne,expandValues:ke,resetKey:v}),E?Pa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),Be("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:E}),Be("button",{type:"button",onClick:()=>S([]),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,!E&&P?.timezone_defaulted?Be("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,E?null:Pa(ac,{children:[Be(ds,{sourced:w.summary.data,error:w.summary.error,isLoading:w.summary.isLoading,what:"The traffic summary",collecting:P?.collecting,onRetry:w.refetch,children:L=>Pa(ac,{children:[Be(of,{summary:L,selected:R,onSelect:C}),L.previous_unavailable?Pa("p",{className:"af-text-xs af-text-muted-foreground",children:[L.previous_unavailable_reason==="filter"?"No comparison for this filter \u2014 the previous period has too many distinct traffic sources to resolve it. Try a shorter period, or filter by source instead.":"No comparison available right now \u2014 we couldn\u2019t check how far back this site\u2019s history goes. It should return on its own."," ","The numbers above are still for the period you selected."]}):null]})}),Be("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:Be(ds,{sourced:w.timeseries.data,error:w.timeseries.error,isLoading:w.timeseries.isLoading,what:"The visitors chart",collecting:P?.collecting,onRetry:w.refetch,children:L=>{let pe=w.timeseries.data?.status==="ok"?w.timeseries.data.window:{from:"",to:""};return Be(Eo,{rows:L,window:pe,metric:R,timeZone:I??"UTC"})}})}),Pa("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[Be(ai,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>Be(ds,{sourced:w.channels.data,error:w.channels.error,isLoading:w.channels.isLoading,what:"Channels",collecting:P?.collecting,onRetry:w.refetch,children:L=>Be(Jl,{rows:L,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:pe=>h("channel",pe),onFilter:pe=>N("channel",pe)})})},{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")}]}),Be(ai,{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")}]}),Be(ai,{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")}]}),Be(ai,{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")}]})]}),Pa("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[Be("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:Be("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),Pa("div",{className:"af-px-3 af-py-2",children:[x.length>0?Pa("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",x.length===1?"filter":"filters"," above."]}):null,nt!==null?Pa("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:[Be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),Be("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:nt})]}):Be(ds,{sourced:w.conversions.data,error:w.conversions.error,isLoading:w.conversions.isLoading,what:"Conversions",collecting:P?.collecting,onRetry:w.refetch,children:L=>{let pe=w.conversions.data?.status==="ok"?w.conversions.data:null;return Be(ac,{children:Be(Co,{rows:L,primaryConversion:n,denominator:pe?.denominator??0,windowPrecedesCollection:pe?.window_precedes_collection??!1,coverageUnknown:pe?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import*as hf from"react";import{Phone as gf,Mail as sc,ShoppingBag as wh,ExternalLink as Sh,MessageCircle as Nh,Download as Rh,Target as yf}from"lucide-react";import*as Rn from"react";import{Check as nc,ChevronLeft as hh,Loader2 as df}from"lucide-react";import{jsx as ht,jsxs as ga}from"react/jsx-runtime";var uf=90,ff=100;function yh(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function mf(e){return!!e.label&&e.label!==e.target}function xh(e,t,a){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:s,with_a_value:n}=t;return s===0?e===0?"Nothing specific has converted here yet.":null:n===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":n<s?a?`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function ri(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function pf({current:e,onChange:t,onClose:a}){let{api:s}=H(),[n,r]=Rn.useState(null),[i,l]=Rn.useState(!1),[u,c]=Rn.useState({at:"goals"}),[o,f]=Rn.useState(null),[b,g]=Rn.useState(null),[m,v]=Rn.useState(!1),[d,p]=Rn.useState(null),x=Rn.useRef(0);Rn.useEffect(()=>{let N=!0;return r(null),l(!1),c({at:"goals"}),f(null),g(null),v(!1),p(null),x.current+=1,s.getAnalyticsConversions(uf).then(R=>{if(N){if(R.status!=="ok"){l(!0);return}r(R.data)}}).catch(()=>{N&&l(!0)}),()=>{N=!1}},[s]);let S=N=>{c({at:"targets",row:N}),f(null),g(null),v(!1),p(null);let R=++x.current;s.getAnalyticsGoalTargets(N.goal,uf,ff).then(C=>{if(R===x.current){if(C.status!=="ok"){g("failed");return}f(C.data),v(C.truncated===!0),p(C.coverage??null)}}).catch(C=>{if(R!==x.current)return;let w=C instanceof aa?C.details?.code:void 0;g(w==="goal_has_no_targets"?"no-values":"failed")})},k=N=>{t(N),a()};if(i)return ht("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return ga("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[ht(df,{className:"af-h-4 af-w-4 af-animate-spin"}),ht("span",{children:"Loading your conversions\u2026"})]});if(u.at==="targets"){let N=u.row,R=new Map;for(let C of o??[])R.set(C.label,(R.get(C.label)??0)+1);return ga("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:[ht("header",{className:"af-flex af-items-center af-gap-1",children:ga(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>c({at:"goals"}),children:[ht(hh,{className:"af-h-4 af-w-4"}),ht("span",{children:"All conversions"})]})}),ga("button",{type:"button","aria-current":e&&ri(N,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:()=>k({goal:N.goal,implicit:N.implicit}),children:[e&&ri(N,e)&&!e.target&&ht(nc,{className:"af-h-4 af-w-4 af-shrink-0"}),ga("span",{children:["Any ",N.goal.toLowerCase()]})]}),b==="no-values"&&ht("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"&&ga("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[ht("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),ht(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>S(N),children:"Try again"})]}),!o&&b===null&&ga("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:[ht(df,{className:"af-h-4 af-w-4 af-animate-spin"}),ht("span",{children:"Loading\u2026"})]}),o&&ht("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:xh(o.length,d,m)}),m&&ga("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",ff,". If what you want isn\u2019t here, pick the conversion itself instead."]}),o?.some(mf)&&ht("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),o?.map(C=>{let w=!!(e&&ri(N,e)&&e.target===C.target),P=R.get(C.label)>1;return mf(C)?ga("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:[ga("span",{className:"af-min-w-0",children:[ht("span",{className:"af-block af-truncate",children:C.label}),P&&ht("span",{className:"af-block af-truncate af-text-xs",children:C.target})]}),ht("span",{className:"af-shrink-0 af-text-xs",children:C.visitors.toLocaleString()})]},C.target):ga("button",{type:"button","aria-current":w?"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:()=>k({goal:N.goal,implicit:N.implicit,target:C.target,...C.label&&C.label!==C.target?{label:C.label}:{}}),children:[ga("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[w&&ht(nc,{className:"af-h-4 af-w-4 af-shrink-0"}),ga("span",{className:"af-min-w-0",children:[ht("span",{className:"af-block af-truncate",children:C.label}),P&&ht("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:C.target})]})]}),ht("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:C.visitors.toLocaleString()})]},C.target)})]})}let h=e?.goal&&!n.some(N=>ri(N,e));return ga("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[h&&ga("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&ht("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(N=>{let R=e?ri(N,e):!1;return ga("div",{className:"af-flex af-items-center af-gap-1",children:[ga("button",{type:"button","aria-current":R?"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:()=>k({goal:N.goal,implicit:N.implicit}),children:[ga("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[R&&ht(nc,{className:"af-h-4 af-w-4 af-shrink-0"}),ht("span",{className:"af-truncate",children:N.goal})]}),ht("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:N.visitors.toLocaleString()})]}),yh(N)&&ht(y,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${N.goal}`,onClick:()=>S(N),children:"Narrow"})]},N.goal)}),e?.goal&&ht("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:()=>k(null),children:"No main conversion"})]})}import{Fragment as Ch,jsx as Ys,jsxs as bf}from"react/jsx-runtime";function _h(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let a of t)try{let{hostname:s}=new URL(a);if(s)return s.toLowerCase().replace(/^www\./,"")}catch{}return null}function kh(e){if(rc(e,"whatsapp"))return!0;let t=_h(e);return t===null?!1:["wa.me","whatsapp.com"].some(a=>t===a||t.endsWith(`.${a}`))}function rc(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var vf=[{goal:"Contact",target:e=>rc(e,"tel"),icon:gf,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>rc(e,"mailto"),icon:sc,line:"This site is set up to get you emails."},{goal:"Contact",icon:gf,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>kh(e),icon:Nh,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:Sh,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:sc,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:sc,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:wh,line:"This site is set up to sell."},{goal:"File Download",icon:Rh,line:"This site is set up to get your file downloaded."}];function xf(e){let{goal:t,target:a}=e;return e.implicit!==!0?null:(a?vf.find(n=>n.goal===t&&n.target?.(a)):void 0)??vf.find(n=>n.goal===t&&!n.target)??null}function Ph(e){return xf(e)?.icon??yf}function wf({primaryConversion:e,onChange:t}){let[a,s]=hf.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?xf(e):null,i=e?.label?.trim(),l=e?Ph(e):yf,u=e?.goal?i?`Your main conversion is ${i}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",c=bf(Ch,{children:[Ys(l,{className:"af-h-4 af-w-4 af-shrink-0"}),Ys("span",{children:u})]});return t?bf(Ii,{open:a,onOpenChange:s,children:[Ys(Ai,{asChild:!0,children:Ys("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:c})}),Ys(Dr,{align:"start",className:"af-w-80 af-p-1",children:a&&Ys(pf,{current:e,onChange:t,onClose:()=>s(!1)})})]}):Ys("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:c})}import{Fragment as Th,jsx as Cs,jsxs as Io}from"react/jsx-runtime";function Sf({refreshKey:e,onViewAll:t,primaryConversion:a}){let s=wr(7,{refreshKey:e,breakdowns:[]}),n=s.status.data??void 0,{nothingToReport:r,notCollecting:i,holdingForFirstData:l}=No(n);return Ro({status:n,holdingForFirstData:l,refetchStatus:s.refetchStatus,refetch:s.refetch}),Io("section",{className:"af-rounded-md af-border af-p-3",children:[Io("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Cs("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&Cs(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?Cs("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:i?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):Io(Th,{children:[Cs(ds,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let c=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return Cs(Eo,{rows:u,window:c?.window??{from:"",to:""},metric:"visitors",timeZone:c?.timezone,height:140})}}),Io("div",{className:"af-mt-3",children:[Cs("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),Cs(ds,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let c=s.conversions.data?.status==="ok"?s.conversions.data:null;return Cs(Co,{rows:u,primaryConversion:a,denominator:c?.denominator??0,windowPrecedesCollection:c?.window_precedes_collection??!1,coverageUnknown:c?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as Fn,jsxs as ii}from"react/jsx-runtime";var ic=5;function oc({title:e,viewAllLabel:t,onViewAll:a}){return ii("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Fn("h3",{className:"af-text-sm af-font-medium",children:e}),a&&Fn(y,{type:"button",variant:"ghost",size:"sm",onClick:a,children:t})]})}function Eh({refreshKey:e,onBackToWebsite:t,primaryConversion:a,onChangePrimaryConversion:s,onOpenSurface:n,needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l}){let u=dr({refreshKey:e}),c=(u.summary?.products.count??0)>0||(u.summary?.commerce?.storefront_orders??!1),o=c||(u.summary?.commerce?.invoicing??!1);return Fn(Ut,{title:"Dashboard",onBackToWebsite:t,children:ii("div",{className:"af-flex af-flex-col af-gap-4",children:[Fn(wf,{primaryConversion:a,onChange:s}),Fn(Sf,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:a}),ii("section",{className:"af-rounded-md af-border af-p-3",children:[Fn(oc,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),Fn(Qi,{refreshKey:e,maxRows:ic,onViewAll:n&&(()=>n("leads"))})]}),c&&ii("section",{className:"af-rounded-md af-border af-p-3",children:[Fn(oc,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),Fn(bs,{refreshKey:e,maxRows:ic,onViewAll:n&&(()=>n("orders"))})]}),o&&ii("section",{className:"af-rounded-md af-border af-p-3",children:[Fn(oc,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),Fn(ys,{refreshKey:e,maxRows:ic,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l})]})]})})}export{vr as AUDIENCE_PAGE_SIZE,aa as AifeaturesApiError,_f as AifeaturesProvider,bh as AnalyticsView,lo as ContactImport,Ui as CustomerDetail,Vi as CustomersList,bo as DOUBLE_OPT_IN_HELP,Eh as DashboardView,gl as EMAIL_ORG_ACTIONS,nu as EMAIL_READINESS_TEXT,qu as EmailView,wa as ExportCsvButton,Ri as FormSettings,xi as FormSubmissions,Ic as FormsDashboard,ui as FormsList,hl as IMPORT_ATTESTATION,tl as InvoiceDetail,Or as InvoiceLabelBadge,ro as InvoiceSettingsPanel,ys as InvoicesList,au as InvoicesView,Qi as LeadsView,Gs as MAX_ANALYTICS_FILTERS,Ks as MAX_ANALYTICS_FILTER_VALUES,eu as NotificationRecipientsSettings,Bi as OrderDetail,Ds as OrderStatusBadge,bs as OrdersList,ud as OrdersView,ld as PaymentsDashboard,ir as PaymentsSetup,Ti as ProductSettings,Pi as ProductsList,yd as ProductsView,Qs as PromosPanel,Gl as REALTIME_FAILURES_BEFORE_ERROR,Wl as REALTIME_POLL_MS,al as RetainerStatusBadge,rr as RetainersPanel,Jd as StoreSettings,vi as SubmissionDetail,Dd as SubscriptionsView,Ci as VariantsEditor,Ut as ViewShell,Si as WebhookDeliveries,Ni as WebhookSettings,uv as buildEmailOrgRequest,is as chargedTotal,Fo as createApiClient,Ns as emailReadinessText,Q as formatPrice,dv as isEmailOrgAction,bn as isZeroDecimalCurrency,Ot as toMajorUnits,va as toMinorUnits,H as useAifeatures,H as useAifeaturesContext,wr as useAnalytics,io as useAudience,yr as useBroadcasts,dr as useBusinessSummary,yi as useCsvExport,$i as useCustomers,xr as useEmailDrafts,wi as useEventDestinations,Js as useForms,nr as useInvoices,Ei as useOrders,gs as usePaymentsStatus,Ji as usePeople,Xi as usePerson,or as useProducts,So as useRealtimeVisitors,lr as useRetainers,Ss as useSiteSettings,pi as useSubmissions,eo as useSubscriptions};