@aifeatures/admin-react 0.25.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +109 -90
- package/dist/index.d.ts +109 -90
- package/dist/index.js +6 -6
- package/dist/styles.css +21 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import*as as from"react";var bo="aifeatures:analytics:timezone",ho;function pr(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function jl(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function ts(){return yo()??pr()}function yo(){if(ho!==void 0)return ho;try{let e=window.localStorage.getItem(bo);return jl(e)?e:null}catch{return null}}function xo(e){if(!(e!==null&&!jl(e))){ho=e;try{e===null?window.localStorage.removeItem(bo):window.localStorage.setItem(bo,e)}catch{}}}function Wr(e,t){let a=new URLSearchParams({period:String(e)}),s=ts();return s&&a.set("timezone",s),t&&t.length>0&&a.set("filters",JSON.stringify(t)),a.toString()}var Yt=class extends Error{constructor(a,s,n){super(a);this.status=s;this.details=n;this.name="AifeaturesApiError"}};function Gr(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 gr(e,t){let a=t.toString();return a?`${e}?${a}`:e}function Wl(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 Gl(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 wo(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 f;try{f=await l.json()}catch{}throw new Yt(Gr(f?.error,l.status),l.status,f)}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 Yt(Gr(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(),f=`/api/v1/forms/${n}/submissions${l?`?${l}`:""}`;return a(f)},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(gr(`/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,f=i.id??i.name,d=`${t}/api/v1/submissions/${n}/attachments/${encodeURIComponent(f)}`,o=await fetch(d,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let m;try{m=await o.json()}catch{}throw new Yt(Gr(m?.error,o.status),o.status,m)}let c=await o.blob(),b=URL.createObjectURL(c),g=document.createElement("a");g.href=b,g.download=l,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(b)},async getSite(n){return a(`/api/v1/sites/${encodeURIComponent(n)}`)},async updateSite(n,r){return a(`/api/v1/sites/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return a("/api/v1/payments/status")},getPromos(n){let r=new URLSearchParams({limit:"10"});return n&&r.set("cursor",n),a(`/api/v1/promos?${r}`)},getPromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}`)},createPromo(n){return a("/api/v1/promos",{method:"POST",body:JSON.stringify(n)})},disablePromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}/disable`,{method:"POST"})},replacePromo(n,r){return a(`/api/v1/promos/${encodeURIComponent(n)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(n={}){let r=new URLSearchParams;n.include&&r.set("include",n.include);let i=r.toString();return(await a(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(n){return a(`/api/v1/products/${n}`)},async createProduct(n){return a("/api/v1/products",{method:"POST",body:JSON.stringify(n)})},async updateProduct(n,r){return a(`/api/v1/products/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(n){await a(`/api/v1/products/${n}`,{method:"DELETE"})},async attachProductFile(n,r){let i=new FormData;i.append("file",r);let l=await fetch(`${t}/api/v1/products/${n}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!l.ok){let f;try{f=await l.json()}catch{}throw new Yt(Gr(f?.error,l.status),l.status,f)}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=Wl(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(gr("/api/v1/orders/export",Wl(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=Gl(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(gr("/api/v1/retainers/export",Gl(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(gr("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let n=new URLSearchParams,r=ts();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?${Wr(n,r)}`)},async getAnalyticsTimeseries(n,r){return a(`/api/v1/analytics/timeseries?${Wr(n,r)}`)},async getAnalyticsRealtime(){return a("/api/v1/analytics/realtime")},async getAnalyticsChannels(n,r){return a(`/api/v1/analytics/channels?${Wr(n,r)}`)},async getAnalyticsConversions(n){return a((()=>{let r=new URLSearchParams({period:String(n)}),i=ts();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)}),f=ts();return f&&l.set("timezone",f),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}?${Wr(r,i)}`)},async getBusinessSummary(n){let r=new URLSearchParams;r.set("tz_offset_minutes",String(n.tzOffsetMinutes));let i=ts();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(gr("/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(`${qa(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(`${qa(n)}/contacts${l?`?${l}`:""}`)},async getMarketingContactStats(n){return a(`${qa(n)}/contacts/stats`)},async getMarketingTags(n){return(await a(`${qa(n)}/contact-tags`)).tags},async getEmailDrafts(n,r){let i=r?`?kind=${r}`:"";return(await a(`${qa(n)}/marketing/drafts${i}`)).drafts},async getEmailDraft(n,r){return a(`${qa(n)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(n,r,i){let l=i?.editable?"?mode=editable":"";return a(`${qa(n)}/marketing/drafts/${encodeURIComponent(r)}/preview${l}`)},async getEmailTemplates(n){return(await a(`${qa(n)}/marketing/templates`)).templates},async previewEmailTemplate(n,r,i){let l=i?`?draft_id=${encodeURIComponent(i)}`:"";return a(`${qa(n)}/marketing/templates/${encodeURIComponent(r)}/preview${l}`)},async getBroadcasts(n){return(await a(`${qa(n)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(n,r){return a(`${qa(n)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getWelcomeSequence(n){return a(`${qa(n)}/marketing/welcome`)},async getRecoveryFlow(n){return a(`${qa(n)}/marketing/recovery`)}}}function qa(e){return`/api/v1/sites/${encodeURIComponent(e)}`}import{jsx as vr,jsxs as Hu}from"react/jsx-runtime";var Kl=as.createContext(null);function $u(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 Vu({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:n}){let r=as.useMemo(()=>$u(e),[e]),i=as.useMemo(()=>wo(e,t),[e,t]),l=as.useMemo(()=>({siteToken:e,apiUrl:t,api:i}),[e,t,i]);return r?vr("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:Hu("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[vr("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),vr("p",{className:"af-text-sm af-text-destructive",children:r})]})}):vr(Kl.Provider,{value:l,children:vr("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:n})})}function H(){let e=as.useContext(Kl);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as Yn from"react";import{ArrowLeft as Yf,Settings as Jf,Inbox as Xf}from"lucide-react";import*as Kr from"react";import*as hn from"@radix-ui/react-tabs";import{clsx as zu}from"clsx";import{extendTailwindMerge as qu}from"tailwind-merge";var ju=qu({prefix:"af-"});function G(...e){return ju(zu(e))}import{jsx as So}from"react/jsx-runtime";var Zr=hn.Root,br=Kr.forwardRef(({className:e,...t},a)=>So(hn.List,{ref:a,className:G("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}));br.displayName=hn.List.displayName;var yn=Kr.forwardRef(({className:e,...t},a)=>So(hn.Trigger,{ref:a,className:G("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}));yn.displayName=hn.Trigger.displayName;var xn=Kr.forwardRef(({className:e,...t},a)=>So(hn.Content,{ref:a,className:G("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}));xn.displayName=hn.Content.displayName;import*as Zl from"react";import{Slot as Wu}from"@radix-ui/react-slot";import{cva as Gu}from"class-variance-authority";import{jsx as Zu}from"react/jsx-runtime";var Ku=Gu("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=Zl.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...n},r)=>Zu(s?Wu:"button",{className:G(Ku({variant:t,size:a,className:e})),ref:r,...n}));y.displayName="Button";import{Inbox as Yl,Settings as Xu}from"lucide-react";import*as Wn from"react";import{jsx as jn}from"react/jsx-runtime";var lt=Wn.forwardRef(({className:e,...t},a)=>jn("div",{className:"af-relative af-w-full af-overflow-auto",children:jn("table",{ref:a,className:G("af-w-full af-caption-bottom af-text-sm",e),...t})}));lt.displayName="Table";var ct=Wn.forwardRef(({className:e,...t},a)=>jn("thead",{ref:a,className:G("[&_tr]:af-border-b",e),...t}));ct.displayName="TableHeader";var dt=Wn.forwardRef(({className:e,...t},a)=>jn("tbody",{ref:a,className:G("[&_tr:last-child]:af-border-0",e),...t}));dt.displayName="TableBody";var Yu=Wn.forwardRef(({className:e,...t},a)=>jn("tfoot",{ref:a,className:G("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Yu.displayName="TableFooter";var Ce=Wn.forwardRef(({className:e,...t},a)=>jn("tr",{ref:a,className:G("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Ce.displayName="TableRow";var q=Wn.forwardRef(({className:e,...t},a)=>jn("th",{ref:a,className:G("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}));q.displayName="TableHead";var j=Wn.forwardRef(({className:e,...t},a)=>jn("td",{ref:a,className:G("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));j.displayName="TableCell";var Ju=Wn.forwardRef(({className:e,...t},a)=>jn("caption",{ref:a,className:G("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Ju.displayName="TableCaption";import*as wn from"react";function Us(){let{api:e}=H(),[t,a]=wn.useState([]),[s,n]=wn.useState(!0),[r,i]=wn.useState(null),l=wn.useCallback(async()=>{try{n(!0),i(null);let c=await e.getForms();a(c)}catch(c){i(c instanceof Error?c:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);wn.useEffect(()=>{l()},[l]);let f=wn.useCallback(async c=>{let b=await e.createForm(c);return a(g=>[...g,b]),b},[e]),d=wn.useCallback(async(c,b)=>{let g=await e.updateForm(c,b);return a(m=>m.map(p=>p.id===c?g:p)),g},[e]),o=wn.useCallback(async c=>{await e.deleteForm(c),a(b=>b.filter(g=>g.id!==c))},[e]);return{forms:t,isLoading:s,error:r,refetch:l,createForm:f,updateForm:d,deleteForm:o}}import{jsx as Da,jsxs as Gn}from"react/jsx-runtime";function Yr({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:n}=Us();return s?Da("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Da("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?Da("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Gn("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):a.length===0?Gn("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Da(Yl,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Gn("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",Da("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):Da("div",{className:t,children:Gn(lt,{children:[Da(ct,{children:Gn(Ce,{children:[Da(q,{children:"Name"}),Da(q,{className:"af-text-right",children:"Actions"})]})}),Da(dt,{children:a.map(r=>Gn(Ce,{children:[Da(j,{className:"af-font-medium",children:r.name}),Da(j,{className:"af-text-right",children:Gn("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Gn(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[Da(Yl,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Gn(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[Da(Xu,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}import{AlertTriangle as af}from"lucide-react";import{cva as Qu}from"class-variance-authority";import{jsx as tf}from"react/jsx-runtime";var ef=Qu("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 tf("div",{className:G(ef({variant:t}),e),...a})}import{jsx as hs,jsxs as Jr}from"react/jsx-runtime";var nf={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 Xr(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 No(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function sf(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 hr({deliveries:e,label:t="Email needs attention"}){return No(e)?Jr("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:[hs(af,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function In({deliveries:e,problemsOnly:t=!1,className:a=""}){let s=(e??[]).filter(n=>!t||No([n]));return s.length?hs("div",{className:`af-space-y-3 ${a}`,"aria-label":"Email delivery",children:s.map(n=>{let r=Xr(n),i=sf(n);return Jr("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[Jr("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[hs("span",{className:"af-font-medium",children:nf[n.kind]??"Email notification"}),hs(ee,{variant:r.variant,children:r.label})]}),Jr("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&No([n])&&hs("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&&hs("p",{className:"af-mt-1",children:r.detail}),i&&hs("p",{className:"af-mt-1",children:i})]},n.id)})}):null}import*as ss from"react";import{ArrowLeft as _f,ChevronLeft as Pf,ChevronRight as kf,Eye as Cf,Inbox as Tf,Paperclip as Ef}from"lucide-react";import*as ns from"react";import*as Ve from"@radix-ui/react-select";import{Check as rf,ChevronDown as Jl,ChevronUp as of}from"lucide-react";import{jsx as ga,jsxs as Ro}from"react/jsx-runtime";var nn=Ve.Root;var sn=Ve.Value,ja=ns.forwardRef(({className:e,children:t,...a},s)=>Ro(Ve.Trigger,{ref:s,className:G("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,ga(Ve.Icon,{asChild:!0,children:ga(Jl,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));ja.displayName=Ve.Trigger.displayName;var Xl=ns.forwardRef(({className:e,...t},a)=>ga(Ve.ScrollUpButton,{ref:a,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:ga(of,{className:"af-h-4 af-w-4"})}));Xl.displayName=Ve.ScrollUpButton.displayName;var Ql=ns.forwardRef(({className:e,...t},a)=>ga(Ve.ScrollDownButton,{ref:a,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:ga(Jl,{className:"af-h-4 af-w-4"})}));Ql.displayName=Ve.ScrollDownButton.displayName;var Wa=ns.forwardRef(({className:e,children:t,position:a="popper",...s},n)=>ga(Ve.Portal,{children:Ro(Ve.Content,{ref:n,className:G("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:[ga(Xl,{}),ga(Ve.Viewport,{className:G("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}),ga(Ql,{})]})}));Wa.displayName=Ve.Content.displayName;var lf=ns.forwardRef(({className:e,...t},a)=>ga(Ve.Label,{ref:a,className:G("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));lf.displayName=Ve.Label.displayName;var xt=ns.forwardRef(({className:e,children:t,...a},s)=>Ro(Ve.Item,{ref:s,className:G("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:[ga("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:ga(Ve.ItemIndicator,{children:ga(rf,{className:"af-h-4 af-w-4"})})}),ga(Ve.ItemText,{children:t})]}));xt.displayName=Ve.Item.displayName;var cf=ns.forwardRef(({className:e,...t},a)=>ga(Ve.Separator,{ref:a,className:G("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));cf.displayName=Ve.Separator.displayName;import*as Ra from"react";function Qr({formId:e,initialPageSize:t=25}){let{api:a}=H(),[s,n]=Ra.useState([]),[r,i]=Ra.useState(0),[l,f]=Ra.useState(!0),[d,o]=Ra.useState(null),[c,b]=Ra.useState(0),[g,m]=Ra.useState(t),p=Ra.useRef(0),u=Ra.useCallback(async()=>{if(!e)return;let P=++p.current;try{f(!0),o(null);let h={limit:g,offset:c*g},S=await a.getSubmissions(e,h);if(P!==p.current)return;if(S.submissions.length===0&&c>0){b(Math.max(0,Math.ceil(S.total/g)-1));return}n(S.submissions),i(S.total)}catch(h){if(P!==p.current)return;o(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{P===p.current&&f(!1)}},[a,e,c,g]);Ra.useEffect(()=>{u()},[u]);let v=Ra.useRef(u);v.current=u;let x=Ra.useCallback(async P=>{await a.deleteSubmission(P),v.current()},[a]),R=Math.ceil(r/g);return{submissions:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<R-1,hasPreviousPage:c>0,setPage:b,setPageSize:P=>{m(P),b(0)},refetch:u,deleteSubmission:x}}import*as ei from"react";import{Trash2 as ff}from"lucide-react";import*as yr from"react";import*as Jt from"@radix-ui/react-dialog";import{X as df}from"lucide-react";import{jsx as Kn,jsxs as _o}from"react/jsx-runtime";var rn=Jt.Root;var uf=Jt.Portal;var ec=yr.forwardRef(({className:e,...t},a)=>Kn(Jt.Overlay,{ref:a,className:G("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));ec.displayName=Jt.Overlay.displayName;var Ga=yr.forwardRef(({className:e,children:t,...a},s)=>Kn(uf,{children:_o("div",{className:"aifeatures-admin",children:[Kn(ec,{}),_o(Jt.Content,{ref:s,className:G("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,_o(Jt.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[Kn(df,{className:"af-h-4 af-w-4"}),Kn("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Ga.displayName=Jt.Content.displayName;var Ka=({className:e,...t})=>Kn("div",{className:G("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Ka.displayName="DialogHeader";var Za=({className:e,...t})=>Kn("div",{className:G("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Za.displayName="DialogFooter";var Ya=yr.forwardRef(({className:e,...t},a)=>Kn(Jt.Title,{ref:a,className:G("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Ya.displayName=Jt.Title.displayName;var Ja=yr.forwardRef(({className:e,...t},a)=>Kn(Jt.Description,{ref:a,className:G("af-text-sm af-text-muted-foreground",e),...t}));Ja.displayName=Jt.Description.displayName;import{Fragment as mf,jsx as ys,jsxs as xr}from"react/jsx-runtime";function $s({onDelete:e,iconOnly:t}){let[a,s]=ei.useState(!1),[n,r]=ei.useState(!1),[i,l]=ei.useState(null);return xr(mf,{children:[xr(y,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{l(null),s(!0)},children:[ys(ff,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),ys(rn,{open:a,onOpenChange:d=>{!d&&!n&&s(!1)},children:xr(Ga,{children:[xr(Ka,{children:[ys(Ya,{children:"Delete this submission?"}),ys(Ja,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),i&&ys("p",{className:"af-text-sm af-text-destructive",children:i}),xr(Za,{children:[ys(y,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),ys(y,{variant:"destructive",onClick:async()=>{r(!0),l(null);try{await e(),s(!1)}catch(d){l(d instanceof Error?d.message:"Failed to delete submission")}finally{r(!1)}},disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}import*as ac from"react";import{ArrowLeft as pf,Download as gf,Globe as vf,Clock as bf,FileText as hf,Loader2 as yf,Monitor as xf,Mail as wf}from"lucide-react";import{jsx as Bt,jsxs as Tt}from"react/jsx-runtime";function tc(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Sf(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({submission:e,onBack:t,onDelete:a}){let{api:s}=H(),[n,r]=ac.useState(null),i=d=>d.id??d.name,l=async d=>{r(i(d));try{await s.downloadAttachment(e.id,d)}catch(o){console.error("Download failed:",o)}finally{r(null)}},f=Object.entries(e.data).filter(([d])=>!d.startsWith("_"));return Tt("div",{children:[Tt("div",{className:"af-mb-6",children:[Tt(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[Bt(pf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Tt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[Tt("div",{children:[Bt("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),Tt("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",tc(e.metadata.submitted_at)]})]}),a&&Bt($s,{onDelete:a})]})]}),Tt("div",{className:"af-space-y-6",children:[Bt(In,{deliveries:e.email_deliveries}),Tt("div",{children:[Bt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),Tt("div",{className:"af-space-y-3",children:[f.map(([d,o])=>Tt("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[Bt("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:d.replace(/_/g," ")}),Bt("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof o=="string"&&o.includes(`
|
|
3
|
-
`)?Bt("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:o}):String(o)})]},d)),f.length===0&&Bt("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&Tt("div",{children:[Bt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),Bt("div",{className:"af-space-y-2",children:e.attachments.map((d,o)=>Tt("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[Tt("div",{className:"af-flex af-items-center af-gap-2",children:[Bt(hf,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Bt("span",{className:"af-text-sm",children:d.name}),Tt("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Sf(d.size),")"]})]}),Tt(y,{variant:"ghost",size:"sm",onClick:()=>l(d),disabled:n===i(d),children:[n===i(d)?Bt(yf,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Bt(gf,{className:"af-h-4 af-w-4 af-mr-1"}),n===i(d)?"Downloading...":"Download"]})]},o))})]}),Tt("div",{children:[Bt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),Tt("div",{className:"af-space-y-2 af-text-sm",children:[Tt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Bt(bf,{className:"af-h-4 af-w-4"}),Bt("span",{children:tc(e.metadata.submitted_at)})]}),e.metadata.ip_address&&Tt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Bt(vf,{className:"af-h-4 af-w-4"}),Tt("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&Tt("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[Bt(xf,{className:"af-h-4 af-w-4 af-mt-0.5"}),Bt("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&Tt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Bt(wf,{className:"af-h-4 af-w-4"}),Tt("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{Download as Rf}from"lucide-react";import*as xs from"react";var Nf=/^\+[1-9]\d{1,14}$/;function nc(e){let t=e==null?"":String(e),a=!Nf.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 ai(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function ni(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 si({fetchCsv:e,filename:t}){let[a,s]=xs.useState(!1),[n,r]=xs.useState(null),i=xs.useRef(!1);return{exportCsv:xs.useCallback(async()=>{if(!i.current){i.current=!0,s(!0),r(null);try{let f=await e();ni(f,ai(t))}catch(f){r(f instanceof Error?f:new Error("Export failed"))}finally{i.current=!1,s(!1)}}},[e,t]),exporting:a,error:n}}import{jsx as sc,jsxs as rc}from"react/jsx-runtime";function va({fetchCsv:e,filename:t,label:a="Export CSV",disabled:s,className:n}){let{exportCsv:r,exporting:i,error:l}=si({fetchCsv:e,filename:t});return rc("span",{className:n,children:[rc(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||i,"aria-busy":i,children:[sc(Rf,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Exporting\u2026":a]}),l&&sc("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}import{jsx as Be,jsxs as Ut}from"react/jsx-runtime";function If(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Df(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 Af=["message","comments","comment","inquiry","question","details","body","notes"];function Lf(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=(Af.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 ri({formId:e,className:t,defaultSubmissionId:a,submissionId:s,onSelectSubmission:n}){let{api:r}=H(),{submissions:i,total:l,isLoading:f,error:d,page:o,pageSize:c,hasNextPage:b,hasPreviousPage:g,setPage:m,setPageSize:p,deleteSubmission:u}=Qr({formId:e}),v=ss.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[x,R]=ss.useState(a??null),P=n?s??null:x,h=n??R,S=U=>!!U&&U.id===P&&U.form_id===e,N=i.find(S),[C,w]=ss.useState(null),k=S(C)?C:null,[T,_]=ss.useState(null);if(ss.useEffect(()=>{if(_(null),!P||N||k)return;let U=!1;return r.getSubmission(P).then(ae=>{if(!U){if(ae.form_id!==e){_("This submission could not be found.");return}w(ae)}}).catch(()=>{U||_("This submission could not be found.")}),()=>{U=!0}},[r,e,P,N,k]),P){let U=N??k;return U?Be("div",{className:t,children:Be(ti,{submission:U,onBack:()=>h(null),onDelete:async()=>{await u(U.id),h(null)}})}):T?Ut("div",{className:t,children:[Ut(y,{variant:"ghost",size:"sm",onClick:()=>h(null),className:"af-mb-2 af--ml-2",children:[Be(_f,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Be("p",{className:"af-text-sm af-text-destructive",children:T})]}):Be("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Be("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(f)return Be("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Be("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(d)return Be("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ut("div",{className:"af-text-destructive",children:["Error: ",d.message]})});if(i.length===0&&o===0)return Ut("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Be(Tf,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ut("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",Be("br",{}),"Submissions will appear here when visitors use your form."]})]});let z=o*c+1,Z=Math.min((o+1)*c,l);return Ut("div",{className:t,children:[Be("div",{className:"af-mb-2 af-flex af-justify-end",children:Be(va,{fetchCsv:v,filename:"submissions"})}),Ut(lt,{children:[Be(ct,{children:Ut(Ce,{children:[Be(q,{children:"Email"}),Be(q,{children:"Preview"}),Be(q,{children:"Date"}),Be(q,{className:"af-text-right",children:"Actions"})]})}),Be(dt,{children:i.map(U=>{let ae=Df(U.data),le=Lf(U.data);return Ut(Ce,{children:[Ut(j,{className:"af-font-medium",children:[Ut("div",{className:"af-flex af-items-center af-gap-2",children:[ae||Be("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),U.attachments.length>0&&Ut("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${U.attachments.length} attachment(s)`,children:[Be(Ef,{className:"af-h-3 af-w-3"}),Be("span",{className:"af-text-xs",children:U.attachments.length})]})]}),Be(hr,{deliveries:U.email_deliveries,label:"Notification email needs attention"})]}),Be(j,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:le||Be("span",{className:"af-italic",children:"No preview available"})}),Be(j,{className:"af-text-muted-foreground",children:If(U.metadata.submitted_at)}),Ut(j,{className:"af-text-right",children:[Be(y,{variant:"ghost",size:"icon",onClick:()=>h(U.id),title:"View details",children:Be(Cf,{className:"af-h-4 af-w-4"})}),Be($s,{iconOnly:!0,onDelete:()=>u(U.id)})]})]},U.id)})})]}),Ut("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Ut("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ut("span",{children:["Showing ",z,"-",Z," of ",l]}),Ut(nn,{value:String(c),onValueChange:U=>p(Number(U)),children:[Be(ja,{className:"af-w-[70px] af-h-8",children:Be(sn,{})}),Ut(Wa,{children:[Be(xt,{value:"10",children:"10"}),Be(xt,{value:"25",children:"25"}),Be(xt,{value:"50",children:"50"}),Be(xt,{value:"100",children:"100"})]})]}),Be("span",{children:"per page"})]}),Ut("div",{className:"af-flex af-items-center af-gap-2",children:[Ut(y,{variant:"outline",size:"sm",onClick:()=>m(o-1),disabled:!g,children:[Be(Pf,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ut(y,{variant:"outline",size:"sm",onClick:()=>m(o+1),disabled:!b,children:["Next",Be(kf,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Qa from"react";import{Plus as Wf,X as Gf,Loader2 as Kf,Check as Zf}from"lucide-react";import*as ic from"react";import{jsx as Of}from"react/jsx-runtime";var te=ic.forwardRef(({className:e,type:t,...a},s)=>Of("input",{type:t,className:G("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}));te.displayName="Input";import*as oc from"react";import{cva as Bf}from"class-variance-authority";import{jsx as Mf}from"react/jsx-runtime";var Ff=Bf("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Ie=oc.forwardRef(({className:e,...t},a)=>Mf("label",{ref:a,className:G(Ff(),e),...t}));Ie.displayName="Label";import*as ln from"react";import{Plus as $f,Loader2 as Po,Copy as Vf,Check as Hf,Trash2 as zf,RefreshCw as qf,AlertTriangle as jf}from"lucide-react";import*as Xa from"react";function ii(){let{api:e}=H(),[t,a]=Xa.useState([]),[s,n]=Xa.useState(!0),[r,i]=Xa.useState(null),l=Xa.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]);Xa.useEffect(()=>{l()},[l]);let f=Xa.useCallback(async g=>{let m=await e.createEventDestination(g);return a(p=>[m,...p]),m},[e]),d=Xa.useCallback(async(g,m)=>{let p=await e.updateEventDestination(g,m);return a(u=>u.map(v=>v.id===g?p:v)),p},[e]),o=Xa.useCallback(async g=>{await e.deleteEventDestination(g),a(m=>m.filter(p=>p.id!==g))},[e]),c=Xa.useCallback(async g=>{let m=await e.rotateEventDestinationSecret(g);return a(p=>p.map(u=>u.id===g?m:u)),m},[e]),b=Xa.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:s,error:r,refetch:l,createDestination:f,updateDestination:d,deleteDestination:o,rotateSecret:c,getSecret:b}}import*as Zn from"react";import{Loader2 as lc,RotateCw as Uf}from"lucide-react";import{jsx as on,jsxs as wr}from"react/jsx-runtime";function oi({destinationId:e,limit:t=25,className:a}){let{api:s}=H(),[n,r]=Zn.useState([]),[i,l]=Zn.useState(!0),[f,d]=Zn.useState(null),[o,c]=Zn.useState(null),b=Zn.useCallback(async()=>{try{l(!0),d(null),r(await s.getEventDeliveries(e,t))}catch(m){d(m instanceof Error?m.message:"Failed to load deliveries")}finally{l(!1)}},[s,e,t]);Zn.useEffect(()=>{b()},[b]);let g=async m=>{try{c(m.id),d(null);let p=await s.retryEventDelivery(e,m.id);r(u=>u.map(v=>v.id===m.id?p:v))}catch(p){d(p instanceof Error?p.message:"Retry failed")}finally{c(null)}};return i?wr("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[on(lc,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):f?on("div",{className:"af-text-sm af-text-destructive af-py-2",children:f}):n.length===0?on("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):on("div",{className:a,children:on("div",{className:"af-divide-y af-border af-rounded",children:n.map(m=>{let p=m.delivered_at!==null;return wr("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[wr("div",{className:"af-min-w-0",children:[wr("div",{className:"af-flex af-items-center af-gap-2",children:[p?on(ee,{variant:"secondary",children:m.last_status??200}):on(ee,{variant:"destructive",children:m.last_status??"failed"}),on("span",{className:"af-text-sm af-truncate",children:m.type})]}),wr("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[m.event_id," \xB7 ",m.created_at,m.attempts>0&&` \xB7 ${m.attempts} failed ${m.attempts===1?"attempt":"attempts"}`]}),!p&&m.last_error&&on("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:m.last_error})]}),on(y,{variant:"ghost",size:"sm",title:"Send this event again",disabled:o===m.id,onClick:()=>g(m),children:o===m.id?on(lc,{className:"af-h-4 af-w-4 af-animate-spin"}):on(Uf,{className:"af-h-4 af-w-4"})})]},m.id)})})})}import{jsx as Ye,jsxs as qt}from"react/jsx-runtime";function li({formId:e,topics:t,description:a,className:s}){let{destinations:n,isLoading:r,error:i,createDestination:l,updateDestination:f,deleteDestination:d,rotateSecret:o,getSecret:c}=ii(),[b,g]=ln.useState(""),[m,p]=ln.useState(!1),[u,v]=ln.useState(null),[x,R]=ln.useState(null),[P,h]=ln.useState(null),[S,N]=ln.useState(!1),[C,w]=ln.useState(null),[k,T]=ln.useState(null),[_,z]=ln.useState(null),Z=ln.useMemo(()=>n.filter(A=>A.form_id===e),[n,e]),U=async()=>{let A=b.trim();if(A){if(!A.startsWith("https://")){v("Webhook URLs must start with https://");return}try{p(!0),v(null),await l({url:A,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(de){v(de instanceof Error?de.message:"Failed to add webhook")}finally{p(!1)}}},ae=async A=>{try{T(A.id),v(null),await o(A.id),N(!1),h(await c(A.id))}catch(de){v(de instanceof Error?de.message:"Failed to rotate secret")}finally{T(null)}},le=async A=>{try{T(A.id),v(null),await f(A.id,{status:"active"})}catch(de){v(de instanceof Error?de.message:"Failed to re-enable")}finally{T(null)}},fe=async()=>{if(C)try{T(C.id),await d(C.id),w(null)}catch(A){v(A instanceof Error?A.message:"Failed to delete")}finally{T(null)}},M=async A=>{if(x===A.id){R(null),h(null);return}try{T(A.id),v(null),N(!1),R(A.id),h(await c(A.id))}catch(de){R(null),v(de instanceof Error?de.message:"Failed to read secret")}finally{T(null)}},W=async()=>{if(P)try{await navigator.clipboard.writeText(P),N(!0)}catch{}};return qt("div",{className:s,children:[qt("div",{className:"af-space-y-1",children:[Ye(Ie,{children:"Webhooks"}),Ye("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."})]}),qt("div",{className:"af-flex af-gap-2 af-mt-4",children:[Ye(te,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:A=>g(A.target.value),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),U())},disabled:m}),qt(y,{onClick:U,disabled:m||!b.trim(),children:[m?Ye(Po,{className:"af-h-4 af-w-4 af-animate-spin"}):Ye($f,{className:"af-h-4 af-w-4"}),Ye("span",{className:"af-ml-1",children:"Add"})]})]}),(u||i)&&Ye("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:u||i?.message}),qt("div",{className:"af-mt-4 af-space-y-2",children:[r&&qt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ye(Po,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&Z.length===0&&Ye("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),Z.map(A=>qt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[qt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[qt("div",{className:"af-min-w-0",children:[qt("div",{className:"af-flex af-items-center af-gap-2",children:[Ye("span",{className:"af-font-mono af-text-sm af-truncate",children:A.url}),A.status==="disabled"?Ye(ee,{variant:"destructive",children:"Disabled"}):Ye(ee,{variant:"secondary",children:"Active"})]}),Ye("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:A.topics.includes("*")?"All events":A.topics.join(", ")})]}),qt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[Ye(y,{variant:"ghost",size:"sm",onClick:()=>z(_===A.id?null:A.id),children:_===A.id?"Hide log":"Deliveries"}),Ye(y,{variant:"ghost",size:"sm",onClick:()=>M(A),disabled:k===A.id,children:x===A.id?"Hide secret":"Show secret"}),Ye(y,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:k===A.id,onClick:()=>w(A),children:Ye(zf,{className:"af-h-4 af-w-4"})})]})]}),A.status==="disabled"&&qt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[Ye(jf,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),qt("div",{className:"af-text-sm",children:[qt("p",{children:["We stopped sending after repeated failures."," ",A.disabled_reason]}),Ye(y,{variant:"outline",size:"sm",className:"af-mt-2",disabled:k===A.id,onClick:()=>le(A),children:"Re-enable"})]})]}),x===A.id&&P&&qt("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[Ye("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."}),qt("div",{className:"af-flex af-gap-2",children:[Ye(te,{readOnly:!0,value:P,className:"af-font-mono"}),Ye(y,{variant:"outline",title:"Copy signing secret",onClick:W,children:S?Ye(Hf,{className:"af-h-4 af-w-4"}):Ye(Vf,{className:"af-h-4 af-w-4"})}),Ye(y,{variant:"outline",title:"Rotate signing secret",disabled:k===A.id,onClick:()=>ae(A),children:k===A.id?Ye(Po,{className:"af-h-4 af-w-4 af-animate-spin"}):Ye(qf,{className:"af-h-4 af-w-4"})})]})]}),_===A.id&&Ye(oi,{destinationId:A.id})]},A.id))]}),Ye(rn,{open:!!C,onOpenChange:A=>{!A&&!k&&w(null)},children:qt(Ga,{children:[qt(Ka,{children:[Ye(Ya,{children:"Delete this webhook?"}),qt(Ja,{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."]})]}),qt(Za,{children:[Ye(y,{variant:"outline",onClick:()=>w(null),disabled:!!k,children:"Cancel"}),Ye(y,{variant:"destructive",onClick:fe,disabled:!!k,children:k?"Deleting...":"Delete"})]})]})})]})}import{jsx as tt,jsxs as Sn}from"react/jsx-runtime";function ci({form:e,onSaved:t,className:a}){let{updateForm:s}=Us(),[n,r]=Qa.useState(!1),[i,l]=Qa.useState(null),[f,d]=Qa.useState(null),[o,c]=Qa.useState(e.name),[b,g]=Qa.useState(e.redirect_url||""),[m,p]=Qa.useState(e.email_recipients),[u,v]=Qa.useState("");Qa.useEffect(()=>{c(e.name),g(e.redirect_url||""),p(e.email_recipients),d(null)},[e]);let x=Qa.useCallback(async N=>{try{r(!0),d(null);let C=await s(e.id,N);l(new Date),t?.(C)}catch(C){d(C instanceof Error?C.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);Qa.useEffect(()=>{if(i){let N=setTimeout(()=>l(null),2e3);return()=>clearTimeout(N)}},[i]);let R=async()=>{let N=u.trim().toLowerCase();if(!N)return;if(!N.includes("@")){d("Please enter a valid email address");return}if(m.includes(N)){d("This email is already added");return}let C=[...m,N];p(C),v(""),d(null),await x({email_recipients:C})},P=async N=>{let C=m.filter(w=>w!==N);p(C),await x({email_recipients:C})},h=async()=>{o!==e.name&&await x({name:o})},S=async()=>{let N=b||null;N!==e.redirect_url&&await x({redirect_url:N})};return Sn("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(n||i)&&tt("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?Sn("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:[tt(Kf,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),tt("span",{className:"af-text-sm",children:"Saving..."})]}):Sn("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:[tt(Zf,{className:"af-h-4 af-w-4 af-text-green-600"}),tt("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{htmlFor:"form-name",children:"Form Name"}),tt(te,{id:"form-name",value:o,onChange:N=>c(N.target.value),onBlur:h,placeholder:"Contact Form"}),tt("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{children:"Email Recipients"}),tt("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),Sn("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[m.map(N=>Sn(ee,{variant:"secondary",className:"af-gap-1",children:[N,tt("button",{type:"button",onClick:()=>P(N),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:tt(Gf,{className:"af-h-3 af-w-3"})})]},N)),m.length===0&&tt("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Sn("div",{className:"af-flex af-gap-2",children:[tt(te,{type:"email",value:u,onChange:N=>v(N.target.value),placeholder:"Add email address",onKeyDown:N=>{N.key==="Enter"&&(N.preventDefault(),R())},disabled:n}),tt(y,{type:"button",variant:"outline",onClick:R,disabled:!u.trim()||n,children:tt(Wf,{className:"af-h-4 af-w-4"})})]})]}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{htmlFor:"redirect-url",children:"Redirect URL"}),tt(te,{id:"redirect-url",value:b,onChange:N=>g(N.target.value),onBlur:S,placeholder:"/thank-you"}),tt("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."})]}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{children:"Form Endpoint"}),tt("div",{className:"af-flex af-items-center af-gap-2",children:tt("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})}),tt("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{children:"Captcha Protection"}),tt("div",{className:"af-flex af-items-center af-gap-2",children:tt(ee,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),tt("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),tt(li,{formId:e.id}),f&&tt("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f})]})}import{jsx as Aa,jsxs as Dn}from"react/jsx-runtime";function cc({className:e,location:t,onNavigate:a,submissionId:s}){let{api:n}=H(),[r,i]=Yn.useState({submissionId:s});Yn.useEffect(()=>{s&&i({submissionId:s})},[s]);let l=a?t??{}:r,f=a??i,[d,o]=Yn.useState(null),c=`${l.formId??""}|${l.submissionId??""}`,[b,g]=Yn.useState(null),m=b?.key===c?b.message:null,p=l.formId??(d&&d.submissionId===l.submissionId?d.formId:void 0);Yn.useEffect(()=>{let N=l.submissionId;if(!N||l.formId)return;let C=!1;return n.getSubmission(N).then(w=>{C||(g(null),o({submissionId:N,formId:w.form_id}))}).catch(()=>{C||g({key:c,message:"This submission could not be found."})}),()=>{C=!0}},[n,l.submissionId,l.formId,c]);let[u,v]=Yn.useState(null);Yn.useEffect(()=>{if(!p||u?.id===p)return;let N=!1;return n.getForm(p).then(C=>{N||(g(null),v(C))}).catch(()=>{N||g({key:c,message:"This form could not be found."})}),()=>{N=!0}},[n,p,u?.id,c]);let x=(N,C)=>{v(N),f({formId:N.id,tab:C})},R=()=>f({});if(!l.formId&&!l.submissionId)return Dn("div",{className:e,children:[Dn("div",{className:"af-mb-6",children:[Aa("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),Aa("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),Aa(Yr,{onSelectForm:x})]});let h=Dn(y,{variant:"ghost",size:"sm",onClick:R,className:"af-mb-2 af--ml-2",children:[Aa(Yf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(m)return Dn("div",{className:e,children:[h,Aa("p",{className:"af-text-sm af-text-destructive",children:m})]});if(!p||u?.id!==p)return Aa("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:Aa("div",{className:"af-text-muted-foreground",children:"Loading..."})});let S=l.submissionId?"submissions":l.tab??"submissions";return Dn("div",{className:e,children:[Dn("div",{className:"af-mb-6",children:[h,Aa("h2",{className:"af-text-lg af-font-semibold",children:u.name})]}),Dn(Zr,{value:S,onValueChange:N=>f({formId:p,tab:N}),children:[Dn(br,{className:"af-mb-4",children:[Dn(yn,{value:"submissions",className:"af-gap-2",children:[Aa(Xf,{className:"af-h-4 af-w-4"}),"Submissions"]}),Dn(yn,{value:"settings",className:"af-gap-2",children:[Aa(Jf,{className:"af-h-4 af-w-4"}),"Settings"]})]}),Aa(xn,{value:"submissions",children:Aa(ri,{formId:p,submissionId:l.submissionId,onSelectSubmission:N=>f({formId:p,tab:"submissions",submissionId:N??void 0})})}),Aa(xn,{value:"settings",children:Aa(ci,{form:u,onSaved:v})})]})]})}import*as at from"react";import*as An from"react";function rs(){let{api:e}=H(),[t,a]=An.useState(null),[s,n]=An.useState(!0),[r,i]=An.useState(null),l=An.useRef(0),f=An.useCallback(async()=>{let d=++l.current;try{n(!0),i(null);let o=await e.getPaymentsStatus();if(d!==l.current)return;a(o)}catch(o){if(d!==l.current)return;i(o instanceof Error?o:new Error("Failed to fetch payments status"))}finally{d===l.current&&n(!1)}},[e]);return An.useEffect(()=>{f()},[f]),{status:t,isLoading:s,error:r,refetch:f}}var Qf=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function cn(e){return Qf.has(e.toLowerCase())}function Y(e,t,a){let s=cn(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Jn(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 ua(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=cn(t)?a:a*100;return Math.round(s)}function Et(e,t){return cn(t)?e:e/100}function di(e){return e.amount_paid??Math.max(0,Jn(e)-(e.credit_applied??0))}import{Fragment as am,jsx as Qe,jsxs as ft}from"react/jsx-runtime";function Sr(e){return e instanceof Yt&&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 dc(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${Y(e.amount_off,e.currency)} off`:"Discount unavailable"}function Vs(){let{api:e,siteToken:t}=H();return Qe(em,{api:e},t)}function em({api:e}){let{status:t,error:a}=rs(),[s,n]=at.useState([]),[r,i]=at.useState(null),[l,f]=at.useState(null),[d,o]=at.useState(!1),[c,b]=at.useState(!1),[g,m]=at.useState(""),[p,u]=at.useState(null),[v,x]=at.useState(null),[R,P]=at.useState(!1),h=at.useRef(0),S=at.useCallback(async w=>{let k=++h.current;o(!0),m("");try{let T=await e.getPromos(w);if(k!==h.current)return;n(_=>w?[..._,...T.promos.filter(z=>!_.some(Z=>Z.id===z.id))]:T.promos),i(T.next_cursor),f(T.checkout_enabled)}catch(T){k===h.current&&m(Sr(T))}finally{k===h.current&&o(!1)}},[e]);at.useEffect(()=>(S(),()=>{h.current++}),[S]);async function N(w){let k=++h.current;o(!0),m(""),P(!1);try{let T=await e.getPromo(w);k===h.current&&u(T)}catch(T){k===h.current&&m(Sr(T))}finally{k===h.current&&o(!1)}}async function C(){if(p){b(!0),o(!0),m("");try{let w=await e.disablePromo(p.id);if(u(w),!["inactive","expired","exhausted"].includes(w.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");P(!1),await S()}catch(w){m(Sr(w))}finally{b(!1),o(!1)}}}return v?Qe(tm,{currency:t?.currency??void 0,replaces:v.replaces,onCancel:()=>x(null),onSave:async w=>{let k=v.replaces?await e.replacePromo(v.replaces.id,w):await e.createPromo(w),T=await e.getPromo(k.id);if(T.status==="pending"||T.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");u(T),x(null),await S()}}):ft("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[ft("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[Qe("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),Qe(y,{disabled:d||!t?.currency,onClick:()=>{m(""),x({})},children:"Create promo code"})]}),Qe("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&&Qe("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&&Qe("p",{className:"af-text-sm",children:a?Sr(a):"Connect Stripe and set the payment currency before creating codes."}),g&&ft("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",Qe(y,{variant:"outline",disabled:d,onClick:()=>p?void N(p.id):void S(),children:"Refresh"})]}),p?ft("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[Qe(y,{variant:"ghost",disabled:c,onClick:()=>{u(null),P(!1),S()},children:"Back to codes"}),ft("h4",{className:"af-font-semibold af-break-all",children:[p.code," \xB7 ",p.name]}),ft("p",{children:[dc(p)," \xB7 ",p.status]}),ft("p",{className:"af-text-sm",children:[p.times_redeemed==null?"Usage unavailable":`${p.times_redeemed} redemptions`,p.max_redemptions!=null?` / ${p.max_redemptions} maximum`:""]}),ft("p",{className:"af-text-sm",children:[p.minimum_amount!=null&&p.currency?`Minimum order: ${Y(p.minimum_amount,p.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),ft("p",{className:"af-text-sm",children:["Subscription discount:"," ",p.duration==="repeating"?`${p.duration_in_months} months`:p.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),Qe("p",{className:"af-text-sm",children:p.expires_at?`Expires ${new Date(p.expires_at).toLocaleString()}`:"No expiry"}),ft("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Qe(y,{variant:"outline",disabled:d,onClick:()=>void N(p.id),children:"Refresh details"}),Qe(y,{variant:"outline",disabled:d||p.status==="pending"||p.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:p}),children:"Replace with new code"}),Qe(y,{variant:"outline",disabled:d||!["active","pending","unavailable"].includes(p.status),onClick:()=>P(!0),children:p.status==="pending"?"Cancel pending offer":"Disable code"})]}),R&&ft("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[ft("p",{className:"af-text-sm",children:[p.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${p.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),Qe(y,{disabled:d,onClick:()=>void C(),children:p.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",Qe(y,{variant:"ghost",disabled:d,onClick:()=>P(!1),children:"Cancel"})]})]}):ft(am,{children:[s.map(w=>ft("button",{type:"button",disabled:d,onClick:()=>void N(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:[ft("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[Qe("span",{className:"af-font-semibold af-break-all",children:w.code}),Qe("span",{className:"af-text-sm",children:w.status})]}),ft("div",{className:"af-text-sm",children:[dc(w)," \xB7"," ",w.times_redeemed==null?"Usage unavailable":`${w.times_redeemed} redemptions`]})]},w.id)),!d&&!g&&s.length===0&&Qe("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),d&&Qe("p",{role:"status",children:"Loading promo codes\u2026"}),r&&Qe(y,{variant:"outline",disabled:d,onClick:()=>void S(r),children:"Load more"})]})]})}function tm({currency:e,replaces:t,onCancel:a,onSave:s}){let[n,r]=at.useState(""),[i,l]=at.useState(t?.name??""),[f,d]=at.useState(t?.amount_off!=null?"fixed":"percent"),[o,c]=at.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(Et(t.amount_off,e)):"")),[b,g]=at.useState(t?.minimum_amount!=null&&e?String(Et(t.minimum_amount,e)):""),[m,p]=at.useState(()=>{if(!t?.expires_at)return"";let le=new Date(t.expires_at);return Number.isFinite(le.getTime())?new Date(le.getTime()-le.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[u,v]=at.useState(t?.max_redemptions?.toString()??""),[x,R]=at.useState(t?.duration??"once"),[P,h]=at.useState(t?.duration_in_months?.toString()??"3"),[S,N]=at.useState(null),[C,w]=at.useState(!1),[k,T]=at.useState(""),_=at.useRef(!1),z=e&&cn(e)?"1":"0.01";async function Z(le){if(le.preventDefault(),_.current)return;T("");let fe=S;if(!fe){if(!e){T("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){T("Choose a different code for the replacement.");return}let M=ua(o,e),W=b?ua(b,e):null;if(f==="fixed"&&(!M||M>999999999999)||b&&(!W||W>999999999999)){T("Enter a positive amount within the supported range.");return}if(m&&new Date(m).getTime()<=Date.now()){T("Choose a future expiry.");return}fe={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:i.trim(),duration:x,...f==="percent"?{percent_off:Number(o)}:{amount_off:M,currency:e},...b?{minimum_amount:W,currency:e}:{},...m?{expires_at:new Date(m).toISOString()}:{},...u?{max_redemptions:Number(u)}:{},...x==="repeating"?{duration_in_months:Number(P)}:{}},N(fe)}_.current=!0,w(!0);try{await s(fe)}catch(M){T(Sr(M)),M instanceof Yt&&M.status>=400&&M.status<500&&M.details?.retryable!==!0&&N(null)}finally{_.current=!1,w(!1)}}let U=(le,fe,M,W={})=>ft("label",{className:"af-grid af-gap-1 af-text-sm",children:[le,Qe(te,{"aria-label":le,value:fe,onChange:A=>M(A.target.value),...W})]}),ae="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return ft("form",{onSubmit:Z,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[Qe("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&Qe("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."}),ft("fieldset",{disabled:C||!!S,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}),ft("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",ft("select",{"aria-label":"Discount type",className:ae,value:f,onChange:le=>d(le.target.value),children:[Qe("option",{value:"percent",children:"Percentage"}),ft("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),U("Discount",o,c,{type:"number",required:!0,min:f==="percent"?"0.01":z,max:f==="percent"?"100":void 0,step:f==="percent"?"0.01":z}),U("Minimum order amount",b,g,{type:"number",min:z,step:z,placeholder:e?.toUpperCase()}),ft("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,p,{type:"datetime-local",step:1}),U("Maximum redemptions",u,v,{type:"number",min:1,max:1e6,step:1}),ft("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",ft("select",{"aria-label":"Subscription duration",className:ae,value:x,onChange:le=>R(le.target.value),children:[Qe("option",{value:"once",children:"First invoice only"}),Qe("option",{value:"forever",children:"Every invoice"}),Qe("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&U("Months",P,h,{type:"number",required:!0,min:1,max:36,step:1})]}),k&&Qe("p",{role:"alert",className:"af-text-sm af-text-destructive",children:k}),S&&!C&&ft("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",Qe("span",{className:"af-break-all",children:S.request_id})]}),ft("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Qe(y,{type:"submit",disabled:C,children:C?"Saving\u2026":S?"Retry same request":t?"Create replacement":"Create code"}),Qe(y,{type:"button",variant:"ghost",disabled:C||!!S,onClick:a,children:"Cancel"})]})]})}import*as Js from"react";import{ArrowLeft as Pp,FileText as kp,Package as Cp,Receipt as Tp,Settings as Ep,Users as Ip}from"lucide-react";import*as ui from"react";import{Package as nm,Pencil as sm,Plus as uc,Trash2 as rm}from"lucide-react";import{jsx as ut,jsxs as ba}from"react/jsx-runtime";function im(e){if(e.allow_custom_amount){let t=e.min_amount!==null?Y(e.min_amount,e.currency):"?",a=e.max_amount!==null?Y(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":Y(e.unit_amount,e.currency)}function om(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function fi({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:n,isLoading:r,error:i,deleteProduct:l}=e,[f,d]=ui.useState(null),[o,c]=ui.useState(!1),[b,g]=ui.useState(null),m=async()=>{if(f)try{c(!0),g(null),await l(f.id),d(null)}catch(p){g(p instanceof Error?p.message:"Failed to delete product")}finally{c(!1)}};return r?ut("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ut("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):i?ut("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ba("div",{className:"af-text-destructive",children:["Error: ",i.message]})}):n.length===0?ba("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[ut(nm,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),ba("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",ut("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),ba(y,{variant:"outline",onClick:()=>a?.(),children:[ut(uc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):ba("div",{className:s,children:[ut("div",{className:"af-flex af-justify-end af-mb-4",children:ba(y,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[ut(uc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),ba(lt,{children:[ut(ct,{children:ba(Ce,{children:[ut(q,{children:"Name"}),ut(q,{children:"Price"}),ut(q,{children:"Fulfillment"}),ut(q,{children:"Status"}),ut(q,{className:"af-text-right",children:"Actions"})]})}),ut(dt,{children:n.map(p=>ba(Ce,{children:[ut(j,{className:"af-font-medium",children:p.name}),ut(j,{children:im(p)}),ut(j,{className:"af-text-muted-foreground",children:om(p)}),ut(j,{children:ut(ee,{variant:p.active?"success":"secondary",children:p.active?"Active":"Inactive"})}),ut(j,{className:"af-text-right",children:ba("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[ba(y,{variant:"ghost",size:"sm",onClick:()=>t?.(p),children:[ut(sm,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),ba(y,{variant:"ghost",size:"sm",onClick:()=>{g(null),d(p)},children:[ut(rm,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},p.id))})]}),ut(rn,{open:!!f,onOpenChange:p=>{!p&&!o&&d(null)},children:ba(Ga,{children:[ba(Ka,{children:[ut(Ya,{children:"Delete product?"}),ba(Ja,{children:['"',f?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&ut("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),ba(Za,{children:[ut(y,{variant:"outline",onClick:()=>d(null),disabled:o,children:"Cancel"}),ut(y,{variant:"destructive",onClick:m,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})}import*as St from"react";import{FileText as cm,Link2 as dm,Loader2 as pc,Plus as um,Upload as fm,X as mm}from"lucide-react";import*as jt from"react";import{Loader2 as fc,Plus as ko,Trash2 as mc,X as lm}from"lucide-react";import{jsx as ne,jsxs as _e}from"react/jsx-runtime";function Co(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function mi({productId:e,currency:t,className:a}){let{api:s}=H(),n=cn(t)?"1":"0.01",[r,i]=jt.useState(null),[l,f]=jt.useState(!0),[d,o]=jt.useState(null),[c,b]=jt.useState(null),[g,m]=jt.useState(!1),p=jt.useRef(!0);jt.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);let u=jt.useCallback(async()=>{try{let E=await s.getProduct(e);if(!p.current)return;i(E)}catch(E){if(!p.current)return;o(E instanceof Error?E.message:"Failed to load product")}finally{p.current&&f(!1)}},[s,e]);jt.useEffect(()=>{u()},[u]);let v=async E=>{b(null),m(!0);try{await E(),await u()}catch(O){p.current&&b(O instanceof Error?O.message:"Something went wrong")}finally{p.current&&m(!1)}},[x,R]=jt.useState(""),[P,h]=jt.useState(""),[S,N]=jt.useState({}),C=()=>v(async()=>{let E=x.trim(),O=P.split(",").map(B=>B.trim()).filter(Boolean);if(!E)throw new Error("Option name is required");if(O.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:E,values:O}),p.current&&(R(""),h(""))}),w=E=>v(async()=>{let O=(S[E.id]??"").trim();if(!O)throw new Error("Enter a value");await s.updateOption(E.id,{add_values:[O]}),p.current&&N(B=>({...B,[E.id]:""}))}),k=(E,O)=>v(()=>s.updateOption(E.id,{remove_values:[O]})),T=E=>v(()=>s.deleteOption(E.id)),[_,z]=jt.useState(null),[Z,U]=jt.useState(null),[ae,le]=jt.useState(!1),[fe,M]=jt.useState(null),W=r?.options??[],A=r?.variants??[],de=()=>{U(null),z({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(W.map(E=>[E.id,E.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},ce=E=>{U(null);let O=E.inventory?.on_hand??0,B=O<0?"":String(O);z({variant:E,title:E.title??"",sku:E.sku??"",unitAmount:E.unit_amount!=null?String(Et(E.unit_amount,t)):"",compareAt:E.compare_at_amount!=null?String(Et(E.compare_at_amount,t)):"",active:E.active,optionValues:{},tracked:E.inventory?.tracked??!1,onHand:B,initialOnHand:B,allowBackorder:E.inventory?.allow_backorder??!1})},Le=async()=>{if(!_)return;U(null);let E=_.variant?.allow_custom_amount??!1,O=null,B=null;if(!E){if(O=ua(_.unitAmount,t),O===null||O<=0){U("Enter a valid price");return}if(_.compareAt.trim()&&(B=ua(_.compareAt,t),B===null||B<=O)){U("Compare-at price must be greater than the price");return}}let we=_.onHand.trim()!==_.initialOnHand.trim(),X=parseInt(_.onHand,10);if(_.tracked&&we&&(!Number.isFinite(X)||X<0)){U("On-hand quantity must be zero or more");return}try{if(le(!0),_.variant)await s.updateVariant(_.variant.id,{title:_.title.trim()||null,sku:_.sku.trim()||null,...E?{}:{unit_amount:O,compare_at_amount:B},active:_.active}),await s.setVariantInventory(_.variant.id,{tracked:_.tracked,on_hand:_.tracked&&we?X:void 0,allow_backorder:_.allowBackorder});else{let ve={};for(let Me of W){let ht=_.optionValues[Me.id];if(!ht){U(`Choose a ${Me.title}`),le(!1);return}ve[Me.title]=ht}await s.createVariant(e,{title:_.title.trim()||null,sku:_.sku.trim()||null,unit_amount:O,compare_at_amount:B,active:_.active,option_values:W.length>0?ve:void 0,inventory:_.tracked?{tracked:!0,on_hand:X,allow_backorder:_.allowBackorder}:{tracked:!1,allow_backorder:_.allowBackorder}})}await u(),p.current&&z(null)}catch(ve){if(p.current&&U(ve instanceof Error?ve.message:"Failed to save variant"),_.variant)try{let Me=await s.getProduct(e);p.current&&i(Me)}catch{}}finally{p.current&&le(!1)}},ye=()=>v(async()=>{fe&&(await s.deleteVariant(fe.id),p.current&&M(null))}),Te=_?.variant?.allow_custom_amount??!1,Oe=_?.variant!=null&&_.variant.option_values.length===0&&W.length>0&&!_.variant.active,oe=_?.variant?.inventory!=null&&_.variant.inventory.on_hand<0?-_.variant.inventory.on_hand:null;function st(E){let O=E.inventory;if(!O||!O.tracked)return ne("span",{className:"af-text-muted-foreground",children:"Unlimited"});let B=O.available??O.on_hand;return B<0?_e("span",{children:[-B," backordered"]}):_e("span",{children:[B," in stock",O.allow_backorder&&ne("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return l?ne("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:ne(fc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):d?ne("div",{className:a,children:ne("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})}):_e("div",{className:`af-space-y-6 ${a||""}`,children:[_e("div",{className:"af-space-y-3",children:[_e("div",{children:[ne(Ie,{children:"Options"}),ne("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."})]}),W.length>0&&ne("div",{className:"af-space-y-3",children:W.map(E=>_e("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[_e("div",{className:"af-flex af-items-center af-justify-between",children:[ne("span",{className:"af-text-sm af-font-medium",children:E.title}),ne(y,{variant:"ghost",size:"sm",onClick:()=>T(E),disabled:g,children:ne(mc,{className:"af-h-4 af-w-4"})})]}),ne("div",{className:"af-flex af-flex-wrap af-gap-2",children:E.values.map(O=>_e(ee,{variant:"secondary",className:"af-gap-1",children:[O.value,ne("button",{type:"button",onClick:()=>k(E,O.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:ne(lm,{className:"af-h-3 af-w-3"})})]},O.id))}),_e("div",{className:"af-flex af-gap-2",children:[ne(te,{value:S[E.id]??"",onChange:O=>N(B=>({...B,[E.id]:O.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),w(E))},disabled:g}),ne(y,{type:"button",variant:"outline",size:"sm",onClick:()=>w(E),disabled:g||!(S[E.id]??"").trim(),children:ne(ko,{className:"af-h-4 af-w-4"})})]})]},E.id))}),_e("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[_e("div",{className:"af-space-y-1",children:[ne(Ie,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),ne(te,{id:"new-option-title",value:x,onChange:E=>R(E.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),_e("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[ne(Ie,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),ne(te,{id:"new-option-values",value:P,onChange:E=>h(E.target.value),placeholder:"S, M, L",disabled:g})]}),_e(y,{type:"button",variant:"outline",onClick:C,disabled:g||!x.trim()||!P.trim(),children:[ne(ko,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),_e("div",{className:"af-space-y-3",children:[_e("div",{className:"af-flex af-items-center af-justify-between",children:[ne(Ie,{children:"Variants"}),_e(y,{type:"button",variant:"outline",size:"sm",onClick:de,disabled:g||W.length===0,children:[ne(ko,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),W.length===0&&ne("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),A.length===0?ne("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):_e(lt,{children:[ne(ct,{children:_e(Ce,{children:[ne(q,{children:"Variant"}),ne(q,{children:"SKU"}),ne(q,{children:"Price"}),ne(q,{children:"Stock"}),ne(q,{children:"Status"}),ne(q,{className:"af-text-right",children:"Actions"})]})}),ne(dt,{children:A.map(E=>_e(Ce,{children:[ne(j,{className:"af-font-medium",children:Co(E)}),ne(j,{className:"af-text-muted-foreground",children:E.sku||"-"}),ne(j,{children:E.unit_amount!=null?_e("span",{children:[E.compare_at_amount!=null&&ne("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:Y(E.compare_at_amount,E.currency)}),Y(E.unit_amount,E.currency)]}):E.allow_custom_amount?ne("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),ne(j,{children:st(E)}),ne(j,{children:ne(ee,{variant:E.active?"success":"secondary",children:E.active?"Active":"Inactive"})}),ne(j,{className:"af-text-right",children:_e("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[ne(y,{variant:"ghost",size:"sm",onClick:()=>ce(E),disabled:g,children:"Edit"}),ne(y,{variant:"ghost",size:"icon",onClick:()=>M(E),disabled:g,title:"Delete variant",children:ne(mc,{className:"af-h-4 af-w-4"})})]})})]},E.id))})]})]}),c&&ne("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c}),ne(rn,{open:_!==null,onOpenChange:E=>{!E&&!ae&&z(null)},children:_e(Ga,{children:[_e(Ka,{children:[ne(Ya,{children:_?.variant?"Edit variant":"Add variant"}),ne(Ja,{children:"Price, markdown, and stock live on the variant."})]}),_&&_e("div",{className:"af-space-y-3",children:[_.variant?_.variant.option_values.length>0&&_e("div",{className:"af-text-sm",children:[ne("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Co(_.variant)]}):W.map(E=>_e("div",{className:"af-space-y-1",children:[ne(Ie,{className:"af-text-xs af-text-muted-foreground",children:E.title}),_e(nn,{value:_.optionValues[E.id]??"",onValueChange:O=>z(B=>B&&{...B,optionValues:{...B.optionValues,[E.id]:O}}),children:[ne(ja,{children:ne(sn,{placeholder:`Choose ${E.title}`})}),ne(Wa,{children:E.values.map(O=>ne(xt,{value:O.value,children:O.value},O.id))})]})]},E.id)),Te?_e("div",{className:"af-space-y-1",children:[ne(Ie,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),ne("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):_e("div",{className:"af-flex af-gap-3",children:[_e("div",{className:"af-space-y-1",children:[_e(Ie,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),ne(te,{id:"variant-price",type:"number",min:"0",step:n,value:_.unitAmount,onChange:E=>z(O=>O&&{...O,unitAmount:E.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),_e("div",{className:"af-space-y-1",children:[ne(Ie,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),ne(te,{id:"variant-compare",type:"number",min:"0",step:n,value:_.compareAt,onChange:E=>z(O=>O&&{...O,compareAt:E.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),_e("div",{className:"af-space-y-1",children:[ne(Ie,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),ne(te,{id:"variant-sku",value:_.sku,onChange:E=>z(O=>O&&{...O,sku:E.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),_e("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[_e("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ne("input",{type:"checkbox",checked:_.tracked,onChange:E=>z(O=>O&&{...O,tracked:E.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),_.tracked&&_e("div",{className:"af-space-y-1 af-pl-6",children:[_e("div",{className:"af-flex af-items-end af-gap-3",children:[_e("div",{className:"af-space-y-1",children:[ne(Ie,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),ne(te,{id:"variant-onhand",type:"number",min:"0",step:"1",value:_.onHand,onChange:E=>z(O=>O&&{...O,onHand:E.target.value}),placeholder:oe!=null?"0":void 0,className:"af-w-[100px]"})]}),_e("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[ne("input",{type:"checkbox",checked:_.allowBackorder,onChange:E=>z(O=>O&&{...O,allowBackorder:E.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),oe!=null&&_e("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",oe," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),_e("div",{className:"af-space-y-1",children:[_e("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ne("input",{type:"checkbox",checked:_.active,onChange:E=>z(O=>O&&{...O,active:E.target.checked}),className:"af-h-4 af-w-4",disabled:Oe}),"Active (buyers can purchase this variant)"]}),Oe&&ne("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."})]}),Z&&ne("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Z})]}),_e(Za,{children:[ne(y,{variant:"outline",onClick:()=>z(null),disabled:ae,children:"Cancel"}),_e(y,{onClick:Le,disabled:ae,children:[ae?ne(fc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,_?.variant?"Save":"Add variant"]})]})]})}),ne(rn,{open:fe!==null,onOpenChange:E=>{!E&&!g&&M(null)},children:_e(Ga,{children:[_e(Ka,{children:[ne(Ya,{children:"Delete variant?"}),ne(Ja,{children:fe&&`"${Co(fe)}" will no longer be purchasable. Past orders are unaffected.`})]}),_e(Za,{children:[ne(y,{variant:"outline",onClick:()=>M(null),disabled:g,children:"Cancel"}),ne(y,{variant:"destructive",onClick:ye,disabled:g,children:"Delete"})]})]})})]})}import{Fragment as gm,jsx as Pe,jsxs as qe}from"react/jsx-runtime";function pm(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 pi({productsState:e,product:t,currency:a,onSaved:s,className:n}){let{createProduct:r,updateProduct:i,attachProductFile:l,attachProductFileFromUrl:f}=e,d=!!t,o=t?.currency??a,c=cn(o)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,m]=St.useState(!1),[p,u]=St.useState(null),v=St.useRef(!0);St.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);let[x,R]=St.useState(t?.name??""),[P,h]=St.useState(t?.description??""),[S,N]=St.useState(t?.allow_custom_amount?"custom":"fixed"),[C,w]=St.useState(t?.unit_amount!=null?String(Et(t.unit_amount,o)):""),[k,T]=St.useState(t?.min_amount!=null?String(Et(t.min_amount,o)):""),[_,z]=St.useState(t?.max_amount!=null?String(Et(t.max_amount,o)):""),[Z,U]=St.useState(String(t?.max_quantity??10)),ae=St.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(Et(t.unit_amount,o)):"",minAmount:t?.min_amount!=null?String(Et(t.min_amount,o)):"",maxAmount:t?.max_amount!=null?String(Et(t.max_amount,o)):"",maxQuantity:String(t?.max_quantity??10)}).current,[le,fe]=St.useState(t?.collect_shipping_address??!1),[M,W]=St.useState(t?.active??!0),[A,de]=St.useState(t?.images??[]),[ce,Le]=St.useState(""),[ye,Te]=St.useState(t?.fulfillment??null),[Oe,oe]=St.useState(!1),[st,E]=St.useState(""),[O,B]=St.useState(null),we=St.useRef(null),X=g||Oe,ve=()=>{let pe=ce.trim();if(pe){if(A.includes(pe)){u("This image URL is already added");return}de(ke=>[...ke,pe]),Le(""),u(null)}},Me=pe=>{de(ke=>ke.filter(rt=>rt!==pe))},ht=async()=>{if(u(null),!x.trim()){u("Product name is required");return}let pe=null,ke=null,rt=null,Je=!d||S!==ae.pricingMode||(S==="fixed"?C!==ae.unitAmount:k!==ae.minAmount||_!==ae.maxAmount),zt=!d||Z!==ae.maxQuantity,Ot=b||S==="fixed";if(!(b||!Je))if(S==="fixed"){if(pe=ua(C,o),pe===null||pe<=0){u("Enter a valid price");return}}else{if(ke=ua(k,o),rt=ua(_,o),ke===null||rt===null){u("Enter valid minimum and maximum amounts");return}if(rt<ke){u("Maximum amount must be at least the minimum amount");return}}let sa=parseInt(Z,10);if(Ot&&zt&&(!Number.isFinite(sa)||sa<1)){u("Max quantity must be at least 1");return}try{m(!0);let it;if(d&&t){let vt={name:x.trim(),description:P.trim()||null,images:A,collect_shipping_address:le,active:M};!b&&Je&&(vt.allow_custom_amount=S==="custom",S==="fixed"?vt.unit_amount=pe:(vt.min_amount=ke,vt.max_amount=rt)),Ot&&zt&&(vt.max_quantity=sa),it=await i(t.id,vt),ae.pricingMode=it.allow_custom_amount?"custom":"fixed",ae.unitAmount=it.unit_amount!=null?String(Et(it.unit_amount,o)):"",ae.minAmount=it.min_amount!=null?String(Et(it.min_amount,o)):"",ae.maxAmount=it.max_amount!=null?String(Et(it.max_amount,o)):"",ae.maxQuantity=String(it.max_quantity)}else{let vt={name:x.trim(),allow_custom_amount:S==="custom",collect_shipping_address:le,active:M};P.trim()&&(vt.description=P.trim()),A.length>0&&(vt.images=A),S==="fixed"?(vt.unit_amount=pe,vt.max_quantity=sa):(vt.min_amount=ke,vt.max_amount=rt),it=await r(vt)}if(!v.current)return;Te(it.fulfillment),s?.(it)}catch(it){if(!v.current)return;u(it instanceof Error?it.message:"Failed to save product")}finally{v.current&&m(!1)}},Ke=async pe=>{let ke=pe.target.files?.[0];if(!(!ke||!t))try{oe(!0),B(null);let rt=await l(t.id,ke);if(!v.current)return;Te(rt.fulfillment),s?.(rt)}catch(rt){if(!v.current)return;B(rt instanceof Error?rt.message:"Failed to upload file")}finally{v.current&&(oe(!1),we.current&&(we.current.value=""))}},Ct=async()=>{let pe=st.trim();if(!(!pe||!t))try{oe(!0),B(null);let ke=await f(t.id,pe);if(!v.current)return;Te(ke.fulfillment),E(""),s?.(ke)}catch(ke){if(!v.current)return;B(ke instanceof Error?ke.message:"Failed to fetch file")}finally{v.current&&oe(!1)}};return qe("div",{className:`af-space-y-6 ${n||""}`,children:[qe("div",{className:"af-space-y-2",children:[Pe(Ie,{htmlFor:"product-name",children:"Name"}),Pe(te,{id:"product-name",value:x,onChange:pe=>R(pe.target.value),placeholder:"My product"})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{htmlFor:"product-description",children:"Description"}),Pe("textarea",{id:"product-description",value:P,onChange:pe=>h(pe.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"})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{children:"Pricing"}),b?Pe("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):qe(gm,{children:[qe(nn,{value:S,onValueChange:pe=>N(pe),children:[Pe(ja,{className:"af-w-[260px]",children:Pe(sn,{})}),qe(Wa,{children:[Pe(xt,{value:"fixed",children:"Fixed price"}),Pe(xt,{value:"custom",children:"Buyer chooses the amount"})]})]}),S==="fixed"?Pe("div",{className:"af-flex af-items-end af-gap-3",children:qe("div",{className:"af-space-y-1",children:[qe(Ie,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",o.toUpperCase(),")"]}),Pe(te,{id:"product-price",type:"number",min:"0",step:c,value:C,onChange:pe=>w(pe.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):qe("div",{className:"af-space-y-1",children:[qe("div",{className:"af-flex af-items-end af-gap-3",children:[qe("div",{className:"af-space-y-1",children:[qe(Ie,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",o.toUpperCase(),")"]}),Pe(te,{id:"product-min-amount",type:"number",min:"0",step:c,value:k,onChange:pe=>T(pe.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),qe("div",{className:"af-space-y-1",children:[qe(Ie,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",o.toUpperCase(),")"]}),Pe(te,{id:"product-max-amount",type:"number",min:"0",step:c,value:_,onChange:pe=>z(pe.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),Pe("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."})]}),qe("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||S==="fixed")&&qe("div",{className:"af-space-y-1",children:[Pe(Ie,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),Pe(te,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:Z,onChange:pe=>U(pe.target.value),className:"af-w-[140px]"})]})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{children:"Images"}),Pe("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),qe("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[A.map(pe=>qe(ee,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[Pe("span",{className:"af-truncate",children:pe}),Pe("button",{type:"button",onClick:()=>Me(pe),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:Pe(mm,{className:"af-h-3 af-w-3"})})]},pe)),A.length===0&&Pe("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),qe("div",{className:"af-flex af-gap-2",children:[Pe(te,{type:"url",value:ce,onChange:pe=>Le(pe.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:pe=>{pe.key==="Enter"&&(pe.preventDefault(),ve())},disabled:g}),Pe(y,{type:"button",variant:"outline",onClick:ve,disabled:!ce.trim()||g,children:Pe(um,{className:"af-h-4 af-w-4"})})]})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{children:"Digital File"}),Pe("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, Word, Excel, PowerPoint, CSV, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),d?qe("div",{className:"af-space-y-3",children:[ye?.type==="download"&&qe("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Pe(cm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Pe("span",{className:"af-text-sm",children:ye.filename}),ye.size!=null&&qe("span",{className:"af-text-xs af-text-muted-foreground",children:["(",pm(ye.size),")"]})]}),ye?.type==="redirect"&&ye.url&&qe("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Pe(dm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),qe("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",ye.url]})]}),qe("div",{className:"af-flex af-items-center af-gap-2",children:[Pe("input",{ref:we,type:"file",onChange:Ke,className:"af-hidden",disabled:X}),qe(y,{type:"button",variant:"outline",size:"sm",onClick:()=>we.current?.click(),disabled:X,children:[Oe?Pe(pc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Pe(fm,{className:"af-h-4 af-w-4 af-mr-1"}),ye?.type==="download"?"Replace file":"Upload file"]}),Pe("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),Pe(te,{type:"url",value:st,onChange:pe=>E(pe.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Oe}),Pe(y,{type:"button",variant:"outline",size:"sm",onClick:Ct,disabled:!st.trim()||X,children:"Fetch from URL"})]}),O&&Pe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:O})]}):Pe("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{children:"Settings"}),qe("div",{className:"af-space-y-2",children:[qe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Pe("input",{type:"checkbox",checked:le,onChange:pe=>fe(pe.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),qe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Pe("input",{type:"checkbox",checked:M,onChange:pe=>W(pe.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),d&&t&&qe("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[Pe(Ie,{children:"Options & Variants"}),Pe(mi,{productId:t.id,currency:o})]}),p&&Pe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:p}),Pe("div",{className:"af-flex af-items-center af-gap-2",children:qe(y,{type:"button",onClick:ht,disabled:X,children:[g?Pe(pc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?"Save changes":"Create product"]})})]})}import*as Xt from"react";import{ChevronLeft as Um,ChevronRight as _c,Loader2 as $m,Receipt as Vm,Search as Hm,SlidersHorizontal as zm}from"lucide-react";import*as It from"react";var vm=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function gi({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=It.useState([]),[r,i]=It.useState(0),[l,f]=It.useState(!0),[d,o]=It.useState(null),[c,b]=It.useState(0),[g,m]=It.useState(e),[p,u]=It.useState(void 0),[v,x]=It.useState(""),[R,P]=It.useState(""),[h,S]=It.useState(""),[N,C]=It.useState(!1),[w,k]=It.useState(!1),[T,_]=It.useState(void 0),z=T?T.join(","):"",Z=It.useMemo(()=>{if(!z)return;let M=new Set(z.split(","));return vm.filter(W=>!M.has(W))},[z]),U=It.useMemo(()=>{let M={};return p?M.status=p:Z?M.excludeStatus=Z:N||(M.excludeStatus=["pending","expired"]),v.trim()&&(M.customerEmail=v.trim()),R.trim()&&(M.from=R.trim()),h.trim()&&(M.to=h.trim()),w&&(M.unfulfilledOnly=!0),M},[p,Z,N,v,R,h,w]),ae=It.useRef(0),le=It.useCallback(async()=>{let M=++ae.current;try{f(!0),o(null);let W={...U,limit:g,offset:c*g},A=await a.getOrders(W);if(M!==ae.current)return;n(A.orders),i(A.total)}catch(W){if(M!==ae.current)return;o(W instanceof Error?W:new Error("Failed to fetch orders"))}finally{M===ae.current&&f(!1)}},[a,c,g,U,t]);It.useEffect(()=>{le()},[le]);let fe=Math.ceil(r/g);return{orders:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<fe-1,hasPreviousPage:c>0,setPage:b,setPageSize:M=>{m(M),b(0)},status:p,setStatus:M=>{u(M),b(0)},statusIn:T,setStatusIn:M=>{_(M&&M.length>0?M:void 0),b(0)},customerEmail:v,setCustomerEmail:M=>{x(M),b(0)},from:R,setFrom:M=>{P(M),b(0)},to:h,setTo:M=>{S(M),b(0)},showAbandoned:N,setShowAbandoned:M=>{C(M),b(0)},unfulfilledOnly:w,setUnfulfilledOnly:M=>{k(M),b(0)},clearFilters:()=>{u(void 0),_(void 0),C(!1),k(!1),x(""),P(""),S(""),b(0)},filters:U,refetch:le}}import*as $t from"react";import{ArrowLeft as ym,Check as bc,ChevronLeft as xm,ChevronRight as wm,ClipboardCopy as Sm,Copy as Nm,Download as Rm,Loader2 as yi,Mail as hc,MoreHorizontal as _m,Package as Pm,RotateCcw as km,Truck as Cm,Undo2 as yc}from"lucide-react";import*as gc from"react";import*as Ln from"@radix-ui/react-popover";import{jsx as To}from"react/jsx-runtime";var vi=Ln.Root,bi=Ln.Trigger;var Nr=gc.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},n)=>To(Ln.Portal,{children:To("div",{className:"aifeatures-admin",children:To(Ln.Content,{ref:n,align:t,sideOffset:a,className:G("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})})}));Nr.displayName=Ln.Content.displayName;import{jsx as hi}from"react/jsx-runtime";var bm={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function hm(e){return bm[e]??e}function vc(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 ws({status:e,className:t}){return hi(ee,{variant:vc(e),className:t,children:hm(e)})}function Ss({status:e}){return hi(ws,{status:e})}function Hs({order:e,className:t}){return e.line_items.some(a=>a.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?hi(ee,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?hi(ee,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Xn(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as Bm,jsx as D,jsxs as re}from"react/jsx-runtime";var Nc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ns="af-text-xs af-text-muted-foreground";function Eo(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 Tm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rc(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 xi=24,Em=["paid","partially_refunded"],Im=["paid","partially_refunded","disputed"],Dm=/^[A-Za-z0-9 _-]*$/,xc=100;function Ao(e,t,a,s,n){let r=Em.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 ${xi} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${xi} 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<xi&&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<xi&&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 wc({title:e,recipient:t,status:a,attempts:s,side:n,orderStatus:r,action:i,delivery:l}){if(l)return re("div",{children:[D(In,{deliveries:[l]}),i&&D("div",{className:"af-mt-2",children:i})]});let f=Ao(n,a,s,r,t);return re("div",{children:[re("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[re("div",{className:"af-min-w-0",children:[D("div",{className:"af-text-sm",children:e}),t&&D("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),D(ee,{variant:f.variant,className:"af-shrink-0",children:f.label})]}),f.detail&&D("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:f.detail}),i&&D("div",{className:"af-mt-2",children:i})]})}function Sc(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=Tm(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}: ${Rc(n)}`)}function Am(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Lo({value:e,label:t,children:a,className:s,size:n="icon"}){let[r,i]=$t.useState(!1);if(!Am())return null;let l=async()=>{try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},f=r?D(bc,{className:"af-h-3 af-w-3"}):D(Nm,{className:"af-h-3 af-w-3"});return n==="icon"?D(y,{variant:"ghost",size:"icon",className:G("af-h-6 af-w-6 af-shrink-0",s),onClick:l,title:t,"aria-label":t,children:f}):re(y,{variant:"outline",size:"sm",className:s,onClick:l,"aria-label":t,children:[r?D(bc,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):D(Sm,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":a]})}function Io({label:e,value:t}){return re("div",{children:[D("div",{className:Ns,children:e}),re("div",{className:"af-flex af-items-center af-gap-1",children:[D("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),D(Lo,{value:t,label:`Copy ${e}`})]})]})}function Lm({src:e}){let[t,a]=$t.useState(!1);return!e||t?D("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:D(Pm,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):D("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 On({title:e,action:t,children:a,className:s}){return re("section",{className:G("af-rounded-lg af-border af-p-4",s),children:[re("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[D("h4",{className:Nc,children:e}),t]}),D("div",{className:"af-mt-3",children:a})]})}function La({label:e,emphasis:t,divider:a,children:s}){return re("div",{className:G("af-flex af-items-baseline af-justify-between af-gap-6",a&&"af-mt-2 af-border-t af-pt-2"),children:[D("span",{className:t?"af-text-base af-font-semibold":Ns,children:e}),D("span",{className:G("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function Do({onSelect:e,disabled:t,icon:a,children:s}){return re(y,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[D("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function Om(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 ${Y(di(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?Xr(a):Ao("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?Xr(a):Ao("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 ${Y(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 wi({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:n=!1,onPrevOrder:r,onNextOrder:i,hasPrevOrder:l=!1,hasNextOrder:f=!1}){let{api:d}=H(),[o,c]=$t.useState(e),[b,g]=$t.useState(null),[m,p]=$t.useState(null),[u,v]=$t.useState(!1),[x,R]=$t.useState(!1),[P,h]=$t.useState(!1),[S,N]=$t.useState(!1),[C,w]=$t.useState(""),[k,T]=$t.useState(!1),[_,z]=$t.useState(null),[Z,U]=$t.useState(!1),[ae,le]=$t.useState(""),[fe,M]=$t.useState([]),[W,A]=$t.useState(!1),[de,ce]=$t.useState(!1),[Le,ye]=$t.useState(null);$t.useEffect(()=>{c(e)},[e]);let Te=F=>{let Xe=F.id===o.id&&F.email_deliveries===void 0?{...F,email_deliveries:o.email_deliveries}:F;c(Xe),s?.(Xe)},Oe=Object.entries(o.metadata??{}),oe=Math.max(0,di(o)-o.amount_refunded),st=(o.status==="paid"||o.status==="partially_refunded")&&oe>0,E=o.exclusive_tax_total!=null,O=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),B=Math.max(0,(o.shipping_total??0)-(o.shipping_refunded??0)),we=fe.reduce((F,Xe)=>F+O(o.line_items[Xe]??{}),0)+(W?B:0),X=o.tax_total??0,ve=Math.max(0,(o.exclusive_tax_total??0)-o.line_items.reduce((F,Xe)=>F+(Xe.exclusiveTax??0),0)),Me=E?W&&B>0?ve:0:o.automatic_tax&&o.tax_behavior==="exclusive"&&X>0&&o.amount_total+(o.shipping_total??0)>0?Math.min(Math.max(0,X-(o.tax_refunded??0)),Math.round(X*we/(o.amount_total+(o.shipping_total??0)))):0,ht=o.source==="subscription"&&(o.credit_applied??0)>0&&o.line_items.length===1?Math.min(we+Me,oe):we+Me,Ke=fe.length>0||W,Ct=Ke?ht:ua(ae,o.currency),pe=cn(o.currency)?"1":"0.01",ke=async()=>{try{v(!0),g(null),p(null),await d.resendOrderReceipt(o.id);let F=await d.getOrder(o.id);Te(F),p("Receipt email queued.")}catch(F){g(F instanceof Error?F.message:"Failed to resend receipt")}finally{v(!1)}},rt=async()=>{try{R(!0),g(null),p(null);let F=await d.resetOrderDownloads(o.id);Te(F),h(!1),p("Download count reset.")}catch(F){g(F instanceof Error?F.message:"Failed to reset downloads")}finally{R(!1)}},Je=o.line_items.some(F=>F.collectShippingAddress===!0&&!F.refunded&&!F.unavailableReason),zt=typeof o.merchant_fulfilled_at=="string",Ot=Im.includes(o.status)||o.status==="refunded"&&o.line_items.some(F=>F.collectShippingAddress===!0&&F.amountNet===0&&!F.refunded&&!F.unavailableReason),sa=C.trim(),it=Dm.test(sa)&&sa.length<=xc,vt=async F=>{try{T(!0),z(null),p(null);let Xe=await d.setOrderFulfillment(o.id,{fulfilled:F,...F&&sa?{trackingNumber:sa}:{}});Te(Xe),w(""),p(F?"Marked as shipped.":"Marked as not shipped.")}catch(Xe){Xe instanceof Yt&&Xe.status===409?z(`This order is ${o.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):z(Xe instanceof Error?Xe.message:"Failed to update the order")}finally{T(!1)}},xe=()=>{ye(null),le(String(Et(oe,o.currency))),M([]),A(!1),U(!0)},ot=F=>M(Xe=>Xe.includes(F)?Xe.filter(Ia=>Ia!==F):[...Xe,F]),Ze=async(F,Xe)=>{if(a)try{ce(!0),ye(null),await a(o,F,Xe);let Ia=await d.getOrder(o.id);Te(Ia),U(!1),p("Refund issued.")}catch(Ia){ye(Ia instanceof Error?Ia.message:"Refund failed")}finally{ce(!1)}},yt=async()=>{if(Ke){if(ht<=0){ye("The lines you picked were charged nothing");return}if(ht>oe){ye(`That selection exceeds the refundable remainder (${Y(oe,o.currency)})`);return}await Ze(ht,{...fe.length>0?{line_items:[...fe].sort((Xe,Ia)=>Xe-Ia)}:{},...W?{shipping:!0}:{}});return}let F=ua(ae,o.currency);if(F===null||F<=0){ye("Enter a valid refund amount");return}if(F>oe){ye(`Amount exceeds the refundable remainder (${Y(oe,o.currency)})`);return}await Ze(F,{amount:F})},$=()=>Ze(oe,{full:!0}),Ge=!o.subscription_history_only&&o.fulfillment_type==="download",ra=!o.subscription_history_only&&n&&Je,Ms=Om(o),Q=o.shipping_address?Sc(o.shipping_address).join(`
|
|
4
|
-
`):"",Na=o.shipping_total!=null,vo=o.exclusive_tax_total??(o.automatic_tax&&o.tax_behavior==="exclusive"?o.tax_total??0:0),$l=o.exclusive_tax_total!=null?Math.max(0,(o.tax_total??0)-vo):o.automatic_tax&&o.tax_behavior==="exclusive"?0:o.tax_total??0,Vl=vo>0,Uu=$l>0,Hl=o.amount_subtotal!=null||Na||Vl||(o.discount_total??0)>0,mr=[];return o.subscription_history_only||mr.push(D(Do,{icon:u?D(yi,{className:"af-h-4 af-w-4 af-animate-spin"}):D(hc,{className:"af-h-4 af-w-4"}),disabled:u||o.fulfillment_status!=="fulfilled",onSelect:()=>{N(!1),ke()},children:"Resend receipt"},"resend")),Ge&&mr.push(D(Do,{icon:D(km,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{N(!1),h(!0)},children:"Reset download count"},"reset")),st&&mr.push(re("div",{children:[D(Do,{icon:D(yc,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{N(!1),xe()},children:"Refund\u2026"}),!a&&D("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),re("div",{children:[re("div",{className:"af-mb-6",children:[re(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[D(ym,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),re("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[re("div",{className:"af-min-w-0",children:[re("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[D("h3",{className:"af-text-xl af-font-semibold",children:Xn(o)}),D(ws,{status:o.status}),n&&!o.subscription_history_only&&D(Hs,{order:o}),o.is_test&&D(ee,{variant:"outline",children:"Test"})]}),re("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Eo(o.created_at)]}),o.is_test&&D("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),re("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||i)&&re("div",{className:"af-flex af-items-center",children:[D(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:D(xm,{className:"af-h-4 af-w-4"})}),D(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:i,disabled:!f,"aria-label":"Next order",children:D(wm,{className:"af-h-4 af-w-4"})})]}),ra&&(zt?re("div",{className:"af-flex af-items-center af-gap-1",children:[re("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",o.merchant_fulfilled_at?` \xB7 ${Eo(o.merchant_fulfilled_at)}`:""]}),Ot&&re(y,{variant:"ghost",size:"sm",onClick:()=>vt(!1),disabled:k,children:[k?D(yi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(yc,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Ot?re("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[D(te,{value:C,onChange:F=>w(F.target.value),placeholder:"Tracking number (optional)",maxLength:xc,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:k}),re(y,{variant:"default",className:"af-shrink-0",onClick:()=>vt(!0),disabled:k||!it,children:[k?D(yi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(Cm,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),mr.length>0&&re(vi,{open:S,onOpenChange:N,children:[D(bi,{asChild:!0,children:D(y,{variant:"outline",size:"icon","aria-label":"More actions",children:D(_m,{className:"af-h-4 af-w-4"})})}),D(Nr,{children:D("div",{className:"af-space-y-0.5",children:mr})})]})]})]}),ra&&!zt&&!it&&D("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."}),_&&D("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&&D("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&&D("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})]}),re("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[re("div",{className:"af-space-y-6",children:[o.line_items.length>0&&D(On,{title:"Items",children:D("ul",{className:"af-space-y-3",children:o.line_items.map((F,Xe)=>{let Ia=typeof F.name=="string"&&F.name?F.name:"Item",zl=typeof F.quantity=="number"&&F.quantity>0?F.quantity:1,ql=typeof F.unitAmount=="number";return re("li",{className:"af-flex af-items-start af-gap-3",children:[D(Lm,{src:typeof F.imageUrl=="string"&&F.imageUrl?F.imageUrl:void 0}),re("div",{className:"af-min-w-0 af-flex-1",children:[re("div",{className:"af-text-sm af-font-medium",children:[Ia,typeof F.variantTitle=="string"&&F.variantTitle&&re("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",F.variantTitle]})]}),re("div",{className:Ns,children:[zl," \xD7"," ",ql?Y(F.unitAmount,o.currency):"\u2014"]}),F.unavailableReason==="oversold"&&!F.refunded&&D(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&&D(ee,{variant:"secondary",className:"af-mt-1",children:F.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),D("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof F.amountNet=="number"||ql?Y(F.amountNet??F.unitAmount*zl,o.currency):"\u2014"})]},Xe)})})}),Oe.length>0&&D(On,{title:"Order details",children:D("dl",{className:"af-space-y-2",children:Oe.map(([F,Xe])=>re("div",{children:[D("dt",{className:G(Ns,"af-capitalize"),children:F.replace(/_/g," ")}),D("dd",{className:"af-text-sm af-break-words",children:Rc(Xe)})]},F))})}),D(On,{title:"Totals",children:re("div",{className:"af-w-full",children:[Hl&&D(La,{label:"Subtotal",children:Y(o.amount_subtotal??o.amount_total+(o.discount_total??0),o.currency)}),(o.discount_total??0)>0&&re(La,{label:"Discount",children:["\u2212",Y(o.discount_total,o.currency)]}),Na&&D(La,{label:"Shipping",children:o.shipping_total===0?"Free":Y(o.shipping_total??0,o.currency)}),Vl&&D(La,{label:"Tax",children:Y(vo,o.currency)}),D(La,{label:"Total",emphasis:!0,divider:Hl,children:Y(Jn(o),o.currency)}),(o.credit_applied??0)>0&&re(La,{label:"Credit applied",children:["\u2212",Y(o.credit_applied,o.currency)]}),o.amount_paid!=null&&D(La,{label:"Amount paid",children:Y(o.amount_paid,o.currency)}),Uu&&D(La,{label:"incl. tax",children:Y($l,o.currency)}),o.base_currency!=null&&o.base_amount_total!=null&&re(La,{label:"Your price",children:[Y(o.base_amount_total,o.base_currency),re("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",o.currency.toUpperCase()]})]}),o.amount_refunded>0&&re(Bm,{children:[re(La,{label:"Refunded",children:["\u2212",Y(o.amount_refunded,o.currency),(o.shipping_refunded??0)>0&&re("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",Y(o.shipping_refunded??0,o.currency)," ","shipping"]})]}),D(La,{label:"Net",children:D("span",{className:"af-font-medium",children:Y(Math.max(0,di(o)-o.amount_refunded),o.currency)})})]})]})}),o.application_fee_state&&re(On,{title:"Platform fee",children:[o.application_fee_original!=null&&D(La,{label:"Collected",children:Y(o.application_fee_original,o.application_fee_currency??o.currency)}),o.application_fee_returned!=null&&D(La,{label:"Returned",children:Y(o.application_fee_returned,o.application_fee_currency??o.currency)}),o.application_fee_retained!=null&&D(La,{label:"Retained",children:Y(o.application_fee_retained,o.application_fee_currency??o.currency)}),o.application_fee_state!=="complete"&&D("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"})]}),D(On,{title:"Timeline",children:D("ol",{className:"af-space-y-3",children:Ms.map(F=>re("li",{className:"af-flex af-gap-3",children:[D("span",{"aria-hidden":"true",className:G("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")}),re("div",{className:"af-min-w-0",children:[D("div",{className:"af-text-sm af-break-words",children:F.text}),F.at&&D("div",{className:"af-text-xs af-text-muted-foreground",children:Eo(F.at)})]})]},F.key))})})]}),re("div",{className:"af-space-y-6",children:[D(On,{title:"Customer",children:re("div",{className:"af-space-y-2",children:[re("div",{children:[D("div",{className:Ns,children:"Email"}),re("div",{className:"af-flex af-items-center af-gap-1",children:[D("span",{className:"af-min-w-0 af-break-all af-text-sm",children:o.customer_email||D("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),o.customer_email&&D(Lo,{value:o.customer_email,label:"Copy email"})]})]}),o.customer_name&&re("div",{children:[D("div",{className:Ns,children:"Name"}),D("div",{className:"af-text-sm",children:o.customer_name})]}),o.customer&&re("div",{children:[D("div",{className:Ns,children:"Customer record"}),re("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[D("span",{className:"af-break-all af-text-sm",children:o.customer.name||o.customer.email}),D(ee,{variant:"secondary",children:"Linked"})]})]})]})}),o.shipping_address&&D(On,{title:"Ship to",action:D(Lo,{value:Q,label:"Copy address",size:"sm",children:"Copy address"}),children:D("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Sc(o.shipping_address).map((F,Xe)=>D("div",{children:F},Xe))})}),o.subscription_history_only?D(On,{title:"Subscription history",children:D("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."})}):re(On,{title:"Emails",children:[D(In,{deliveries:o.email_deliveries?.filter(F=>!["purchase_receipt","merchant_sale"].includes(F.kind)),problemsOnly:!0,className:"af-mb-4"}),re("div",{className:"af-space-y-4",children:[D(wc,{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:re(y,{variant:"outline",size:"sm",onClick:ke,disabled:u||o.fulfillment_status!=="fulfilled",children:[u?D(yi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(hc,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),D(wc,{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})]})]}),Ge&&D(On,{title:"Download",children:re("div",{className:"af-space-y-2",children:[re("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[D(Rm,{className:"af-h-4 af-w-4"}),re("span",{children:["Downloaded ",o.download_count," time",o.download_count===1?"":"s"]})]}),o.download_url&&D("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"})]})}),re("details",{className:"af-rounded-lg af-border af-p-4",children:[D("summary",{className:G(Nc,"af-cursor-pointer af-select-none"),children:"Technical details"}),re("div",{className:"af-mt-3 af-space-y-2",children:[D(Io,{label:"Order ID",value:o.id}),o.stripe_checkout_session_id&&D(Io,{label:"Checkout session",value:o.stripe_checkout_session_id}),o.stripe_payment_intent_id&&D(Io,{label:"Payment",value:o.stripe_payment_intent_id})]})]})]})]}),D(rn,{open:P,onOpenChange:F=>{!F&&!x&&h(!1)},children:re(Ga,{children:[re(Ka,{children:[D(Ya,{children:"Reset download count?"}),D(Ja,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),re(Za,{children:[D(y,{variant:"outline",onClick:()=>h(!1),disabled:x,children:"Cancel"}),D(y,{onClick:rt,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),D(rn,{open:Z,onOpenChange:F=>{!F&&!de&&U(!1)},children:re(Ga,{children:[re(Ka,{children:[D(Ya,{children:"Refund order"}),re(Ja,{children:["Refund up to ",Y(oe,o.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),re("div",{className:"af-space-y-4",children:[(o.line_items.length>0||B>0)&&re("div",{className:"af-space-y-2",children:[D(Ie,{children:"Items"}),re("div",{className:"af-space-y-2",children:[o.line_items.map((F,Xe)=>{let Ia=F.refunded===!0;return re("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[D("input",{type:"checkbox",checked:fe.includes(Xe),onChange:()=>ot(Xe),disabled:de||Ia||!!F.unavailableReason||O(F)<=0,className:"af-h-4 af-w-4"}),re("span",{className:Ia?"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}`:""]}),D("span",{className:"af-ml-auto af-text-muted-foreground",children:Ia?"Refunded":Y(O(F),o.currency)})]},Xe)}),B>0&&re("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[D("input",{type:"checkbox",checked:W,onChange:F=>A(F.target.checked),disabled:de,className:"af-h-4 af-w-4"}),D("span",{children:"Shipping"}),D("span",{className:"af-ml-auto af-text-muted-foreground",children:Y(B,o.currency)})]})]})]}),re("div",{className:"af-space-y-2",children:[re(Ie,{htmlFor:"refund-amount",children:["Amount (",o.currency.toUpperCase(),")"]}),D(te,{id:"refund-amount",type:"number",min:"0",step:pe,value:Ke?String(Et(ht,o.currency)):ae,onChange:F=>le(F.target.value),disabled:de||Ke}),Ke&&D("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Le&&D("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Le}),re(Za,{children:[D(y,{variant:"outline",onClick:()=>U(!1),disabled:de,children:"Cancel"}),D(y,{variant:"outline",onClick:$,disabled:de,children:"Refund everything"}),D(y,{variant:"destructive",onClick:yt,disabled:de,children:de?"Refunding...":Ct!==null&&Ct>0?`Refund ${Y(Ct,o.currency)}`:"Refund"})]})]})})]})}import*as Si from"react";import{ArrowLeft as Fm,RefreshCw as Mm}from"lucide-react";import{jsx as Oa,jsxs as is}from"react/jsx-runtime";function Ft({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:n}){let r=Si.useRef(null);return Si.useEffect(()=>{r.current?.focus()},[]),is("div",{className:G("af-bg-background",n),children:[is("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:[Oa("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&&is(y,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[Oa(Fm,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Oa("div",{className:"af-p-4",children:s})]})}function J({className:e}){return Oa("div",{"aria-hidden":"true",className:G("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function mt({label:e,children:t,detail:a,valueClassName:s}){return is("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Oa("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Oa("div",{className:G("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&Oa("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function Nt({message:e,onRetry:t}){return is("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Oa("span",{children:e}),is(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[Oa(Mm,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function ha({icon:e,children:t}){return is("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Oa("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function zs({icon:e,heading:t,body:a,action:s,className:n,children:r}){return is("div",{className:G("af-px-6 af-py-10 af-text-center",n),children:[Oa(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),Oa("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),Oa("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&Oa(y,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}import{jsx as V,jsxs as Ue}from"react/jsx-runtime";var qm={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Pc={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function kc(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 Cc(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 Ni(e){return e.customer?.name||e.customer_name||null}function jm({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:n=!1,emptyMessage:r,onDetailOpenChange:i,maxRows:l,onViewAll:f}){let d=typeof l=="number",{api:o}=H(),c=gi({refreshKey:a}),{orders:b,total:g,isLoading:m,error:p,page:u,pageSize:v,hasNextPage:x,hasPreviousPage:R,setPage:P,setPageSize:h,customerEmail:S,setCustomerEmail:N,setStatusIn:C,from:w,setFrom:k,to:T,setTo:_,showAbandoned:z,setShowAbandoned:Z,setUnfulfilledOnly:U,filters:ae,refetch:le}=c,fe=Xt.useCallback(()=>o.exportOrdersCsv(ae),[o,ae]),[M,W]=Xt.useState("list"),[A,de]=Xt.useState(null),[ce,Le]=Xt.useState(""),[ye,Te]=Xt.useState(""),[Oe,oe]=Xt.useState(!d&&n?"needs_shipping":"all"),[st,E]=Xt.useState(!1),[O,B]=Xt.useState(!!s&&!d),[we,X]=Xt.useState(null);Xt.useEffect(()=>{if(!s||d)return;let Q=!1;return B(!0),X(null),o.getOrder(s).then(Na=>{Q||(de(Na),W("detail"))}).catch(()=>{Q||X("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{Q||B(!1)}),()=>{Q=!0}},[o,s,d]);let ve=Xt.useCallback(Q=>{oe(Q);let Na=Pc[Q];C(Na.statusIn),U(Na.unfulfilledOnly)},[C,U]);Xt.useEffect(()=>{n&&!d&&U(!0)},[]);let Me=Xt.useRef(!n);Xt.useEffect(()=>{Me.current||m||(Me.current=!0,b.length===0&&ve("all"))},[m,b.length,ve]);let ht=M==="detail"&&!!A;Xt.useEffect(()=>{i?.(ht)},[ht,i]);let Ke=(w?1:0)+(T?1:0)+(z?1:0),Ct=Ke>0||!!S||!!ye,pe=!!w&&!!T&&w>T,ke=!d||!!f,rt=Q=>{if(d){f?.();return}de(Q),W("detail")},Je=()=>{W("list"),de(null),le()},zt=Q=>{let Na=Q.trim();if(!Na){Te(""),S&&N("");return}if(Na.startsWith("#")||/^\d+$/.test(Na)){Te(Na),S&&N("");return}Te(""),N(Na)},Ot=()=>{Le(""),Te(""),N(""),k(""),_(""),Z(!1),E(!1)},sa=ye.replace(/^#/,"").toLowerCase(),it=sa?b.filter(Q=>String(Q.order_number??"")===sa||Q.id.toLowerCase().startsWith(sa)):b,vt=d?it.slice(0,l):it,xe=A?b.findIndex(Q=>Q.id===A.id):-1,ot=xe>0,Ze=xe>=0&&xe<b.length-1;if(O)return V("div",{className:t,children:V("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:V($m,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(M==="detail"&&A)return V("div",{className:t,children:V(wi,{order:A,onBack:Je,onRefund:e,onOrderUpdated:Q=>de(Q),allowFulfillment:n,onPrevOrder:ot?()=>de(b[xe-1]):void 0,onNextOrder:Ze?()=>de(b[xe+1]):void 0,hasPrevOrder:ot,hasNextOrder:Ze},A.id)});let $=Ue("div",{className:"af-mb-4 af-space-y-3",children:[we&&V("p",{className:"af-text-xs af-text-muted-foreground",children:we}),Ue("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[V("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(Q=>V("button",{type:"button","aria-pressed":Oe===Q,onClick:()=>ve(Q),className:G("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",Oe===Q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:qm[Q]},Q))}),Ue("div",{className:"af-relative af-w-full af-max-w-xs",children:[V(Hm,{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"}),V(te,{type:"text",value:ce,onChange:Q=>Le(Q.target.value),onBlur:()=>zt(ce),onKeyDown:Q=>{Q.key==="Enter"&&(Q.preventDefault(),zt(ce))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),Ue(y,{type:"button",variant:Ke>0?"secondary":"ghost",size:"sm",onClick:()=>E(Q=>!Q),"aria-expanded":st,children:[V(zm,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ke>0&&V(ee,{variant:"secondary",className:"af-ml-2",children:Ke})]}),Ct&&V(y,{type:"button",variant:"ghost",size:"sm",onClick:Ot,children:"Clear filters"}),V(va,{fetchCsv:fe,filename:"orders",disabled:!!ye,className:"af-ml-auto"})]}),(st||!!w||!!T)&&Ue("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:[V(Ie,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),V(te,{id:"orders-from",type:"date",value:w,max:T||void 0,onChange:Q=>k(Q.target.value),className:"af-w-[170px]"}),V(Ie,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),V(te,{id:"orders-to",type:"date",value:T,min:w||void 0,onChange:Q=>_(Q.target.value),className:"af-w-[170px]"}),!Pc[Oe].statusIn&&V(y,{type:"button",variant:z?"secondary":"ghost",size:"sm",onClick:()=>Z(!z),"aria-pressed":z,children:z?"Hide abandoned":"Show abandoned"})]}),pe&&V("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(m)return Ue("div",{className:t,children:[d?null:$,V("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(Q=>Ue("div",{className:"af-rounded-md af-border af-p-3",children:[Ue("div",{className:"af-flex af-items-center af-justify-between",children:[V(J,{className:"af-h-4 af-w-16"}),V(J,{className:"af-h-4 af-w-14"})]}),V(J,{className:"af-mt-2 af-h-3 af-w-40"}),V(J,{className:"af-mt-2 af-h-3 af-w-24"})]},Q))}),V("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ue(lt,{children:[V(ct,{children:Ue(Ce,{children:[V(q,{children:"Order"}),V(q,{children:"Date"}),V(q,{children:"Customer"}),V(q,{children:"Items"}),V(q,{className:"af-text-right",children:"Total"}),V(q,{children:"Status"}),V(q,{className:"af-w-8"})]})}),V(dt,{"aria-hidden":"true",children:[0,1,2,3,4].map(Q=>Ue(Ce,{children:[V(j,{children:V(J,{className:"af-h-4 af-w-14"})}),V(j,{children:V(J,{className:"af-h-4 af-w-24"})}),V(j,{children:V(J,{className:"af-h-4 af-w-40"})}),V(j,{children:V(J,{className:"af-h-4 af-w-32"})}),V(j,{children:V(J,{className:"af-ml-auto af-h-4 af-w-16"})}),V(j,{children:V(J,{className:"af-h-5 af-w-16"})}),V(j,{})]},Q))})]})}),V("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(p)return Ue("div",{className:t,children:[d?null:$,Ue("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[V("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),V(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>le(),children:"Try again"})]})]});let Ge=Oe!=="all";if(it.length===0&&u===0)return Ct||Ge?Ue("div",{className:t,children:[!d&&$,V(ha,{children:"No orders match these filters."})]}):V("div",{className:t,children:V(zs,{icon:Vm,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!d&&V(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>Z(!0),children:"Show abandoned checkouts"})})});let ra=u*v+1,Ms=Math.min((u+1)*v,g);return Ue("div",{className:t,children:[d?null:$,V("div",{className:"af-space-y-3 lg:af-hidden",children:vt.map(Q=>Ue("button",{type:"button",onClick:()=>rt(Q),disabled:!ke,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${ke?" hover:af-bg-muted/50":""}`,children:[Ue("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[V("span",{className:"af-font-medium",children:Xn(Q)}),V("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:Y(Jn(Q),Q.currency)})]}),Ue("div",{className:"af-mt-1 af-min-w-0",children:[Ue("div",{className:"af-truncate af-text-sm",children:[Q.customer_email||V("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Ni(Q)&&Ue("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Ni(Q)]})]}),V("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Cc(Q)}),Q.amount_refunded>0&&Ue("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Y(Q.amount_refunded,Q.currency)," refunded"]})]}),Ue("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[V(ws,{status:Q.status}),V(hr,{deliveries:Q.email_deliveries}),Q.is_test&&V(ee,{variant:"outline",children:"Test"}),n&&V(Hs,{order:Q}),V("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:kc(Q.created_at)})]})]},Q.id))}),V("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ue(lt,{children:[V(ct,{children:Ue(Ce,{children:[V(q,{children:"Order"}),V(q,{children:"Date"}),V(q,{children:"Customer"}),V(q,{children:"Items"}),V(q,{className:"af-text-right",children:"Total"}),V(q,{children:"Status"}),V(q,{className:"af-w-8"})]})}),V(dt,{children:vt.map(Q=>Ue(Ce,{onClick:ke?()=>rt(Q):void 0,className:ke?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[Ue(j,{className:"af-whitespace-nowrap af-font-medium",children:[V("button",{type:"button",onClick:Na=>{Na.stopPropagation(),rt(Q)},disabled:!ke,"aria-label":`Open order ${Xn(Q)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${ke?" hover:af-underline":""}`,children:Xn(Q)}),Q.is_test&&V(ee,{variant:"outline",className:"af-ml-2",children:"Test"})]}),V(j,{className:"af-whitespace-nowrap af-text-muted-foreground",children:kc(Q.created_at)}),Ue(j,{className:"af-max-w-[220px]",children:[V("div",{className:"af-truncate",children:Q.customer_email||V("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Ni(Q)&&V("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Ni(Q)})]}),V(j,{className:"af-max-w-[220px]",children:V("div",{className:"af-truncate af-text-muted-foreground",children:Cc(Q)})}),Ue(j,{className:"af-whitespace-nowrap af-text-right",children:[V("div",{className:"af-font-medium af-tabular-nums",children:Y(Jn(Q),Q.currency)}),Q.amount_refunded>0&&Ue("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Y(Q.amount_refunded,Q.currency)," ","refunded"]})]}),V(j,{children:Ue("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[V(ws,{status:Q.status}),V(hr,{deliveries:Q.email_deliveries}),n&&V(Hs,{order:Q})]})}),V(j,{className:"af-w-8 af-text-right",children:V(_c,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},Q.id))})]})}),d?null:Ue("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Ue("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[V("span",{children:sa?`${it.length} matching this page`:`Showing ${ra}-${Ms} of ${g}`}),Ue(nn,{value:String(v),onValueChange:Q=>h(Number(Q)),children:[V(ja,{className:"af-w-[70px] af-h-8",children:V(sn,{})}),Ue(Wa,{children:[V(xt,{value:"10",children:"10"}),V(xt,{value:"25",children:"25"}),V(xt,{value:"50",children:"50"}),V(xt,{value:"100",children:"100"})]})]}),V("span",{children:"per page"})]}),Ue("div",{className:"af-flex af-items-center af-gap-2",children:[Ue(y,{variant:"outline",size:"sm",onClick:()=>P(u-1),disabled:!R,children:[V(Um,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ue(y,{variant:"outline",size:"sm",onClick:()=>P(u+1),disabled:!x,children:["Next",V(_c,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function os(e){return V(jm,{...e},e.maxRows==null?"full":"compact")}import*as qs from"react";import{ChevronLeft as Zm,ChevronRight as Ym,Eye as Jm,Search as Xm,Users as Qm}from"lucide-react";import*as Ba from"react";function Ri({initialPageSize:e=25}={}){let{api:t}=H(),[a,s]=Ba.useState([]),[n,r]=Ba.useState(0),[i,l]=Ba.useState(!0),[f,d]=Ba.useState(null),[o,c]=Ba.useState(0),[b,g]=Ba.useState(e),[m,p]=Ba.useState(""),u=Ba.useRef(0),v=Ba.useCallback(async()=>{let R=++u.current;try{l(!0),d(null);let P={limit:b,offset:o*b};m.trim()&&(P.email=m.trim());let h=await t.getCustomers(P);if(R!==u.current)return;s(h.customers),r(h.total)}catch(P){if(R!==u.current)return;d(P instanceof Error?P:new Error("Failed to fetch customers"))}finally{R===u.current&&l(!1)}},[t,o,b,m]);Ba.useEffect(()=>{v()},[v]);let x=Math.ceil(n/b);return{customers:a,total:n,isLoading:i,error:f,page:o,pageSize:b,hasNextPage:o<x-1,hasPreviousPage:o>0,setPage:c,setPageSize:R=>{g(R),c(0)},email:m,setEmail:R=>{p(R),c(0)},refetch:v}}import*as Rs from"react";import{ArrowLeft as Wm,Loader2 as Gm}from"lucide-react";import{jsx as et,jsxs as fa}from"react/jsx-runtime";function Tc(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 Km(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 _i({customer:e,onBack:t,className:a}){let{api:s}=H(),[n,r]=Rs.useState(null),[i,l]=Rs.useState([]),[f,d]=Rs.useState(!0),[o,c]=Rs.useState(null);Rs.useEffect(()=>{let m=!1;return d(!0),c(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([p,u])=>{m||(r(p),l(u.orders))}).catch(p=>{m||c(p instanceof Error?p.message:"Failed to load customer")}).finally(()=>{m||d(!1)}),()=>{m=!0}},[s,e.id,e.email]);let b=n?.addresses??[],g=n?.order_count??i.length;return fa("div",{className:a,children:[fa("div",{className:"af-mb-6",children:[fa(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[et(Wm,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),et("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),fa("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Tc(e.created_at)]})]}),f?et("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:et(Gm,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):o?et("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o}):fa("div",{className:"af-space-y-6",children:[et(In,{deliveries:n?.email_deliveries}),fa("div",{children:[et("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),fa("div",{className:"af-space-y-1 af-text-sm",children:[fa("div",{className:"af-flex af-gap-2",children:[et("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),et("span",{children:e.email})]}),e.name&&fa("div",{className:"af-flex af-gap-2",children:[et("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),et("span",{children:e.name})]}),e.phone&&fa("div",{className:"af-flex af-gap-2",children:[et("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),et("span",{children:e.phone})]}),fa("div",{className:"af-flex af-gap-2",children:[et("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),et("span",{children:g})]})]})]}),b.length>0&&fa("div",{children:[et("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),et("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(m=>fa("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[m.is_default&&et(ee,{variant:"secondary",className:"af-mb-1",children:"Default"}),Km(m).map((p,u)=>et("div",{children:p},u))]},m.id))})]}),fa("div",{children:[et("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),i.length===0?et("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):fa(lt,{children:[et(ct,{children:fa(Ce,{children:[et(q,{children:"Date"}),et(q,{children:"Amount"}),et(q,{children:"Status"})]})}),et(dt,{children:i.map(m=>fa(Ce,{children:[et(j,{className:"af-text-muted-foreground",children:Tc(m.created_at)}),et(j,{children:Y(Jn(m),m.currency)}),et(j,{children:et(Ss,{status:m.status})})]},m.id))})]})]})]})]})}import{Fragment as tp,jsx as $e,jsxs as Wt}from"react/jsx-runtime";function ep(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Pi({className:e}){let{customers:t,total:a,isLoading:s,error:n,page:r,pageSize:i,hasNextPage:l,hasPreviousPage:f,setPage:d,setPageSize:o,email:c,setEmail:b,refetch:g}=Ri(),{api:m}=H(),p=qs.useCallback(()=>m.exportCustomersCsv(),[m]),[u,v]=qs.useState("list"),[x,R]=qs.useState(null),[P,h]=qs.useState(""),S=T=>{R(T),v("detail")},N=()=>{v("list"),R(null),g()};if(u==="detail"&&x)return $e("div",{className:e,children:$e(_i,{customer:x,onBack:N})});let C=Wt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[$e(te,{type:"email",value:P,onChange:T=>h(T.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),b(P.trim()))}}),Wt(y,{type:"button",variant:"outline",size:"sm",onClick:()=>b(P.trim()),children:[$e(Xm,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),c&&$e(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),b("")},children:"Clear"}),$e(va,{fetchCsv:p,filename:"customers",className:"af-ml-auto"})]});if(s)return Wt("div",{className:e,children:[C,$e("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:$e("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return Wt("div",{className:e,children:[C,$e("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Wt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&r===0)return Wt("div",{className:e,children:[c&&C,Wt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[$e(Qm,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),$e("p",{className:"af-text-muted-foreground af-text-center",children:c?"No customers match that email.":Wt(tp,{children:["No customers yet.",$e("br",{}),"Customers appear here after their first purchase."]})})]})]});let w=r*i+1,k=Math.min((r+1)*i,a);return Wt("div",{className:e,children:[C,Wt(lt,{children:[$e(ct,{children:Wt(Ce,{children:[$e(q,{children:"Email"}),$e(q,{children:"Name"}),$e(q,{children:"Phone"}),$e(q,{children:"Customer since"}),$e(q,{className:"af-text-right",children:"Actions"})]})}),$e(dt,{children:t.map(T=>Wt(Ce,{children:[$e(j,{className:"af-font-medium",children:T.email}),$e(j,{children:T.name||$e("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),$e(j,{children:T.phone||$e("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),$e(j,{className:"af-text-muted-foreground",children:ep(T.created_at)}),$e(j,{className:"af-text-right",children:$e(y,{variant:"ghost",size:"icon",onClick:()=>S(T),title:"View customer",children:$e(Jm,{className:"af-h-4 af-w-4"})})})]},T.id))})]}),Wt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Wt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Wt("span",{children:["Showing ",w,"-",k," of ",a]}),Wt(nn,{value:String(i),onValueChange:T=>o(Number(T)),children:[$e(ja,{className:"af-w-[70px] af-h-8",children:$e(sn,{})}),Wt(Wa,{children:[$e(xt,{value:"10",children:"10"}),$e(xt,{value:"25",children:"25"}),$e(xt,{value:"50",children:"50"}),$e(xt,{value:"100",children:"100"})]})]}),$e("span",{children:"per page"})]}),Wt("div",{className:"af-flex af-items-center af-gap-2",children:[Wt(y,{variant:"outline",size:"sm",onClick:()=>d(r-1),disabled:!f,children:[$e(Zm,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Wt(y,{variant:"outline",size:"sm",onClick:()=>d(r+1),disabled:!l,children:["Next",$e(Ym,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as He from"react";import{ArrowLeft as ap,ChevronLeft as np,ChevronRight as Ec,Copy as sp,Download as rp,ExternalLink as ip,FileText as Ac,Loader2 as op,Search as lp}from"lucide-react";import*as Gt from"react";function js({initialPageSize:e=25,refreshKey:t,includeAggregates:a=!1}={}){let{api:s}=H(),[n,r]=Gt.useState([]),[i,l]=Gt.useState(0),[f,d]=Gt.useState(null),[o,c]=Gt.useState(!0),[b,g]=Gt.useState(null),[m,p]=Gt.useState(0),[u,v]=Gt.useState(e),[x,R]=Gt.useState(void 0),[P,h]=Gt.useState(""),[S,N]=Gt.useState(""),[C,w]=Gt.useState(""),[k,T]=Gt.useState(""),[_,z]=Gt.useState(""),Z=x?x.join(","):"",U=Gt.useRef(0),ae=Gt.useCallback(async()=>{let fe=++U.current;c(!0),g(null);try{let M={labels:Z?Z.split(","):void 0,customerEmail:P||void 0,q:S||void 0,from:C||void 0,to:k||void 0,retainerId:_||void 0,includeAggregates:a,limit:u,offset:m*u},W=await s.getInvoices(M);if(fe!==U.current)return;if(m>0&&m*u>=W.total){p(Math.max(0,Math.ceil(W.total/u)-1));return}r(W.invoices),l(W.total),a&&d(W.aggregates??null)}catch(M){if(fe!==U.current)return;g(M instanceof Error?M:new Error("Failed to fetch invoices"))}finally{fe===U.current&&c(!1)}},[s,Z,P,S,C,k,_,m,u,a]);Gt.useEffect(()=>{ae()},[ae,t]);let le=fe=>M=>{p(0),fe(M)};return{invoices:n,total:i,aggregates:f,isLoading:o,error:b,page:m,pageSize:u,hasNextPage:(m+1)*u<i,hasPreviousPage:m>0,setPage:p,setPageSize:le(v),labels:x,setLabels:le(R),customerEmail:P,setCustomerEmail:le(h),q:S,setQ:le(N),from:C,setFrom:le(w),to:k,setTo:le(T),retainerId:_,setRetainerId:le(z),clearFilters:()=>{p(0),R(void 0),h(""),N(""),w(""),T(""),z("")},refetch:ae}}import{Fragment as gp,jsx as L,jsxs as se}from"react/jsx-runtime";var cp={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 Mo(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:cp[e.label]??e.label}function dp(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 Fo={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},up={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Rr({invoice:e,className:t}){return se("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[L(ee,{variant:dp(e.label),className:t,children:Mo(e)}),e.collection_method==="charge_automatically"&&L(ee,{variant:"secondary",children:"Managed in Stripe"})]})}function Ti({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 L(ee,{variant:a,className:t,children:Fo[e.state]??e.state})}function Ws(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function un(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 Ic={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},ki={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},Oo=100,Bo=5e3;async function fp(e,t){let a=[],s=0;for(let n=0;n<Bo;n+=Oo){let r=await e.getInvoices({...t,limit:Oo,offset:n});if(s=r.total,a.push(...r.invoices),r.invoices.length<Oo||a.length>=s)break}return{invoices:a.slice(0,Bo),total:s,truncated:s>a.length||s>Bo}}function Lc(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,Ws(s),Mo(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),Y(s.amount_subtotal,s.currency),Y(s.tax_total,s.currency),Y(s.amount_total,s.currency),s.amount_due===null?"":Y(s.amount_due,s.currency),s.amount_paid===null?"":Y(s.amount_paid,s.currency),Y(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?"":Y(s.discount_total,s.currency),s.collection_method??""]);return[t,...a].map(s=>s.map(nc).join(",")).join(`
|
|
5
|
-
`)}function mp(e){ni(new Blob([Lc(e)],{type:"text/csv;charset=utf-8"}),ai("invoices"))}function pp({className:e,refreshKey:t,initialInvoiceId:a,onDetailOpenChange:s,onConnectStripe:n,onUpgradePlan:r,needsPaidPlan:i=!1,retainerFilter:l=null,onClearRetainerFilter:f,maxRows:d,onViewAll:o}){let c=typeof d=="number",{api:b}=H(),{invoices:g,total:m,isLoading:p,error:u,page:v,pageSize:x,hasNextPage:R,hasPreviousPage:P,setPage:h,labels:S,setLabels:N,customerEmail:C,setCustomerEmail:w,q:k,setQ:T,from:_,setFrom:z,to:Z,setTo:U,retainerId:ae,setRetainerId:le,refetch:fe}=js({refreshKey:t}),[M,W]=He.useState(typeof d=="number"?"all":"open"),[A,de]=He.useState(""),[ce,Le]=He.useState(null),ye=He.useRef(0),Te=!c||!!o,Oe=He.useCallback($=>{if(c){o?.();return}ye.current++,st(!1),Le($)},[c,o]),[oe,st]=He.useState(!1),[E,O]=He.useState(0),[B,we]=He.useState(null),[X,ve]=He.useState(!1),[Me,ht]=He.useState(0);He.useEffect(()=>{Le($=>{if(!$)return $;let Ge=g.find(ra=>ra.id===$.id);return Ge&&Ge!==$?Ge:$})},[g]);let[Ke,Ct]=He.useState(!1),[pe,ke]=He.useState(null),rt=async()=>{if(!Ke){Ct(!0),ke(null);try{let{invoices:$,total:Ge,truncated:ra}=await fp(b,{labels:S,customerEmail:C,q:k,from:_,to:Z,retainerId:ae});mp($),ke(ra?`Exported the first ${$.length.toLocaleString()} of ${Ge.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{ke("Couldn't export \u2014 try again.")}finally{Ct(!1)}}},Je=!C&&!k&&!_&&!Z&&!ae,[zt,Ot]=He.useState(null);He.useEffect(()=>{if(p||m>0||!Je||M!=="open")return;let $=!1;return b.getInvoices({limit:1}).then(Ge=>{$||Ot(Ge.total>0)}).catch(()=>{$||Ot(!0)}),()=>{$=!0}},[b,p,m,Je,M,t]),He.useEffect(()=>{N(c?ki.all:ki.open)},[]),He.useEffect(()=>{let $=l?.id??"";$!==ae&&(le($),$&&(W("all"),N(ki.all),w(""),T(""),de(""),z(""),U("")))},[l?.id]),He.useEffect(()=>{let $=!1;return ve(!1),b.getInvoiceSettings().then(Ge=>{$||we({payments_active:Ge.payments_active,blocked:Ge.blocked})}).catch(()=>{$||ve(!0)}),()=>{$=!0}},[b,t,Me]),He.useEffect(()=>{if(!a||c)return;let $=!1,Ge=ye.current;return st(!1),b.getInvoice(a).then(ra=>{!$&&Ge===ye.current&&Le(ra)}).catch(()=>{!$&&Ge===ye.current&&st(!0)}),()=>{$=!0}},[b,a,E,c]),He.useEffect(()=>{s?.(ce!==null)},[ce,s]);let sa=$=>{W($),N(ki[$])},it=$=>{let Ge=$.trim();if(!Ge){k&&T(""),C&&w("");return}if(Ge.includes("@")){k&&T(""),w(Ge);return}C&&w(""),T(Ge.replace(/^#/,""))},vt=g,xe=c?vt.slice(0,d):vt,ot=oe&&se("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. ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>O($=>$+1),children:"Retry opening invoice"})]});if(ce)return se("div",{className:e,children:[ot,L(Uo,{invoice:ce,refreshKey:t,onBack:()=>{Oe(null),fe()}},ce.id)]});let Ze=se("div",{className:"af-mb-4 af-space-y-3",children:[X&&se("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>ht($=>$+1),children:"Retry setup check"})]}),ot,B?.blocked&&se("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",B.blocked.reason?`: ${B.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),l&&se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[se(ee,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",l.label]}),f&&L(y,{type:"button",variant:"link",size:"sm",onClick:f,children:"Clear schedule filter"})]}),se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[L("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(Ic).map($=>L("button",{type:"button","aria-pressed":M===$,onClick:()=>sa($),className:G("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",M===$?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ic[$]},$))}),se("div",{className:"af-relative af-w-full af-max-w-xs",children:[L(lp,{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"}),L(te,{type:"text",value:A,onChange:$=>de($.target.value),onBlur:()=>it(A),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),it(A))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),se("div",{className:"af-flex af-items-center af-gap-2",children:[L(Ie,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),L(te,{id:"invoices-from",type:"date",value:_,max:Z||void 0,onChange:$=>z($.target.value),className:"af-invoice-date af-w-[150px]"})]}),se("div",{className:"af-flex af-items-center af-gap-2",children:[L(Ie,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),L(te,{id:"invoices-to",type:"date",value:Z,min:_||void 0,onChange:$=>U($.target.value),className:"af-invoice-date af-w-[150px]"})]}),se(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void rt(),disabled:Ke||p||!!u||m===0,"aria-busy":Ke,children:[L(rp,{className:"af-h-4 af-w-4 af-mr-1"}),Ke?"Exporting\u2026":"Export CSV (all matching)"]})]}),pe&&L("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:pe})]});return p?se("div",{className:e,children:[c?null:Ze,L("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map($=>se("div",{className:"af-rounded-md af-border af-p-3",children:[se("div",{className:"af-flex af-items-center af-justify-between",children:[L(J,{className:"af-h-4 af-w-20"}),L(J,{className:"af-h-4 af-w-16"})]}),L(J,{className:"af-mt-2 af-h-3 af-w-40"})]},$))})]}):u?se("div",{className:e,children:[c?null:Ze,se("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>void fe(),children:"Retry"})]})]}):m===0&&Je&&(M==="all"||zt===!1)&&(M==="open"||M==="all")?B?.blocked?se("div",{className:e,children:[c?null:Ze,L(Ci,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):i?se("div",{className:e,children:[c?null:Ze,L(Ci,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):B&&!B.payments_active?se("div",{className:e,children:[c?null:Ze,L(Ci,{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})]}):se("div",{className:e,children:[c?null:Ze,L(Ci,{heading:"No invoices yet",body:!B||X?"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."})]}):se("div",{className:e,children:[c?null:Ze,xe.length===0?L("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."}):se(gp,{children:[L("div",{className:"af-space-y-3 lg:af-hidden",children:xe.map($=>se("button",{type:"button",onClick:()=>Oe($),disabled:!Te,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Te?" hover:af-bg-muted/50":""}`,children:[se("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[L("span",{className:"af-font-medium",children:Ws($)}),L(Rr,{invoice:$})]}),L("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:$.customer_name??$.customer_email??"\u2014"}),$.delivery&&L("div",{className:"af-mt-1",children:L(Ti,{delivery:$.delivery})}),se("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[L("span",{children:$.collection_method==="charge_automatically"?"Automatic collection":$.due_at?`Due ${un($.due_at)}`:"Due on receipt"}),L("span",{className:"af-font-medium af-tabular-nums",children:Y($.amount_due??$.amount_total,$.currency)})]})]},$.id))}),L("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:se(lt,{children:[L(ct,{children:se(Ce,{children:[L(q,{children:"Invoice"}),L(q,{children:"Created"}),L(q,{children:"Customer"}),L(q,{children:"Due"}),L(q,{className:"af-text-right",children:"Amount"}),L(q,{children:"Status"}),L(q,{children:"Delivery"}),L(q,{className:"af-w-8"})]})}),L(dt,{children:xe.map($=>se(Ce,{className:Te?"af-cursor-pointer":void 0,onClick:Te?()=>Oe($):void 0,children:[L(j,{className:"af-font-medium",children:L("button",{type:"button",disabled:!Te,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Te?" hover:af-underline":""}`,onClick:Ge=>{Ge.stopPropagation(),Oe($)},"aria-label":`Open invoice ${Ws($)}`,children:Ws($)})}),L(j,{children:un($.created_at)}),se(j,{children:[L("div",{children:$.customer_name??"\u2014"}),L("div",{className:"af-text-xs af-text-muted-foreground",children:$.customer_email})]}),L(j,{children:$.collection_method==="charge_automatically"?"Automatic":$.due_at?un($.due_at):"On receipt"}),L(j,{className:"af-text-right af-tabular-nums",children:Y($.amount_due??$.amount_total,$.currency)}),L(j,{children:L(Rr,{invoice:$})}),L(j,{children:L(Ti,{delivery:$.delivery})}),L(j,{children:L(Ec,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},$.id))})]})}),c?null:se("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[se("span",{children:[m," invoice",m===1?"":"s"]}),se("div",{className:"af-flex af-items-center af-gap-1",children:[L(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(v-1),disabled:!P,"aria-label":"Previous page",children:L(np,{className:"af-h-4 af-w-4"})}),se("span",{className:"af-tabular-nums",children:[v*x+1,"\u2013",Math.min((v+1)*x,m)]}),L(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(v+1),disabled:!R,"aria-label":"Next page",children:L(Ec,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Ci({heading:e,body:t,action:a}){return L(zs,{icon:Ac,heading:e,body:t,action:a})}function cs(e){return L(pp,{...e},e.maxRows==null?"full":"compact")}var Qn="af-text-xs af-text-muted-foreground";function Dc(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Uo({invoice:e,onBack:t,refreshKey:a,className:s}){let{api:n}=H(),r=He.useRef(null);He.useEffect(()=>{r.current?.focus()},[e.id]);let[i,l]=He.useState(!1),[f,d]=He.useState(null),[o,c]=He.useState(!1),[b,g]=He.useState(!1),m=He.useRef(0),[p,u]=He.useState(null),[v,x]=He.useState(!1),[R,P]=He.useState(0);He.useEffect(()=>{let _=!1;return x(!1),n.getInvoice(e.id).then(z=>{_||u({source:e,value:z})}).catch(()=>{_||x(!0)}),()=>{_=!0}},[n,e,a,R]);let h=p?.source===e?p.value:e,S=h.collection_method==="charge_automatically";He.useEffect(()=>(m.current++,d(null),c(!1),g(!1),l(!1),()=>{m.current++}),[n,h,a]);let N=_=>_==null?"\u2014":Y(_,h.currency),C=async()=>{if(!(!h.pay_url||!Dc()))try{await navigator.clipboard.writeText(h.pay_url),l(!0),setTimeout(()=>l(!1),1500)}catch{}},w=async()=>{if(f){d(null);return}let _=++m.current;g(!1),c(!0);try{let z=await n.getInvoicePreview(h.id);_===m.current&&d(z)}catch{_===m.current&&g(!0)}finally{_===m.current&&c(!1)}},k=h.bill_to,T=k?[k.company,k.name,k.address?.line1,k.address?.line2,[k.address?.city,k.address?.state,k.address?.postal_code].filter(Boolean).join(", "),k.address?.country,k.tax_id?`${k.tax_id.value}`:null,k.po_number?`PO ${k.po_number}`:null,k.service_period?`Service period: ${k.service_period}`:null].filter(_=>!!_&&_.length>0):[];return se("div",{className:s,children:[se("div",{className:"af-mb-4",children:[se(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[L(ap,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[se("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",Ws(h)]}),L(Rr,{invoice:h}),L(Ti,{delivery:h.delivery})]}),se("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[h.customer_name??h.customer_email,h.customer_name&&h.customer_email?` \xB7 ${h.customer_email}`:""]})]}),v&&se("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. ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>P(_=>_+1),children:"Retry details"})]}),h.label==="failed"&&L("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"&&L("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."}),se("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[se("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[se("section",{className:"af-rounded-md af-border af-p-4",children:[se(lt,{children:[L(ct,{children:se(Ce,{children:[L(q,{children:"Description"}),L(q,{className:"af-text-right",children:"Qty"}),L(q,{className:"af-text-right",children:"Amount"})]})}),L(dt,{children:h.line_items.map((_,z)=>se(Ce,{children:[L(j,{style:{overflowWrap:"anywhere"},children:_.description}),L(j,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_.quantity}),L(j,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:N(_.amount)})]},z))})]}),se("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[L(ls,{label:"Subtotal",value:N(h.amount_subtotal)}),(h.discount_total??0)>0&&L(ls,{label:"Discount",value:`-${N(h.discount_total)}`}),h.tax_total>0&&L(ls,{label:h.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:N(h.tax_total)}),L(ls,{label:"Total",value:N(h.amount_total),strong:!0}),h.credit_applied>0&&L(ls,{label:"Credit applied",value:`-${N(h.credit_applied)}`}),h.amount_due!==null&&h.amount_due!==h.amount_total&&L(ls,{label:"Amount due",value:N(h.amount_due),strong:!0}),h.amount_paid!==null&&h.amount_paid>0&&L(ls,{label:"Amount paid",value:N(h.amount_paid)}),h.amount_refunded>0&&L(ls,{label:"Refunded",value:N(h.amount_refunded)})]}),h.credit_notes?.length>0&&se("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[L("div",{className:Qn,children:"Credit notes"}),h.credit_notes.map(_=>se("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[se("span",{className:"af-text-muted-foreground",children:[un(_.created_at)," \xB7 ",_.origin==="dashboard"?"issued in Stripe":"refund",_.stripe_credit_note_id?"":" \xB7 being created"]}),se("span",{className:"af-tabular-nums",children:["-",Y(_.amount,_.currency)]})]},_.id))]})]}),(h.note||h.footer)&&se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[h.note&&se("div",{children:[L("div",{className:Qn,children:"Note"}),L("div",{className:"af-whitespace-pre-wrap af-break-words",children:h.note})]}),h.footer&&se("div",{children:[L("div",{className:Qn,children:"Footer"}),L("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:h.footer})]})]}),f&&!S&&se("section",{className:"af-rounded-md af-border af-p-4",children:[se("div",{className:G(Qn,"af-break-words"),children:["Email preview \u2014 ",f.subject]}),L("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),L("iframe",{title:"Invoice email preview",srcDoc:f.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),se("div",{className:"af-min-w-0 af-space-y-4",children:[se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[L(dn,{label:"Created",value:un(h.created_at)}),L(dn,{label:"Due",value:h.collection_method==="charge_automatically"?"Managed in Stripe":h.due_at?un(h.due_at):"On receipt"}),h.paid_at&&L(dn,{label:"Paid",value:un(h.paid_at)}),h.payment_method&&L(dn,{label:"Paid by",value:h.paid_out_of_band?`${h.payment_method} (recorded outside Stripe)`:h.payment_method}),h.payment_state!=="none"&&L(dn,{label:"Payment",value:h.payment_state==="processing"?"Processing":h.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),h.delivery&&L(dn,{label:"Delivery",value:`${Fo[h.delivery.state]} \xB7 ${h.delivery.recipient}`}),h.marked_uncollectible_at&&L(dn,{label:"Written off",value:un(h.marked_uncollectible_at)}),h.correction_reason&&L(dn,{label:"Correction",value:h.correction_reason}),h.replaced_by_order_id&&L(dn,{label:"Replaced by",value:h.replaced_by_order_id}),h.collection_method==="charge_automatically"?L(dn,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):h.retainer_id&&L(dn,{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&&L(dn,{label:"Replaces",value:h.replaces_order_id})]}),se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[L("div",{className:Qn,children:"Reminders"}),S?L("div",{children:"View automatic payment reminders in Stripe."}):h.reminders.disabled?L("div",{children:"Off for this invoice."}):h.reminders.paused_until?se("div",{children:["Paused until ",un(h.reminders.paused_until),"."]}):h.reminders.next_at?se("div",{children:["Next on ",un(h.reminders.next_at),"."]}):h.reminders.final_sent_at?se("div",{children:["Final reminder sent ",un(h.reminders.final_sent_at),"."]}):L("div",{children:"None scheduled."}),!S&&se("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&&se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[L("div",{className:Qn,children:"Email delivery history"}),h.communications.map(_=>se("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[se("span",{className:"af-min-w-0 af-break-words",children:[up[_.kind]??_.kind,_.kind==="reminder"&&_.slot!==null?` #${_.slot}`:"",se("span",{className:"af-text-muted-foreground",children:[" \xB7 ",_.recipient]})]}),se("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Fo[_.state]??_.state," \xB7 ",un(_.state_at??_.created_at)]})]},_.id))]}),T.length>0&&se("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[L("div",{className:Qn,children:"Bill to"}),T.map((_,z)=>L("div",{className:"af-break-words",children:_},z))]}),se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[h.pay_url&&se(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void C(),disabled:!Dc(),children:[L(sp,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Copied":S?"Copy invoice link":"Copy pay link"]}),h.pdf_url&&L(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:se("a",{href:h.pdf_url,target:"_blank",rel:"noreferrer",children:[L(ip,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!S&&se(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void w(),disabled:o,children:[o?L(op,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):L(Ac,{className:"af-h-4 af-w-4 af-mr-1"}),f?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!S&&L("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),h.pay_url&&L("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:h.pay_url}),L("p",{className:"af-text-xs af-text-muted-foreground",children:S?"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 dn({label:e,value:t}){return se("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[L("span",{className:G(Qn,"af-shrink-0"),children:e}),L("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function ls({label:e,value:t,strong:a}){return se("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[L("dt",{className:G(Qn,a&&"af-font-medium af-text-foreground"),children:e}),L("dd",{className:G("af-tabular-nums",a&&"af-font-semibold"),children:t})]})}import{Repeat as vp}from"lucide-react";import{jsx as Vt,jsxs as Nn}from"react/jsx-runtime";var bp={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Oc={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function hp(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 Bc(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>Oc[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>Oc[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":bp[e.status]}function Fc(e){let t=e.interval==="year"?"every year":"every month";return`${Y(e.amount,e.currency)} ${t}`}function yp(e){return e.status==="canceled"?`Ended ${Ei(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Ei(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 ${Ei(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Ei(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Ei(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 $o({retainer:e,className:t}){return Vt(ee,{variant:hp(e.status),className:G("af-max-w-full af-whitespace-normal af-break-words",t),children:Bc(e)})}function Gs({retainers:e,isLoading:t,error:a,onRetry:s,onShowCycles:n,activeRetainerId:r,total:i,endedTotal:l=0,isLoadingMore:f=!1,onLoadMore:d,includeEnded:o=!1,onIncludeEndedChange:c,exportCsv:b,className:g}){let m=!!c;if(!t&&!a&&e.length===0&&!(m&&(o||l>0)))return null;let p=i!==void 0?Math.max(0,i-e.length):0;return Nn("section",{className:G("af-mb-6",g),"aria-label":"Recurring invoices",children:[Nn("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[Vt(vp,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),Vt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),Vt("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&&Vt(y,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":o,onClick:()=>c?.(!o),children:o?"Hide ended recurring invoices":l>0&&e.length===0?`Show ended recurring invoices (${l})`:"Show ended recurring invoices"}),b&&Vt(va,{fetchCsv:b,filename:"retainers",className:m?void 0:"af-ml-auto"})]}),a?Nn("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",Vt(y,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?Vt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(u=>Nn("div",{className:"af-rounded-md af-border af-p-3",children:[Vt(J,{className:"af-h-4 af-w-48"}),Vt(J,{className:"af-mt-2 af-h-3 af-w-32"})]},u))}):e.length===0?Vt("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."}):Vt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(u=>{let v=r===u.id;return Nn("li",{className:G("af-rounded-md af-border af-p-3",v&&"af-border-primary af-bg-muted/40"),children:[Nn("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[Nn("div",{className:"af-min-w-0",children:[Vt("div",{className:"af-truncate af-font-medium",children:u.customer_name??u.customer_email??"\u2014"}),Vt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:u.description})]}),Vt($o,{retainer:u})]}),u.collection_method==="charge_automatically"?Nn("div",{className:"af-mt-2 af-space-y-1",children:[Vt(ee,{variant:"secondary",children:"Managed in Stripe"}),Vt("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."})]}):Vt("div",{className:"af-mt-2 af-text-sm",children:Fc(u)}),Nn("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:[Nn("span",{children:[yp(u)," \xB7 ",u.cycles.count===0?"no invoices yet":`${u.cycles.paid} paid${u.cycles.open>0?`, ${u.cycles.open} open`:""}`]}),u.cycles.count>0&&Vt(y,{type:"button",variant:v?"secondary":"ghost",size:"sm",onClick:()=>n(u),"aria-pressed":v,children:v?"Showing invoices":"View invoices"})]}),u.status==="failed"&&u.operation?.last_error&&Nn("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",u.operation.last_error,". Ask in the chat to try again."]})]},u.id)})}),!t&&!a&&p>0&&d&&Vt("div",{className:"af-mt-2",children:Vt(y,{type:"button",variant:"outline",size:"sm",onClick:d,disabled:f,children:f?"Loading\u2026":`Load more (${p} more)`})})]})}import*as Uc from"react";import{AlertTriangle as Mc,CheckCircle2 as xp,CreditCard as Vo,Loader2 as wp,RefreshCw as Sp}from"lucide-react";import{jsx as Rt,jsxs as ia}from"react/jsx-runtime";function Ks({onConnectStripe:e,onUpgradePlan:t,whenActive:a,className:s}){let{status:n,isLoading:r,error:i,refetch:l}=rs(),[f,d]=Uc.useState(!1),o=async()=>{d(!0);try{await l()}finally{d(!1)}};return r&&!n?Rt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Rt("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!n?Rt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ia("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):n.status==="active"?a!==void 0?Rt("div",{className:s,children:a}):Rt("div",{className:s,children:ia("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:[Rt(xp,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),ia("div",{children:[Rt("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),ia("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."]})]})]})}):ia("div",{className:`af-space-y-4 ${s||""}`,children:[n.reason==="needs_stripe"&&ia("div",{className:"af-space-y-3",children:[ia("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Rt(Vo,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),ia("div",{children:[Rt("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),Rt("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?ia(y,{onClick:e,children:[Rt(Vo,{className:"af-h-4 af-w-4 af-mr-1"}),n.stripe_account_connected?"Finish setting up":"Set up payments"]}):Rt("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"&&ia("div",{className:"af-space-y-3",children:[ia("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Rt(Mc,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),ia("div",{children:[Rt("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),Rt("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?Rt(y,{onClick:t,children:"Upgrade plan"}):Rt("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),n.reason==="account_disabled"&&ia("div",{className:"af-space-y-3",children:[ia("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:[Rt(Mc,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),ia("div",{children:[Rt("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),n.stripe_account_connected?Rt("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."}):Rt("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."})]})]}),ia("div",{className:"af-flex af-gap-2",children:[e&&n.stripe_account_connected&&ia(y,{onClick:e,children:[Rt(Vo,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),ia(y,{variant:"outline",onClick:o,disabled:f,children:[f?Rt(wp,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Rt(Sp,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as _a from"react";function Ho(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function Zs({includeStats:e=!1,refreshKey:t}={}){let{api:a}=H(),[s,n]=_a.useState([]),[r,i]=_a.useState(!0),[l,f]=_a.useState(null),d=_a.useRef(0),o=_a.useCallback(async()=>{let u=++d.current;try{i(!0),f(null);let v=await a.getProducts(e?{include:"stats"}:{});if(u!==d.current)return;n(v)}catch(v){if(u!==d.current)return;f(v instanceof Error?v:new Error("Failed to fetch products"))}finally{u===d.current&&i(!1)}},[a,e,t]);_a.useEffect(()=>{o()},[o]);let c=_a.useCallback(async u=>{let v=await a.createProduct(u);return n(x=>[v,...x]),v},[a]),b=_a.useCallback(async(u,v)=>{let x=await a.updateProduct(u,v);return n(R=>Ho(R,u,x)),x},[a]),g=_a.useCallback(async u=>{await a.deleteProduct(u),n(v=>v.filter(x=>x.id!==u))},[a]),m=_a.useCallback(async(u,v)=>{let x=await a.attachProductFile(u,v);return n(R=>Ho(R,u,x)),x},[a]),p=_a.useCallback(async(u,v)=>{let x=await a.attachProductFileFromUrl(u,v);return n(R=>Ho(R,u,x)),x},[a]);return{products:s,isLoading:r,error:l,refetch:o,createProduct:c,updateProduct:b,deleteProduct:g,attachProductFile:m,attachProductFileFromUrl:p}}import*as Pa from"react";var zo=["creating","active","paused","canceling"],Np=["canceled","failed"],Rp={statuses:zo},_p={};function Ys({refreshKey:e,includeEnded:t=!1,limit:a=50}={}){let{api:s}=H(),[n,r]=Pa.useState([]),[i,l]=Pa.useState(0),[f,d]=Pa.useState(0),[o,c]=Pa.useState(!0),[b,g]=Pa.useState(!1),[m,p]=Pa.useState(null),[u,v]=Pa.useState(t),x=Pa.useRef(0),R=Pa.useCallback(async()=>{let h=++x.current;c(!0),g(!1),p(null);try{let S=await s.getRetainers({statuses:u?void 0:zo,limit:a,offset:0});if(h!==x.current)return;if(r(S.retainers),l(S.total),!u&&S.total===0){let N=await s.getRetainers({statuses:Np,limit:1,offset:0});if(h!==x.current)return;d(N.total)}else d(0)}catch(S){if(h!==x.current)return;p(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{h===x.current&&c(!1)}},[s,u,a]);Pa.useEffect(()=>{R()},[R,e]);let P=Pa.useCallback(async()=>{if(o||b||n.length>=i)return;let h=x.current;g(!0);try{let S=await s.getRetainers({statuses:u?void 0:zo,limit:a,offset:n.length});if(h!==x.current)return;r(N=>{let C=new Set(N.map(w=>w.id));return[...N,...S.retainers.filter(w=>!C.has(w.id))]}),l(S.total)}catch(S){if(h!==x.current)return;p(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{h===x.current&&g(!1)}},[s,u,a,o,b,n.length,i]);return{retainers:n,total:i,endedTotal:f,hasMore:n.length<i,isLoading:o,isLoadingMore:b,error:m,includeEnded:u,setIncludeEnded:v,loadMore:P,refetch:R,filters:u?_p:Rp}}import{Fragment as Ap,jsx as pt,jsxs as Fa}from"react/jsx-runtime";function $c({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:n}){let[r,i]=Js.useState(t),[l,f]=Js.useState("list"),[d,o]=Js.useState(null),c=Zs(),{status:b,error:g}=rs(),m=b?.currency,p=R=>{o(R),f("edit")},u=()=>{o(null),f("create")},v=()=>{f("list"),o(null)},x=R=>{o(R),f("edit")};return Fa("div",{className:e,children:[Fa("div",{className:"af-mb-6",children:[pt("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),pt("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Fa(Zr,{value:r,onValueChange:R=>i(R),children:[Fa(br,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Fa(yn,{value:"products",className:"af-gap-2",children:[pt(Cp,{className:"af-h-4 af-w-4"}),"Products"]}),Fa(yn,{value:"orders",className:"af-gap-2",children:[pt(Tp,{className:"af-h-4 af-w-4"}),"Orders"]}),Fa(yn,{value:"invoices",className:"af-gap-2",children:[pt(kp,{className:"af-h-4 af-w-4"}),"Invoices"]}),Fa(yn,{value:"customers",className:"af-gap-2",children:[pt(Ip,{className:"af-h-4 af-w-4"}),"Customers"]}),pt(yn,{value:"promos",children:"Promo codes"}),Fa(yn,{value:"setup",className:"af-gap-2",children:[pt(Ep,{className:"af-h-4 af-w-4"}),"Setup"]})]}),pt(xn,{value:"products",children:l==="list"?pt(fi,{productsState:c,onSelectProduct:p,onCreateProduct:u}):Fa("div",{children:[Fa("div",{className:"af-mb-6",children:[Fa(y,{variant:"ghost",size:"sm",onClick:v,className:"af-mb-2 af--ml-2",children:[pt(Pp,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),pt("h3",{className:"af-text-lg af-font-semibold",children:l==="create"?"New Product":d?.name})]}),l==="create"&&!m?pt("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?Fa("div",{className:"af-text-destructive",children:["Error: ",g.message]}):pt("div",{className:"af-text-muted-foreground",children:"Loading..."})}):pt(pi,{productsState:c,product:l==="edit"?d:null,currency:m??"usd",onSaved:x},l==="edit"?d?.id??"edit":"new")]})}),pt(xn,{value:"orders",children:pt(os,{onRefund:s})}),pt(xn,{value:"invoices",children:pt(Dp,{onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),pt(xn,{value:"customers",children:pt(Pi,{})}),pt(xn,{value:"promos",children:pt(Vs,{})}),pt(xn,{value:"setup",children:pt(Ks,{onConnectStripe:a,onUpgradePlan:n})})]})]})}function Dp({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a}){let s=Ys(),[n,r]=Js.useState(null),[i,l]=Js.useState(!1);return Fa(Ap,{children:[!i&&pt(Gs,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:n?.id??null,onShowCycles:f=>r(d=>d?.id===f.id?null:f),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),pt(cs,{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 Hc from"react";import*as Bn from"react";function Xs({refreshKey:e}={}){let{api:t}=H(),[a,s]=Bn.useState(null),[n,r]=Bn.useState(!0),[i,l]=Bn.useState(null),f=Bn.useRef(0),d=Bn.useCallback(async()=>{let o=++f.current;try{r(!0),l(null);let c=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(o!==f.current)return;s(c)}catch(c){if(o!==f.current)return;l(c instanceof Error?c:new Error("Failed to fetch summary"))}finally{o===f.current&&r(!1)}},[t,e]);return Bn.useEffect(()=>{d()},[d]),{summary:a,isLoading:n,error:i,refetch:d}}import{Fragment as qo,jsx as oa,jsxs as jo}from"react/jsx-runtime";function Vc(e,t){if(e.settled.complete)return{headline:Y(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:Y(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${Y(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:Y(0,t),extra:[]}}function zc({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:n,className:r}){let{summary:i,isLoading:l,error:f,refetch:d}=Xs({refreshKey:e}),[o,c]=Hc.useState(!1),b=oa("div",{className:"af-mb-6",children:f&&!i?oa(Nt,{message:"Couldn't load your revenue summary.",onRetry:()=>d()}):oa("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:l||!i?jo(qo,{children:[oa(mt,{label:"This week",children:oa(J,{className:"af-h-6 af-w-24"})}),oa(mt,{label:"Today",children:oa(J,{className:"af-h-6 af-w-24"})}),oa(mt,{label:"Needs attention",children:oa(J,{className:"af-h-6 af-w-10"})})]}):oa(qo,{children:(()=>{let g=Vc(i.revenue.d7,i.currency),m=Vc(i.revenue.today,i.currency);return jo(qo,{children:[oa(mt,{label:"This week",detail:g.extra.length>0?oa("div",{children:g.extra.map(p=>oa("div",{children:p},p))}):void 0,children:g.headline}),oa(mt,{label:"Today",detail:m.extra.length>0?oa("div",{children:m.extra.map(p=>oa("div",{children:p},p))}):void 0,children:m.headline}),oa(mt,{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 jo(Ft,{title:"Orders",onBackToWebsite:n,hideBackButton:o,className:r,children:[b,oa(os,{refreshKey:e,initialOrderId:t,onDetailOpenChange:c,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as fn from"react";import{ImageOff as Mp,Package as Up,Search as $p}from"lucide-react";import*as Fn from"react";import{ArrowLeft as Bp,ImageOff as Fp}from"lucide-react";import{jsx as Rn,jsxs as _r}from"react/jsx-runtime";var qc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ds="af-text-xs af-text-muted-foreground",Ii="af-text-sm af-font-medium af-tabular-nums",Lp=3;function Op(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let f=e.min_amount??t?.min_amount??null,d=e.max_amount??t?.max_amount??null;return f!==null&&d!==null?{text:`Buyer chooses (${Y(f,a)} \u2013 ${Y(d,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(n===null||r===null)return{text:"Varies by variant",compareAt:null};let i=n===r?Y(n,a):`${Y(n,a)} \u2013 ${Y(r,a)}`,l=t?.compare_at_amount??null;return{text:i,compareAt:l!==null&&l>r?Y(l,a):null}}function Di({product:e,className:t}){let a=Op(e);return _r("div",{className:t,children:[Rn("span",{className:Ii,children:a.text}),a.compareAt&&Rn("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function Ai({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?Rn(ee,{variant:"destructive",children:"Out of stock"}):t.low_stock?_r(ee,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?Rn(ee,{variant:"secondary",children:"Backorder"}):t.available===null?null:_r(ee,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?Rn(ee,{variant:"warning",children:"Low stock"}):null}function Li(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Oi(e){return e.map(t=>Y(t.amount,t.currency)).join(" + ")}function jc(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${Y(e.min_amount,e.currency)} \u2013 ${Y(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":Y(e.unit_amount,e.currency)}function Wc({variant:e}){let t=e.inventory;if(!t||!t.tracked)return Rn("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?_r("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Rn("span",{className:"af-tabular-nums",children:Math.max(0,a)}),Rn(ee,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?Rn(ee,{variant:"destructive",children:"Out of stock"}):_r("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Rn("span",{className:"af-tabular-nums",children:a}),a<=Lp&&Rn(ee,{variant:"warning",children:"Low"})]})}import{jsx as he,jsxs as _t}from"react/jsx-runtime";function Pr({title:e,children:t,className:a}){return _t("section",{className:G("af-rounded-lg af-border af-p-4",a),children:[he("h4",{className:qc,children:e}),he("div",{className:"af-mt-3",children:t})]})}function Gc({src:e,className:t}){let[a,s]=Fn.useState(!1);return Fn.useEffect(()=>s(!1),[e]),!e||a?he("div",{"aria-hidden":"true",className:G("af-flex af-items-center af-justify-center af-bg-muted",t),children:he(Fp,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):he("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:G("af-object-cover",t)})}function Kc({product:e,showStats:t=!1,onBack:a}){let{api:s}=H(),[n,r]=Fn.useState(null),[i,l]=Fn.useState(!0),[f,d]=Fn.useState(null),[o,c]=Fn.useState(0),[b,g]=Fn.useState(0);Fn.useEffect(()=>{let h=!1;return l(!0),d(null),s.getProduct(e.id).then(S=>{h||r(S)}).catch(S=>{h||d(S instanceof Error?S:new Error("Failed to load product"))}).finally(()=>{h||l(!1)}),()=>{h=!0}},[s,e.id,o]);let m=n?{...e,...n}:e,p=m.images.length>0?m.images:e.images,u=p[b]??p[0],v=Li(m),x=t?m.stats:void 0,R=n?.variants??[],P=R.length>1;return _t("div",{children:[_t("div",{className:"af-mb-6",children:[_t(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[he(Bp,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),_t("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[he("h3",{className:"af-text-xl af-font-semibold af-break-words",children:m.name}),he(ee,{variant:m.active?"success":"secondary",children:m.active?"Active":"Draft"}),he(Ai,{product:m})]}),he(Di,{product:m,className:"af-mt-1"}),!m.active&&he("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),_t("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[_t("div",{className:"af-space-y-2",children:[he(Gc,{src:u,className:"af-h-48 af-w-full af-rounded-md af-border"}),p.length>1&&he("div",{className:"af-flex af-flex-wrap af-gap-2",children:p.map((h,S)=>he("button",{type:"button",onClick:()=>g(S),"aria-label":`Show photo ${S+1} of ${p.length}`,"aria-pressed":S===b,className:G("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",S===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:he(Gc,{src:h,className:"af-h-12 af-w-12 af-rounded-md"})},`${h}-${S}`))})]}),_t("div",{className:"af-space-y-6",children:[m.description&&he(Pr,{title:"Description",children:he("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:m.description})}),i?_t(Pr,{title:"Variants",children:[he("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(h=>_t("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[he(J,{className:"af-h-4 af-w-28"}),he(J,{className:"af-h-4 af-w-20"}),he(J,{className:"af-h-4 af-w-16"})]},h))}),he("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):f?he(Nt,{message:"Couldn't load this product's variants.",onRetry:()=>c(h=>h+1)}):P?he(Pr,{title:`Variants \xB7 ${R.length}`,children:he("div",{className:"af-overflow-x-auto",children:_t(lt,{children:[he(ct,{children:_t(Ce,{children:[he(q,{children:"Variant"}),he(q,{children:"SKU"}),he(q,{className:"af-text-right",children:"Price"}),he(q,{children:"Stock"})]})}),he(dt,{children:R.map(h=>_t(Ce,{children:[_t(j,{className:"af-font-medium",children:[h.title||h.option_values.map(S=>S.value).join(" / ")||"\u2014",!h.active&&he(ee,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),he(j,{className:"af-text-muted-foreground",children:h.sku?he("code",{className:"af-font-mono af-text-xs af-break-all",children:h.sku}):"\u2014"}),_t(j,{className:"af-whitespace-nowrap af-text-right",children:[he("div",{className:Ii,children:jc(h)}),h.compare_at_amount!==null&&h.unit_amount!==null&&h.compare_at_amount>h.unit_amount&&he("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:Y(h.compare_at_amount,h.currency)})]}),he(j,{className:"af-text-sm",children:he(Wc,{variant:h})})]},h.id))})]})})}):null,he(Pr,{title:"Details",children:_t("dl",{className:"af-space-y-2",children:[_t("div",{children:[he("dt",{className:ds,children:"Delivery"}),he("dd",{className:"af-text-sm",children:v==="Digital download"?m.fulfillment.filename??"Digital download":v??"Nothing to deliver"})]}),m.fulfillment.type==="redirect"&&m.fulfillment.url&&_t("div",{children:[he("dt",{className:ds,children:"Sends buyers to"}),he("dd",{className:"af-break-all af-text-sm",children:m.fulfillment.url})]}),_t("div",{children:[he("dt",{className:ds,children:"Shipping address"}),he("dd",{className:"af-text-sm",children:m.collect_shipping_address?"Collected at checkout":"Not collected"})]}),_t("div",{children:[he("dt",{className:ds,children:"Most one buyer can order"}),he("dd",{className:"af-text-sm af-tabular-nums",children:m.max_quantity})]})]})}),x&&he(Pr,{title:"Last 30 days",children:_t("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[_t("div",{children:[he("dt",{className:ds,children:"Units sold"}),he("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),_t("div",{children:[he("dt",{className:ds,children:"Orders"}),he("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),_t("div",{children:[he("dt",{className:ds,children:"Gross"}),he("dd",{className:Ii,children:x.gross.length>0?Oi(x.gross):"\u2014"})]})]})}),he("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 us,jsx as me,jsxs as Pt}from"react/jsx-runtime";var Vp={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Hp=["all","active","draft","low_stock","out_of_stock"];function Zc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function Yc(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function zp(e){return e.inventory?.out_of_stock??!1}function qp(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Yc(e);case"out_of_stock":return zp(e);default:return!0}}function jp({product:e,showStats:t,onOpen:a}){let s=e.images[0],n=t?e.stats:void 0,r=Li(e),i=e.variant_count??0;return Pt("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?me("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):me("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:me(Mp,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Pt("div",{className:"af-space-y-2 af-p-3",children:[Pt("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Pt("div",{className:"af-min-w-0",children:[me("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),me(Di,{product:e,className:"af-mt-0.5"})]}),!e.active&&me(ee,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Pt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[me(Ai,{product:e}),i>1&&Pt(ee,{variant:"outline",children:[i," variants"]}),r&&me(ee,{variant:"outline",children:r})]}),n&&Pt("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Oi(n.gross)}`:""," ",me("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Wp(){return me("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=>Pt("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[me("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),Pt("div",{className:"af-space-y-2 af-p-3",children:[me(J,{className:"af-w-32"}),me(J,{className:"af-w-16"}),me(J,{className:"af-h-5 af-w-24"})]})]},e))})}function Jc({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:n,isLoading:r,error:i,refetch:l}=Zs({includeStats:t,refreshKey:e}),[f,d]=fn.useState(!1),[o,c]=fn.useState(null),[b,g]=fn.useState("all"),{api:m}=H(),p=fn.useCallback(()=>m.exportProductsCsv(),[m]),[u,v]=fn.useState(""),[x,R]=fn.useState("newest"),P=fn.useMemo(()=>{if(!t)return null;let Z=null;for(let U of n)!U.stats||U.stats.units_sold===0||(!Z||U.stats.units_sold>(Z.stats?.units_sold??0))&&(Z=U);return Z},[n,t]),h=fn.useMemo(()=>n.filter(Yc).length,[n]),S=u.trim().toLowerCase(),N=fn.useMemo(()=>{let U=[...n.filter(ae=>qp(ae,b)&&(!S||ae.name.toLowerCase().includes(S)))];return x==="name"?U.sort((ae,le)=>ae.name.localeCompare(le.name)):x==="best_selling"?U.sort((ae,le)=>(le.stats?.units_sold??0)-(ae.stats?.units_sold??0)):U.sort((ae,le)=>Zc(le.created_at)-Zc(ae.created_at)),U},[n,b,S,x]),C=b!=="all"||!!S,w=()=>{g("all"),v("")},k=r||i!==null&&n.length===0,T=me("div",{className:"af-mb-6",children:me("div",{className:G("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:k?Pt(us,{children:[me(mt,{label:"Products",children:me(J,{className:"af-h-6 af-w-10"})}),t?Pt(us,{children:[me(mt,{label:"Best seller",children:me(J,{className:"af-h-6 af-w-28"})}),me(mt,{label:"Low stock",children:me(J,{className:"af-h-6 af-w-10"})})]}):me(mt,{label:"Active",children:me(J,{className:"af-h-6 af-w-10"})})]}):Pt(us,{children:[me(mt,{label:"Products",children:n.length}),t?Pt(us,{children:[me(mt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:P?`${P.stats?.units_sold??0} sold, last 30 days`:void 0,children:P?me("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:P.name}):me("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),me(mt,{label:"Low stock",children:h})]}):me(mt,{label:"Active",children:n.filter(Z=>Z.active).length})]})})}),_=Pt("div",{className:"af-mb-4 af-space-y-3",children:[Pt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[me("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:Hp.map(Z=>me("button",{type:"button","aria-pressed":b===Z,onClick:()=>g(Z),className:G("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===Z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Vp[Z]},Z))}),Pt("div",{className:"af-relative af-w-full af-max-w-xs",children:[me($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"}),me(te,{type:"text",value:u,onChange:Z=>v(Z.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Pt(nn,{value:x,onValueChange:Z=>R(Z),children:[me(ja,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:me(sn,{})}),Pt(Wa,{children:[me(xt,{value:"newest",children:"Newest"}),me(xt,{value:"name",children:"Name A\u2013Z"}),t&&me(xt,{value:"best_selling",children:"Best selling"})]})]}),C&&me(y,{type:"button",variant:"ghost",size:"sm",onClick:w,children:"Clear filters"}),me(va,{fetchCsv:p,filename:"products",label:C?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&n.length===0?me(J,{className:"af-h-4 af-w-28"}):me("p",{className:"af-text-sm af-text-muted-foreground",children:C?`${N.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),z;return o?z=me(Kc,{product:o,showStats:t,onBack:()=>{c(null),l()}},o.id):r&&n.length===0?z=Pt(us,{children:[_,me(Wp,{}),me("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):i&&n.length===0?z=me("div",{className:"af-flex af-justify-center af-py-8",children:me(Nt,{message:"Couldn't load your products.",onRetry:()=>l()})}):n.length===0?z=Pt(ha,{icon:me(Up,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",me("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):z=Pt(us,{children:[_,i&&me("div",{className:"af-mb-4",children:me(Nt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>l()})}),N.length===0?Pt(ha,{children:["No products match these filters.",me("br",{}),me(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:w,children:"Show all products"})]}):me("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:N.map(Z=>me(jp,{product:Z,showStats:t,onOpen:()=>c(Z)},Z.id))})]}),me(Ft,{title:"Products",onBackToWebsite:a,hideBackButton:!!o,className:s,children:f?Pt(us,{children:[me(y,{variant:"ghost",onClick:()=>d(!1),children:"Back to products"}),me(Vs,{})]}):Pt(us,{children:[!o&&me("div",{className:"af-mb-4 af-flex af-justify-end",children:me(y,{variant:"outline",onClick:()=>d(!0),children:"Promo codes"})}),!o&&T,z]})})}import*as Ua from"react";import{ArrowLeft as nd,Check as Gp,ChevronLeft as Xc,ChevronRight as Qc,ClipboardCopy as Kp,Mail as Go,Search as Zp,Users as Yp}from"lucide-react";import*as Ma from"react";function Bi({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=Ma.useState([]),[r,i]=Ma.useState(!0),[l,f]=Ma.useState(null),[d,o]=Ma.useState(0),[c]=Ma.useState(e),[b,g]=Ma.useState(""),[m,p]=Ma.useState(void 0),u=Ma.useRef(0),v=Ma.useCallback(async({afterRemoval:x=!1}={})=>{let R=++u.current;try{i(!0),f(null);let P={limit:c,offset:d*c};b.trim()&&(P.q=b.trim()),m&&(P.source=m);let h=await a.getPeople(P);if(R!==u.current)return;if(x&&h.people.length===0&&d>0){o(d-1);return}n(h.people)}catch(P){if(R!==u.current)return;f(P instanceof Error?P:new Error("Failed to fetch people"))}finally{R===u.current&&i(!1)}},[a,d,c,b,m,t]);return Ma.useEffect(()=>{v()},[v]),{people:s,isLoading:r,error:l,page:d,pageSize:c,hasNextPage:s.length===c,hasPreviousPage:d>0,setPage:o,q:b,setQ:x=>{g(x),o(0)},source:m,setSource:x=>{p(x),o(0)},refetch:()=>v(),refetchAfterRemoval:()=>v({afterRemoval:!0})}}import*as Mn from"react";function Fi(e,{refreshKey:t}={}){let{api:a}=H(),[s,n]=Mn.useState(null),[r,i]=Mn.useState(e!==null),[l,f]=Mn.useState(null),d=Mn.useRef(0),o=Mn.useCallback(async()=>{if(e===null){n(null),i(!1),f(null);return}let c=++d.current;try{i(!0),f(null);let b=await a.getPerson(e);if(c!==d.current)return;n(b)}catch(b){if(c!==d.current)return;f(b instanceof Error?b:new Error("Failed to fetch person"))}finally{c===d.current&&i(!1)}},[a,e,t]);return Mn.useEffect(()=>{o()},[o]),{person:s,isLoading:r,error:l,refetch:o}}import{jsx as I,jsxs as be}from"react/jsx-runtime";var Wo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Jp="af-text-xs af-text-muted-foreground";function Qs(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Ko(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function Xp(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Qp({value:e,label:t}){let[a,s]=Ua.useState(!1);return Xp()?be(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?I(Gp,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):I(Kp,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function ed(e){return be("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&be(ee,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&I(ee,{variant:"secondary",children:"Contact form"})]})}function td(e){return e.name?e.name:e.email?e.email:I("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var eg=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,tg=40;function ag(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),s=t.find(([n,r])=>eg.test(n)&&typeof r=="string"&&r.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=tg).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 ng(e){return e.replace(/_/g," ")}function sg(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function rg({data:e}){let{message:t,rest:a}=ag(e);return t===null&&a.length===0?I("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):be("div",{className:"af-space-y-3",children:[t!==null&&I("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),a.length>0&&I("dl",{className:"af-space-y-1",children:a.map(([s,n])=>be("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[I("dt",{className:G(Jp,"af-w-28 af-shrink-0 af-capitalize"),children:ng(s)}),I("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:sg(n)})]},s))})]})}function sd({formName:e,createdAt:t,data:a,onDelete:s}){return be("div",{className:"af-rounded-md af-border af-p-3",children:[be("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[I(ee,{variant:"outline",children:"Form submission (unverified)"}),e&&I("span",{className:"af-text-xs af-text-muted-foreground",children:e}),I("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Qs(t)}),I($s,{iconOnly:!0,onDelete:s})]}),I(rg,{data:a})]})}function ig(e){return e.charged_total??e.amount_total}function og({email:e,refreshKey:t,onBack:a,onRemoved:s}){let{api:n}=H(),{person:r,isLoading:i,error:l,refetch:f}=Fi(e,{refreshKey:t}),d=async c=>{await n.deleteSubmission(c),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?f():a()},o=Ko(e,r?.submissions[0]?.form_name);return be("div",{children:[be("div",{className:"af-mb-6",children:[be(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[I(nd,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),be("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[be("div",{className:"af-min-w-0",children:[i?I(J,{className:"af-h-7 af-w-48"}):I("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),be("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[I("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),I(Qp,{value:e,label:"Copy email address"})]})]}),I(y,{asChild:!0,children:be("a",{href:o,children:[I(Go,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),i?be("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(c=>be("div",{className:"af-rounded-md af-border af-p-3",children:[I(J,{className:"af-w-40"}),I(J,{className:"af-mt-2 af-w-64"})]},c)),I("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):l||!r?I("div",{className:"af-flex af-justify-center af-py-8",children:I(Nt,{message:"Couldn't load this person.",onRetry:()=>f()})}):be("div",{className:"af-space-y-6",children:[r.customer&&be("div",{children:[I("h4",{className:G(Wo,"af-mb-3"),children:"Customer"}),be("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&be("div",{className:"af-flex af-gap-2",children:[I("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),I("dd",{children:r.customer.name})]}),r.customer.phone&&be("div",{className:"af-flex af-gap-2",children:[I("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),I("dd",{children:r.customer.phone})]}),be("div",{className:"af-flex af-gap-2",children:[I("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),I("dd",{children:Qs(r.customer.created_at)})]})]})]}),r.orders.length>0&&be("div",{children:[I("h4",{className:G(Wo,"af-mb-3"),children:"Purchases"}),I("div",{className:"af-overflow-x-auto",children:be(lt,{children:[I(ct,{children:be(Ce,{children:[I(q,{children:"Order"}),I(q,{children:"Date"}),I(q,{className:"af-text-right",children:"Total"}),I(q,{children:"Status"})]})}),I(dt,{children:r.orders.map(c=>be(Ce,{children:[I(j,{className:"af-whitespace-nowrap af-font-medium",children:Xn(c)}),I(j,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Qs(c.created_at)}),I(j,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:Y(ig(c),c.currency)}),I(j,{children:I(Ss,{status:c.status})})]},c.id))})]})}),I("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&&be("div",{children:[I("h4",{className:G(Wo,"af-mb-3"),children:"Messages"}),I("div",{className:"af-space-y-3",children:r.submissions.map(c=>I(sd,{formName:c.form_name,createdAt:c.created_at,data:c.data,onDelete:()=>d(c.id)},c.id))})]})]})]})}function lg({submissionId:e,onBack:t,onRemoved:a}){let{api:s}=H(),[n,r]=Ua.useState(null),[i,l]=Ua.useState(!0),[f,d]=Ua.useState(null),[o,c]=Ua.useState(0);return Ua.useEffect(()=>{let b=!1;return l(!0),d(null),s.getSubmission(e).then(g=>{b||r(g)}).catch(g=>{b||d(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{b||l(!1)}),()=>{b=!0}},[s,e,o]),be("div",{children:[be("div",{className:"af-mb-6",children:[be(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[I(nd,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),I("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?I(J,{className:"af-mt-1 af-h-4 af-w-32"}):n&&I("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Qs(n.metadata.submitted_at)})]}),i?be("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[I(J,{className:"af-w-40"}),I(J,{className:"af-mt-2 af-w-64"}),I(J,{className:"af-mt-2 af-w-52"}),I("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):f||!n?I("div",{className:"af-flex af-justify-center af-py-8",children:I(Nt,{message:"Couldn't load this submission.",onRetry:()=>c(b=>b+1)})}):be("div",{className:"af-space-y-3",children:[I(sd,{formName:null,createdAt:n.metadata.submitted_at,data:n.data,onDelete:async()=>{await s.deleteSubmission(e),a(),t()}}),I("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 cg={all:"All",customers:"Customers",leads:"Leads"},dg=["all","customers","leads"],ad={all:void 0,customers:"customer",leads:"lead"};function ug({refreshKey:e,onBackToWebsite:t,className:a,maxRows:s,onViewAll:n}){let r=typeof s=="number",{people:i,isLoading:l,error:f,page:d,pageSize:o,hasNextPage:c,hasPreviousPage:b,setPage:g,q:m,setQ:p,source:u,setSource:v,refetch:x,refetchAfterRemoval:R}=Bi({refreshKey:e}),[P,h]=Ua.useState({kind:"list"}),[S,N]=Ua.useState(""),C=u==="customer"?"customers":u==="lead"?"leads":"all",w=W=>{ad[W]!==u&&v(ad[W])},{api:k}=H(),T=Ua.useCallback(()=>k.exportPeopleCsv({...m?{q:m}:{},...u?{source:u}:{}}),[k,m,u]),_=!r||!!n,z=W=>{if(r){n?.();return}W.email?h({kind:"person",email:W.email}):W.submission_id&&h({kind:"submission",submissionId:W.submission_id})},Z=Ua.useRef(!1),U=()=>{Z.current=!0},ae=()=>{h({kind:"list"}),Z.current?(Z.current=!1,R()):x()},le=W=>{let A=W.trim();A!==m&&p(A)},fe=r?i.slice(0,s):i,M;if(P.kind==="person")M=I(og,{email:P.email,refreshKey:e,onBack:ae,onRemoved:U});else if(P.kind==="submission")M=I(lg,{submissionId:P.submissionId,onBack:ae,onRemoved:U});else{let W=be("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[I("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:dg.map(A=>I("button",{type:"button","aria-pressed":C===A,onClick:()=>w(A),className:G("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:cg[A]},A))}),be("div",{className:"af-relative af-w-full af-max-w-xs",children:[I(Zp,{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"}),I(te,{type:"text",value:S,onChange:A=>N(A.target.value),onBlur:()=>le(S),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),le(S))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),m&&I(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{N(""),p("")},children:"Clear search"}),I(va,{fetchCsv:T,filename:"people",className:"af-ml-auto"})]});if(l)M=be("div",{children:[r?null:W,I("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(A=>be("div",{className:"af-rounded-md af-border af-p-3",children:[be("div",{className:"af-flex af-items-center af-justify-between",children:[I(J,{className:"af-h-4 af-w-32"}),I(J,{className:"af-h-4 af-w-16"})]}),I(J,{className:"af-mt-2 af-h-5 af-w-28"}),I(J,{className:"af-mt-2 af-h-3 af-w-56"})]},A))}),I("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:be(lt,{children:[I(ct,{children:be(Ce,{children:[I(q,{children:"Person"}),I(q,{children:"Came from"}),I(q,{children:"Latest message"}),I(q,{children:"Last activity"}),I(q,{className:"af-w-8"}),I(q,{className:"af-w-8"})]})}),I(dt,{"aria-hidden":"true",children:[0,1,2,3,4].map(A=>be(Ce,{children:[I(j,{children:I(J,{className:"af-h-4 af-w-40"})}),I(j,{children:I(J,{className:"af-h-5 af-w-24"})}),I(j,{children:I(J,{className:"af-h-4 af-w-56"})}),I(j,{children:I(J,{className:"af-h-4 af-w-24"})}),I(j,{}),I(j,{})]},A))})]})}),I("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(f)M=be("div",{children:[r?null:W,I("div",{className:"af-flex af-justify-center af-py-8",children:I(Nt,{message:"Couldn't load your leads.",onRetry:()=>x()})})]});else if(fe.length===0&&d===0){let A=!!m||C!=="all";M=be("div",{children:[A&&W,A?I(ha,{children:m?"Nobody matches that search.":C==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):I(zs,{icon:Yp,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(i.length===0)M=be("div",{children:[r?null:W,I(ha,{children:"No more results."}),I("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:be(y,{variant:"outline",size:"sm",onClick:()=>g(d-1),children:[I(Xc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let A=d*o+1,de=d*o+i.length;M=be("div",{children:[r?null:W,I("div",{className:"af-space-y-3 lg:af-hidden",children:fe.map((ce,Le)=>be("div",{onClick:_?()=>z(ce):void 0,className:`af-rounded-md af-border af-p-3${_?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[be("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[be("div",{className:"af-min-w-0",children:[I("button",{type:"button",onClick:ye=>{ye.stopPropagation(),z(ce)},disabled:!_,"aria-label":`Open ${ce.name||ce.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:td(ce)}),ce.name&&ce.email&&I("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ce.email})]}),be("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[I("span",{className:"af-text-xs af-text-muted-foreground",children:Qs(ce.last_activity_at)}),ce.email&&I(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:I("a",{href:Ko(ce.email),onClick:ye=>ye.stopPropagation(),"aria-label":`Email ${ce.email}`,children:I(Go,{className:"af-h-4 af-w-4"})})})]})]}),I("div",{className:"af-mt-2",children:ed(ce)}),ce.latest_message_excerpt&&I("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:ce.latest_message_excerpt})]},ce.email??ce.submission_id??Le))}),I("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:be(lt,{children:[I(ct,{children:be(Ce,{children:[I(q,{children:"Person"}),I(q,{children:"Came from"}),I(q,{children:"Latest message"}),I(q,{children:"Last activity"}),I(q,{className:"af-w-8",children:I("span",{className:"af-sr-only",children:"Reply"})}),I(q,{className:"af-w-8"})]})}),I(dt,{children:fe.map((ce,Le)=>be(Ce,{onClick:_?()=>z(ce):void 0,className:_?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[be(j,{className:"af-max-w-[260px] af-font-medium",children:[I("button",{type:"button",onClick:ye=>{ye.stopPropagation(),z(ce)},disabled:!_,"aria-label":`Open ${ce.name||ce.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:td(ce)}),ce.name&&ce.email&&I("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:ce.email})]}),I(j,{children:ed(ce)}),I(j,{className:"af-max-w-[320px]",children:ce.latest_message_excerpt?I("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:ce.latest_message_excerpt}):I("span",{className:"af-text-muted-foreground",children:"\u2014"})}),I(j,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Qs(ce.last_activity_at)}),I(j,{className:"af-w-8",children:ce.email&&I(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:I("a",{href:Ko(ce.email),onClick:ye=>ye.stopPropagation(),"aria-label":`Email ${ce.email}`,children:I(Go,{className:"af-h-4 af-w-4"})})})}),I(j,{className:"af-w-8 af-text-right",children:I(Qc,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},ce.email??ce.submission_id??Le))})]})}),!r&&be("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[I("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${A}-${de}`}),be("div",{className:"af-flex af-items-center af-gap-2",children:[be(y,{variant:"outline",size:"sm",onClick:()=>g(d-1),disabled:!b,children:[I(Xc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),be(y,{variant:"outline",size:"sm",onClick:()=>g(d+1),disabled:!c,children:["Next",I(Qc,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?I("div",{className:a,children:M}):I(Ft,{title:"Leads",onBackToWebsite:t,hideBackButton:P.kind!=="list",className:a,children:M})}function Mi(e){return I(ug,{...e},e.maxRows==null?"full":"compact")}import*as dd from"react";import{ChevronLeft as rd,ChevronRight as fg,Repeat as mg}from"lucide-react";import*as $a from"react";function Ui({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=$a.useState([]),[r,i]=$a.useState(0),[l,f]=$a.useState(!0),[d,o]=$a.useState(null),[c,b]=$a.useState(0),[g,m]=$a.useState(e),[p,u]=$a.useState(void 0),v=$a.useRef(0),x=$a.useCallback(async()=>{let P=++v.current;try{f(!0),o(null);let h={limit:g,offset:c*g};p&&(h.status=p);let S=await a.getSubscriptions(h);if(P!==v.current)return;n(S.subscriptions),i(S.total)}catch(h){if(P!==v.current)return;o(h instanceof Error?h:new Error("Failed to fetch subscriptions"))}finally{P===v.current&&f(!1)}},[a,c,g,p,t]);$a.useEffect(()=>{x()},[x]);let R=Math.ceil(r/g);return{subscriptions:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<R-1,hasPreviousPage:c>0,setPage:b,setPageSize:P=>{m(P),b(0)},status:p,setStatus:P=>{u(P),b(0)},refetch:x}}import{jsx as ie,jsxs as kt}from"react/jsx-runtime";function id(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 od({sub:e}){return e.status==="canceled"?ie(ee,{variant:"outline",children:"Canceled"}):e.status==="past_due"?ie(ee,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?ie(ee,{variant:"warning",children:"Scheduled to cancel"}):ie(ee,{variant:"success",children:"Active"}):ie(ee,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function pg(e,t){let a=Y(t,e.currency);return e.plan_interval_count===1?`${a} / ${e.plan_interval}`:`${a} every ${e.plan_interval_count} ${e.plan_interval}s`}function ld({sub:e}){let t=e.current_amount!==e.plan_amount;return kt("div",{children:[ie("div",{className:"af-font-medium af-tabular-nums",children:pg(e,e.current_amount)}),t&&kt("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",Y(e.plan_amount,e.currency)]})]})}function cd(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${id(e.current_period_end)}`:"Ends at period end":e.current_period_end?id(e.current_period_end):"\u2014"}function ud({refreshKey:e,onBackToWebsite:t,className:a}){let{subscriptions:s,total:n,isLoading:r,error:i,page:l,pageSize:f,hasNextPage:d,hasPreviousPage:o,setPage:c,status:b,refetch:g}=Ui({refreshKey:e}),{api:m}=H(),p=dd.useCallback(()=>m.exportSubscriptionsCsv(b?{status:b}:{}),[m,b]),u;if(r)u=kt("div",{children:[ie("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(v=>kt("div",{className:"af-rounded-md af-border af-p-3",children:[kt("div",{className:"af-flex af-items-center af-justify-between",children:[ie(J,{className:"af-h-4 af-w-40"}),ie(J,{className:"af-h-4 af-w-20"})]}),ie(J,{className:"af-mt-2 af-h-3 af-w-32"}),ie(J,{className:"af-mt-2 af-h-5 af-w-24"})]},v))}),ie("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:kt(lt,{children:[ie(ct,{children:kt(Ce,{children:[ie(q,{children:"Subscriber"}),ie(q,{children:"Plan"}),ie(q,{className:"af-text-right",children:"Amount"}),ie(q,{children:"Renews"}),ie(q,{children:"Status"})]})}),ie(dt,{"aria-hidden":"true",children:[0,1,2,3,4].map(v=>kt(Ce,{children:[ie(j,{children:ie(J,{className:"af-h-4 af-w-44"})}),ie(j,{children:ie(J,{className:"af-h-4 af-w-32"})}),ie(j,{className:"af-text-right",children:ie(J,{className:"af-ml-auto af-h-4 af-w-24"})}),ie(j,{children:ie(J,{className:"af-h-4 af-w-24"})}),ie(j,{children:ie(J,{className:"af-h-5 af-w-20"})})]},v))})]})}),ie("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(i)u=ie("div",{className:"af-flex af-justify-center af-py-8",children:ie(Nt,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(s.length===0&&l===0)u=ie(ha,{icon:ie(mg,{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)u=kt("div",{children:[ie(ha,{children:"No more results."}),ie("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:kt(y,{variant:"outline",size:"sm",onClick:()=>c(l-1),children:[ie(rd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let v=l*f+1,x=l*f+s.length;u=kt("div",{children:[ie("div",{className:"af-mb-3 af-flex af-justify-end",children:ie(va,{fetchCsv:p,filename:"subscriptions"})}),ie("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(R=>kt("div",{className:"af-rounded-md af-border af-p-3",children:[kt("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[kt("div",{className:"af-min-w-0",children:[ie("div",{className:"af-truncate af-text-sm af-font-medium",children:R.customer_email||ie("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),ie("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:R.plan_title||"Untitled plan"})]}),ie("div",{className:"af-shrink-0 af-text-right",children:ie(ld,{sub:R})})]}),kt("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[ie(od,{sub:R}),R.is_test&&ie(ee,{variant:"outline",children:"Test"}),ie("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:cd(R)})]}),ie(In,{deliveries:R.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},R.id))}),ie("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:kt(lt,{children:[ie(ct,{children:kt(Ce,{children:[ie(q,{children:"Subscriber"}),ie(q,{children:"Plan"}),ie(q,{className:"af-text-right",children:"Amount"}),ie(q,{children:"Renews"}),ie(q,{children:"Status"})]})}),ie(dt,{children:s.map(R=>kt(Ce,{children:[ie(j,{className:"af-max-w-[240px]",children:ie("div",{className:"af-truncate af-font-medium",children:R.customer_email||ie("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),ie(j,{className:"af-max-w-[220px]",children:ie("div",{className:"af-truncate",children:R.plan_title||ie("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),ie(j,{className:"af-whitespace-nowrap af-text-right",children:ie(ld,{sub:R})}),ie(j,{className:"af-whitespace-nowrap af-text-muted-foreground",children:cd(R)}),kt(j,{children:[kt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ie(od,{sub:R}),R.is_test&&ie(ee,{variant:"outline",children:"Test"})]}),ie(In,{deliveries:R.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},R.id))})]})}),kt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[ie("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${v}-${x} of ${n}`}),kt("div",{className:"af-flex af-items-center af-gap-2",children:[kt(y,{variant:"outline",size:"sm",onClick:()=>c(l-1),disabled:!o,children:[ie(rd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),kt(y,{variant:"outline",size:"sm",onClick:()=>c(l+1),disabled:!d,children:["Next",ie(fg,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return ie(Ft,{title:"Subscriptions",onBackToWebsite:t,className:a,children:u})}import*as Vn from"react";import{Loader2 as Rg}from"lucide-react";import*as ya from"react";import*as $i from"react";var _s=typeof window>"u"?$i.useEffect:$i.useLayoutEffect;var Vi=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},gg=(e,t)=>e instanceof Error?e:new Error(t);function vg(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 fd(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function fs({siteId:e,refreshKey:t,onSaveInvoiceSettings:a}){let{api:s}=H(),[n,r]=ya.useState(null),[i,l]=ya.useState(!0),[f,d]=ya.useState(null),o=ya.useRef(null),[c,b]=ya.useState(()=>fd(s,e)),g=c.api!==s||c.siteId!==e,m=c;g&&(m=fd(s,e),b(m),r(null),l(!0),d(null));let p=ya.useRef(m);_s(()=>{p.current!==m&&(p.current=m,o.current=null)},[m]);let u=(w,k)=>p.current===w&&k>w.applied,v=(w,k,T)=>u(w,k)?(w.applied=k,o.current=T,r(T),l(!1),!0):!1,x=async w=>{for(;w.writing;)await w.idle;let k=++w.seq;try{let T=await w.api.getSite(w.siteId);return v(w,k,T)&&d(null),{seq:k,error:null}}catch(T){return{seq:k,error:gg(T,"Failed to load store settings")}}},R=(w,k)=>{let T=async()=>{if(p.current!==w)throw new Error("Not saved: the store switched to another site first.");w.writing=!0,w.idle=new Promise(z=>{w.markIdle=z});try{return await k(++w.seq)}finally{w.writing=!1,w.markIdle()}},_=w.queue.then(T,T);return w.queue=_.catch(()=>{}),_},P=ya.useCallback(async()=>{let w=await x(m);w.error&&u(m,w.seq)&&(d(w.error),l(!1))},[m]);ya.useEffect(()=>{P()},[P,t]);let h=ya.useCallback(w=>R(m,async k=>{let T=await m.api.updateSite(m.siteId,w),{currency_restatement:_,...z}=T;return v(m,k,z)&&d(Z=>Z instanceof Vi?Z:null),T}),[m]),S=ya.useRef(a);_s(()=>{S.current=a});let N=ya.useCallback(async(w,k)=>{await R(m,()=>w());let T=await x(m);return T.error&&u(m,T.seq)&&o.current&&(v(m,T.seq,{...o.current,...k}),d(new Vi(`Saved, but couldn't refresh settings: ${T.error.message}`))),p.current===m?o.current:null},[m]),C=ya.useCallback(w=>{let k=S.current;return N(()=>k(w),vg(w))},[N]);return{site:g?null:n,isLoading:g||i,error:g?null:f,refetch:P,updateSite:h,saveInvoiceSettings:a?C:null}}import*as Qt from"react";import{Loader2 as md}from"lucide-react";import{jsx as mn,jsxs as Un}from"react/jsx-runtime";function Hi(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var _n="af-grid af-gap-1 af-text-sm",pd="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",gd="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 Va({children:e}){return mn("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function kr({children:e}){return mn("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var $n=Qt.forwardRef(function({id:t,title:a,description:s,children:n},r){let i=`af-store-${t}-title`;return Un("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:[Un("div",{className:"af-space-y-1",children:[mn("h3",{id:i,className:"af-text-sm af-font-semibold",children:a}),s&&mn(Va,{children:s})]}),n]})});function zi({label:e,description:t,checked:a,onSave:s,disabled:n=!1,disabledReason:r}){let[i,l]=Qt.useState(null),[f,d]=Qt.useState(null),o=i??a,c=async b=>{l(b),d(null);try{await s(b)}catch(g){d(Hi(g))}finally{l(null)}};return Un("div",{className:"af-space-y-1",children:[Un("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[mn("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":o,checked:o,disabled:n||i!==null,onChange:b=>void c(b.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),Un("span",{className:"af-space-y-0.5",children:[Un("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,i!==null&&mn(md,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&mn(Va,{children:t})]})]}),(n&&r||f)&&Un("div",{className:"af-space-y-1 af-pl-6",children:[n&&r&&mn(Va,{children:r}),f&&mn(kr,{children:f})]})]})}var Yo=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Zo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bg(e,t,a,s=[]){if(!Zo(e)||!Zo(t)||!Zo(a))return{draft:Yo(e,t)?a:e,dropped:[]};let n=[],r={...a};for(let i of Object.keys(a))Yo(e[i],t[i])||(s.includes(i)?n.push(i):r[i]=e[i]);return{draft:r,dropped:n}}function er(e,t){let a=JSON.stringify(e),[s,n]=Qt.useState(e),[r,i]=Qt.useState([]),l=Qt.useRef(e),f=Qt.useRef(e),d=Qt.useRef(s);_s(()=>{f.current=e,d.current=s});let o=Qt.useRef(t?.when);Qt.useEffect(()=>{let b=Object.is(o.current,t?.when)?[]:t?.fields??[];if(o.current=t?.when,Yo(l.current,f.current)&&b.length===0)return;let g=bg(d.current,l.current,f.current,b);l.current=f.current,n(g.draft),g.dropped.length&&i(g.dropped)},[a,t?.when]);let c=Qt.useCallback(b=>{n(b??f.current),i([])},[]);return{draft:s,setDraft:n,dirty:JSON.stringify(s)!==a,reset:c,dropped:r}}function tr({dirty:e,saving:t,error:a,onSave:s,onDiscard:n}){return e?Un("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[Un(y,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&mn(md,{className:"af-animate-spin"}),"Save"]}),mn(y,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:n,children:"Discard"}),a&&mn("p",{role:"alert",className:G("af-text-sm af-text-destructive"),children:a})]}):null}function ar(){let[e,t]=Qt.useState(!1),[a,s]=Qt.useState(null),n=Qt.useCallback(async r=>{t(!0),s(null);try{await r()}catch(i){s(Hi(i))}finally{t(!1)}},[]);return{saving:e,error:a,setError:s,run:n}}function vd({what:e}){return Un(Va,{children:["Only the site owner can change ",e,"."]})}import*as pn from"react";import{ExternalLink as hg,Plus as yg,X as xd}from"lucide-react";import{Fragment as Ng,jsx as Se,jsxs as Ee}from"react/jsx-runtime";var Xo=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function wd({site:e,updateSite:t}){return Ee("div",{className:"af-space-y-4",children:[Se(zi,{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&&Se(zi,{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 bd(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(Et(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(Et(e.free_shipping_over,e.currency))}}function Sd({site:e,updateSite:t,refetch:a,providerSlot:s,currencyChanging:n=!1}){let{draft:r,setDraft:i,dirty:l,reset:f,dropped:d}=er(bd(e),{when:e.currency,fields:["rates","threshold"]}),{saving:o,error:c,setError:b,run:g}=ar(),m=e.currency.toUpperCase(),p=()=>g(async()=>{let v={},x=[...new Set(r.countries.split(/[\s,]+/).map(w=>w.trim().toUpperCase()).filter(Boolean))],R=x.find(w=>!/^[A-Z]{2}$/.test(w));if(R)throw new Error(`"${R}" isn't a two-letter country code (e.g. US, CA).`);let P=x.length?x:null;Xo(P,e.shipping_countries)||(v.shipping_countries=P);let h=[];for(let w of r.rates){let k=w.label.trim(),T=ua(w.amount,e.currency);if(!k)throw new Error("Every rate needs a name.");if(w.amount.trim()===""||T===null)throw new Error(`Enter a price for "${k}" (0 for free).`);h.push({label:k,amount:T})}let S=h.length?h:null;Xo(S,e.shipping_rates)||(v.shipping_rates=S);let N=null;if(r.threshold.trim()!==""&&(N=ua(r.threshold,e.currency),N===null||N===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(N!==e.free_shipping_over&&(v.free_shipping_over=N),Object.keys(v).length===0){f();return}("shipping_rates"in v||"free_shipping_over"in v)&&(v.expected_currency=e.currency);let C;try{C=await t(v)}catch(w){throw w instanceof Yt&&w.details?.code==="currency_changed"&&await a?.(),w}f(bd(C))}),u=(v,x)=>i({...r,rates:r.rates.map((R,P)=>P===v?{...R,...x}:R)});return Ee("fieldset",{disabled:o||n,className:"af-space-y-4",children:[Ee("label",{className:_n,children:["Countries you ship to",Se(te,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:v=>i({...r,countries:v.target.value})}),Se(Va,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),Ee("div",{className:"af-space-y-2",children:[Ee("p",{className:"af-text-sm",children:["Flat shipping rates (",m,")"]}),r.rates.length===0&&Se(Va,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((v,x)=>Ee("div",{className:"af-flex af-items-center af-gap-2",children:[Se(te,{"aria-label":`Rate ${x+1} name`,value:v.label,placeholder:"Standard",onChange:R=>u(x,{label:R.target.value})}),Se(te,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:v.amount,placeholder:"0",className:"af-w-32",onChange:R=>u(x,{amount:R.target.value})}),Se(y,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${x+1}`,onClick:()=>i({...r,rates:r.rates.filter((R,P)=>P!==x)}),children:Se(xd,{})})]},x)),Ee(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[Se(yg,{})," Add rate"]}),Se(Va,{children:"Buyers pick one at checkout. The first is preselected."})]}),Ee("label",{className:_n,children:["Free shipping over (",m,")",Se(te,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:v=>i({...r,threshold:v.target.value})}),Se(Va,{children:"Orders at or above this get the cheapest rate free."})]}),d.length>0&&Ee("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."]}),Se(tr,{dirty:l,saving:o,error:c,onSave:()=>void p(),onDiscard:()=>{b(null),f()}}),s]})}var Jo="exclusive",xg=[{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 wg({href:e,children:t}){return Ee("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,Se(hg,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function Nd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=er(e.tax_behavior??Jo),{saving:i,error:l,setError:f,run:d}=ar(),[o,c]=pn.useState(!1),b=e.stripe_tax_enabled,g=b||o,m=()=>d(async()=>{let v=a;if(v===e.tax_behavior){r();return}let x={tax_behavior:v};v!=="inclusive"&&e.tax_rate_bps!=null&&(x.tax_rate_bps=null);let R=await t(x);r(R.tax_behavior??Jo)}),p=()=>d(async()=>{let v={stripe_tax_enabled:!0,tax_behavior:a};a!=="inclusive"&&e.tax_rate_bps!=null&&(v.tax_rate_bps=null);let x=await t(v);r(x.tax_behavior??Jo),c(!1)}),u=(n||o)&&a!=="inclusive"&&e.tax_rate_bps!=null;return Ee("div",{className:"af-space-y-5",children:[Ee("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[Se("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."}),Se("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."}),Se("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:xg.map(v=>Se("li",{children:Se(wg,{href:v.href,children:v.label})},v.href))})]}),Se(zi,{label:"Stripe automatic tax",description:b?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:g,onSave:async v=>{if(o){c(!1),f(null),r();return}if(v&&!e.tax_behavior){c(!0);return}return t({stripe_tax_enabled:v})}}),g&&Ee("fieldset",{disabled:i,className:"af-space-y-4 af-pl-6",children:[Ee("label",{className:_n,children:["Do your prices already include tax?",Ee("select",{"aria-label":"Your prices",className:pd,value:a,onChange:v=>s(v.target.value),children:[Se("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),Se("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),Se(Va,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),u&&Ee(Va,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),o?Ee("div",{className:"af-space-y-2",children:[Ee("div",{className:"af-flex af-gap-2",children:[Se(y,{type:"button",size:"sm",disabled:i,onClick:()=>void p(),children:"Turn on"}),Se(y,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>{c(!1),f(null),r()},children:"Cancel"})]}),l&&Se(kr,{children:l})]}):Se(tr,{dirty:n,saving:i,error:l,onSave:()=>void m(),onDiscard:()=>{f(null),r()}})]})]})}function hd(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function Rd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=er(hd(e)),{saving:i,error:l,setError:f,run:d}=ar(),o=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),c=()=>d(async()=>{let b={},g=null;if(o&&a.rate.trim()!==""){let v=Number(a.rate);if(!Number.isFinite(v)||v<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(v*100)}o&&g!==e.tax_rate_bps&&(b.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let m=a.taxId.trim()||null;m!==e.tax_id&&(b.tax_id=m);let p=a.label.trim()||null;if(p!==e.tax_label&&(b.tax_label=p),Object.keys(b).length===0){r();return}let u=await t(b);r(hd(u))});return Ee("fieldset",{disabled:i,className:"af-space-y-4",children:[Ee("label",{className:_n,children:["Tax rate (%)",Se(te,{"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})}),Se(Va,{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."})]}),Ee("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[Ee("label",{className:_n,children:["Tax ID",Se(te,{"aria-label":"Tax ID",value:a.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...a,taxId:b.target.value})})]}),Ee("label",{className:_n,children:["Tax label",Se(te,{"aria-label":"Tax label",value:a.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...a,label:b.target.value})})]})]}),Se(tr,{dirty:n,saving:i,error:l,onSave:()=>void c(),onDiscard:()=>{f(null),r()}})]})}function _d({site:e,updateSite:t,onChangeStart:a}){let[s,n]=pn.useState(e.currency.toUpperCase()),[r,i]=pn.useState(!1),[l,f]=pn.useState(!1),[d,o]=pn.useState(null),c=e.currency.toUpperCase(),b=pn.useRef(c);pn.useEffect(()=>{b.current!==c&&(n(v=>v===b.current?c:v),b.current=c)},[c]);let g=s.trim().toUpperCase(),m=g!==c,p=/^[A-Z]{3}$/.test(g),u=async()=>{f(!0);let v=a?.(),x=!1;o(null);try{let R=await t({currency:g.toLowerCase()});x=!0;let P=R.currency_restatement;P&&!P.applied?o(P.reason?`Not changed: ${P.reason}.`:"The currency was not changed."):(n(R.currency.toUpperCase()),b.current=R.currency.toUpperCase()),i(!1)}catch(R){o(Hi(R))}finally{f(!1),v?.(x)}};return Ee("div",{className:"af-space-y-3",children:[Ee("div",{className:"af-flex af-items-end af-gap-2",children:[Ee("label",{className:_n,children:["Store currency",Se(te,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:l||r,onChange:v=>{n(v.target.value),o(null)}})]}),m&&!r&&Ee(Ng,{children:[Se(y,{type:"button",size:"sm",disabled:!p,onClick:()=>i(!0),children:"Change currency"}),Se(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>{n(c),o(null)},children:"Discard"})]})]}),Se(Va,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&Ee("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[Ee("p",{className:"af-text-sm",children:["Change the store currency from ",c," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",Y(2e3,c)," becomes ",Y(2e3,g),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),Ee("div",{className:"af-flex af-gap-2",children:[Se(y,{type:"button",size:"sm",disabled:l,onClick:()=>void u(),children:"Confirm change"}),Se(y,{type:"button",size:"sm",variant:"ghost",disabled:l,onClick:()=>i(!1),children:"Cancel"})]})]}),d&&Se(kr,{children:d})]})}function yd(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function Sg(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 Pd({site:e,save:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=er(yd(e)),{saving:i,error:l,setError:f,run:d}=ar();if(!t)return Ee("div",{className:"af-space-y-2 af-text-sm",children:[Ee("p",{children:["Due ",e.invoice_due_days," days after sending"]}),Ee("p",{children:["Reminders: ",Sg(e.invoice_reminder_schedule)]}),Ee("p",{children:["Footer: ",e.invoice_footer||"None"]}),Se(vd,{what:"invoice defaults"})]});let o=()=>d(async()=>{let c={},b=Number(a.dueDays);if(a.dueDays.trim()===""||!Number.isInteger(b)||b<0||b>90)throw new Error("Due days must be a whole number from 0 to 90.");b!==e.invoice_due_days&&(c.due_days=b);let m=a.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(m.some(x=>!Number.isInteger(x)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let p=[...new Set(m)].sort((x,R)=>x-R);Xo(p,e.invoice_reminder_schedule)||(c.reminder_schedule=p);let u=a.footer.trim()||null;if(u!==e.invoice_footer&&(c.footer=u),Object.keys(c).length===0){r();return}let v=await t(c);r(v?yd(v):void 0)});return Ee("fieldset",{disabled:i,className:"af-space-y-4",children:[Ee("label",{className:_n,children:["Days until due",Se(te,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:a.dueDays,onChange:c=>s({...a,dueDays:c.target.value})})]}),Ee("label",{className:_n,children:["Reminder schedule",Se(te,{"aria-label":"Reminder schedule",value:a.reminders,placeholder:"Off",onChange:c=>s({...a,reminders:c.target.value})}),Se(Va,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),Ee("label",{className:_n,children:["Invoice footer",Se("textarea",{"aria-label":"Invoice footer",className:gd,maxLength:300,value:a.footer,onChange:c=>s({...a,footer:c.target.value})})]}),Se(tr,{dirty:n,saving:i,error:l,onSave:()=>void o(),onDiscard:()=>{f(null),r()}})]})}function kd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=er(e.default_email_recipients),{saving:i,error:l,setError:f,run:d}=ar(),[o,c]=pn.useState(""),[b,g]=pn.useState(null),m=()=>{let u=o.trim().toLowerCase();if(u){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u)){g("Enter a valid email address.");return}if(a.some(v=>v.toLowerCase()===u)){g("Already added.");return}s([...a,u]),c(""),g(null)}},p=()=>d(async()=>{let u=await t({default_email_recipients:a});r(u.default_email_recipients)});return Ee("fieldset",{disabled:i,className:"af-space-y-3",children:[Ee("div",{className:"af-flex af-flex-wrap af-gap-2",children:[a.map(u=>Ee(ee,{variant:"secondary",className:"af-gap-1",children:[u,Se("button",{type:"button","aria-label":`Remove ${u}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(a.filter(v=>v!==u)),children:Se(xd,{className:"af-h-3 af-w-3"})})]},u)),a.length===0&&Se("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),Ee("div",{className:"af-flex af-gap-2",children:[Se(te,{"aria-label":"Add notification email",type:"email",value:o,placeholder:"Add email address",onChange:u=>{c(u.target.value),g(null)},onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),m())}}),Se(y,{type:"button",variant:"outline",disabled:!o.trim(),onClick:m,children:"Add"})]}),b&&Se(kr,{children:b}),Se(tr,{dirty:n,saving:i,error:l,onSave:()=>void p(),onDiscard:()=>{f(null),r()}})]})}import{jsx as en,jsxs as Cd}from"react/jsx-runtime";function Td({siteId:e,refreshKey:t,section:a,shippingProviderSlot:s,onConnectStripe:n,onUpgradePlan:r,className:i}){let{site:l,isLoading:f,error:d,refetch:o,updateSite:c}=fs({siteId:e,refreshKey:t}),b=Vn.useRef(o),g=Vn.useRef(e);_s(()=>{b.current=o,g.current=e});let m=Vn.useRef({}),[p,u]=Vn.useState([]),v=p.some(S=>S.siteId===e),x=Vn.useCallback(()=>{let S={siteId:e},N=b.current;return u(C=>[...C,S]),C=>{let w=()=>u(T=>T.filter(_=>_!==S));!(g.current===S.siteId)||C&&b.current===N?w():b.current().finally(w)}},[e]),R=S=>N=>{m.current[S]=N},P=l!==null&&l.payments_active;if(Vn.useEffect(()=>{if(!P||!a)return;let S=m.current[a];S&&(S.scrollIntoView?.({behavior:"smooth",block:"start"}),S.focus({preventScroll:!0}))},[P,a]),f)return Cd("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[en(Rg,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!l)return en("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d?.message??"Could not load store settings."});if(!l.payments_active)return en(Ks,{className:i,onConnectStripe:n,onUpgradePlan:r,whenActive:en("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let h={site:l,updateSite:c,refetch:o};return Cd("div",{className:`af-space-y-6 ${i??""}`,children:[d&&en("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d.message}),en($n,{ref:R("checkout"),id:"checkout",title:"Checkout",children:en(wd,{...h})}),en($n,{ref:R("shipping"),id:"shipping",title:"Shipping",children:en(Sd,{...h,providerSlot:s,currencyChanging:v})}),en($n,{ref:R("tax"),id:"tax",title:"Tax",children:en(Nd,{...h})}),en($n,{ref:R("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:en(_d,{...h,onChangeStart:x})})]},e)}import{Loader2 as _g}from"lucide-react";import{jsx as Ps,jsxs as Ed}from"react/jsx-runtime";function qi({siteId:e,refreshKey:t,onSaveInvoiceSettings:a,className:s}){let{site:n,isLoading:r,error:i,updateSite:l,refetch:f,saveInvoiceSettings:d}=fs({siteId:e,refreshKey:t,onSaveInvoiceSettings:a});return r?Ed("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ps(_g,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):n?Ed("div",{className:`af-space-y-6 ${s??""}`,children:[i&&Ps("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}),Ps($n,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:Ps(Pd,{site:n,save:d})}),Ps($n,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:Ps(Rd,{site:n,updateSite:l,refetch:f})})]},e):Ps("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 Pg}from"lucide-react";import{jsx as Cr,jsxs as Id}from"react/jsx-runtime";function Dd({siteId:e,refreshKey:t,className:a}){let{site:s,isLoading:n,error:r,updateSite:i,refetch:l}=fs({siteId:e,refreshKey:t});return n?Id("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Cr(Pg,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?Id("div",{className:`af-space-y-3 ${a??""}`,children:[r&&Cr("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}),Cr($n,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:Cr(kd,{site:s,updateSite:i,refetch:l})})]},e):Cr("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 nr from"react";import{Fragment as Ad,jsx as xa,jsxs as Tr}from"react/jsx-runtime";function Ld({refreshKey:e,initialInvoiceId:t,onBackToWebsite:a,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,siteId:i,onSaveInvoiceSettings:l,className:f}){let{aggregates:d,isLoading:o,error:c,refetch:b}=js({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=Ys({refreshKey:e}),{api:m}=H(),p=g.filters,u=nr.useCallback(()=>m.exportRetainersCsv(p),[m,p]),[v,x]=nr.useState(!1),[R,P]=nr.useState(null),[h,S]=nr.useState(!1),N=xa("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:c||!o&&!d?Tr("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. ",xa(y,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):o||!d?Tr(Ad,{children:[xa(mt,{label:"Outstanding",children:xa(J,{className:"af-h-6 af-w-24"})}),xa(mt,{label:"Overdue",children:xa(J,{className:"af-h-6 af-w-24"})}),xa(mt,{label:"Paid this month",children:xa(J,{className:"af-h-6 af-w-24"})})]}):Tr(Ad,{children:[xa(mt,{label:"Outstanding",detail:`${d.outstanding.count} open`,children:Y(d.outstanding.amount,d.currency)}),xa(mt,{label:"Overdue",detail:d.overdue.count===0?"Nothing overdue":`${d.overdue.count} overdue`,valueClassName:d.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:Y(d.overdue.amount,d.currency)}),xa(mt,{label:"Paid this month",detail:`${d.paid_this_month.count} paid`,children:Y(d.paid_this_month.amount,d.currency)})]})});return Tr(Ft,{title:"Invoices",onBackToWebsite:a,hideBackButton:v,className:f,children:[N,i&&!v&&Tr("div",{className:"af-mb-6",children:[xa(y,{type:"button",variant:"outline",size:"sm","aria-expanded":h,"aria-controls":"af-invoice-settings",onClick:()=>S(C=>!C),children:"Invoice settings"}),h&&xa("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:xa(qi,{siteId:i,refreshKey:e,onSaveInvoiceSettings:l})})]}),!v&&xa(Gs,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:R?.id??null,onShowCycles:C=>P(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:u}),xa(cs,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:x,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,retainerFilter:R?{id:R.id,label:`${R.customer_name??R.customer_email??"Recurring invoices"} \u2014 ${R.description}`}:null,onClearRetainerFilter:()=>P(null)})]})}import*as ta from"react";import*as gn from"react";function Kt(e,t,a){let[s,n]=gn.useState(null),[r,i]=gn.useState(!0),[l,f]=gn.useState(null),d=gn.useRef(0),o=gn.useRef(e);o.current=e;let c=gn.useRef(a);c.current=a;let b=gn.useCallback(async()=>{let m=++d.current,p=c.current;i(!0),f(null);try{let u=await o.current();m===d.current&&n({scope:p,value:u})}catch(u){m===d.current&&f(u instanceof Error?u:new Error("Request failed"))}finally{m===d.current&&i(!1)}},[]);gn.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 Qo={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"]},importContacts:{method:"POST",path:"/sites/{siteId}/contacts/import"},exportContacts:{method:"GET",path:"/sites/{siteId}/contacts/export"},createTag:{method:"POST",path:"/sites/{siteId}/contact-tags"},updateTag:{method:"PATCH",path:"/sites/{siteId}/contact-tags/{tagId}",params:["tagId"]},bulkTagContacts:{method:"POST",path:"/sites/{siteId}/contacts/tags"},unsubscribeContact:{method:"POST",path:"/sites/{siteId}/contacts/{contactId}/unsubscribe",params:["contactId"]},updateSettings:{method:"PUT",path:"/sites/{siteId}/marketing"},setFormPurpose:{method:"PATCH",path:"/forms/{formId}",params:["formId"]},createWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps"},updateWelcomeStep:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},deleteWelcomeStep:{method:"DELETE",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},publishWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}/publish",params:["stepId"]},activateWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/activate"},pauseWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/pause"},updateWelcome:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome"},setRecoveryStep:{method:"PUT",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},publishRecoveryStep:{method:"POST",path:"/sites/{siteId}/marketing/recovery/steps/{step}/publish",params:["step"]},deleteRecoveryStep:{method:"DELETE",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},activateRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/activate"},pauseRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/pause"}};function kg(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Qo,e)}function Cg(e,t,a){let s=Qo[e],n="params"in s?s.params:[],r={...a};delete r.siteId;let i=s.path.replace("{siteId}",encodeURIComponent(t));for(let f of n){let d=r[f];if(typeof d!="string"&&typeof d!="number")throw new Error(`${e} needs ${f}`);i=i.replace(`{${f}}`,encodeURIComponent(String(d))),delete r[f]}let l=s.method==="GET"||s.method==="DELETE"?void 0:r;return{method:s.method,path:i,body:l}}var Od={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."},Er=new Set(["sending_not_enabled","domain_not_verified","dmarc_missing","postal_address_missing"]);function sr(e){return e?Od[e]??"Sending is not available right now.":null}import*as Hn from"react";var rr=50;function ji({siteId:e,q:t="",offset:a=0,refreshKey:s=0}){let{api:n}=H(),r=Kt(()=>n.getMarketingContacts(e,{q:t||void 0,limit:rr,offset:a}),`${e}|${t}|${a}|${s}`,e),i=Kt(()=>n.getMarketingContactStats(e),`${e}|${s}`,e),l=Kt(()=>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 lr from"react";import*as Pn from"react";import{Fragment as Tg,jsx as Ir,jsxs as Fd}from"react/jsx-runtime";var Dr=e=>`af-email-settings-${e}`,el=Pn.createContext(null);function nt(){let e=Pn.useContext(el);if(!e)throw new Error("Email panels render inside EmailView");return e}function Bd(e){let{setInlineEditOpen:t}=nt();Pn.useEffect(()=>(t(e),()=>t(!1)),[e,t])}function tl(e){return e.status==="sending"||e.status==="sent"||(e.status==="cancelled"||e.status==="failed")&&e.recipients.consumed>0}function Wi(e,t){return new Set([...e.filter(a=>a.sent).map(a=>a.id),...t.filter(tl).flatMap(a=>a.draft_id?[a.draft_id]:[])])}function ks({onClick:e,children:t}){return Ir("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function ir({reason:e}){let{openSetup:t,onOpenStoreSettings:a}=nt(),s=e&&Er.has(e)?Ir(ks,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&a?Ir(ks,{onClick:a,children:"Open Store settings"}):null;return s&&Fd(Tg,{children:[" ",s]})}function Gi(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 vn(e,t){return Gi(e)===t?!0:e instanceof Error&&e.message.includes(t)}function or(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function Dt(){let{onOrgAction:e}=nt(),[t,a]=Pn.useState(!1),[s,n]=Pn.useState(null),r=Pn.useCallback(async(i,l={})=>{a(!0),n(null);try{return{ok:!0,result:await e(i,l)}}catch(f){return n(or(f)),{ok:!1,error:f}}finally{a(!1)}},[e]);return{busy:t,error:s,setError:n,run:r}}function Ne({tone:e="info",children:t,className:a}){return Ir("div",{role:e==="error"?"alert":"status",className:G("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 tn({children:e,action:t,id:a}){return Fd("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:[Ir("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function Fe(e){return e.toLocaleString("en-US")}import{jsx as an,jsxs as ms}from"react/jsx-runtime";var al="I confirm that everyone in this file agreed to receive marketing email from my business.",Eg={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 Ki({onImported:e}){let{canWrite:t}=nt(),[a,s]=lr.useState(""),[n,r]=lr.useState(null),[i,l]=lr.useState(""),[f,d]=lr.useState(!1),[o,c]=lr.useState(null),b=Dt(),g=async()=>{if(!f||!a.trim())return;let m=i.split(",").map(u=>u.trim()).filter(Boolean),p=await b.run("importContacts",{csv:a,attested:!0,...m.length?{tags:m}:{}});if(p.ok){let u=p.result;c(u),e?.(u)}};if(o){let m=new Map;for(let p of o.skipped_rows)m.set(p.reason,(m.get(p.reason)??0)+1);return ms("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[an("div",{className:"af-font-medium",children:"Import finished"}),ms("p",{className:"af-text-sm",children:[Fe(o.rows)," rows: ",Fe(o.created)," new, ",Fe(o.updated)," updated, ",Fe(o.skipped)," skipped."]}),m.size>0&&an("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...m].map(([p,u])=>ms("li",{children:[Fe(u)," ",Eg[p]??p]},p))}),an("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),an(y,{type:"button",size:"sm",variant:"outline",onClick:()=>{c(null),s(""),r(null),d(!1)},children:"Import another file"})]})}return ms("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:m=>{m.preventDefault(),g()},children:[ms("label",{className:"af-block af-space-y-1",children:[an("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),an("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async m=>{let p=m.target.files?.[0];p&&(r(p.name),s(await p.text()))}}),an("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&&an("span",{className:"af-block af-text-xs",children:n})]}),ms("label",{className:"af-block af-space-y-1",children:[an("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),an(te,{"aria-label":"Tags for imported contacts",value:i,onChange:m=>l(m.target.value)})]}),ms("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[an("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:f,onChange:m=>d(m.target.checked)}),ms("span",{children:[al," Importing people who didn't agree can get your sending paused."]})]}),b.error&&an(Ne,{tone:"error",children:b.error}),an(y,{type:"submit",size:"sm",disabled:!t||!f||!a.trim()||b.busy,children:b.busy?"Importing\u2026":"Import contacts"})]})}import{Fragment as Ud,jsx as De,jsxs as Mt}from"react/jsx-runtime";var Ig={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function Md(){let{siteId:e,canWrite:t,refreshKey:a}=nt(),[s,n]=Hn.useState(""),[r,i]=Hn.useState(""),[l,f]=Hn.useState(0),[d,o]=Hn.useState(0),[c,b]=Hn.useState(new Set),[g,m]=Hn.useState(!1),p=ji({siteId:e,q:r,offset:l,refreshKey:d+a}),u=Dt(),v=()=>o(N=>N+1),x=p.stats.data,R=p.contacts.data,P=p.tags.data??[],h=x?x.growth.slice(-4).reduce((N,C)=>N+C.new_subscribers,0):null,S=async()=>{let N=await u.run("exportContacts",{});if(!N.ok||typeof N.result!="string"||typeof document>"u")return;let C=URL.createObjectURL(new Blob([N.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 Mt("div",{children:[Mt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[De(mt,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:x?Fe(x.total):De(J,{className:"af-h-6 af-w-16"})}),De(mt,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:x?Fe(x.mailable):De(J,{className:"af-h-6 af-w-16"})}),De(mt,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:h!==null?Fe(h):De(J,{className:"af-h-6 af-w-16"})})]}),Mt("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[Mt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:N=>{N.preventDefault(),f(0),i(s.trim())},children:[De(te,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:s,onChange:N=>n(N.target.value)}),De(y,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),De(y,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>m(N=>!N),children:g?"Close import":"Import"}),De(y,{type:"button",variant:"outline",size:"sm",disabled:!t||u.busy,onClick:()=>void S(),children:"Export"})]}),g&&De("div",{className:"af-mt-3",children:De(Ki,{onImported:v})}),u.error&&De(Ne,{tone:"error",className:"af-mt-2",children:u.error}),t&&c.size>0&&De(Ag,{tags:P.filter(N=>!N.system),count:c.size,busy:u.busy,onApply:async(N,C)=>{(await u.run("bulkTagContacts",{action:N,tag_id:C,contact_ids:[...c]})).ok&&(b(new Set),v())}}),De("div",{className:"af-mt-3",children:p.contacts.error?De(Nt,{message:"Couldn't load contacts.",onRetry:()=>void p.contacts.refetch()}):R?R.contacts.length===0?De(ha,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):Mt(Ud,{children:[De("ul",{className:"af-divide-y af-rounded-md af-border",children:R.contacts.map(N=>De(Dg,{contact:N,canWrite:t,busy:u.busy,selected:c.has(N.id),onSelect:C=>b(w=>{let k=new Set(w);return C?k.add(N.id):k.delete(N.id),k}),onUnsubscribe:async()=>{(await u.run("unsubscribeContact",{contactId:N.id})).ok&&v()}},N.id))}),Mt("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[Mt("span",{children:[Fe(l+1),"\u2013",Fe(l+R.contacts.length)," of ",Fe(R.total)]}),Mt("div",{className:"af-flex af-gap-2",children:[De(y,{type:"button",variant:"ghost",size:"sm",disabled:l===0,onClick:()=>f(Math.max(0,l-rr)),children:"Previous"}),De(y,{type:"button",variant:"ghost",size:"sm",disabled:l+R.contacts.length>=R.total,onClick:()=>f(l+rr),children:"Next"})]})]})]}):De(J,{className:"af-h-24 af-w-full"})}),De(Lg,{tags:P,canWrite:t,onChanged:v})]})}function Dg({contact:e,canWrite:t,busy:a,selected:s,onSelect:n,onUnsubscribe:r}){return Mt("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&De("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:s,onChange:i=>n(i.target.checked)}),Mt("div",{className:"af-min-w-0 af-flex-1",children:[Mt("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?Mt("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),Mt("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[De(ee,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":Ig[e.status]}),e.tags.map(i=>De(ee,{variant:"outline",children:i.label},i.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&De(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:r,children:"Unsubscribe"})]})}function Ag({tags:e,count:t,busy:a,onApply:s}){let[n,r]=Hn.useState("");return Mt("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:[Mt("span",{children:[Fe(t)," selected"]}),Mt("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:[De("option",{value:"",children:"Choose a tag\u2026"}),e.map(i=>De("option",{value:i.id,children:i.label},i.id))]}),De(y,{type:"button",size:"sm",variant:"outline",disabled:!n||a,onClick:()=>s("add",n),children:"Add tag"}),De(y,{type:"button",size:"sm",variant:"ghost",disabled:!n||a,onClick:()=>s("remove",n),children:"Remove tag"})]})}function Lg({tags:e,canWrite:t,onChanged:a}){let[s,n]=Hn.useState(""),[r,i]=Hn.useState(null),l=Dt();return Mt("div",{children:[De(tn,{children:"Tags"}),e.length===0?De("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."}):De("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(f=>De("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===f.id?Mt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async d=>{d.preventDefault(),(await l.run("updateTag",{tagId:f.id,label:r.label.trim()})).ok&&(i(null),a())},children:[De(te,{"aria-label":`New name for ${f.label}`,value:r.label,onChange:d=>i({id:f.id,label:d.target.value})}),De(y,{type:"submit",size:"sm",disabled:!r.label.trim()||l.busy,children:"Save"})]}):Mt(Ud,{children:[Mt("span",{children:[f.label," ",Mt("span",{className:"af-text-muted-foreground",children:["\xB7 ",Fe(f.total)," contacts, ",Fe(f.mailable)," can be emailed"]})]}),t&&!f.system&&De(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>i({id:f.id,label:f.label}),children:"Rename"})]})},f.id))}),t&&Mt("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async f=>{f.preventDefault(),(await l.run("createTag",{label:s.trim()})).ok&&(n(""),a())},children:[De(te,{"aria-label":"New tag",placeholder:"New tag",value:s,maxLength:100,onChange:f=>n(f.target.value)}),De(y,{type:"submit",size:"sm",variant:"outline",disabled:!s.trim()||l.busy,children:"Add tag"})]}),l.error&&De(Ne,{tone:"error",className:"af-mt-2",children:l.error})]})}import*as wt from"react";import{ArrowLeft as jg}from"lucide-react";function cr({siteId:e,refreshKey:t=0}){let{api:a}=H();return Kt(()=>a.getBroadcasts(e),`${e}|${t}`,e)}function dr({siteId:e,kind:t,refreshKey:a=0}){let{api:s}=H();return Kt(()=>s.getEmailDrafts(e,t),`${e}|${t??""}|${a}`,`${e}|${t??""}`)}import*as ze from"react";var Ar=e=>typeof e=="number"&&Number.isFinite(e);function nl(e){if(!e||typeof e!="object")return null;let t=e;return Ar(t.x)&&Ar(t.y)&&Ar(t.width)&&Ar(t.height)?{x:t.x,y:t.y,width:t.width,height:t.height}:null}var sl=(e,t)=>Number.isInteger(e)&&e>=0&&e<t;function $d(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=nl(s.rect);return sl(s.section,a)&&n?{type:"hover",section:s.section,rect:n}:null}case"focus":case"open":{let n=nl(s.rect);return sl(s.section,a)&&n?{type:s.type,section:s.section,rect:n}:null}case"layout":{if(!Ar(s.height)||!Array.isArray(s.sections))return null;let n=s.sections.flatMap(r=>{let i=r,l=i?nl(i.rect):null;return i&&sl(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 Lr=(e,t,a)=>Math.min(Math.max(e,t),Math.max(t,a));function rl(e,t){let a=Lr(e.x,0,t.width),s=Lr(e.y,0,t.height);return{x:a,y:s,width:Lr(e.width,0,t.width-a),height:Lr(e.height,0,t.height-s)}}var Or={min:240,max:6e3,initial:480},Vd=e=>Lr(Math.ceil(e),Or.min,Or.max);import*as Cs from"react";import{jsx as wa,jsxs as kn}from"react/jsx-runtime";var il={heading:"Heading",text:"Text",button:"Button",image:"Image",cart:"Cart"};function zd(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 ol(e){switch(e.type){case"heading":case"text":return e.text;case"button":return`${e.label}
|
|
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 ta=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 c;try{c=await l.json()}catch{}throw new ta(li(c?.error,l.status),l.status,c)}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 ta(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(),c=`/api/v1/forms/${n}/submissions${l?`?${l}`:""}`;return a(c)},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,c=i.id??i.name,d=`${t}/api/v1/submissions/${n}/attachments/${encodeURIComponent(c)}`,o=await fetch(d,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let m;try{m=await o.json()}catch{}throw new ta(li(m?.error,o.status),o.status,m)}let u=await o.blob(),b=URL.createObjectURL(u),v=document.createElement("a");v.href=b,v.download=l,document.body.appendChild(v),v.click(),document.body.removeChild(v),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 c;try{c=await l.json()}catch{}throw new ta(li(c?.error,l.status),l.status,c)}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)}),c=us();return c&&l.set("timezone",c),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 _f}from"react/jsx-runtime";var vc=fs.createContext(null);function Nf(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 Rf({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:n}){let r=fs.useMemo(()=>Nf(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:_f("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 Am,Settings as Dm,Inbox as Om}from"lucide-react";import*as ci from"react";import*as _n from"@radix-ui/react-tabs";import{clsx as kf}from"clsx";import{extendTailwindMerge as Pf}from"tailwind-merge";var Cf=Pf({prefix:"af-"});function W(...e){return Cf(kf(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 Tf}from"@radix-ui/react-slot";import{cva as Ef}from"class-variance-authority";import{jsx as Af}from"react/jsx-runtime";var If=Ef("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)=>Af(s?Tf:"button",{className:W(If({variant:t,size:a,className:e})),ref:r,...n}));y.displayName="Button";import{Inbox as hc,Settings as Lf}from"lucide-react";import*as ts from"react";import{jsx as es}from"react/jsx-runtime";var lt=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})}));lt.displayName="Table";var ct=ts.forwardRef(({className:e,...t},a)=>es("thead",{ref:a,className:W("[&_tr]:af-border-b",e),...t}));ct.displayName="TableHeader";var dt=ts.forwardRef(({className:e,...t},a)=>es("tbody",{ref:a,className:W("[&_tr:last-child]:af-border-0",e),...t}));dt.displayName="TableBody";var Df=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}));Df.displayName="TableFooter";var Ee=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}));Ee.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 Of=ts.forwardRef(({className:e,...t},a)=>es("caption",{ref:a,className:W("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Of.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 u=await e.getForms();a(u)}catch(u){i(u instanceof Error?u:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);Cn.useEffect(()=>{l()},[l]);let c=Cn.useCallback(async u=>{let b=await e.createForm(u);return a(v=>[...v,b]),b},[e]),d=Cn.useCallback(async(u,b)=>{let v=await e.updateForm(u,b);return a(m=>m.map(g=>g.id===u?v:g)),v},[e]),o=Cn.useCallback(async u=>{await e.deleteForm(u),a(b=>b.filter(v=>v.id!==u))},[e]);return{forms:t,isLoading:s,error:r,refetch:l,createForm:c,updateForm:d,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(lt,{children:[Fa(ct,{children:as(Ee,{children:[Fa(K,{children:"Name"}),Fa(K,{className:"af-text-right",children:"Actions"})]})}),Fa(dt,{children:a.map(r=>as(Ee,{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(Lf,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}import{AlertTriangle as $f}from"lucide-react";import{cva as Bf}from"class-variance-authority";import{jsx as Mf}from"react/jsx-runtime";var Ff=Bf("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 te({className:e,variant:t,...a}){return Mf("div",{className:W(Ff({variant:t}),e),...a})}import{jsx as Ts,jsxs as fi}from"react/jsx-runtime";var Uf={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 Vf(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($f,{"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=Vf(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:Uf[n.kind]??"Email notification"}),Ts(te,{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 om,ChevronLeft as lm,ChevronRight as cm,Eye as dm,Inbox as um,Paperclip as fm}from"lucide-react";import*as ms from"react";import*as ze from"@radix-ui/react-select";import{Check as Hf,ChevronDown as yc,ChevronUp as zf}from"lucide-react";import{jsx as xa,jsxs as Vo}from"react/jsx-runtime";var un=ze.Root;var fn=ze.Value,Xa=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"})})]}));Xa.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(zf,{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 Qa=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,{})]})}));Qa.displayName=ze.Content.displayName;var jf=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}));jf.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(Hf,{className:"af-h-4 af-w-4"})})}),xa(ze.ItemText,{children:t})]}));St.displayName=ze.Item.displayName;var qf=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}));qf.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,c]=Ca.useState(!0),[d,o]=Ca.useState(null),[u,b]=Ca.useState(0),[v,m]=Ca.useState(t),g=Ca.useRef(0),f=Ca.useCallback(async()=>{if(!e)return;let k=++g.current;try{c(!0),o(null);let h={limit:v,offset:u*v},N=await a.getSubmissions(e,h);if(k!==g.current)return;if(N.submissions.length===0&&u>0){b(Math.max(0,Math.ceil(N.total/v)-1));return}n(N.submissions),i(N.total)}catch(h){if(k!==g.current)return;o(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{k===g.current&&c(!1)}},[a,e,u,v]);Ca.useEffect(()=>{f()},[f]);let p=Ca.useRef(f);p.current=f;let x=Ca.useCallback(async k=>{await a.deleteSubmission(k),p.current()},[a]),S=Math.ceil(r/v);return{submissions:s,total:r,isLoading:l,error:d,page:u,pageSize:v,hasNextPage:u<S-1,hasPreviousPage:u>0,setPage:b,setPageSize:k=>{m(k),b(0)},refetch:f,deleteSubmission:x}}import*as gi from"react";import{Trash2 as Kf}from"lucide-react";import*as Tr from"react";import*as aa from"@radix-ui/react-dialog";import{X as Wf}from"lucide-react";import{jsx as ns,jsxs as Ho}from"react/jsx-runtime";var mn=aa.Root;var Gf=aa.Portal;var Sc=Tr.forwardRef(({className:e,...t},a)=>ns(aa.Overlay,{ref:a,className:W("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Sc.displayName=aa.Overlay.displayName;var en=Tr.forwardRef(({className:e,children:t,...a},s)=>ns(Gf,{children:Ho("div",{className:"aifeatures-admin",children:[ns(Sc,{}),Ho(aa.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(aa.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(Wf,{className:"af-h-4 af-w-4"}),ns("span",{className:"af-sr-only",children:"Close"})]})]})]})}));en.displayName=aa.Content.displayName;var tn=({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});tn.displayName="DialogHeader";var an=({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});an.displayName="DialogFooter";var nn=Tr.forwardRef(({className:e,...t},a)=>ns(aa.Title,{ref:a,className:W("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));nn.displayName=aa.Title.displayName;var sn=Tr.forwardRef(({className:e,...t},a)=>ns(aa.Description,{ref:a,className:W("af-text-sm af-text-muted-foreground",e),...t}));sn.displayName=aa.Description.displayName;import{Fragment as Zf,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(Zf,{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(Kf,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),Es(mn,{open:a,onOpenChange:d=>{!d&&!n&&s(!1)},children:Er(en,{children:[Er(tn,{children:[Es(nn,{children:"Delete this submission?"}),Es(sn,{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(an,{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(d){l(d instanceof Error?d.message:"Failed to delete submission")}finally{r(!1)}},disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}import*as Rc from"react";import{ArrowLeft as Yf,Download as Jf,Globe as Xf,Clock as Qf,FileText as em,Loader2 as tm,Monitor as am,Mail as nm}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 sm(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=d=>d.id??d.name,l=async d=>{r(i(d));try{await s.downloadAttachment(e.id,d)}catch(o){console.error("Download failed:",o)}finally{r(null)}},c=Object.entries(e.data).filter(([d])=>!d.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(Yf,{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:[c.map(([d,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:d.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)})]},d)),c.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((d,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(em,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),$t("span",{className:"af-text-sm",children:d.name}),At("span",{className:"af-text-xs af-text-muted-foreground",children:["(",sm(d.size),")"]})]}),At(y,{variant:"ghost",size:"sm",onClick:()=>l(d),disabled:n===i(d),children:[n===i(d)?$t(tm,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):$t(Jf,{className:"af-h-4 af-w-4 af-mr-1"}),n===i(d)?"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(Qf,{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(Xf,{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(am,{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(nm,{className:"af-h-4 af-w-4"}),At("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{Download as im}from"lucide-react";import*as Is from"react";var rm=/^\+[1-9]\d{1,14}$/;function _c(e){let t=e==null?"":String(e),a=!rm.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 c=await e();hi(c,bi(t))}catch(c){r(c instanceof Error?c: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(im,{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 $e,jsxs as jt}from"react/jsx-runtime";function mm(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function pm(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 gm=["message","comments","comment","inquiry","question","details","body","notes"];function vm(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=(gm.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:c,error:d,page:o,pageSize:u,hasNextPage:b,hasPreviousPage:v,setPage:m,setPageSize:g,deleteSubmission:f}=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),[P,w]=ps.useState(null),C=N(P)?P:null,[E,_]=ps.useState(null);if(ps.useEffect(()=>{if(_(null),!k||R||C)return;let U=!1;return r.getSubmission(k).then(ae=>{if(!U){if(ae.form_id!==e){_("This submission could not be found.");return}w(ae)}}).catch(()=>{U||_("This submission could not be found.")}),()=>{U=!0}},[r,e,k,R,C]),k){let U=R??C;return U?$e("div",{className:t,children:$e(vi,{submission:U,onBack:()=>h(null),onDelete:async()=>{await f(U.id),h(null)}})}):E?jt("div",{className:t,children:[jt(y,{variant:"ghost",size:"sm",onClick:()=>h(null),className:"af-mb-2 af--ml-2",children:[$e(om,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),$e("p",{className:"af-text-sm af-text-destructive",children:E})]}):$e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:$e("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(c)return $e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:$e("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(d)return $e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:jt("div",{className:"af-text-destructive",children:["Error: ",d.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:[$e(um,{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.",$e("br",{}),"Submissions will appear here when visitors use your form."]})]});let j=o*u+1,q=Math.min((o+1)*u,l);return jt("div",{className:t,children:[$e("div",{className:"af-mb-2 af-flex af-justify-end",children:$e(wa,{fetchCsv:p,filename:"submissions"})}),jt(lt,{children:[$e(ct,{children:jt(Ee,{children:[$e(K,{children:"Email"}),$e(K,{children:"Preview"}),$e(K,{children:"Date"}),$e(K,{className:"af-text-right",children:"Actions"})]})}),$e(dt,{children:i.map(U=>{let ae=pm(U.data),ce=vm(U.data);return jt(Ee,{children:[jt(Z,{className:"af-font-medium",children:[jt("div",{className:"af-flex af-items-center af-gap-2",children:[ae||$e("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:[$e(fm,{className:"af-h-3 af-w-3"}),$e("span",{className:"af-text-xs",children:U.attachments.length})]})]}),$e(Cr,{deliveries:U.email_deliveries,label:"Notification email needs attention"})]}),$e(Z,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:ce||$e("span",{className:"af-italic",children:"No preview available"})}),$e(Z,{className:"af-text-muted-foreground",children:mm(U.metadata.submitted_at)}),jt(Z,{className:"af-text-right",children:[$e(y,{variant:"ghost",size:"icon",onClick:()=>h(U.id),title:"View details",children:$e(dm,{className:"af-h-4 af-w-4"})}),$e(Xs,{iconOnly:!0,onDelete:()=>f(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 ",j,"-",q," of ",l]}),jt(un,{value:String(u),onValueChange:U=>g(Number(U)),children:[$e(Xa,{className:"af-w-[70px] af-h-8",children:$e(fn,{})}),jt(Qa,{children:[$e(St,{value:"10",children:"10"}),$e(St,{value:"25",children:"25"}),$e(St,{value:"50",children:"50"}),$e(St,{value:"100",children:"100"})]})]}),$e("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:!v,children:[$e(lm,{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",$e(cm,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as on from"react";import{Plus as Cm,X as Tm,Loader2 as Em,Check as Im}from"lucide-react";import*as Cc from"react";import{jsx as bm}from"react/jsx-runtime";var se=Cc.forwardRef(({className:e,type:t,...a},s)=>bm("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}));se.displayName="Input";import*as Tc from"react";import{cva as hm}from"class-variance-authority";import{jsx as xm}from"react/jsx-runtime";var ym=hm("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)=>xm("label",{ref:a,className:W(ym(),e),...t}));Oe.displayName="Label";import*as gn from"react";import{Plus as Sm,Loader2 as zo,Copy as Nm,Check as Rm,Trash2 as _m,RefreshCw as km,AlertTriangle as Pm}from"lucide-react";import*as rn from"react";function wi(){let{api:e}=H(),[t,a]=rn.useState([]),[s,n]=rn.useState(!0),[r,i]=rn.useState(null),l=rn.useCallback(async()=>{try{n(!0),i(null),a(await e.getEventDestinations())}catch(v){i(v instanceof Error?v:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);rn.useEffect(()=>{l()},[l]);let c=rn.useCallback(async v=>{let m=await e.createEventDestination(v);return a(g=>[m,...g]),m},[e]),d=rn.useCallback(async(v,m)=>{let g=await e.updateEventDestination(v,m);return a(f=>f.map(p=>p.id===v?g:p)),g},[e]),o=rn.useCallback(async v=>{await e.deleteEventDestination(v),a(m=>m.filter(g=>g.id!==v))},[e]),u=rn.useCallback(async v=>{let m=await e.rotateEventDestinationSecret(v);return a(g=>g.map(f=>f.id===v?m:f)),m},[e]),b=rn.useCallback(v=>e.getEventDestinationSecret(v),[e]);return{destinations:t,isLoading:s,error:r,refetch:l,createDestination:c,updateDestination:d,deleteDestination:o,rotateSecret:u,getSecret:b}}import*as ss from"react";import{Loader2 as Ec,RotateCw as wm}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),[c,d]=ss.useState(null),[o,u]=ss.useState(null),b=ss.useCallback(async()=>{try{l(!0),d(null),r(await s.getEventDeliveries(e,t))}catch(m){d(m instanceof Error?m.message:"Failed to load deliveries")}finally{l(!1)}},[s,e,t]);ss.useEffect(()=>{b()},[b]);let v=async m=>{try{u(m.id),d(null);let g=await s.retryEventDelivery(e,m.id);r(f=>f.map(p=>p.id===m.id?g:p))}catch(g){d(g instanceof Error?g.message:"Retry failed")}finally{u(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..."]}):c?pn("div",{className:"af-text-sm af-text-destructive af-py-2",children:c}):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 g=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:[g?pn(te,{variant:"secondary",children:m.last_status??200}):pn(te,{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"}`]}),!g&&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:()=>v(m),children:o===m.id?pn(Ec,{className:"af-h-4 af-w-4 af-animate-spin"}):pn(wm,{className:"af-h-4 af-w-4"})})]},m.id)})})})}import{jsx as tt,jsxs as Kt}from"react/jsx-runtime";function Ni({formId:e,topics:t,description:a,className:s}){let{destinations:n,isLoading:r,error:i,createDestination:l,updateDestination:c,deleteDestination:d,rotateSecret:o,getSecret:u}=wi(),[b,v]=gn.useState(""),[m,g]=gn.useState(!1),[f,p]=gn.useState(null),[x,S]=gn.useState(null),[k,h]=gn.useState(null),[N,R]=gn.useState(!1),[P,w]=gn.useState(null),[C,E]=gn.useState(null),[_,j]=gn.useState(null),q=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{g(!0),p(null),await l({url:A,form_id:e,...t&&t.length>0?{topics:t}:{}}),v("")}catch(ne){p(ne instanceof Error?ne.message:"Failed to add webhook")}finally{g(!1)}}},ae=async A=>{try{E(A.id),p(null),await o(A.id),R(!1),h(await u(A.id))}catch(ne){p(ne instanceof Error?ne.message:"Failed to rotate secret")}finally{E(null)}},ce=async A=>{try{E(A.id),p(null),await c(A.id,{status:"active"})}catch(ne){p(ne instanceof Error?ne.message:"Failed to re-enable")}finally{E(null)}},fe=async()=>{if(P)try{E(P.id),await d(P.id),w(null)}catch(A){p(A instanceof Error?A.message:"Failed to delete")}finally{E(null)}},T=async A=>{if(x===A.id){S(null),h(null);return}try{E(A.id),p(null),R(!1),S(A.id),h(await u(A.id))}catch(ne){S(null),p(ne instanceof Error?ne.message:"Failed to read secret")}finally{E(null)}},V=async()=>{if(k)try{await navigator.clipboard.writeText(k),R(!0)}catch{}};return Kt("div",{className:s,children:[Kt("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."})]}),Kt("div",{className:"af-flex af-gap-2 af-mt-4",children:[tt(se,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:A=>v(A.target.value),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),U())},disabled:m}),Kt(y,{onClick:U,disabled:m||!b.trim(),children:[m?tt(zo,{className:"af-h-4 af-w-4 af-animate-spin"}):tt(Sm,{className:"af-h-4 af-w-4"}),tt("span",{className:"af-ml-1",children:"Add"})]})]}),(f||i)&&tt("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:f||i?.message}),Kt("div",{className:"af-mt-4 af-space-y-2",children:[r&&Kt("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&&q.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."}),q.map(A=>Kt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[Kt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[Kt("div",{className:"af-min-w-0",children:[Kt("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(te,{variant:"destructive",children:"Disabled"}):tt(te,{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(", ")})]}),Kt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[tt(y,{variant:"ghost",size:"sm",onClick:()=>j(_===A.id?null:A.id),children:_===A.id?"Hide log":"Deliveries"}),tt(y,{variant:"ghost",size:"sm",onClick:()=>T(A),disabled:C===A.id,children:x===A.id?"Hide secret":"Show secret"}),tt(y,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:C===A.id,onClick:()=>w(A),children:tt(_m,{className:"af-h-4 af-w-4"})})]})]}),A.status==="disabled"&&Kt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[tt(Pm,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),Kt("div",{className:"af-text-sm",children:[Kt("p",{children:["We stopped sending after repeated failures."," ",A.disabled_reason]}),tt(y,{variant:"outline",size:"sm",className:"af-mt-2",disabled:C===A.id,onClick:()=>ce(A),children:"Re-enable"})]})]}),x===A.id&&k&&Kt("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."}),Kt("div",{className:"af-flex af-gap-2",children:[tt(se,{readOnly:!0,value:k,className:"af-font-mono"}),tt(y,{variant:"outline",title:"Copy signing secret",onClick:V,children:N?tt(Rm,{className:"af-h-4 af-w-4"}):tt(Nm,{className:"af-h-4 af-w-4"})}),tt(y,{variant:"outline",title:"Rotate signing secret",disabled:C===A.id,onClick:()=>ae(A),children:C===A.id?tt(zo,{className:"af-h-4 af-w-4 af-animate-spin"}):tt(km,{className:"af-h-4 af-w-4"})})]})]}),_===A.id&&tt(Si,{destinationId:A.id})]},A.id))]}),tt(mn,{open:!!P,onOpenChange:A=>{!A&&!C&&w(null)},children:Kt(en,{children:[Kt(tn,{children:[tt(nn,{children:"Delete this webhook?"}),Kt(sn,{children:["New submissions will stop being sent to ",P?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),Kt(an,{children:[tt(y,{variant:"outline",onClick:()=>w(null),disabled:!!C,children:"Cancel"}),tt(y,{variant:"destructive",onClick:fe,disabled:!!C,children:C?"Deleting...":"Delete"})]})]})})]})}import{jsx as it,jsxs as Tn}from"react/jsx-runtime";function Ri({form:e,onSaved:t,className:a}){let{updateForm:s}=Js(),[n,r]=on.useState(!1),[i,l]=on.useState(null),[c,d]=on.useState(null),[o,u]=on.useState(e.name),[b,v]=on.useState(e.redirect_url||""),[m,g]=on.useState(e.email_recipients),[f,p]=on.useState("");on.useEffect(()=>{u(e.name),v(e.redirect_url||""),g(e.email_recipients),d(null)},[e]);let x=on.useCallback(async R=>{try{r(!0),d(null);let P=await s(e.id,R);l(new Date),t?.(P)}catch(P){d(P instanceof Error?P.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);on.useEffect(()=>{if(i){let R=setTimeout(()=>l(null),2e3);return()=>clearTimeout(R)}},[i]);let S=async()=>{let R=f.trim().toLowerCase();if(!R)return;if(!R.includes("@")){d("Please enter a valid email address");return}if(m.includes(R)){d("This email is already added");return}let P=[...m,R];g(P),p(""),d(null),await x({email_recipients:P})},k=async R=>{let P=m.filter(w=>w!==R);g(P),await x({email_recipients:P})},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)&&it("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:[it(Em,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),it("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:[it(Im,{className:"af-h-4 af-w-4 af-text-green-600"}),it("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Tn("div",{className:"af-space-y-2",children:[it(Oe,{htmlFor:"form-name",children:"Form Name"}),it(se,{id:"form-name",value:o,onChange:R=>u(R.target.value),onBlur:h,placeholder:"Contact Form"}),it("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:[it(Oe,{children:"Email Recipients"}),it("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(te,{variant:"secondary",className:"af-gap-1",children:[R,it("button",{type:"button",onClick:()=>k(R),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:it(Tm,{className:"af-h-3 af-w-3"})})]},R)),m.length===0&&it("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Tn("div",{className:"af-flex af-gap-2",children:[it(se,{type:"email",value:f,onChange:R=>p(R.target.value),placeholder:"Add email address",onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),S())},disabled:n}),it(y,{type:"button",variant:"outline",onClick:S,disabled:!f.trim()||n,children:it(Cm,{className:"af-h-4 af-w-4"})})]})]}),Tn("div",{className:"af-space-y-2",children:[it(Oe,{htmlFor:"redirect-url",children:"Redirect URL"}),it(se,{id:"redirect-url",value:b,onChange:R=>v(R.target.value),onBlur:N,placeholder:"/thank-you"}),it("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:[it(Oe,{children:"Form Endpoint"}),it("div",{className:"af-flex af-items-center af-gap-2",children:it("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})}),it("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:[it(Oe,{children:"Captcha Protection"}),it("div",{className:"af-flex af-items-center af-gap-2",children:it(te,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),it("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),it(Ni,{formId:e.id}),c&&it("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c})]})}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,c=a??i,[d,o]=rs.useState(null),u=`${l.formId??""}|${l.submissionId??""}`,[b,v]=rs.useState(null),m=b?.key===u?b.message:null,g=l.formId??(d&&d.submissionId===l.submissionId?d.formId:void 0);rs.useEffect(()=>{let R=l.submissionId;if(!R||l.formId)return;let P=!1;return n.getSubmission(R).then(w=>{P||(v(null),o({submissionId:R,formId:w.form_id}))}).catch(()=>{P||v({key:u,message:"This submission could not be found."})}),()=>{P=!0}},[n,l.submissionId,l.formId,u]);let[f,p]=rs.useState(null);rs.useEffect(()=>{if(!g||f?.id===g)return;let R=!1;return n.getForm(g).then(P=>{R||(v(null),p(P))}).catch(()=>{R||v({key:u,message:"This form could not be found."})}),()=>{R=!0}},[n,g,f?.id,u]);let x=(R,P)=>{p(R),c({formId:R.id,tab:P})},S=()=>c({});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(Am,{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(!g||f?.id!==g)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:f.name})]}),Un(di,{value:N,onValueChange:R=>c({formId:g,tab:R}),children:[Un(Pr,{className:"af-mb-4",children:[Un(kn,{value:"submissions",className:"af-gap-2",children:[Ma(Om,{className:"af-h-4 af-w-4"}),"Submissions"]}),Un(kn,{value:"settings",className:"af-gap-2",children:[Ma(Dm,{className:"af-h-4 af-w-4"}),"Settings"]})]}),Ma(Pn,{value:"submissions",children:Ma(xi,{formId:g,submissionId:l.submissionId,onSelectSubmission:R=>c({formId:g,tab:"submissions",submissionId:R??void 0})})}),Ma(Pn,{value:"settings",children:Ma(Ri,{form:f,onSaved:p})})]})]})}import*as ot 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),c=Vn.useCallback(async()=>{let d=++l.current;try{n(!0),i(null);let o=await e.getPaymentsStatus();if(d!==l.current)return;a(o)}catch(o){if(d!==l.current)return;i(o instanceof Error?o:new Error("Failed to fetch payments status"))}finally{d===l.current&&n(!1)}},[e]);return Vn.useEffect(()=>{c()},[c]),{status:t,isLoading:s,error:r,refetch:c}}var Lm=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function vn(e){return Lm.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 Mm,jsx as st,jsxs as mt}from"react/jsx-runtime";function Ar(e){return e instanceof ta&&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 st(Bm,{api:e},t)}function Bm({api:e}){let{status:t,error:a}=gs(),[s,n]=ot.useState([]),[r,i]=ot.useState(null),[l,c]=ot.useState(null),[d,o]=ot.useState(!1),[u,b]=ot.useState(!1),[v,m]=ot.useState(""),[g,f]=ot.useState(null),[p,x]=ot.useState(null),[S,k]=ot.useState(!1),h=ot.useRef(0),N=ot.useCallback(async w=>{let C=++h.current;o(!0),m("");try{let E=await e.getPromos(w);if(C!==h.current)return;n(_=>w?[..._,...E.promos.filter(j=>!_.some(q=>q.id===j.id))]:E.promos),i(E.next_cursor),c(E.checkout_enabled)}catch(E){C===h.current&&m(Ar(E))}finally{C===h.current&&o(!1)}},[e]);ot.useEffect(()=>(N(),()=>{h.current++}),[N]);async function R(w){let C=++h.current;o(!0),m(""),k(!1);try{let E=await e.getPromo(w);C===h.current&&f(E)}catch(E){C===h.current&&m(Ar(E))}finally{C===h.current&&o(!1)}}async function P(){if(g){b(!0),o(!0),m("");try{let w=await e.disablePromo(g.id);if(f(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?st(Fm,{currency:t?.currency??void 0,replaces:p.replaces,onCancel:()=>x(null),onSave:async w=>{let C=p.replaces?await e.replacePromo(p.replaces.id,w):await e.createPromo(w),E=await e.getPromo(C.id);if(E.status==="pending"||E.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");f(E),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:[st("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),st(y,{disabled:d||!t?.currency,onClick:()=>{m(""),x({})},children:"Create promo code"})]}),st("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&&st("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&&st("p",{className:"af-text-sm",children:a?Ar(a):"Connect Stripe and set the payment currency before creating codes."}),v&&mt("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[v," ",st(y,{variant:"outline",disabled:d,onClick:()=>g?void R(g.id):void N(),children:"Refresh"})]}),g?mt("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[st(y,{variant:"ghost",disabled:u,onClick:()=>{f(null),k(!1),N()},children:"Back to codes"}),mt("h4",{className:"af-font-semibold af-break-all",children:[g.code," \xB7 ",g.name]}),mt("p",{children:[Ac(g)," \xB7 ",g.status]}),mt("p",{className:"af-text-sm",children:[g.times_redeemed==null?"Usage unavailable":`${g.times_redeemed} redemptions`,g.max_redemptions!=null?` / ${g.max_redemptions} maximum`:""]}),mt("p",{className:"af-text-sm",children:[g.minimum_amount!=null&&g.currency?`Minimum order: ${Q(g.minimum_amount,g.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),mt("p",{className:"af-text-sm",children:["Subscription discount:"," ",g.duration==="repeating"?`${g.duration_in_months} months`:g.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),st("p",{className:"af-text-sm",children:g.expires_at?`Expires ${new Date(g.expires_at).toLocaleString()}`:"No expiry"}),mt("div",{className:"af-flex af-flex-wrap af-gap-2",children:[st(y,{variant:"outline",disabled:d,onClick:()=>void R(g.id),children:"Refresh details"}),st(y,{variant:"outline",disabled:d||g.status==="pending"||g.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:g}),children:"Replace with new code"}),st(y,{variant:"outline",disabled:d||!["active","pending","unavailable"].includes(g.status),onClick:()=>k(!0),children:g.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:[g.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${g.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),st(y,{disabled:d,onClick:()=>void P(),children:g.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",st(y,{variant:"ghost",disabled:d,onClick:()=>k(!1),children:"Cancel"})]})]}):mt(Mm,{children:[s.map(w=>mt("button",{type:"button",disabled:d,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:[st("span",{className:"af-font-semibold af-break-all",children:w.code}),st("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)),!d&&!v&&s.length===0&&st("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),d&&st("p",{role:"status",children:"Loading promo codes\u2026"}),r&&st(y,{variant:"outline",disabled:d,onClick:()=>void N(r),children:"Load more"})]})]})}function Fm({currency:e,replaces:t,onCancel:a,onSave:s}){let[n,r]=ot.useState(""),[i,l]=ot.useState(t?.name??""),[c,d]=ot.useState(t?.amount_off!=null?"fixed":"percent"),[o,u]=ot.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(Dt(t.amount_off,e)):"")),[b,v]=ot.useState(t?.minimum_amount!=null&&e?String(Dt(t.minimum_amount,e)):""),[m,g]=ot.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):""}),[f,p]=ot.useState(t?.max_redemptions?.toString()??""),[x,S]=ot.useState(t?.duration??"once"),[k,h]=ot.useState(t?.duration_in_months?.toString()??"3"),[N,R]=ot.useState(null),[P,w]=ot.useState(!1),[C,E]=ot.useState(""),_=ot.useRef(!1),j=e&&vn(e)?"1":"0.01";async function q(ce){if(ce.preventDefault(),_.current)return;E("");let fe=N;if(!fe){if(!e){E("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){E("Choose a different code for the replacement.");return}let T=va(o,e),V=b?va(b,e):null;if(c==="fixed"&&(!T||T>999999999999)||b&&(!V||V>999999999999)){E("Enter a positive amount within the supported range.");return}if(m&&new Date(m).getTime()<=Date.now()){E("Choose a future expiry.");return}fe={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:i.trim(),duration:x,...c==="percent"?{percent_off:Number(o)}:{amount_off:T,currency:e},...b?{minimum_amount:V,currency:e}:{},...m?{expires_at:new Date(m).toISOString()}:{},...f?{max_redemptions:Number(f)}:{},...x==="repeating"?{duration_in_months:Number(k)}:{}},R(fe)}_.current=!0,w(!0);try{await s(fe)}catch(T){E(Ar(T)),T instanceof ta&&T.status>=400&&T.status<500&&T.details?.retryable!==!0&&R(null)}finally{_.current=!1,w(!1)}}let U=(ce,fe,T,V={})=>mt("label",{className:"af-grid af-gap-1 af-text-sm",children:[ce,st(se,{"aria-label":ce,value:fe,onChange:A=>T(A.target.value),...V})]}),ae="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return mt("form",{onSubmit:q,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[st("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&st("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:P||!!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:ae,value:c,onChange:ce=>d(ce.target.value),children:[st("option",{value:"percent",children:"Percentage"}),mt("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),U("Discount",o,u,{type:"number",required:!0,min:c==="percent"?"0.01":j,max:c==="percent"?"100":void 0,step:c==="percent"?"0.01":j}),U("Minimum order amount",b,v,{type:"number",min:j,step:j,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,g,{type:"datetime-local",step:1}),U("Maximum redemptions",f,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:ae,value:x,onChange:ce=>S(ce.target.value),children:[st("option",{value:"once",children:"First invoice only"}),st("option",{value:"forever",children:"Every invoice"}),st("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&U("Months",k,h,{type:"number",required:!0,min:1,max:36,step:1})]}),C&&st("p",{role:"alert",className:"af-text-sm af-text-destructive",children:C}),N&&!P&&mt("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",st("span",{className:"af-break-all",children:N.request_id})]}),mt("div",{className:"af-flex af-flex-wrap af-gap-2",children:[st(y,{type:"submit",disabled:P,children:P?"Saving\u2026":N?"Retry same request":t?"Create replacement":"Create code"}),st(y,{type:"button",variant:"ghost",disabled:P||!!N,onClick:a,children:"Cancel"})]})]})}import*as cr from"react";import{ArrowLeft as lg,FileText as cg,Package as dg,Receipt as ug,Settings as fg,Users as mg}from"lucide-react";import*as ki from"react";import{Package as $m,Pencil as Um,Plus as Dc,Trash2 as Vm}from"lucide-react";import{jsx as ut,jsxs as Sa}from"react/jsx-runtime";function Hm(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 zm(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,[c,d]=ki.useState(null),[o,u]=ki.useState(!1),[b,v]=ki.useState(null),m=async()=>{if(c)try{u(!0),v(null),await l(c.id),d(null)}catch(g){v(g instanceof Error?g.message:"Failed to delete product")}finally{u(!1)}};return r?ut("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ut("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):i?ut("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:[ut($m,{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.",ut("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:[ut(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Sa("div",{className:s,children:[ut("div",{className:"af-flex af-justify-end af-mb-4",children:Sa(y,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[ut(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Sa(lt,{children:[ut(ct,{children:Sa(Ee,{children:[ut(K,{children:"Name"}),ut(K,{children:"Price"}),ut(K,{children:"Fulfillment"}),ut(K,{children:"Status"}),ut(K,{className:"af-text-right",children:"Actions"})]})}),ut(dt,{children:n.map(g=>Sa(Ee,{children:[ut(Z,{className:"af-font-medium",children:g.name}),ut(Z,{children:Hm(g)}),ut(Z,{className:"af-text-muted-foreground",children:zm(g)}),ut(Z,{children:ut(te,{variant:g.active?"success":"secondary",children:g.active?"Active":"Inactive"})}),ut(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?.(g),children:[ut(Um,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Sa(y,{variant:"ghost",size:"sm",onClick:()=>{v(null),d(g)},children:[ut(Vm,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},g.id))})]}),ut(mn,{open:!!c,onOpenChange:g=>{!g&&!o&&d(null)},children:Sa(en,{children:[Sa(tn,{children:[ut(nn,{children:"Delete product?"}),Sa(sn,{children:['"',c?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&ut("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),Sa(an,{children:[ut(y,{variant:"outline",onClick:()=>d(null),disabled:o,children:"Cancel"}),ut(y,{variant:"destructive",onClick:m,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})}import*as _t from"react";import{FileText as qm,Link2 as Wm,Loader2 as Bc,Plus as Gm,Upload as Km,X as Zm}from"lucide-react";import*as Zt from"react";import{Loader2 as Oc,Plus as jo,Trash2 as Lc,X as jm}from"lucide-react";import{jsx as re,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]=Zt.useState(null),[l,c]=Zt.useState(!0),[d,o]=Zt.useState(null),[u,b]=Zt.useState(null),[v,m]=Zt.useState(!1),g=Zt.useRef(!0);Zt.useEffect(()=>(g.current=!0,()=>{g.current=!1}),[]);let f=Zt.useCallback(async()=>{try{let I=await s.getProduct(e);if(!g.current)return;i(I)}catch(I){if(!g.current)return;o(I instanceof Error?I.message:"Failed to load product")}finally{g.current&&c(!1)}},[s,e]);Zt.useEffect(()=>{f()},[f]);let p=async I=>{b(null),m(!0);try{await I(),await f()}catch(M){g.current&&b(M instanceof Error?M.message:"Something went wrong")}finally{g.current&&m(!1)}},[x,S]=Zt.useState(""),[k,h]=Zt.useState(""),[N,R]=Zt.useState({}),P=()=>p(async()=>{let I=x.trim(),M=k.split(",").map(B=>B.trim()).filter(Boolean);if(!I)throw new Error("Option name is required");if(M.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:I,values:M}),g.current&&(S(""),h(""))}),w=I=>p(async()=>{let M=(N[I.id]??"").trim();if(!M)throw new Error("Enter a value");await s.updateOption(I.id,{add_values:[M]}),g.current&&R(B=>({...B,[I.id]:""}))}),C=(I,M)=>p(()=>s.updateOption(I.id,{remove_values:[M]})),E=I=>p(()=>s.deleteOption(I.id)),[_,j]=Zt.useState(null),[q,U]=Zt.useState(null),[ae,ce]=Zt.useState(!1),[fe,T]=Zt.useState(null),V=r?.options??[],A=r?.variants??[],ne=()=>{U(null),j({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(V.map(I=>[I.id,I.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},ie=I=>{U(null);let M=I.inventory?.on_hand??0,B=M<0?"":String(M);j({variant:I,title:I.title??"",sku:I.sku??"",unitAmount:I.unit_amount!=null?String(Dt(I.unit_amount,t)):"",compareAt:I.compare_at_amount!=null?String(Dt(I.compare_at_amount,t)):"",active:I.active,optionValues:{},tracked:I.inventory?.tracked??!1,onHand:B,initialOnHand:B,allowBackorder:I.inventory?.allow_backorder??!1})},Fe=async()=>{if(!_)return;U(null);let I=_.variant?.allow_custom_amount??!1,M=null,B=null;if(!I){if(M=va(_.unitAmount,t),M===null||M<=0){U("Enter a valid price");return}if(_.compareAt.trim()&&(B=va(_.compareAt,t),B===null||B<=M)){U("Compare-at price must be greater than the price");return}}let ee=_.onHand.trim()!==_.initialOnHand.trim(),J=parseInt(_.onHand,10);if(_.tracked&&ee&&(!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,...I?{}:{unit_amount:M,compare_at_amount:B},active:_.active}),await s.setVariantInventory(_.variant.id,{tracked:_.tracked,on_hand:_.tracked&&ee?J:void 0,allow_backorder:_.allowBackorder});else{let pe={};for(let Ue of V){let ft=_.optionValues[Ue.id];if(!ft){U(`Choose a ${Ue.title}`),ce(!1);return}pe[Ue.title]=ft}await s.createVariant(e,{title:_.title.trim()||null,sku:_.sku.trim()||null,unit_amount:M,compare_at_amount:B,active:_.active,option_values:V.length>0?pe:void 0,inventory:_.tracked?{tracked:!0,on_hand:J,allow_backorder:_.allowBackorder}:{tracked:!1,allow_backorder:_.allowBackorder}})}await f(),g.current&&j(null)}catch(pe){if(g.current&&U(pe instanceof Error?pe.message:"Failed to save variant"),_.variant)try{let Ue=await s.getProduct(e);g.current&&i(Ue)}catch{}}finally{g.current&&ce(!1)}},Se=()=>p(async()=>{fe&&(await s.deleteVariant(fe.id),g.current&&T(null))}),Ae=_?.variant?.allow_custom_amount??!1,Ye=_?.variant!=null&&_.variant.option_values.length===0&&V.length>0&&!_.variant.active,Re=_?.variant?.inventory!=null&&_.variant.inventory.on_hand<0?-_.variant.inventory.on_hand:null;function Xe(I){let M=I.inventory;if(!M||!M.tracked)return re("span",{className:"af-text-muted-foreground",children:"Unlimited"});let B=M.available??M.on_hand;return B<0?Ce("span",{children:[-B," backordered"]}):Ce("span",{children:[B," in stock",M.allow_backorder&&re("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return l?re("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:re(Oc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):d?re("div",{className:a,children:re("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})}):Ce("div",{className:`af-space-y-6 ${a||""}`,children:[Ce("div",{className:"af-space-y-3",children:[Ce("div",{children:[re(Oe,{children:"Options"}),re("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&&re("div",{className:"af-space-y-3",children:V.map(I=>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:[re("span",{className:"af-text-sm af-font-medium",children:I.title}),re(y,{variant:"ghost",size:"sm",onClick:()=>E(I),disabled:v,children:re(Lc,{className:"af-h-4 af-w-4"})})]}),re("div",{className:"af-flex af-flex-wrap af-gap-2",children:I.values.map(M=>Ce(te,{variant:"secondary",className:"af-gap-1",children:[M.value,re("button",{type:"button",onClick:()=>C(I,M.value),className:"af-ml-1 hover:af-text-destructive",disabled:v,title:"Remove value",children:re(jm,{className:"af-h-3 af-w-3"})})]},M.id))}),Ce("div",{className:"af-flex af-gap-2",children:[re(se,{value:N[I.id]??"",onChange:M=>R(B=>({...B,[I.id]:M.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),w(I))},disabled:v}),re(y,{type:"button",variant:"outline",size:"sm",onClick:()=>w(I),disabled:v||!(N[I.id]??"").trim(),children:re(jo,{className:"af-h-4 af-w-4"})})]})]},I.id))}),Ce("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[Ce("div",{className:"af-space-y-1",children:[re(Oe,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),re(se,{id:"new-option-title",value:x,onChange:I=>S(I.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:v})]}),Ce("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[re(Oe,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),re(se,{id:"new-option-values",value:k,onChange:I=>h(I.target.value),placeholder:"S, M, L",disabled:v})]}),Ce(y,{type:"button",variant:"outline",onClick:P,disabled:v||!x.trim()||!k.trim(),children:[re(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:[re(Oe,{children:"Variants"}),Ce(y,{type:"button",variant:"outline",size:"sm",onClick:ne,disabled:v||V.length===0,children:[re(jo,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),V.length===0&&re("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),A.length===0?re("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):Ce(lt,{children:[re(ct,{children:Ce(Ee,{children:[re(K,{children:"Variant"}),re(K,{children:"SKU"}),re(K,{children:"Price"}),re(K,{children:"Stock"}),re(K,{children:"Status"}),re(K,{className:"af-text-right",children:"Actions"})]})}),re(dt,{children:A.map(I=>Ce(Ee,{children:[re(Z,{className:"af-font-medium",children:qo(I)}),re(Z,{className:"af-text-muted-foreground",children:I.sku||"-"}),re(Z,{children:I.unit_amount!=null?Ce("span",{children:[I.compare_at_amount!=null&&re("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:Q(I.compare_at_amount,I.currency)}),Q(I.unit_amount,I.currency)]}):I.allow_custom_amount?re("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),re(Z,{children:Xe(I)}),re(Z,{children:re(te,{variant:I.active?"success":"secondary",children:I.active?"Active":"Inactive"})}),re(Z,{className:"af-text-right",children:Ce("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[re(y,{variant:"ghost",size:"sm",onClick:()=>ie(I),disabled:v,children:"Edit"}),re(y,{variant:"ghost",size:"icon",onClick:()=>T(I),disabled:v,title:"Delete variant",children:re(Lc,{className:"af-h-4 af-w-4"})})]})})]},I.id))})]})]}),u&&re("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u}),re(mn,{open:_!==null,onOpenChange:I=>{!I&&!ae&&j(null)},children:Ce(en,{children:[Ce(tn,{children:[re(nn,{children:_?.variant?"Edit variant":"Add variant"}),re(sn,{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:[re("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),qo(_.variant)]}):V.map(I=>Ce("div",{className:"af-space-y-1",children:[re(Oe,{className:"af-text-xs af-text-muted-foreground",children:I.title}),Ce(un,{value:_.optionValues[I.id]??"",onValueChange:M=>j(B=>B&&{...B,optionValues:{...B.optionValues,[I.id]:M}}),children:[re(Xa,{children:re(fn,{placeholder:`Choose ${I.title}`})}),re(Qa,{children:I.values.map(M=>re(St,{value:M.value,children:M.value},M.id))})]})]},I.id)),Ae?Ce("div",{className:"af-space-y-1",children:[re(Oe,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),re("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(),")"]}),re(se,{id:"variant-price",type:"number",min:"0",step:n,value:_.unitAmount,onChange:I=>j(M=>M&&{...M,unitAmount:I.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),Ce("div",{className:"af-space-y-1",children:[re(Oe,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),re(se,{id:"variant-compare",type:"number",min:"0",step:n,value:_.compareAt,onChange:I=>j(M=>M&&{...M,compareAt:I.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),Ce("div",{className:"af-space-y-1",children:[re(Oe,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),re(se,{id:"variant-sku",value:_.sku,onChange:I=>j(M=>M&&{...M,sku:I.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:[re("input",{type:"checkbox",checked:_.tracked,onChange:I=>j(M=>M&&{...M,tracked:I.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:[re(Oe,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),re(se,{id:"variant-onhand",type:"number",min:"0",step:"1",value:_.onHand,onChange:I=>j(M=>M&&{...M,onHand:I.target.value}),placeholder:Re!=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:[re("input",{type:"checkbox",checked:_.allowBackorder,onChange:I=>j(M=>M&&{...M,allowBackorder:I.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Re!=null&&Ce("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Re," 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:[re("input",{type:"checkbox",checked:_.active,onChange:I=>j(M=>M&&{...M,active:I.target.checked}),className:"af-h-4 af-w-4",disabled:Ye}),"Active (buyers can purchase this variant)"]}),Ye&&re("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),q&&re("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:q})]}),Ce(an,{children:[re(y,{variant:"outline",onClick:()=>j(null),disabled:ae,children:"Cancel"}),Ce(y,{onClick:Fe,disabled:ae,children:[ae?re(Oc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,_?.variant?"Save":"Add variant"]})]})]})}),re(mn,{open:fe!==null,onOpenChange:I=>{!I&&!v&&T(null)},children:Ce(en,{children:[Ce(tn,{children:[re(nn,{children:"Delete variant?"}),re(sn,{children:fe&&`"${qo(fe)}" will no longer be purchasable. Past orders are unaffected.`})]}),Ce(an,{children:[re(y,{variant:"outline",onClick:()=>T(null),disabled:v,children:"Cancel"}),re(y,{variant:"destructive",onClick:Se,disabled:v,children:"Delete"})]})]})})]})}import{Fragment as Jm,jsx as Te,jsxs as Ge}from"react/jsx-runtime";function Ym(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:c}=e,d=!!t,o=t?.currency??a,u=vn(o)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[v,m]=_t.useState(!1),[g,f]=_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"),[P,w]=_t.useState(t?.unit_amount!=null?String(Dt(t.unit_amount,o)):""),[C,E]=_t.useState(t?.min_amount!=null?String(Dt(t.min_amount,o)):""),[_,j]=_t.useState(t?.max_amount!=null?String(Dt(t.max_amount,o)):""),[q,U]=_t.useState(String(t?.max_quantity??10)),ae=_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,fe]=_t.useState(t?.collect_shipping_address??!1),[T,V]=_t.useState(t?.active??!0),[A,ne]=_t.useState(t?.images??[]),[ie,Fe]=_t.useState(""),[Se,Ae]=_t.useState(t?.fulfillment??null),[Ye,Re]=_t.useState(!1),[Xe,I]=_t.useState(""),[M,B]=_t.useState(null),ee=_t.useRef(null),J=v||Ye,pe=()=>{let be=ie.trim();if(be){if(A.includes(be)){f("This image URL is already added");return}ne(Me=>[...Me,be]),Fe(""),f(null)}},Ue=be=>{ne(Me=>Me.filter(yt=>yt!==be))},ft=async()=>{if(f(null),!x.trim()){f("Product name is required");return}let be=null,Me=null,yt=null,It=!d||N!==ae.pricingMode||(N==="fixed"?P!==ae.unitAmount:C!==ae.minAmount||_!==ae.maxAmount),Mt=!d||q!==ae.maxQuantity,et=b||N==="fixed";if(!(b||!It))if(N==="fixed"){if(be=va(P,o),be===null||be<=0){f("Enter a valid price");return}}else{if(Me=va(C,o),yt=va(_,o),Me===null||yt===null){f("Enter valid minimum and maximum amounts");return}if(yt<Me){f("Maximum amount must be at least the minimum amount");return}}let ea=parseInt(q,10);if(et&&Mt&&(!Number.isFinite(ea)||ea<1)){f("Max quantity must be at least 1");return}try{m(!0);let Je;if(d&&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=Me,wt.max_amount=yt)),et&&Mt&&(wt.max_quantity=ea),Je=await i(t.id,wt),ae.pricingMode=Je.allow_custom_amount?"custom":"fixed",ae.unitAmount=Je.unit_amount!=null?String(Dt(Je.unit_amount,o)):"",ae.minAmount=Je.min_amount!=null?String(Dt(Je.min_amount,o)):"",ae.maxAmount=Je.max_amount!=null?String(Dt(Je.max_amount,o)):"",ae.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=ea):(wt.min_amount=Me,wt.max_amount=yt),Je=await r(wt)}if(!p.current)return;Ae(Je.fulfillment),s?.(Je)}catch(Je){if(!p.current)return;f(Je instanceof Error?Je.message:"Failed to save product")}finally{p.current&&m(!1)}},Qe=async be=>{let Me=be.target.files?.[0];if(!(!Me||!t))try{Re(!0),B(null);let yt=await l(t.id,Me);if(!p.current)return;Ae(yt.fulfillment),s?.(yt)}catch(yt){if(!p.current)return;B(yt instanceof Error?yt.message:"Failed to upload file")}finally{p.current&&(Re(!1),ee.current&&(ee.current.value=""))}},Et=async()=>{let be=Xe.trim();if(!(!be||!t))try{Re(!0),B(null);let Me=await c(t.id,be);if(!p.current)return;Ae(Me.fulfillment),I(""),s?.(Me)}catch(Me){if(!p.current)return;B(Me instanceof Error?Me.message:"Failed to fetch file")}finally{p.current&&Re(!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(se,{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(Jm,{children:[Ge(un,{value:N,onValueChange:be=>R(be),children:[Te(Xa,{className:"af-w-[260px]",children:Te(fn,{})}),Ge(Qa,{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(se,{id:"product-price",type:"number",min:"0",step:u,value:P,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(se,{id:"product-min-amount",type:"number",min:"0",step:u,value:C,onChange:be=>E(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(se,{id:"product-max-amount",type:"number",min:"0",step:u,value:_,onChange:be=>j(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(se,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:q,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(te,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[Te("span",{className:"af-truncate",children:be}),Te("button",{type:"button",onClick:()=>Ue(be),className:"af-ml-1 hover:af-text-destructive",disabled:v,children:Te(Zm,{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(se,{type:"url",value:ie,onChange:be=>Fe(be.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:be=>{be.key==="Enter"&&(be.preventDefault(),pe())},disabled:v}),Te(y,{type:"button",variant:"outline",onClick:pe,disabled:!ie.trim()||v,children:Te(Gm,{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."}),d?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(qm,{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:["(",Ym(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(Wm,{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:ee,type:"file",onChange:Qe,className:"af-hidden",disabled:J}),Ge(y,{type:"button",variant:"outline",size:"sm",onClick:()=>ee.current?.click(),disabled:J,children:[Ye?Te(Bc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Te(Km,{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(se,{type:"url",value:Xe,onChange:be=>I(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:!Xe.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=>fe(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)"]})]})]}),d&&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})]}),g&&Te("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g}),Te("div",{className:"af-flex af-items-center af-gap-2",children:Ge(y,{type:"button",onClick:ft,disabled:J,children:[v?Te(Bc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?"Save changes":"Create product"]})})]})}import*as na from"react";import{ChevronLeft as wp,ChevronRight as Gc,Loader2 as Sp,Receipt as Np,Search as Rp,SlidersHorizontal as _p}from"lucide-react";import*as Ot from"react";var Xm=["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,c]=Ot.useState(!0),[d,o]=Ot.useState(null),[u,b]=Ot.useState(0),[v,m]=Ot.useState(e),[g,f]=Ot.useState(void 0),[p,x]=Ot.useState(""),[S,k]=Ot.useState(""),[h,N]=Ot.useState(""),[R,P]=Ot.useState(!1),[w,C]=Ot.useState(!1),[E,_]=Ot.useState(void 0),j=E?E.join(","):"",q=Ot.useMemo(()=>{if(!j)return;let T=new Set(j.split(","));return Xm.filter(V=>!T.has(V))},[j]),U=Ot.useMemo(()=>{let T={};return g?T.status=g:q?T.excludeStatus=q: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},[g,q,R,p,S,h,w]),ae=Ot.useRef(0),ce=Ot.useCallback(async()=>{let T=++ae.current;try{c(!0),o(null);let V={...U,limit:v,offset:u*v},A=await a.getOrders(V);if(T!==ae.current)return;n(A.orders),i(A.total)}catch(V){if(T!==ae.current)return;o(V instanceof Error?V:new Error("Failed to fetch orders"))}finally{T===ae.current&&c(!1)}},[a,u,v,U,t]);Ot.useEffect(()=>{ce()},[ce]);let fe=Math.ceil(r/v);return{orders:s,total:r,isLoading:l,error:d,page:u,pageSize:v,hasNextPage:u<fe-1,hasPreviousPage:u>0,setPage:b,setPageSize:T=>{m(T),b(0)},status:g,setStatus:T=>{f(T),b(0)},statusIn:E,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=>{P(T),b(0)},unfulfilledOnly:w,setUnfulfilledOnly:T=>{C(T),b(0)},clearFilters:()=>{f(void 0),_(void 0),P(!1),C(!1),x(""),k(""),N(""),b(0)},filters:U,refetch:ce}}import*as qt from"react";import{ArrowLeft as tp,Check as $c,ChevronLeft as ap,ChevronRight as np,ClipboardCopy as sp,Copy as rp,Download as ip,Loader2 as Oi,Mail as Uc,MoreHorizontal as op,Package as lp,RotateCcw as cp,Truck as dp,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 Qm={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function ep(e){return Qm[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(te,{variant:Mc(e),className:t,children:ep(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(te,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?Di(te,{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 hp,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 up(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,fp=["paid","partially_refunded"],mp=["paid","partially_refunded","disputed"],pp=/^[A-Za-z0-9 _-]*$/,Hc=100;function Yo(e,t,a,s,n){let r=fp.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 c=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(te,{variant:c.variant,className:"af-shrink-0",children:c.label})]}),c.detail&&O("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:c.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=up(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 gp(){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(!gp())return null;let l=async()=>{try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},c=r?O($c,{className:"af-h-3 af-w-3"}):O(rp,{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:c}):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(sp,{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 vp({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(lp,{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 bp(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:c=!1}){let{api:d}=H(),[o,u]=qt.useState(e),[b,v]=qt.useState(null),[m,g]=qt.useState(null),[f,p]=qt.useState(!1),[x,S]=qt.useState(!1),[k,h]=qt.useState(!1),[N,R]=qt.useState(!1),[P,w]=qt.useState(""),[C,E]=qt.useState(!1),[_,j]=qt.useState(null),[q,U]=qt.useState(!1),[ae,ce]=qt.useState(""),[fe,T]=qt.useState([]),[V,A]=qt.useState(!1),[ne,ie]=qt.useState(!1),[Fe,Se]=qt.useState(null);qt.useEffect(()=>{u(e)},[e]);let Ae=F=>{let nt=F.id===o.id&&F.email_deliveries===void 0?{...F,email_deliveries:o.email_deliveries}:F;u(nt),s?.(nt)},Ye=Object.entries(o.metadata??{}),Re=Math.max(0,_i(o)-o.amount_refunded),Xe=(o.status==="paid"||o.status==="partially_refunded")&&Re>0,I=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),B=Math.max(0,(o.shipping_total??0)-(o.shipping_refunded??0)),ee=fe.reduce((F,nt)=>F+M(o.line_items[nt]??{}),0)+(V?B:0),J=o.tax_total??0,pe=Math.max(0,(o.exclusive_tax_total??0)-o.line_items.reduce((F,nt)=>F+(nt.exclusiveTax??0),0)),Ue=I?V&&B>0?pe: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*ee/(o.amount_total+(o.shipping_total??0)))):0,ft=o.source==="subscription"&&(o.credit_applied??0)>0&&o.line_items.length===1?Math.min(ee+Ue,Re):ee+Ue,Qe=fe.length>0||V,Et=Qe?ft:va(ae,o.currency),be=vn(o.currency)?"1":"0.01",Me=async()=>{try{p(!0),v(null),g(null),await d.resendOrderReceipt(o.id);let F=await d.getOrder(o.id);Ae(F),g("Receipt email queued.")}catch(F){v(F instanceof Error?F.message:"Failed to resend receipt")}finally{p(!1)}},yt=async()=>{try{S(!0),v(null),g(null);let F=await d.resetOrderDownloads(o.id);Ae(F),h(!1),g("Download count reset.")}catch(F){v(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=mp.includes(o.status)||o.status==="refunded"&&o.line_items.some(F=>F.collectShippingAddress===!0&&F.amountNet===0&&!F.refunded&&!F.unavailableReason),ea=P.trim(),Je=pp.test(ea)&&ea.length<=Hc,wt=async F=>{try{E(!0),j(null),g(null);let nt=await d.setOrderFulfillment(o.id,{fulfilled:F,...F&&ea?{trackingNumber:ea}:{}});Ae(nt),w(""),g(F?"Marked as shipped.":"Marked as not shipped.")}catch(nt){nt instanceof ta&&nt.status===409?j(`This order is ${o.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):j(nt instanceof Error?nt.message:"Failed to update the order")}finally{E(!1)}},Ja=()=>{Se(null),ce(String(Dt(Re,o.currency))),T([]),A(!1),U(!0)},Mn=F=>T(nt=>nt.includes(F)?nt.filter(La=>La!==F):[...nt,F]),ye=async(F,nt)=>{if(a)try{ie(!0),Se(null),await a(o,F,nt);let La=await d.getOrder(o.id);Ae(La),U(!1),g("Refund issued.")}catch(La){Se(La instanceof Error?La.message:"Refund failed")}finally{ie(!1)}},Rt=async()=>{if(Qe){if(ft<=0){Se("The lines you picked were charged nothing");return}if(ft>Re){Se(`That selection exceeds the refundable remainder (${Q(Re,o.currency)})`);return}await ye(ft,{...fe.length>0?{line_items:[...fe].sort((nt,La)=>nt-La)}:{},...V?{shipping:!0}:{}});return}let F=va(ae,o.currency);if(F===null||F<=0){Se("Enter a valid refund amount");return}if(F>Re){Se(`Amount exceeds the refundable remainder (${Q(Re,o.currency)})`);return}await ye(F,{amount:F})},$=()=>ye(Re,{full:!0}),Pe=!o.subscription_history_only&&o.fulfillment_type==="download",zt=!o.subscription_history_only&&n&&It,Rn=bp(o),X=o.shipping_address?jc(o.shipping_address).join(`
|
|
4
|
+
`):"",oa=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,Sf=lc>0,dc=o.amount_subtotal!=null||oa||cc||(o.discount_total??0)>0,Nr=[];return o.subscription_history_only||Nr.push(O(Zo,{icon:f?O(Oi,{className:"af-h-4 af-w-4 af-animate-spin"}):O(Uc,{className:"af-h-4 af-w-4"}),disabled:f||o.fulfillment_status!=="fulfilled",onSelect:()=>{R(!1),Me()},children:"Resend receipt"},"resend")),Pe&&Nr.push(O(Zo,{icon:O(cp,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{R(!1),h(!0)},children:"Reset download count"},"reset")),Xe&&Nr.push(le("div",{children:[O(Zo,{icon:O(Vc,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{R(!1),Ja()},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(tp,{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(te,{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(ap,{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:!c,"aria-label":"Next order",children:O(np,{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:C,children:[C?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(se,{value:P,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:C}),le(y,{variant:"default",className:"af-shrink-0",onClick:()=>wt(!0),disabled:C||!Je,children:[C?O(Oi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):O(dp,{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(op,{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,nt)=>{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(vp,{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(te,{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(te,{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"})]},nt)})})}),Ye.length>0&&O(zn,{title:"Order details",children:O("dl",{className:"af-space-y-2",children:Ye.map(([F,nt])=>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(nt)})]},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)]}),oa&&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)}),Sf&&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(hp,{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(te,{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,nt)=>O("div",{children:F},nt))})}),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:Me,disabled:f||o.fulfillment_status!=="fulfilled",children:[f?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(ip,{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(en,{children:[le(tn,{children:[O(nn,{children:"Reset download count?"}),O(sn,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),le(an,{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:q,onOpenChange:F=>{!F&&!ne&&U(!1)},children:le(en,{children:[le(tn,{children:[O(nn,{children:"Refund order"}),le(sn,{children:["Refund up to ",Q(Re,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||B>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,nt)=>{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:fe.includes(nt),onChange:()=>Mn(nt),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)})]},nt)}),B>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(B,o.currency)})]})]})]}),le("div",{className:"af-space-y-2",children:[le(Oe,{htmlFor:"refund-amount",children:["Amount (",o.currency.toUpperCase(),")"]}),O(se,{id:"refund-amount",type:"number",min:"0",step:be,value:Qe?String(Dt(ft,o.currency)):ae,onChange:F=>ce(F.target.value),disabled:ne||Qe}),Qe&&O("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Fe&&O("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Fe}),le(an,{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 yp,RefreshCw as xp}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(yp,{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(xp,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function la({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 kp={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 Pp({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:n=!1,emptyMessage:r,onDetailOpenChange:i,maxRows:l,onViewAll:c}){let d=typeof l=="number",{api:o}=H(),u=Ei({refreshKey:a}),{orders:b,total:v,isLoading:m,error:g,page:f,pageSize:p,hasNextPage:x,hasPreviousPage:S,setPage:k,setPageSize:h,customerEmail:N,setCustomerEmail:R,setStatusIn:P,from:w,setFrom:C,to:E,setTo:_,showAbandoned:j,setShowAbandoned:q,setUnfulfilledOnly:U,filters:ae,refetch:ce}=u,fe=na.useCallback(()=>o.exportOrdersCsv(ae),[o,ae]),[T,V]=na.useState("list"),[A,ne]=na.useState(null),[ie,Fe]=na.useState(""),[Se,Ae]=na.useState(""),[Ye,Re]=na.useState(!d&&n?"needs_shipping":"all"),[Xe,I]=na.useState(!1),[M,B]=na.useState(!!s&&!d),[ee,J]=na.useState(null);na.useEffect(()=>{if(!s||d)return;let X=!1;return B(!0),J(null),o.getOrder(s).then(oa=>{X||(ne(oa),V("detail"))}).catch(()=>{X||J("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{X||B(!1)}),()=>{X=!0}},[o,s,d]);let pe=na.useCallback(X=>{Re(X);let oa=Kc[X];P(oa.statusIn),U(oa.unfulfilledOnly)},[P,U]);na.useEffect(()=>{n&&!d&&U(!0)},[]);let Ue=na.useRef(!n);na.useEffect(()=>{Ue.current||m||(Ue.current=!0,b.length===0&&pe("all"))},[m,b.length,pe]);let ft=T==="detail"&&!!A;na.useEffect(()=>{i?.(ft)},[ft,i]);let Qe=(w?1:0)+(E?1:0)+(j?1:0),Et=Qe>0||!!N||!!Se,be=!!w&&!!E&&w>E,Me=!d||!!c,yt=X=>{if(d){c?.();return}ne(X),V("detail")},It=()=>{V("list"),ne(null),ce()},Mt=X=>{let oa=X.trim();if(!oa){Ae(""),N&&R("");return}if(oa.startsWith("#")||/^\d+$/.test(oa)){Ae(oa),N&&R("");return}Ae(""),R(oa)},et=()=>{Fe(""),Ae(""),R(""),C(""),_(""),q(!1),I(!1)},ea=Se.replace(/^#/,"").toLowerCase(),Je=ea?b.filter(X=>String(X.order_number??"")===ea||X.id.toLowerCase().startsWith(ea)):b,wt=d?Je.slice(0,l):Je,Ja=A?b.findIndex(X=>X.id===A.id):-1,Mn=Ja>0,ye=Ja>=0&&Ja<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(Sp,{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[Ja-1]):void 0,onNextOrder:ye?()=>ne(b[Ja+1]):void 0,hasPrevOrder:Mn,hasNextOrder:ye},A.id)});let $=Ve("div",{className:"af-mb-4 af-space-y-3",children:[ee&&z("p",{className:"af-text-xs af-text-muted-foreground",children:ee}),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:()=>pe(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:kp[X]},X))}),Ve("div",{className:"af-relative af-w-full af-max-w-xs",children:[z(Rp,{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(se,{type:"text",value:ie,onChange:X=>Fe(X.target.value),onBlur:()=>Mt(ie),onKeyDown:X=>{X.key==="Enter"&&(X.preventDefault(),Mt(ie))},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:Qe>0?"secondary":"ghost",size:"sm",onClick:()=>I(X=>!X),"aria-expanded":Xe,children:[z(_p,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Qe>0&&z(te,{variant:"secondary",className:"af-ml-2",children:Qe})]}),Et&&z(y,{type:"button",variant:"ghost",size:"sm",onClick:et,children:"Clear filters"}),z(wa,{fetchCsv:fe,filename:"orders",disabled:!!Se,className:"af-ml-auto"})]}),(Xe||!!w||!!E)&&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(se,{id:"orders-from",type:"date",value:w,max:E||void 0,onChange:X=>C(X.target.value),className:"af-w-[170px]"}),z(Oe,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),z(se,{id:"orders-to",type:"date",value:E,min:w||void 0,onChange:X=>_(X.target.value),className:"af-w-[170px]"}),!Kc[Ye].statusIn&&z(y,{type:"button",variant:j?"secondary":"ghost",size:"sm",onClick:()=>q(!j),"aria-pressed":j,children:j?"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:[d?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(lt,{children:[z(ct,{children:Ve(Ee,{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(dt,{"aria-hidden":"true",children:[0,1,2,3,4].map(X=>Ve(Ee,{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(g)return Ve("div",{className:t,children:[d?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&&f===0)return Et||Pe?Ve("div",{className:t,children:[!d&&$,z(la,{children:"No orders match these filters."})]}):z("div",{className:t,children:z(tr,{icon:Np,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!d&&z(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>q(!0),children:"Show abandoned checkouts"})})});let zt=f*p+1,Rn=Math.min((f+1)*p,v);return Ve("div",{className:t,children:[d?null:$,z("div",{className:"af-space-y-3 lg:af-hidden",children:wt.map(X=>Ve("button",{type:"button",onClick:()=>yt(X),disabled:!Me,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Me?" hover:af-bg-muted/50":""}`,children:[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(te,{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(lt,{children:[z(ct,{children:Ve(Ee,{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(dt,{children:wt.map(X=>Ve(Ee,{onClick:Me?()=>yt(X):void 0,className:Me?"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:oa=>{oa.stopPropagation(),yt(X)},disabled:!Me,"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${Me?" hover:af-underline":""}`,children:os(X)}),X.is_test&&z(te,{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))})]})}),d?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:ea?`${Je.length} matching this page`:`Showing ${zt}-${Rn} of ${v}`}),Ve(un,{value:String(p),onValueChange:X=>h(Number(X)),children:[z(Xa,{className:"af-w-[70px] af-h-8",children:z(fn,{})}),Ve(Qa,{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(f-1),disabled:!S,children:[z(wp,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ve(y,{variant:"outline",size:"sm",onClick:()=>k(f+1),disabled:!x,children:["Next",z(Gc,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function bs(e){return z(Pp,{...e},e.maxRows==null?"full":"compact")}import*as ar from"react";import{ChevronLeft as Ip,ChevronRight as Ap,Eye as Dp,Search as Op,Users as Lp}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),[c,d]=Va.useState(null),[o,u]=Va.useState(0),[b,v]=Va.useState(e),[m,g]=Va.useState(""),f=Va.useRef(0),p=Va.useCallback(async()=>{let S=++f.current;try{l(!0),d(null);let k={limit:b,offset:o*b};m.trim()&&(k.email=m.trim());let h=await t.getCustomers(k);if(S!==f.current)return;s(h.customers),r(h.total)}catch(k){if(S!==f.current)return;d(k instanceof Error?k:new Error("Failed to fetch customers"))}finally{S===f.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:c,page:o,pageSize:b,hasNextPage:o<x-1,hasPreviousPage:o>0,setPage:u,setPageSize:S=>{v(S),u(0)},email:m,setEmail:S=>{g(S),u(0)},refetch:p}}import*as Ls from"react";import{ArrowLeft as Cp,Loader2 as Tp}from"lucide-react";import{jsx as rt,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 Ep(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([]),[c,d]=Ls.useState(!0),[o,u]=Ls.useState(null);Ls.useEffect(()=>{let m=!1;return d(!0),u(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([g,f])=>{m||(r(g),l(f.orders))}).catch(g=>{m||u(g instanceof Error?g.message:"Failed to load customer")}).finally(()=>{m||d(!1)}),()=>{m=!0}},[s,e.id,e.email]);let b=n?.addresses??[],v=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:[rt(Cp,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),rt("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)]})]}),c?rt("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:rt(Tp,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):o?rt("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:[rt($n,{deliveries:n?.email_deliveries}),ba("div",{children:[rt("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:[rt("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),rt("span",{children:e.email})]}),e.name&&ba("div",{className:"af-flex af-gap-2",children:[rt("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),rt("span",{children:e.name})]}),e.phone&&ba("div",{className:"af-flex af-gap-2",children:[rt("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),rt("span",{children:e.phone})]}),ba("div",{className:"af-flex af-gap-2",children:[rt("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),rt("span",{children:v})]})]})]}),b.length>0&&ba("div",{children:[rt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),rt("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&&rt(te,{variant:"secondary",className:"af-mb-1",children:"Default"}),Ep(m).map((g,f)=>rt("div",{children:g},f))]},m.id))})]}),ba("div",{children:[rt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),i.length===0?rt("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):ba(lt,{children:[rt(ct,{children:ba(Ee,{children:[rt(K,{children:"Date"}),rt(K,{children:"Amount"}),rt(K,{children:"Status"})]})}),rt(dt,{children:i.map(m=>ba(Ee,{children:[rt(Z,{className:"af-text-muted-foreground",children:Jc(m.created_at)}),rt(Z,{children:Q(is(m),m.currency)}),rt(Z,{children:rt(Ds,{status:m.status})})]},m.id))})]})]})]})]})}import{Fragment as Fp,jsx as He,jsxs as Yt}from"react/jsx-runtime";function Bp(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:c,setPage:d,setPageSize:o,email:u,setEmail:b,refetch:v}=$i(),{api:m}=H(),g=ar.useCallback(()=>m.exportCustomersCsv(),[m]),[f,p]=ar.useState("list"),[x,S]=ar.useState(null),[k,h]=ar.useState(""),N=E=>{S(E),p("detail")},R=()=>{p("list"),S(null),v()};if(f==="detail"&&x)return He("div",{className:e,children:He(Ui,{customer:x,onBack:R})});let P=Yt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[He(se,{type:"email",value:k,onChange:E=>h(E.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:E=>{E.key==="Enter"&&(E.preventDefault(),b(k.trim()))}}),Yt(y,{type:"button",variant:"outline",size:"sm",onClick:()=>b(k.trim()),children:[He(Op,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),u&&He(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),b("")},children:"Clear"}),He(wa,{fetchCsv:g,filename:"customers",className:"af-ml-auto"})]});if(s)return Yt("div",{className:e,children:[P,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 Yt("div",{className:e,children:[P,He("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Yt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&r===0)return Yt("div",{className:e,children:[u&&P,Yt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[He(Lp,{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:u?"No customers match that email.":Yt(Fp,{children:["No customers yet.",He("br",{}),"Customers appear here after their first purchase."]})})]})]});let w=r*i+1,C=Math.min((r+1)*i,a);return Yt("div",{className:e,children:[P,Yt(lt,{children:[He(ct,{children:Yt(Ee,{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(dt,{children:t.map(E=>Yt(Ee,{children:[He(Z,{className:"af-font-medium",children:E.email}),He(Z,{children:E.name||He("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),He(Z,{children:E.phone||He("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),He(Z,{className:"af-text-muted-foreground",children:Bp(E.created_at)}),He(Z,{className:"af-text-right",children:He(y,{variant:"ghost",size:"icon",onClick:()=>N(E),title:"View customer",children:He(Dp,{className:"af-h-4 af-w-4"})})})]},E.id))})]}),Yt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Yt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Yt("span",{children:["Showing ",w,"-",C," of ",a]}),Yt(un,{value:String(i),onValueChange:E=>o(Number(E)),children:[He(Xa,{className:"af-w-[70px] af-h-8",children:He(fn,{})}),Yt(Qa,{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"})]}),Yt("div",{className:"af-flex af-items-center af-gap-2",children:[Yt(y,{variant:"outline",size:"sm",onClick:()=>d(r-1),disabled:!c,children:[He(Ip,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Yt(y,{variant:"outline",size:"sm",onClick:()=>d(r+1),disabled:!l,children:["Next",He(Ap,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as je from"react";import{ArrowLeft as Mp,ChevronLeft as $p,ChevronRight as Xc,Copy as Up,Download as Vp,ExternalLink as Hp,FileText as td,Loader2 as zp,Search as jp}from"lucide-react";import*as Jt from"react";function nr({initialPageSize:e=25,refreshKey:t,includeAggregates:a=!1}={}){let{api:s}=H(),[n,r]=Jt.useState([]),[i,l]=Jt.useState(0),[c,d]=Jt.useState(null),[o,u]=Jt.useState(!0),[b,v]=Jt.useState(null),[m,g]=Jt.useState(0),[f,p]=Jt.useState(e),[x,S]=Jt.useState(void 0),[k,h]=Jt.useState(""),[N,R]=Jt.useState(""),[P,w]=Jt.useState(""),[C,E]=Jt.useState(""),[_,j]=Jt.useState(""),q=x?x.join(","):"",U=Jt.useRef(0),ae=Jt.useCallback(async()=>{let fe=++U.current;u(!0),v(null);try{let T={labels:q?q.split(","):void 0,customerEmail:k||void 0,q:N||void 0,from:P||void 0,to:C||void 0,retainerId:_||void 0,includeAggregates:a,limit:f,offset:m*f},V=await s.getInvoices(T);if(fe!==U.current)return;if(m>0&&m*f>=V.total){g(Math.max(0,Math.ceil(V.total/f)-1));return}r(V.invoices),l(V.total),a&&d(V.aggregates??null)}catch(T){if(fe!==U.current)return;v(T instanceof Error?T:new Error("Failed to fetch invoices"))}finally{fe===U.current&&u(!1)}},[s,q,k,N,P,C,_,m,f,a]);Jt.useEffect(()=>{ae()},[ae,t]);let ce=fe=>T=>{g(0),fe(T)};return{invoices:n,total:i,aggregates:c,isLoading:o,error:b,page:m,pageSize:f,hasNextPage:(m+1)*f<i,hasPreviousPage:m>0,setPage:g,setPageSize:ce(p),labels:x,setLabels:ce(S),customerEmail:k,setCustomerEmail:ce(h),q:N,setQ:ce(R),from:P,setFrom:ce(w),to:C,setTo:ce(E),retainerId:_,setRetainerId:ce(j),clearFilters:()=>{g(0),S(void 0),h(""),R(""),w(""),E(""),j("")},refetch:ae}}import{Fragment as Jp,jsx as L,jsxs as oe}from"react/jsx-runtime";var qp={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`:qp[e.label]??e.label}function Wp(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"},Gp={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:[L(te,{variant:Wp(e.label),className:t,children:tl(e)}),e.collection_method==="charge_automatically"&&L(te,{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 L(te,{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 Kp(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 Zp(e){hi(new Blob([ad(e)],{type:"text/csv;charset=utf-8"}),bi("invoices"))}function Yp({className:e,refreshKey:t,initialInvoiceId:a,onDetailOpenChange:s,onConnectStripe:n,onUpgradePlan:r,needsPaidPlan:i=!1,retainerFilter:l=null,onClearRetainerFilter:c,maxRows:d,onViewAll:o}){let u=typeof d=="number",{api:b}=H(),{invoices:v,total:m,isLoading:g,error:f,page:p,pageSize:x,hasNextPage:S,hasPreviousPage:k,setPage:h,labels:N,setLabels:R,customerEmail:P,setCustomerEmail:w,q:C,setQ:E,from:_,setFrom:j,to:q,setTo:U,retainerId:ae,setRetainerId:ce,refetch:fe}=nr({refreshKey:t}),[T,V]=je.useState(typeof d=="number"?"all":"open"),[A,ne]=je.useState(""),[ie,Fe]=je.useState(null),Se=je.useRef(0),Ae=!u||!!o,Ye=je.useCallback($=>{if(u){o?.();return}Se.current++,Xe(!1),Fe($)},[u,o]),[Re,Xe]=je.useState(!1),[I,M]=je.useState(0),[B,ee]=je.useState(null),[J,pe]=je.useState(!1),[Ue,ft]=je.useState(0);je.useEffect(()=>{Fe($=>{if(!$)return $;let Pe=v.find(zt=>zt.id===$.id);return Pe&&Pe!==$?Pe:$})},[v]);let[Qe,Et]=je.useState(!1),[be,Me]=je.useState(null),yt=async()=>{if(!Qe){Et(!0),Me(null);try{let{invoices:$,total:Pe,truncated:zt}=await Kp(b,{labels:N,customerEmail:P,q:C,from:_,to:q,retainerId:ae});Zp($),Me(zt?`Exported the first ${$.length.toLocaleString()} of ${Pe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Me("Couldn't export \u2014 try again.")}finally{Et(!1)}}},It=!P&&!C&&!_&&!q&&!ae,[Mt,et]=je.useState(null);je.useEffect(()=>{if(g||m>0||!It||T!=="open")return;let $=!1;return b.getInvoices({limit:1}).then(Pe=>{$||et(Pe.total>0)}).catch(()=>{$||et(!0)}),()=>{$=!0}},[b,g,m,It,T,t]),je.useEffect(()=>{R(u?Hi.all:Hi.open)},[]),je.useEffect(()=>{let $=l?.id??"";$!==ae&&(ce($),$&&(V("all"),R(Hi.all),w(""),E(""),ne(""),j(""),U("")))},[l?.id]),je.useEffect(()=>{let $=!1;return pe(!1),b.getInvoiceSettings().then(Pe=>{$||ee({payments_active:Pe.payments_active,blocked:Pe.blocked})}).catch(()=>{$||pe(!0)}),()=>{$=!0}},[b,t,Ue]),je.useEffect(()=>{if(!a||u)return;let $=!1,Pe=Se.current;return Xe(!1),b.getInvoice(a).then(zt=>{!$&&Pe===Se.current&&Fe(zt)}).catch(()=>{!$&&Pe===Se.current&&Xe(!0)}),()=>{$=!0}},[b,a,I,u]),je.useEffect(()=>{s?.(ie!==null)},[ie,s]);let ea=$=>{V($),R(Hi[$])},Je=$=>{let Pe=$.trim();if(!Pe){C&&E(""),P&&w("");return}if(Pe.includes("@")){C&&E(""),w(Pe);return}P&&w(""),E(Pe.replace(/^#/,""))},wt=v,Ja=u?wt.slice(0,d):wt,Mn=Re&&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. ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>M($=>$+1),children:"Retry opening invoice"})]});if(ie)return oe("div",{className:e,children:[Mn,L(al,{invoice:ie,refreshKey:t,onBack:()=>{Ye(null),fe()}},ie.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. ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>ft($=>$+1),children:"Retry setup check"})]}),Mn,B?.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",B.blocked.reason?`: ${B.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(te,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",l.label]}),c&&L(y,{type:"button",variant:"link",size:"sm",onClick:c,children:"Clear schedule filter"})]}),oe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[L("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($=>L("button",{type:"button","aria-pressed":T===$,onClick:()=>ea($),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:[L(jp,{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"}),L(se,{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:[L(Oe,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),L(se,{id:"invoices-from",type:"date",value:_,max:q||void 0,onChange:$=>j($.target.value),className:"af-invoice-date af-w-[150px]"})]}),oe("div",{className:"af-flex af-items-center af-gap-2",children:[L(Oe,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),L(se,{id:"invoices-to",type:"date",value:q,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:Qe||g||!!f||m===0,"aria-busy":Qe,children:[L(Vp,{className:"af-h-4 af-w-4 af-mr-1"}),Qe?"Exporting\u2026":"Export CSV (all matching)"]})]}),be&&L("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:be})]});return g?oe("div",{className:e,children:[u?null:ye,L("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:[L(G,{className:"af-h-4 af-w-20"}),L(G,{className:"af-h-4 af-w-16"})]}),L(G,{className:"af-mt-2 af-h-3 af-w-40"})]},$))})]}):f?oe("div",{className:e,children:[u?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."," ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>void fe(),children:"Retry"})]})]}):m===0&&It&&(T==="all"||Mt===!1)&&(T==="open"||T==="all")?B?.blocked?oe("div",{className:e,children:[u?null:ye,L(zi,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):i?oe("div",{className:e,children:[u?null:ye,L(zi,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):B&&!B.payments_active?oe("div",{className:e,children:[u?null:ye,L(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:[u?null:ye,L(zi,{heading:"No invoices yet",body:!B||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:[u?null:ye,Ja.length===0?L("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(Jp,{children:[L("div",{className:"af-space-y-3 lg:af-hidden",children:Ja.map($=>oe("button",{type:"button",onClick:()=>Ye($),disabled:!Ae,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ae?" hover:af-bg-muted/50":""}`,children:[oe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[L("span",{className:"af-font-medium",children:sr($)}),L(Or,{invoice:$})]}),L("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:$.customer_name??$.customer_email??"\u2014"}),$.delivery&&L("div",{className:"af-mt-1",children:L(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:[L("span",{children:$.collection_method==="charge_automatically"?"Automatic collection":$.due_at?`Due ${hn($.due_at)}`:"Due on receipt"}),L("span",{className:"af-font-medium af-tabular-nums",children:Q($.amount_due??$.amount_total,$.currency)})]})]},$.id))}),L("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(lt,{children:[L(ct,{children:oe(Ee,{children:[L(K,{children:"Invoice"}),L(K,{children:"Created"}),L(K,{children:"Customer"}),L(K,{children:"Due"}),L(K,{className:"af-text-right",children:"Amount"}),L(K,{children:"Status"}),L(K,{children:"Delivery"}),L(K,{className:"af-w-8"})]})}),L(dt,{children:Ja.map($=>oe(Ee,{className:Ae?"af-cursor-pointer":void 0,onClick:Ae?()=>Ye($):void 0,children:[L(Z,{className:"af-font-medium",children:L("button",{type:"button",disabled:!Ae,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ae?" hover:af-underline":""}`,onClick:Pe=>{Pe.stopPropagation(),Ye($)},"aria-label":`Open invoice ${sr($)}`,children:sr($)})}),L(Z,{children:hn($.created_at)}),oe(Z,{children:[L("div",{children:$.customer_name??"\u2014"}),L("div",{className:"af-text-xs af-text-muted-foreground",children:$.customer_email})]}),L(Z,{children:$.collection_method==="charge_automatically"?"Automatic":$.due_at?hn($.due_at):"On receipt"}),L(Z,{className:"af-text-right af-tabular-nums",children:Q($.amount_due??$.amount_total,$.currency)}),L(Z,{children:L(Or,{invoice:$})}),L(Z,{children:L(ji,{delivery:$.delivery})}),L(Z,{children:L(Xc,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},$.id))})]})}),u?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:[L(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(p-1),disabled:!k,"aria-label":"Previous page",children:L($p,{className:"af-h-4 af-w-4"})}),oe("span",{className:"af-tabular-nums",children:[p*x+1,"\u2013",Math.min((p+1)*x,m)]}),L(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(p+1),disabled:!S,"aria-label":"Next page",children:L(Xc,{className:"af-h-4 af-w-4"})})]})]})]})]})}function zi({heading:e,body:t,action:a}){return L(tr,{icon:td,heading:e,body:t,action:a})}function ys(e){return L(Yp,{...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),[c,d]=je.useState(null),[o,u]=je.useState(!1),[b,v]=je.useState(!1),m=je.useRef(0),[g,f]=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(j=>{_||f({source:e,value:j})}).catch(()=>{_||x(!0)}),()=>{_=!0}},[n,e,a,S]);let h=g?.source===e?g.value:e,N=h.collection_method==="charge_automatically";je.useEffect(()=>(m.current++,d(null),u(!1),v(!1),l(!1),()=>{m.current++}),[n,h,a]);let R=_=>_==null?"\u2014":Q(_,h.currency),P=async()=>{if(!(!h.pay_url||!ed()))try{await navigator.clipboard.writeText(h.pay_url),l(!0),setTimeout(()=>l(!1),1500)}catch{}},w=async()=>{if(c){d(null);return}let _=++m.current;v(!1),u(!0);try{let j=await n.getInvoicePreview(h.id);_===m.current&&d(j)}catch{_===m.current&&v(!0)}finally{_===m.current&&u(!1)}},C=h.bill_to,E=C?[C.company,C.name,C.address?.line1,C.address?.line2,[C.address?.city,C.address?.state,C.address?.postal_code].filter(Boolean).join(", "),C.address?.country,C.tax_id?`${C.tax_id.value}`:null,C.po_number?`PO ${C.po_number}`:null,C.service_period?`Service period: ${C.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:[L(Mp,{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)]}),L(Or,{invoice:h}),L(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. ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>k(_=>_+1),children:"Retry details"})]}),h.label==="failed"&&L("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"&&L("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(lt,{children:[L(ct,{children:oe(Ee,{children:[L(K,{children:"Description"}),L(K,{className:"af-text-right",children:"Qty"}),L(K,{className:"af-text-right",children:"Amount"})]})}),L(dt,{children:h.line_items.map((_,j)=>oe(Ee,{children:[L(Z,{style:{overflowWrap:"anywhere"},children:_.description}),L(Z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_.quantity}),L(Z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:R(_.amount)})]},j))})]}),oe("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[L(hs,{label:"Subtotal",value:R(h.amount_subtotal)}),(h.discount_total??0)>0&&L(hs,{label:"Discount",value:`-${R(h.discount_total)}`}),h.tax_total>0&&L(hs,{label:h.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:R(h.tax_total)}),L(hs,{label:"Total",value:R(h.amount_total),strong:!0}),h.credit_applied>0&&L(hs,{label:"Credit applied",value:`-${R(h.credit_applied)}`}),h.amount_due!==null&&h.amount_due!==h.amount_total&&L(hs,{label:"Amount due",value:R(h.amount_due),strong:!0}),h.amount_paid!==null&&h.amount_paid>0&&L(hs,{label:"Amount paid",value:R(h.amount_paid)}),h.amount_refunded>0&&L(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:[L("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:[L("div",{className:ls,children:"Note"}),L("div",{className:"af-whitespace-pre-wrap af-break-words",children:h.note})]}),h.footer&&oe("div",{children:[L("div",{className:ls,children:"Footer"}),L("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:h.footer})]})]}),c&&!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 ",c.subject]}),L("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),L("iframe",{title:"Invoice email preview",srcDoc:c.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),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:[L(bn,{label:"Created",value:hn(h.created_at)}),L(bn,{label:"Due",value:h.collection_method==="charge_automatically"?"Managed in Stripe":h.due_at?hn(h.due_at):"On receipt"}),h.paid_at&&L(bn,{label:"Paid",value:hn(h.paid_at)}),h.payment_method&&L(bn,{label:"Paid by",value:h.paid_out_of_band?`${h.payment_method} (recorded outside Stripe)`:h.payment_method}),h.payment_state!=="none"&&L(bn,{label:"Payment",value:h.payment_state==="processing"?"Processing":h.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),h.delivery&&L(bn,{label:"Delivery",value:`${el[h.delivery.state]} \xB7 ${h.delivery.recipient}`}),h.marked_uncollectible_at&&L(bn,{label:"Written off",value:hn(h.marked_uncollectible_at)}),h.correction_reason&&L(bn,{label:"Correction",value:h.correction_reason}),h.replaced_by_order_id&&L(bn,{label:"Replaced by",value:h.replaced_by_order_id}),h.collection_method==="charge_automatically"?L(bn,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):h.retainer_id&&L(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&&L(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:[L("div",{className:ls,children:"Reminders"}),N?L("div",{children:"View automatic payment reminders in Stripe."}):h.reminders.disabled?L("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),"."]}):L("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:[L("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:[Gp[_.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))]}),E.length>0&&oe("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[L("div",{className:ls,children:"Bill to"}),E.map((_,j)=>L("div",{className:"af-break-words",children:_},j))]}),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 P(),disabled:!ed(),children:[L(Up,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Copied":N?"Copy invoice link":"Copy pay link"]}),h.pdf_url&&L(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:[L(Hp,{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?L(zp,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):L(td,{className:"af-h-4 af-w-4 af-mr-1"}),c?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!N&&L("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),h.pay_url&&L("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:h.pay_url}),L("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:[L("span",{className:W(ls,"af-shrink-0"),children:e}),L("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:[L("dt",{className:W(ls,a&&"af-font-medium af-text-foreground"),children:e}),L("dd",{className:W("af-tabular-nums",a&&"af-font-semibold"),children:t})]})}import{Repeat as Xp}from"lucide-react";import{jsx as Wt,jsxs as En}from"react/jsx-runtime";var Qp={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 eg(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":Qp[e.status]}function rd(e){let t=e.interval==="year"?"every year":"every month";return`${Q(e.amount,e.currency)} ${t}`}function tg(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(te,{variant:eg(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:c=!1,onLoadMore:d,includeEnded:o=!1,onIncludeEndedChange:u,exportCsv:b,className:v}){let m=!!u;if(!t&&!a&&e.length===0&&!(m&&(o||l>0)))return null;let g=i!==void 0?Math.max(0,i-e.length):0;return En("section",{className:W("af-mb-6",v),"aria-label":"Recurring invoices",children:[En("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[Wt(Xp,{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:()=>u?.(!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(f=>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"})]},f))}):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(f=>{let p=r===f.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:f.customer_name??f.customer_email??"\u2014"}),Wt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:f.description})]}),Wt(nl,{retainer:f})]}),f.collection_method==="charge_automatically"?En("div",{className:"af-mt-2 af-space-y-1",children:[Wt(te,{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(f)}),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:[tg(f)," \xB7 ",f.cycles.count===0?"no invoices yet":`${f.cycles.paid} paid${f.cycles.open>0?`, ${f.cycles.open} open`:""}`]}),f.cycles.count>0&&Wt(y,{type:"button",variant:p?"secondary":"ghost",size:"sm",onClick:()=>n(f),"aria-pressed":p,children:p?"Showing invoices":"View invoices"})]}),f.status==="failed"&&f.operation?.last_error&&En("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",f.operation.last_error,". Ask in the chat to try again."]})]},f.id)})}),!t&&!a&&g>0&&d&&Wt("div",{className:"af-mt-2",children:Wt(y,{type:"button",variant:"outline",size:"sm",onClick:d,disabled:c,children:c?"Loading\u2026":`Load more (${g} more)`})})]})}import*as od from"react";import{AlertTriangle as id,CheckCircle2 as ag,CreditCard as sl,Loader2 as ng,RefreshCw as sg}from"lucide-react";import{jsx as kt,jsxs as ca}from"react/jsx-runtime";function ir({onConnectStripe:e,onUpgradePlan:t,whenActive:a,className:s}){let{status:n,isLoading:r,error:i,refetch:l}=gs(),[c,d]=od.useState(!1),o=async()=>{d(!0);try{await l()}finally{d(!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:ca("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:ca("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(ag,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),ca("div",{children:[kt("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),ca("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."]})]})]})}):ca("div",{className:`af-space-y-4 ${s||""}`,children:[n.reason==="needs_stripe"&&ca("div",{className:"af-space-y-3",children:[ca("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"}),ca("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?ca(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"&&ca("div",{className:"af-space-y-3",children:[ca("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"}),ca("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"&&ca("div",{className:"af-space-y-3",children:[ca("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"}),ca("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."})]})]}),ca("div",{className:"af-flex af-gap-2",children:[e&&n.stripe_account_connected&&ca(y,{onClick:e,children:[kt(sl,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),ca(y,{variant:"outline",onClick:o,disabled:c,children:[c?kt(ng,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):kt(sg,{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,c]=Ta.useState(null),d=Ta.useRef(0),o=Ta.useCallback(async()=>{let f=++d.current;try{i(!0),c(null);let p=await a.getProducts(e?{include:"stats"}:{});if(f!==d.current)return;n(p)}catch(p){if(f!==d.current)return;c(p instanceof Error?p:new Error("Failed to fetch products"))}finally{f===d.current&&i(!1)}},[a,e,t]);Ta.useEffect(()=>{o()},[o]);let u=Ta.useCallback(async f=>{let p=await a.createProduct(f);return n(x=>[p,...x]),p},[a]),b=Ta.useCallback(async(f,p)=>{let x=await a.updateProduct(f,p);return n(S=>rl(S,f,x)),x},[a]),v=Ta.useCallback(async f=>{await a.deleteProduct(f),n(p=>p.filter(x=>x.id!==f))},[a]),m=Ta.useCallback(async(f,p)=>{let x=await a.attachProductFile(f,p);return n(S=>rl(S,f,x)),x},[a]),g=Ta.useCallback(async(f,p)=>{let x=await a.attachProductFileFromUrl(f,p);return n(S=>rl(S,f,x)),x},[a]);return{products:s,isLoading:r,error:l,refetch:o,createProduct:u,updateProduct:b,deleteProduct:v,attachProductFile:m,attachProductFileFromUrl:g}}import*as Ea from"react";var il=["creating","active","paused","canceling"],rg=["canceled","failed"],ig={statuses:il},og={};function lr({refreshKey:e,includeEnded:t=!1,limit:a=50}={}){let{api:s}=H(),[n,r]=Ea.useState([]),[i,l]=Ea.useState(0),[c,d]=Ea.useState(0),[o,u]=Ea.useState(!0),[b,v]=Ea.useState(!1),[m,g]=Ea.useState(null),[f,p]=Ea.useState(t),x=Ea.useRef(0),S=Ea.useCallback(async()=>{let h=++x.current;u(!0),v(!1),g(null);try{let N=await s.getRetainers({statuses:f?void 0:il,limit:a,offset:0});if(h!==x.current)return;if(r(N.retainers),l(N.total),!f&&N.total===0){let R=await s.getRetainers({statuses:rg,limit:1,offset:0});if(h!==x.current)return;d(R.total)}else d(0)}catch(N){if(h!==x.current)return;g(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{h===x.current&&u(!1)}},[s,f,a]);Ea.useEffect(()=>{S()},[S,e]);let k=Ea.useCallback(async()=>{if(o||b||n.length>=i)return;let h=x.current;v(!0);try{let N=await s.getRetainers({statuses:f?void 0:il,limit:a,offset:n.length});if(h!==x.current)return;r(R=>{let P=new Set(R.map(w=>w.id));return[...R,...N.retainers.filter(w=>!P.has(w.id))]}),l(N.total)}catch(N){if(h!==x.current)return;g(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{h===x.current&&v(!1)}},[s,f,a,o,b,n.length,i]);return{retainers:n,total:i,endedTotal:c,hasMore:n.length<i,isLoading:o,isLoadingMore:b,error:m,includeEnded:f,setIncludeEnded:p,loadMore:k,refetch:S,filters:f?og:ig}}import{Fragment as gg,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,c]=cr.useState("list"),[d,o]=cr.useState(null),u=or(),{status:b,error:v}=gs(),m=b?.currency,g=S=>{o(S),c("edit")},f=()=>{o(null),c("create")},p=()=>{c("list"),o(null)},x=S=>{o(S),c("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(dg,{className:"af-h-4 af-w-4"}),"Products"]}),Ha(kn,{value:"orders",className:"af-gap-2",children:[gt(ug,{className:"af-h-4 af-w-4"}),"Orders"]}),Ha(kn,{value:"invoices",className:"af-gap-2",children:[gt(cg,{className:"af-h-4 af-w-4"}),"Invoices"]}),Ha(kn,{value:"customers",className:"af-gap-2",children:[gt(mg,{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(fg,{className:"af-h-4 af-w-4"}),"Setup"]})]}),gt(Pn,{value:"products",children:l==="list"?gt(Pi,{productsState:u,onSelectProduct:g,onCreateProduct:f}):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(lg,{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":d?.name})]}),l==="create"&&!m?gt("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:v?Ha("div",{className:"af-text-destructive",children:["Error: ",v.message]}):gt("div",{className:"af-text-muted-foreground",children:"Loading..."})}):gt(Ti,{productsState:u,product:l==="edit"?d:null,currency:m??"usd",onSaved:x},l==="edit"?d?.id??"edit":"new")]})}),gt(Pn,{value:"orders",children:gt(bs,{onRefund:s})}),gt(Pn,{value:"invoices",children:gt(pg,{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 pg({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a}){let s=lr(),[n,r]=cr.useState(null),[i,l]=cr.useState(!1);return Ha(gg,{children:[!i&>(rr,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:n?.id??null,onShowCycles:c=>r(d=>d?.id===c.id?null:c),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),c=jn.useRef(0),d=jn.useCallback(async()=>{let o=++c.current;try{r(!0),l(null);let u=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(o!==c.current)return;s(u)}catch(u){if(o!==c.current)return;l(u instanceof Error?u:new Error("Failed to fetch summary"))}finally{o===c.current&&r(!1)}},[t,e]);return jn.useEffect(()=>{d()},[d]),{summary:a,isLoading:n,error:i,refetch:d}}import{Fragment as ol,jsx as da,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:c,refetch:d}=dr({refreshKey:e}),[o,u]=dd.useState(!1),b=da("div",{className:"af-mb-6",children:c&&!i?da(xt,{message:"Couldn't load your revenue summary.",onRetry:()=>d()}):da("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:l||!i?ll(ol,{children:[da(pt,{label:"This week",children:da(G,{className:"af-h-6 af-w-24"})}),da(pt,{label:"Today",children:da(G,{className:"af-h-6 af-w-24"})}),da(pt,{label:"Needs attention",children:da(G,{className:"af-h-6 af-w-10"})})]}):da(ol,{children:(()=>{let v=cd(i.revenue.d7,i.currency),m=cd(i.revenue.today,i.currency);return ll(ol,{children:[da(pt,{label:"This week",detail:v.extra.length>0?da("div",{children:v.extra.map(g=>da("div",{children:g},g))}):void 0,children:v.headline}),da(pt,{label:"Today",detail:m.extra.length>0?da("div",{children:m.extra.map(g=>da("div",{children:g},g))}):void 0,children:m.headline}),da(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,da(bs,{refreshKey:e,initialOrderId:t,onDetailOpenChange:u,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 xg,Package as wg,Search as Sg}from"lucide-react";import*as qn from"react";import{ArrowLeft as hg,ImageOff as yg}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",vg=3;function bg(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let c=e.min_amount??t?.min_amount??null,d=e.max_amount??t?.max_amount??null;return c!==null&&d!==null?{text:`Buyer chooses (${Q(c,a)} \u2013 ${Q(d,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(n===null||r===null)return{text:"Varies by variant",compareAt:null};let i=n===r?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=bg(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(te,{variant:"destructive",children:"Out of stock"}):t.low_stock?Lr(te,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?In(te,{variant:"secondary",children:"Backorder"}):t.available===null?null:Lr(te,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?In(te,{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(te,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?In(te,{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<=vg&&In(te,{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(yg,{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),[c,d]=qn.useState(null),[o,u]=qn.useState(0),[b,v]=qn.useState(0);qn.useEffect(()=>{let h=!1;return l(!0),d(null),s.getProduct(e.id).then(N=>{h||r(N)}).catch(N=>{h||d(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,g=m.images.length>0?m.images:e.images,f=g[b]??g[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(hg,{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(te,{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:f,className:"af-h-48 af-w-full af-rounded-md af-border"}),g.length>1&&we("div",{className:"af-flex af-flex-wrap af-gap-2",children:g.map((h,N)=>we("button",{type:"button",onClick:()=>v(N),"aria-label":`Show photo ${N+1} of ${g.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"})]}):c?we(xt,{message:"Couldn't load this product's variants.",onRetry:()=>u(h=>h+1)}):k?we(Br,{title:`Variants \xB7 ${S.length}`,children:we("div",{className:"af-overflow-x-auto",children:Pt(lt,{children:[we(ct,{children:Pt(Ee,{children:[we(K,{children:"Variant"}),we(K,{children:"SKU"}),we(K,{className:"af-text-right",children:"Price"}),we(K,{children:"Stock"})]})}),we(dt,{children:S.map(h=>Pt(Ee,{children:[Pt(Z,{className:"af-font-medium",children:[h.title||h.option_values.map(N=>N.value).join(" / ")||"\u2014",!h.active&&we(te,{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 ge,jsxs as Ct}from"react/jsx-runtime";var Ng={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Rg=["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 _g(e){return e.inventory?.out_of_stock??!1}function kg(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 _g(e);default:return!0}}function Pg({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?ge("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):ge("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:ge(xg,{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:[ge("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),ge(Gi,{product:e,className:"af-mt-0.5"})]}),!e.active&&ge(te,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Ct("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ge(Ki,{product:e}),i>1&&Ct(te,{variant:"outline",children:[i," variants"]}),r&&ge(te,{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)}`:""," ",ge("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Cg(){return ge("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:[ge("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:[ge(G,{className:"af-w-32"}),ge(G,{className:"af-w-16"}),ge(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}),[c,d]=yn.useState(!1),[o,u]=yn.useState(null),[b,v]=yn.useState("all"),{api:m}=H(),g=yn.useCallback(()=>m.exportProductsCsv(),[m]),[f,p]=yn.useState(""),[x,S]=yn.useState("newest"),k=yn.useMemo(()=>{if(!t)return null;let q=null;for(let U of n)!U.stats||U.stats.units_sold===0||(!q||U.stats.units_sold>(q.stats?.units_sold??0))&&(q=U);return q},[n,t]),h=yn.useMemo(()=>n.filter(hd).length,[n]),N=f.trim().toLowerCase(),R=yn.useMemo(()=>{let U=[...n.filter(ae=>kg(ae,b)&&(!N||ae.name.toLowerCase().includes(N)))];return x==="name"?U.sort((ae,ce)=>ae.name.localeCompare(ce.name)):x==="best_selling"?U.sort((ae,ce)=>(ce.stats?.units_sold??0)-(ae.stats?.units_sold??0)):U.sort((ae,ce)=>bd(ce.created_at)-bd(ae.created_at)),U},[n,b,N,x]),P=b!=="all"||!!N,w=()=>{v("all"),p("")},C=r||i!==null&&n.length===0,E=ge("div",{className:"af-mb-6",children:ge("div",{className:W("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:C?Ct(ws,{children:[ge(pt,{label:"Products",children:ge(G,{className:"af-h-6 af-w-10"})}),t?Ct(ws,{children:[ge(pt,{label:"Best seller",children:ge(G,{className:"af-h-6 af-w-28"})}),ge(pt,{label:"Low stock",children:ge(G,{className:"af-h-6 af-w-10"})})]}):ge(pt,{label:"Active",children:ge(G,{className:"af-h-6 af-w-10"})})]}):Ct(ws,{children:[ge(pt,{label:"Products",children:n.length}),t?Ct(ws,{children:[ge(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?ge("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:k.name}):ge("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),ge(pt,{label:"Low stock",children:h})]}):ge(pt,{label:"Active",children:n.filter(q=>q.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:[ge("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:Rg.map(q=>ge("button",{type:"button","aria-pressed":b===q,onClick:()=>v(q),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===q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ng[q]},q))}),Ct("div",{className:"af-relative af-w-full af-max-w-xs",children:[ge(Sg,{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"}),ge(se,{type:"text",value:f,onChange:q=>p(q.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Ct(un,{value:x,onValueChange:q=>S(q),children:[ge(Xa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:ge(fn,{})}),Ct(Qa,{children:[ge(St,{value:"newest",children:"Newest"}),ge(St,{value:"name",children:"Name A\u2013Z"}),t&&ge(St,{value:"best_selling",children:"Best selling"})]})]}),P&&ge(y,{type:"button",variant:"ghost",size:"sm",onClick:w,children:"Clear filters"}),ge(wa,{fetchCsv:g,filename:"products",label:P?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&n.length===0?ge(G,{className:"af-h-4 af-w-28"}):ge("p",{className:"af-text-sm af-text-muted-foreground",children:P?`${R.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),j;return o?j=ge(vd,{product:o,showStats:t,onBack:()=>{u(null),l()}},o.id):r&&n.length===0?j=Ct(ws,{children:[_,ge(Cg,{}),ge("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):i&&n.length===0?j=ge("div",{className:"af-flex af-justify-center af-py-8",children:ge(xt,{message:"Couldn't load your products.",onRetry:()=>l()})}):n.length===0?j=Ct(la,{icon:ge(wg,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",ge("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):j=Ct(ws,{children:[_,i&&ge("div",{className:"af-mb-4",children:ge(xt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>l()})}),R.length===0?Ct(la,{children:["No products match these filters.",ge("br",{}),ge(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:w,children:"Show all products"})]}):ge("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:R.map(q=>ge(Pg,{product:q,showStats:t,onOpen:()=>u(q)},q.id))})]}),ge(Ut,{title:"Products",onBackToWebsite:a,hideBackButton:!!o,className:s,children:c?Ct(ws,{children:[ge(y,{variant:"ghost",onClick:()=>d(!1),children:"Back to products"}),ge(Qs,{})]}):Ct(ws,{children:[!o&&ge("div",{className:"af-mb-4 af-flex af-justify-end",children:ge(y,{variant:"outline",onClick:()=>d(!0),children:"Promo codes"})}),!o&&E,j]})})}import*as ja from"react";import{ArrowLeft as _d,Check as Tg,ChevronLeft as xd,ChevronRight as wd,ClipboardCopy as Eg,Mail as dl,Search as Ig,Users as Ag}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,c]=za.useState(null),[d,o]=za.useState(0),[u]=za.useState(e),[b,v]=za.useState(""),[m,g]=za.useState(void 0),f=za.useRef(0),p=za.useCallback(async({afterRemoval:x=!1}={})=>{let S=++f.current;try{i(!0),c(null);let k={limit:u,offset:d*u};b.trim()&&(k.q=b.trim()),m&&(k.source=m);let h=await a.getPeople(k);if(S!==f.current)return;if(x&&h.people.length===0&&d>0){o(d-1);return}n(h.people)}catch(k){if(S!==f.current)return;c(k instanceof Error?k:new Error("Failed to fetch people"))}finally{S===f.current&&i(!1)}},[a,d,u,b,m,t]);return za.useEffect(()=>{p()},[p]),{people:s,isLoading:r,error:l,page:d,pageSize:u,hasNextPage:s.length===u,hasPreviousPage:d>0,setPage:o,q:b,setQ:x=>{v(x),o(0)},source:m,setSource:x=>{g(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,c]=Wn.useState(null),d=Wn.useRef(0),o=Wn.useCallback(async()=>{if(e===null){n(null),i(!1),c(null);return}let u=++d.current;try{i(!0),c(null);let b=await a.getPerson(e);if(u!==d.current)return;n(b)}catch(b){if(u!==d.current)return;c(b instanceof Error?b:new Error("Failed to fetch person"))}finally{u===d.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",Dg="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 Og(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Lg({value:e,label:t}){let[a,s]=ja.useState(!1);return Og()?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(Tg,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):D(Eg,{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(te,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&D(te,{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 Bg=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Fg=40;function Mg(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),s=t.find(([n,r])=>Bg.test(n)&&typeof r=="string"&&r.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=Fg).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 $g(e){return e.replace(/_/g," ")}function Ug(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Vg({data:e}){let{message:t,rest:a}=Mg(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(Dg,"af-w-28 af-shrink-0 af-capitalize"),children:$g(s)}),D("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Ug(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(te,{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(Vg,{data:a})]})}function Hg(e){return e.charged_total??e.amount_total}function zg({email:e,refreshKey:t,onBack:a,onRemoved:s}){let{api:n}=H(),{person:r,isLoading:i,error:l,refetch:c}=Xi(e,{refreshKey:t}),d=async u=>{await n.deleteSubmission(u),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?c():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(Lg,{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(u=>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"})]},u)),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:()=>c()})}):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(lt,{children:[D(ct,{children:xe(Ee,{children:[D(K,{children:"Order"}),D(K,{children:"Date"}),D(K,{className:"af-text-right",children:"Total"}),D(K,{children:"Status"})]})}),D(dt,{children:r.orders.map(u=>xe(Ee,{children:[D(Z,{className:"af-whitespace-nowrap af-font-medium",children:os(u)}),D(Z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ur(u.created_at)}),D(Z,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:Q(Hg(u),u.currency)}),D(Z,{children:D(Ds,{status:u.status})})]},u.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(u=>D(kd,{formName:u.form_name,createdAt:u.created_at,data:u.data,onDelete:()=>d(u.id)},u.id))})]})]})]})}function jg({submissionId:e,onBack:t,onRemoved:a}){let{api:s}=H(),[n,r]=ja.useState(null),[i,l]=ja.useState(!0),[c,d]=ja.useState(null),[o,u]=ja.useState(0);return ja.useEffect(()=>{let b=!1;return l(!0),d(null),s.getSubmission(e).then(v=>{b||r(v)}).catch(v=>{b||d(v instanceof Error?v: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"})]}):c||!n?D("div",{className:"af-flex af-justify-center af-py-8",children:D(xt,{message:"Couldn't load this submission.",onRetry:()=>u(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 qg={all:"All",customers:"Customers",leads:"Leads"},Wg=["all","customers","leads"],Rd={all:void 0,customers:"customer",leads:"lead"};function Gg({refreshKey:e,onBackToWebsite:t,className:a,maxRows:s,onViewAll:n}){let r=typeof s=="number",{people:i,isLoading:l,error:c,page:d,pageSize:o,hasNextPage:u,hasPreviousPage:b,setPage:v,q:m,setQ:g,source:f,setSource:p,refetch:x,refetchAfterRemoval:S}=Ji({refreshKey:e}),[k,h]=ja.useState({kind:"list"}),[N,R]=ja.useState(""),P=f==="customer"?"customers":f==="lead"?"leads":"all",w=V=>{Rd[V]!==f&&p(Rd[V])},{api:C}=H(),E=ja.useCallback(()=>C.exportPeopleCsv({...m?{q:m}:{},...f?{source:f}:{}}),[C,m,f]),_=!r||!!n,j=V=>{if(r){n?.();return}V.email?h({kind:"person",email:V.email}):V.submission_id&&h({kind:"submission",submissionId:V.submission_id})},q=ja.useRef(!1),U=()=>{q.current=!0},ae=()=>{h({kind:"list"}),q.current?(q.current=!1,S()):x()},ce=V=>{let A=V.trim();A!==m&&g(A)},fe=r?i.slice(0,s):i,T;if(k.kind==="person")T=D(zg,{email:k.email,refreshKey:e,onBack:ae,onRemoved:U});else if(k.kind==="submission")T=D(jg,{submissionId:k.submissionId,onBack:ae,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:Wg.map(A=>D("button",{type:"button","aria-pressed":P===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",P===A?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:qg[A]},A))}),xe("div",{className:"af-relative af-w-full af-max-w-xs",children:[D(Ig,{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(se,{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(""),g("")},children:"Clear search"}),D(wa,{fetchCsv:E,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(lt,{children:[D(ct,{children:xe(Ee,{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(dt,{"aria-hidden":"true",children:[0,1,2,3,4].map(A=>xe(Ee,{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(c)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(fe.length===0&&d===0){let A=!!m||P!=="all";T=xe("div",{children:[A&&V,A?D(la,{children:m?"Nobody matches that search.":P==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):D(tr,{icon:Ag,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(la,{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:()=>v(d-1),children:[D(xd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let A=d*o+1,ne=d*o+i.length;T=xe("div",{children:[r?null:V,D("div",{className:"af-space-y-3 lg:af-hidden",children:fe.map((ie,Fe)=>xe("div",{onClick:_?()=>j(ie):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(),j(ie)},disabled:!_,"aria-label":`Open ${ie.name||ie.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(ie)}),ie.name&&ie.email&&D("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ie.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(ie.last_activity_at)}),ie.email&&D(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:D("a",{href:ul(ie.email),onClick:Se=>Se.stopPropagation(),"aria-label":`Email ${ie.email}`,children:D(dl,{className:"af-h-4 af-w-4"})})})]})]}),D("div",{className:"af-mt-2",children:Sd(ie)}),ie.latest_message_excerpt&&D("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:ie.latest_message_excerpt})]},ie.email??ie.submission_id??Fe))}),D("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:xe(lt,{children:[D(ct,{children:xe(Ee,{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(dt,{children:fe.map((ie,Fe)=>xe(Ee,{onClick:_?()=>j(ie):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(),j(ie)},disabled:!_,"aria-label":`Open ${ie.name||ie.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(ie)}),ie.name&&ie.email&&D("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:ie.email})]}),D(Z,{children:Sd(ie)}),D(Z,{className:"af-max-w-[320px]",children:ie.latest_message_excerpt?D("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:ie.latest_message_excerpt}):D("span",{className:"af-text-muted-foreground",children:"\u2014"})}),D(Z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ur(ie.last_activity_at)}),D(Z,{className:"af-w-8",children:ie.email&&D(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:D("a",{href:ul(ie.email),onClick:Se=>Se.stopPropagation(),"aria-label":`Email ${ie.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"})})]},ie.email??ie.submission_id??Fe))})]})}),!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:()=>v(d-1),disabled:!b,children:[D(xd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),xe(y,{variant:"outline",size:"sm",onClick:()=>v(d+1),disabled:!u,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(Gg,{...e},e.maxRows==null?"full":"compact")}import*as Ad from"react";import{ChevronLeft as Pd,ChevronRight as Kg,Repeat as Zg}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,c]=qa.useState(!0),[d,o]=qa.useState(null),[u,b]=qa.useState(0),[v,m]=qa.useState(e),[g,f]=qa.useState(void 0),p=qa.useRef(0),x=qa.useCallback(async()=>{let k=++p.current;try{c(!0),o(null);let h={limit:v,offset:u*v};g&&(h.status=g);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&&c(!1)}},[a,u,v,g,t]);qa.useEffect(()=>{x()},[x]);let S=Math.ceil(r/v);return{subscriptions:s,total:r,isLoading:l,error:d,page:u,pageSize:v,hasNextPage:u<S-1,hasPreviousPage:u>0,setPage:b,setPageSize:k=>{m(k),b(0)},status:g,setStatus:k=>{f(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(te,{variant:"outline",children:"Canceled"}):e.status==="past_due"?de(te,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?de(te,{variant:"warning",children:"Scheduled to cancel"}):de(te,{variant:"success",children:"Active"}):de(te,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Yg(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:Yg(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:c,hasNextPage:d,hasPreviousPage:o,setPage:u,status:b,refetch:v}=eo({refreshKey:e}),{api:m}=H(),g=Ad.useCallback(()=>m.exportSubscriptionsCsv(b?{status:b}:{}),[m,b]),f;if(r)f=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(lt,{children:[de(ct,{children:Tt(Ee,{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(dt,{"aria-hidden":"true",children:[0,1,2,3,4].map(p=>Tt(Ee,{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)f=de("div",{className:"af-flex af-justify-center af-py-8",children:de(xt,{message:"Couldn't load your subscriptions.",onRetry:()=>v()})});else if(s.length===0&&l===0)f=de(la,{icon:de(Zg,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(s.length===0)f=Tt("div",{children:[de(la,{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:()=>u(l-1),children:[de(Pd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let p=l*c+1,x=l*c+s.length;f=Tt("div",{children:[de("div",{className:"af-mb-3 af-flex af-justify-end",children:de(wa,{fetchCsv:g,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(te,{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(lt,{children:[de(ct,{children:Tt(Ee,{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(dt,{children:s.map(S=>Tt(Ee,{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(te,{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:()=>u(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:()=>u(l+1),disabled:!d,children:["Next",de(Kg,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return de(Ut,{title:"Subscriptions",onBackToWebsite:t,className:a,children:f})}import*as Zn from"react";import{Loader2 as iv}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"}},Jg=(e,t)=>e instanceof Error?e:new Error(t);function Xg(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),[c,d]=Na.useState(null),o=Na.useRef(null),[u,b]=Na.useState(()=>Od(s,e)),v=u.api!==s||u.siteId!==e,m=u;v&&(m=Od(s,e),b(m),r(null),l(!0),d(null));let g=Na.useRef(m);Bs(()=>{g.current!==m&&(g.current=m,o.current=null)},[m]);let f=(w,C)=>g.current===w&&C>w.applied,p=(w,C,E)=>f(w,C)?(w.applied=C,o.current=E,r(E),l(!1),!0):!1,x=async w=>{for(;w.writing;)await w.idle;let C=++w.seq;try{let E=await w.api.getSite(w.siteId);return p(w,C,E)&&d(null),{seq:C,error:null}}catch(E){return{seq:C,error:Jg(E,"Failed to load store settings")}}},S=(w,C)=>{let E=async()=>{if(g.current!==w)throw new Error("Not saved: the store switched to another site first.");w.writing=!0,w.idle=new Promise(j=>{w.markIdle=j});try{return await C(++w.seq)}finally{w.writing=!1,w.markIdle()}},_=w.queue.then(E,E);return w.queue=_.catch(()=>{}),_},k=Na.useCallback(async()=>{let w=await x(m);w.error&&f(m,w.seq)&&(d(w.error),l(!1))},[m]);Na.useEffect(()=>{k()},[k,t]);let h=Na.useCallback(w=>S(m,async C=>{let E=await m.api.updateSite(m.siteId,w),{currency_restatement:_,...j}=E;return p(m,C,j)&&d(q=>q instanceof ao?q:null),E}),[m]),N=Na.useRef(a);Bs(()=>{N.current=a});let R=Na.useCallback(async(w,C)=>{await S(m,()=>w());let E=await x(m);return E.error&&f(m,E.seq)&&o.current&&(p(m,E.seq,{...o.current,...C}),d(new ao(`Saved, but couldn't refresh settings: ${E.error.message}`))),g.current===m?o.current:null},[m]),P=Na.useCallback(w=>{let C=N.current;return R(()=>C(w),Xg(w))},[R]);return{site:v?null:n,isLoading:v||i,error:v?null:c,refetch:k,updateSite:h,saveInvoiceSettings:a?P:null}}import*as sa 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=sa.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]=sa.useState(null),[c,d]=sa.useState(null),o=i??a,u=async b=>{l(b),d(null);try{await s(b)}catch(v){d(no(v))}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 u(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||c)&&Gn("div",{className:"af-space-y-1 af-pl-6",children:[n&&r&&xn(Wa,{children:r}),c&&xn(Fr,{children:c})]})]})}var ml=(e,t)=>JSON.stringify(e)===JSON.stringify(t),fl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Qg(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]=sa.useState(e),[r,i]=sa.useState([]),l=sa.useRef(e),c=sa.useRef(e),d=sa.useRef(s);Bs(()=>{c.current=e,d.current=s});let o=sa.useRef(t?.when);sa.useEffect(()=>{let b=Object.is(o.current,t?.when)?[]:t?.fields??[];if(o.current=t?.when,ml(l.current,c.current)&&b.length===0)return;let v=Qg(d.current,l.current,c.current,b);l.current=c.current,n(v.draft),v.dropped.length&&i(v.dropped)},[a,t?.when]);let u=sa.useCallback(b=>{n(b??c.current),i([])},[]);return{draft:s,setDraft:n,dirty:JSON.stringify(s)!==a,reset:u,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]=sa.useState(!1),[a,s]=sa.useState(null),n=sa.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 ev,Plus as tv,X as Hd}from"lucide-react";import{Fragment as rv,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:c,dropped:d}=fr($d(e),{when:e.currency,fields:["rates","threshold"]}),{saving:o,error:u,setError:b,run:v}=pr(),m=e.currency.toUpperCase(),g=()=>v(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 C=w.label.trim(),E=va(w.amount,e.currency);if(!C)throw new Error("Every rate needs a name.");if(w.amount.trim()===""||E===null)throw new Error(`Enter a price for "${C}" (0 for free).`);h.push({label:C,amount:E})}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){c();return}("shipping_rates"in p||"free_shipping_over"in p)&&(p.expected_currency=e.currency);let P;try{P=await t(p)}catch(w){throw w instanceof ta&&w.details?.code==="currency_changed"&&await a?.(),w}c($d(P))}),f=(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(se,{"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(se,{"aria-label":`Rate ${x+1} name`,value:p.label,placeholder:"Standard",onChange:S=>f(x,{label:S.target.value})}),Ne(se,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:p.amount,placeholder:"0",className:"af-w-32",onChange:S=>f(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(tv,{})," Add rate"]}),Ne(Wa,{children:"Buyers pick one at checkout. The first is preselected."})]}),De("label",{className:An,children:["Free shipping over (",m,")",Ne(se,{"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."})]}),d.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:u,onSave:()=>void g(),onDiscard:()=>{b(null),c()}}),s]})}var pl="exclusive",av=[{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 nv({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(ev,{"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:c,run:d}=pr(),[o,u]=wn.useState(!1),b=e.stripe_tax_enabled,v=b||o,m=()=>d(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)}),g=()=>d(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),u(!1)}),f=(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:av.map(p=>Ne("li",{children:Ne(nv,{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:v,onSave:async p=>{if(o){u(!1),c(null),r();return}if(p&&!e.tax_behavior){u(!0);return}return t({stripe_tax_enabled:p})}}),v&&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."}),f&&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 g(),children:"Turn on"}),Ne(y,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>{u(!1),c(null),r()},children:"Cancel"})]}),l&&Ne(Fr,{children:l})]}):Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void m(),onDiscard:()=>{c(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:c,run:d}=pr(),o=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),u=()=>d(async()=>{let b={},v=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.");v=Math.round(p*100)}o&&v!==e.tax_rate_bps&&(b.tax_rate_bps=v),v!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let m=a.taxId.trim()||null;m!==e.tax_id&&(b.tax_id=m);let g=a.label.trim()||null;if(g!==e.tax_label&&(b.tax_label=g),Object.keys(b).length===0){r();return}let f=await t(b);r(Ud(f))});return De("fieldset",{disabled:i,className:"af-space-y-4",children:[De("label",{className:An,children:["Tax rate (%)",Ne(se,{"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(se,{"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(se,{"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 u(),onDiscard:()=>{c(null),r()}})]})}function Gd({site:e,updateSite:t,onChangeStart:a}){let[s,n]=wn.useState(e.currency.toUpperCase()),[r,i]=wn.useState(!1),[l,c]=wn.useState(!1),[d,o]=wn.useState(null),u=e.currency.toUpperCase(),b=wn.useRef(u);wn.useEffect(()=>{b.current!==u&&(n(p=>p===b.current?u:p),b.current=u)},[u]);let v=s.trim().toUpperCase(),m=v!==u,g=/^[A-Z]{3}$/.test(v),f=async()=>{c(!0);let p=a?.(),x=!1;o(null);try{let S=await t({currency:v.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{c(!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(se,{"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(rv,{children:[Ne(y,{type:"button",size:"sm",disabled:!g,onClick:()=>i(!0),children:"Change currency"}),Ne(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>{n(u),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 ",u," to ",v,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",v,":"," ",Q(2e3,u)," becomes ",Q(2e3,v),". 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 f(),children:"Confirm change"}),Ne(y,{type:"button",size:"sm",variant:"ghost",disabled:l,onClick:()=>i(!1),children:"Cancel"})]})]}),d&&Ne(Fr,{children:d})]})}function Vd(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function sv(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:c,run:d}=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: ",sv(e.invoice_reminder_schedule)]}),De("p",{children:["Footer: ",e.invoice_footer||"None"]}),Ne(Md,{what:"invoice defaults"})]});let o=()=>d(async()=>{let u={},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&&(u.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 g=[...new Set(m)].sort((x,S)=>x-S);gl(g,e.invoice_reminder_schedule)||(u.reminder_schedule=g);let f=a.footer.trim()||null;if(f!==e.invoice_footer&&(u.footer=f),Object.keys(u).length===0){r();return}let p=await t(u);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(se,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:a.dueDays,onChange:u=>s({...a,dueDays:u.target.value})})]}),De("label",{className:An,children:["Reminder schedule",Ne(se,{"aria-label":"Reminder schedule",value:a.reminders,placeholder:"Off",onChange:u=>s({...a,reminders:u.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:u=>s({...a,footer:u.target.value})})]}),Ne(mr,{dirty:n,saving:i,error:l,onSave:()=>void o(),onDiscard:()=>{c(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:c,run:d}=pr(),[o,u]=wn.useState(""),[b,v]=wn.useState(null),m=()=>{let f=o.trim().toLowerCase();if(f){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f)){v("Enter a valid email address.");return}if(a.some(p=>p.toLowerCase()===f)){v("Already added.");return}s([...a,f]),u(""),v(null)}},g=()=>d(async()=>{let f=await t({default_email_recipients:a});r(f.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(f=>De(te,{variant:"secondary",className:"af-gap-1",children:[f,Ne("button",{type:"button","aria-label":`Remove ${f}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(a.filter(p=>p!==f)),children:Ne(Hd,{className:"af-h-3 af-w-3"})})]},f)),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(se,{"aria-label":"Add notification email",type:"email",value:o,placeholder:"Add email address",onChange:f=>{u(f.target.value),v(null)},onKeyDown:f=>{f.key==="Enter"&&(f.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 g(),onDiscard:()=>{c(null),r()}})]})}import{jsx as ln,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:c,error:d,refetch:o,updateSite:u}=Ss({siteId:e,refreshKey:t}),b=Zn.useRef(o),v=Zn.useRef(e);Bs(()=>{b.current=o,v.current=e});let m=Zn.useRef({}),[g,f]=Zn.useState([]),p=g.some(N=>N.siteId===e),x=Zn.useCallback(()=>{let N={siteId:e},R=b.current;return f(P=>[...P,N]),P=>{let w=()=>f(E=>E.filter(_=>_!==N));!(v.current===N.siteId)||P&&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]),c)return Yd("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[ln(iv,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!l)return ln("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d?.message??"Could not load store settings."});if(!l.payments_active)return ln(ir,{className:i,onConnectStripe:n,onUpgradePlan:r,whenActive:ln("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:u,refetch:o};return Yd("div",{className:`af-space-y-6 ${i??""}`,children:[d&&ln("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d.message}),ln(Kn,{ref:S("checkout"),id:"checkout",title:"Checkout",children:ln(zd,{...h})}),ln(Kn,{ref:S("shipping"),id:"shipping",title:"Shipping",children:ln(jd,{...h,providerSlot:s,currencyChanging:p})}),ln(Kn,{ref:S("tax"),id:"tax",title:"Tax",children:ln(qd,{...h})}),ln(Kn,{ref:S("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:ln(Gd,{...h,onChangeStart:x})})]},e)}import{Loader2 as ov}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:c,saveInvoiceSettings:d}=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(ov,{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:d})}),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:c})})]},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 lv}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(lv,{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:c}){let{aggregates:d,isLoading:o,error:u,refetch:b}=nr({refreshKey:e,initialPageSize:1,includeAggregates:!0}),v=lr({refreshKey:e}),{api:m}=H(),g=v.filters,f=gr.useCallback(()=>m.exportRetainersCsv(g),[m,g]),[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:u||!o&&!d?$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||!d?$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:`${d.outstanding.count} open`,children:Q(d.outstanding.amount,d.currency)}),Ra(pt,{label:"Overdue",detail:d.overdue.count===0?"Nothing overdue":`${d.overdue.count} overdue`,valueClassName:d.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:Q(d.overdue.amount,d.currency)}),Ra(pt,{label:"Paid this month",detail:`${d.paid_this_month.count} paid`,children:Q(d.paid_this_month.amount,d.currency)})]})});return $r(Ut,{title:"Invoices",onBackToWebsite:a,hideBackButton:p,className:c,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(P=>!P),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:v.retainers,isLoading:v.isLoading,error:v.error,onRetry:()=>void v.refetch(),activeRetainerId:S?.id??null,onShowCycles:P=>k(w=>w?.id===P.id?null:P),total:v.total,endedTotal:v.endedTotal,isLoadingMore:v.isLoadingMore,onLoadMore:()=>void v.loadMore(),includeEnded:v.includeEnded,onIncludeEndedChange:v.setIncludeEnded,exportCsv:f}),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 Qt from"react";import*as Sn from"react";function Lt(e,t,a){let[s,n]=Sn.useState(null),[r,i]=Sn.useState(!0),[l,c]=Sn.useState(null),d=Sn.useRef(0),o=Sn.useRef(e);o.current=e;let u=Sn.useRef(a);u.current=a;let b=Sn.useCallback(async()=>{let m=++d.current,g=u.current;i(!0),c(null);try{let f=await o.current();m===d.current&&n({scope:g,value:f})}catch(f){m===d.current&&c(f instanceof Error?f:new Error("Request failed"))}finally{m===d.current&&i(!1)}},[]);Sn.useEffect(()=>{b()},[b,t]);let v=s!==null&&s.scope===a;return{data:v?s.value:null,isLoading:r||!v&&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 cv(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(vl,e)}function dv(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 c of n){let d=r[c];if(typeof d!="string"&&typeof d!="number")throw new Error(`${e} needs ${c}`);i=i.replace(`{${c}}`,encodeURIComponent(String(d))),delete r[c]}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 uv,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 ua({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(ua,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&a?Vr(ua,{onClick:a,children:"Open Store settings"}):null;return s&&ru(uv,{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(c){return n(hr(c)),{ok:!1,error:c}}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 Ie(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.",fv={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(""),[c,d]=$s.useState(!1),[o,u]=$s.useState(!1),[b,v]=$s.useState(null),m=vt(),g=async()=>{if(!c||!a.trim())return;let f=i.split(",").map(x=>x.trim()).filter(Boolean),p=await m.run("importContacts",{csv:a,attested:!0,...f.length?{tags:f}:{},...o?{enroll_automations:!0}:{}});if(p.ok){let x=p.result;v(x),e?.(x)}};if(b){let f=new Map;for(let p of b.skipped_rows)f.set(p.reason,(f.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:[Ie(b.rows)," rows: ",Ie(b.created)," new, ",Ie(b.updated)," updated, ",Ie(b.skipped)," skipped."]}),f.size>0&&Ia("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...f].map(([p,x])=>cs("li",{children:[Ie(x)," ",fv[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:()=>{v(null),s(""),r(null),d(!1)},children:"Import another file"})]})}return cs("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:f=>{f.preventDefault(),g()},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 f=>{let p=f.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(se,{"aria-label":"Tags for imported contacts",value:i,onChange:f=>l(f.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:f=>u(f.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:c,onChange:f=>d(f.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||!c||!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 mv={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,c]=Yn.useState(0),[d,o]=Yn.useState(0),[u,b]=Yn.useState(new Set),[v,m]=Yn.useState(!1),g=io({siteId:e,q:r,offset:l,refreshKey:d+a}),f=vt(),p=()=>o(R=>R+1),x=g.stats.data,S=g.contacts.data,k=g.tags.data??[],h=x?x.growth.slice(-4).reduce((R,P)=>R+P.new_subscribers,0):null,N=async()=>{let R=await f.run("exportContacts",{});if(!R.ok||typeof R.result!="string"||typeof document>"u")return;let P=URL.createObjectURL(new Blob([R.result],{type:"text/csv;charset=utf-8"})),w=document.createElement("a");w.href=P,w.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(P)};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?Ie(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?Ie(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?Ie(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(),c(0),i(s.trim())},children:[Le(se,{"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:v?"Close import":"Import"}),Le(y,{type:"button",variant:"outline",size:"sm",disabled:!t||f.busy,onClick:()=>void N(),children:"Export"})]}),v&&Le("div",{className:"af-mt-3",children:Le(lo,{onImported:p})}),f.error&&Le(ue,{tone:"error",className:"af-mt-2",children:f.error}),t&&u.size>0&&Le(gv,{tags:k.filter(R=>!R.system),count:u.size,busy:f.busy,onApply:async(R,P)=>{(await f.run("bulkTagContacts",{action:R,tag_id:P,contact_ids:[...u]})).ok&&(b(new Set),p())}}),Le("div",{className:"af-mt-3",children:g.contacts.error?Le(xt,{message:"Couldn't load contacts.",onRetry:()=>void g.contacts.refetch()}):S?S.contacts.length===0?Le(la,{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(pv,{contact:R,canWrite:t,busy:f.busy,selected:u.has(R.id),onSelect:P=>b(w=>{let C=new Set(w);return P?C.add(R.id):C.delete(R.id),C}),onUnsubscribe:async()=>{(await f.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:[Ie(l+1),"\u2013",Ie(l+S.contacts.length)," of ",Ie(S.total)]}),Vt("div",{className:"af-flex af-gap-2",children:[Le(y,{type:"button",variant:"ghost",size:"sm",disabled:l===0,onClick:()=>c(Math.max(0,l-vr)),children:"Previous"}),Le(y,{type:"button",variant:"ghost",size:"sm",disabled:l+S.contacts.length>=S.total,onClick:()=>c(l+vr),children:"Next"})]})]})]}):Le(G,{className:"af-h-24 af-w-full"})}),Le(vv,{tags:k,canWrite:t,onChanged:p})]})}function pv({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(te,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":mv[e.status]}),e.tags.map(i=>Le(te,{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 gv({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:[Ie(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 vv({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(c=>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===c.id?Vt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async d=>{d.preventDefault(),(await l.run("updateTag",{tagId:c.id,label:r.label.trim()})).ok&&(i(null),a())},children:[Le(se,{"aria-label":`New name for ${c.label}`,value:r.label,onChange:d=>i({id:c.id,label:d.target.value})}),Le(y,{type:"submit",size:"sm",disabled:!r.label.trim()||l.busy,children:"Save"})]}):Vt(ou,{children:[Vt("span",{children:[c.label," ",Vt("span",{className:"af-text-muted-foreground",children:["\xB7 ",Ie(c.total)," contacts, ",Ie(c.mailable)," can be emailed"]})]}),t&&!c.system&&Le(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>i({id:c.id,label:c.label}),children:"Rename"})]})},c.id))}),t&&Vt("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async c=>{c.preventDefault(),(await l.run("createTag",{label:s.trim()})).ok&&(n(""),a())},children:[Le(se,{"aria-label":"New tag",placeholder:"New tag",value:s,maxLength:100,onChange:c=>n(c.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 Pv}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}
|
|
6
6
|
${e.url}`;case"image":return[e.url,e.alt].filter(Boolean).join(`
|
|
7
|
-
`);case"cart":return e.label}}function Hd(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 Og={...il,text:"Markdown: **bold**, *italic*, [link](https://\u2026), blank line = new paragraph"};function qd({block:e,isNew:t,busy:a,error:s,onPickImage:n,onDone:r,onRemove:i,onCancel:l,style:f,className:d}){let[o,c]=Cs.useState(e),[b,g]=Cs.useState(!1),m=v=>c(x=>({...x,...v})),p=Cs.useRef(null);Cs.useEffect(()=>p.current?.focus(),[]);let u=v=>{v&&!p.current&&(p.current=v)};return wa("form",{"data-testid":"section-editor",style:f,className:d,onSubmit:v=>{v.preventDefault(),Hd(o)&&r(o)},onKeyDown:v=>{v.key==="Escape"&&!a&&l()},children:kn("div",{className:"af-space-y-2",children:[o.type==="heading"&&wa(te,{ref:u,"aria-label":"Heading",value:o.text,maxLength:200,onChange:v=>m({text:v.target.value})}),o.type==="text"&&wa("textarea",{ref:u,"aria-label":"Text",className:"af-min-h-[120px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-font-mono af-text-sm",value:o.text,maxLength:5e3,onChange:v=>m({text:v.target.value})}),o.type==="button"&&kn("div",{className:"af-grid af-gap-2 sm:af-grid-cols-2",children:[kn("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",wa(te,{ref:u,"aria-label":"Button label",value:o.label,maxLength:80,onChange:v=>m({label:v.target.value})})]}),kn("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Opens",wa(te,{"aria-label":"Button link",type:"url",value:o.url,onChange:v=>m({url:v.target.value})})]})]}),o.type==="image"&&kn("div",{className:"af-space-y-2",children:[n?kn("div",{className:"af-flex af-items-center af-gap-2",children:[o.url&&wa("img",{src:o.url,alt:"",className:"af-h-12 af-w-12 af-rounded af-object-cover"}),wa(y,{ref:u,type:"button",variant:"outline",size:"sm",disabled:b,onClick:async()=>{g(!0);try{let v=await n();v&&c(x=>({...x,url:v.url,alt:v.alt??(x.type==="image"?x.alt:"")}))}finally{g(!1)}},children:"Choose from your site's images\u2026"})]}):kn("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Image address (https://\u2026)",wa(te,{ref:u,"aria-label":"Image URL",type:"url",value:o.url,onChange:v=>m({url:v.target.value})})]}),kn("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)",wa(te,{"aria-label":"Image description",value:o.alt??"",maxLength:200,onChange:v=>m({alt:v.target.value})})]})]}),o.type==="cart"&&kn("div",{className:"af-space-y-2",children:[wa("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."}),kn("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",wa(te,{ref:u,"aria-label":"Cart button label",value:o.label,maxLength:80,onChange:v=>m({label:v.target.value})})]})]}),s&&wa(Ne,{tone:"error",children:s}),kn("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[wa("span",{className:"af-grow af-text-xs af-text-muted-foreground",children:Og[o.type]}),!t&&wa(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:i,children:"Remove"}),wa(y,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:l,children:"Cancel"}),wa(y,{type:"submit",size:"sm",disabled:a||!Hd(o),children:"Done"})]})]})})}import*as jd from"react";import{ArrowLeft as Bg}from"lucide-react";import{Fragment as ll,jsx as We,jsxs as ma}from"react/jsx-runtime";var zn="standard",Zi={create:"Create an email template that ",copyStandard:"Create an email template based on Standard that ",update:e=>`Update the "${e}" template to be `};function cl({template:e}){return e?e.status==="archived"?We(ee,{variant:"secondary",children:"Archived"}):e.locked?We(ee,{variant:"secondary",children:"In use"}):null:We(ee,{variant:"secondary",children:"Built in"})}function dl(e){return e>0?`Used by ${e} draft${e===1?"":"s"}`:null}function Wd(e,t){let{api:a}=H(),{siteId:s,refreshKey:n,settings:r}=nt(),i=JSON.stringify([r?.business_name,r?.postal_address,r?.brand]);return Kt(()=>a.previewEmailTemplate(s,e),`${s}|${e}|${t}|${n}|${i}`,`${s}|${e}|${t}`)}function Yi({templateId:e,version:t,className:a,frame:s}){let n=Wd(e,t);return We("div",{"aria-hidden":!0,className:`af-pointer-events-none af-overflow-hidden af-bg-white ${a}`,children:n.data&&We("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 Gd({template:e,onBack:t,onOpenTemplate:a,onOpenDraft:s,onAskAssistant:n,reload:r,refreshKey:i}){let l=Wd(e?.id??zn,e?.updated_at??"builtin");return ma("div",{className:"af-space-y-4",children:[ma(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[We(Bg,{className:"af-mr-1 af-h-4 af-w-4"}),"All templates"]}),ma("div",{className:"af-grid af-gap-4 md:af-grid-cols-[minmax(0,1fr)_280px]",children:[ma("div",{children:[l.data?We("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?ma(Ne,{tone:"warning",children:[Gi(l.error)==="postal_address_missing"?"Add your business postal address to preview your emails.":"Couldn't load this preview.",We(ir,{reason:Gi(l.error)})]}):We(J,{className:"af-h-[520px] af-w-full"}),We("p",{className:"af-mt-2 af-text-center af-text-xs af-text-muted-foreground",children:"Shown with a sample email"})]}),ma("div",{className:"af-space-y-3",children:[We(Fg,{template:e,onOpenTemplate:a,onAskAssistant:n,reload:r}),We(Mg,{templateId:e?.id??null,onOpenDraft:s,refreshKey:i})]})]})]})}function Fg({template:e,onOpenTemplate:t,onAskAssistant:a,reload:s}){let{canWrite:n}=nt(),r=Dt(),[i,l]=jd.useState(null),f=e?.name??"Standard",d=async(u,v)=>{let x=await r.run(u,v);l(null),x.ok&&u==="deleteEmailTemplate"&&t(null),!x.ok&&vn(x.error,"template_in_use")&&r.setError("Emails use this template now."),s()},o=async u=>{let v=await r.run("copyEmailTemplate",{templateId:u.id});v.ok&&(t(v.result.id),s())},c=u=>We(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:r.busy,onClick:()=>void o(u),children:"Make a copy"}),b=We(y,{type:"button",variant:"ghost",size:"sm",disabled:r.busy,onClick:()=>l("delete"),children:"Delete"}),g=We(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[u,v,x]=i==="delete"?["Delete this template?","Delete",()=>d("deleteEmailTemplate",{templateId:e.id})]:["Archive this template?","Archive",()=>d("archiveEmailTemplate",{templateId:e.id})];m=ma(ll,{children:[We("p",{className:"af-text-sm",children:u}),ma("div",{className:"af-flex af-gap-2",children:[We(y,{type:"button",variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),We(y,{type:"button",size:"sm",variant:i==="delete"?"destructive":"default",className:"af-ml-auto",disabled:r.busy,onClick:()=>void x(),children:v})]})]})}else e?e.status==="archived"?m=ma("div",{className:"af-flex af-flex-wrap af-gap-2",children:[We(y,{type:"button",variant:"outline",size:"sm",disabled:r.busy,onClick:()=>void d("unarchiveEmailTemplate",{templateId:e.id}),children:"Unarchive"}),c(e)]}):e.locked?m=ma("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_archive&&g,c(e)]}):m=ma(ll,{children:[a&&We(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>a(Zi.update(e.name)),children:"\u2728 Change this template with the editor"}),(e.can_delete||e.can_archive)&&ma("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_delete&&b,e.can_archive&&g]})]}):m=a&&We(y,{type:"button",size:"sm",onClick:()=>a(Zi.copyStandard),children:"Make a copy"});let p=e&&e.status==="active"&&!e.locked?dl(e.usage.drafts):null;return ma("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[ma("div",{className:"af-flex af-items-center af-gap-2",children:[We("h3",{"data-testid":"template-title",className:"af-grow af-truncate af-text-sm af-font-semibold",children:f}),We(cl,{template:e})]}),p&&We("p",{className:"af-text-xs af-text-muted-foreground",children:p}),r.error&&We(Ne,{tone:"error",children:r.error}),m]})}function Mg({templateId:e,onOpenDraft:t,refreshKey:a}){let{siteId:s}=nt(),n=dr({siteId:s,kind:"broadcast",refreshKey:a}),r=cr({siteId:s,refreshKey:a}),i=n.data?.filter(c=>(c.template?.id??null)===e)??null,l=r.data??[],f=Wi(n.data??[],l),d=new Set(l.flatMap(c=>c.draft_id&&c.status==="scheduled"?[c.draft_id]:[])),o=c=>f.has(c)?"Sent":d.has(c)?"Scheduled":"Draft";return ma("div",{"data-testid":"template-usage",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[We("h3",{className:"af-text-sm af-font-semibold",children:"Emails using it"}),n.error||r.error?We(Nt,{message:"Couldn't load the emails.",onRetry:()=>{n.refetch(),r.refetch()}}):!i||!r.data?We(J,{className:"af-h-10 af-w-full"}):i.length===0?We("p",{className:"af-text-sm af-text-muted-foreground",children:"No emails use it."}):We("ul",{className:"af-space-y-1",children:i.map(c=>{let b=o(c.id),g=ma(ll,{children:[We("span",{className:"af-block af-truncate af-text-sm",children:c.subject||"(no subject)"}),ma("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["Broadcast \xB7 ",b]})]});return We("li",{children:b==="Sent"?We("div",{className:"af-rounded-md af-px-2 af-py-1",children:g}):We("button",{type:"button",onClick:()=>t(c.id),className:"af-w-full af-rounded-md af-px-2 af-py-1 af-text-left hover:af-bg-muted",children:g})},c.id)})})]})}import{jsx as Ts,jsxs as Ji}from"react/jsx-runtime";function Kd({draft:e,disabled:t,onChanged:a}){let{api:s}=H(),{siteId:n,refreshKey:r}=nt(),i=Kt(()=>s.getEmailTemplates(n),`${n}|${r}`,n),l=Dt(),f=e.template?.id??zn,d=f===zn,o=(i.data??[]).filter(p=>p.status==="active"),c=o.find(p=>p.id===f),b=d?"Standard":e.template?.name??c?.name??"",g=d?"builtin":c?.updated_at??"current",m=async p=>{if(p===f)return;let u=await l.run("setDraftTemplate",{draftId:e.id,template_id:p===zn?null:p,expected_version:e.version});u.ok?await a():vn(u.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."):vn(u.error,"version_conflict")?(l.setError("This email changed meanwhile. We've loaded the latest version; switch again if you still want to."),await a()):vn(u.error,"template_archived")&&(l.setError("That template is archived."),await i.refetch())};return Ji("div",{"data-testid":"template-card",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[Ts("div",{className:"af-text-sm af-font-semibold",children:"Template"}),Ji("div",{className:"af-flex af-items-center af-gap-3",children:[Ts(Yi,{templateId:f,version:g,className:"af-h-20 af-w-[72px] af-shrink-0 af-rounded af-border",frame:{width:600,height:670,scale:.12}}),Ts("div",{className:"af-min-w-0 af-grow af-truncate af-text-sm af-font-medium",children:b})]}),Ji("label",{className:"af-grid af-gap-1 af-text-xs af-text-muted-foreground",children:["Switch to",Ji("select",{"aria-label":"Switch to",value:f,disabled:t||l.busy,onChange:p=>void m(p.target.value),className:"af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-text-sm af-text-foreground",children:[Ts("option",{value:zn,children:"Standard"}),o.map(p=>Ts("option",{value:p.id,children:p.name},p.id)),!d&&!c&&Ts("option",{value:f,disabled:!0,children:b})]})]}),l.error&&Ts(Ne,{tone:"error",children:l.error})]})}import{Fragment as ul,jsx as je,jsxs as Zt}from"react/jsx-runtime";var Ug={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"},$g=320,Vg=600,Hg=e=>({top:Math.max(0,e.y-24),left:e.x});function zg(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 Yd({draftId:e,renderCommit:t,onSaved:a,scheduled:s,onAskAssistant:n,onPickImage:r}){let{api:i}=H(),{siteId:l,canWrite:f,refreshKey:d,openSettings:o}=nt(),c=f&&!s,b=ze.useRef(c);b.current=c;let[g,m]=ze.useState(null),[p,u]=ze.useState(null),[v,x]=ze.useState(null),[R,P]=ze.useState(null),[h,S]=ze.useState(null),[N,C]=ze.useState(null),[w,k]=ze.useState(null),[T,_]=ze.useState(null),[z,Z]=ze.useState(null),[U,ae]=ze.useState({}),[le,fe]=ze.useState(Or.initial),[M,W]=ze.useState(!1),A=Dt(),de=Dt(),ce=ze.useRef(null),Le=ze.useRef(null),ye=ze.useRef(0),Te=ze.useRef(!1),Oe=ze.useRef(!1),oe=ze.useCallback(xe=>{Te.current=xe!==null,C(xe)},[]);Bd(N!==null);let st=ze.useRef(g);st.current=g;let E=ze.useRef(0),O=ze.useCallback(async(xe={})=>{let ot=++E.current,Ze=b.current,yt=()=>Ze?i.previewEmailDraft(l,e,{editable:!0}):i.previewEmailDraft(l,e),[$,Ge]=await Promise.allSettled([i.getEmailDraft(l,e),yt()]),ra=Ge,Ms=()=>$.status==="fulfilled"&&ra.status==="fulfilled"&&ra.value.version!==$.value.version;if(Ms()&&ot===E.current&&([ra]=await Promise.allSettled([yt()])),ot===E.current){if(xe.background&&Te.current){Oe.current=!0;return}if(P(null),x(null),$.status==="rejected"){P(or($.reason));return}m($.value),ra.status==="fulfilled"?u({...ra.value,editable:Ze&&!Ms()}):(u(null),x(vn(ra.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:or(ra.reason),code:null}))}},[i,l,e]);ze.useEffect(()=>{m(null),u(null),O()},[O]);let B=ze.useRef(c);ze.useEffect(()=>{B.current!==c&&(B.current=c,c||oe(null),O())},[c,O,oe]);let we=ze.useRef(d);ze.useEffect(()=>{if(d!==we.current){if(we.current=d,Te.current){Oe.current=!0;return}O({background:!0})}},[d,O]);let X=()=>{oe(null),A.setError(null),Oe.current&&(Oe.current=!1,O())},ve=async(xe,ot,Ze)=>{let yt=await A.run("updateDraft",{draftId:e,expected_version:xe.version,...ot});yt.ok?(k(null),Le.current=null,Oe.current=!1,oe(null),await O(),a?.()):vn(yt.error,"version_conflict")&&(A.setError(null),k(Ze),Oe.current=!1,oe(null),await O())},Me=ze.useRef({frame:null,html:null,count:0}),[ht,Ke]=ze.useState(null),Ct=(xe,ot)=>{let Ze=Me.current;Ze.frame!==xe.currentTarget||Ze.html!==ot?Me.current={frame:xe.currentTarget,html:ot,count:1}:++Ze.count>1&&Ke(ot)},pe=p!==null&&ht===p.html,ke=c&&p?.editable===!0&&!pe;if(ze.useEffect(()=>{if(!ke)return;let xe=ot=>{let Ze=st.current;if(!Ze)return;let yt=$d(ot,ce.current?.contentWindow,Ze.blocks.length);if(yt)switch(yt.type){case"hover":Z(yt.section===null?null:{section:yt.section,rect:yt.rect});return;case"focus":Le.current=yt.section;return;case"open":if(Le.current=yt.section,Te.current)return;_(null),W(!1),oe({kind:"section",base:Ze,index:yt.section,block:Ze.blocks[yt.section],isNew:!1,anchor:yt.rect,key:++ye.current});return;case"layout":fe(Vd(yt.height));{let $=Object.fromEntries(yt.sections.map(Ge=>[Ge.section,Ge.rect]));ae(Ge=>zg(Ge,$)?Ge:$)}return;case"template":Te.current||_(yt.region);return}};return window.addEventListener("message",xe),()=>window.removeEventListener("message",xe)},[ke,oe]),R)return Zt(Ne,{tone:"error",children:["Couldn't load this email. ",R]});if(!g)return je(J,{className:"af-h-40 af-w-full"});let rt={width:ce.current?.clientWidth||Vg,height:ke?le:Or.initial},Je=N?.kind==="section"?N:null,zt=(()=>{if(!Je)return null;if(!Je.isNew)return U[Je.index]??Je.anchor;let xe=U[Je.index-1];return xe?{x:xe.x,y:xe.y+xe.height,width:xe.width,height:0}:null})(),Ot=zt?rl(zt,rt):null,sa=g.kind==="recovery",it=g.template?.name??"Standard",vt=Je&&je(qd,{block:Je.block,isNew:Je.isNew,busy:A.busy,error:A.error,onPickImage:r,onCancel:X,onRemove:()=>{let{base:xe}=Je;ve(xe,{subject:xe.subject,preheader:xe.preheader,blocks:xe.blocks.filter((ot,Ze)=>Ze!==Je.index)},ol(Je.block))},onDone:xe=>{let{base:ot}=Je,Ze=Je.isNew?[...ot.blocks.slice(0,Je.index),xe,...ot.blocks.slice(Je.index)]:ot.blocks.map((yt,$)=>$===Je.index?xe:yt);ve(ot,{subject:ot.subject,preheader:ot.preheader,blocks:Ze},ol(xe))},className:Ot?"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:Ot?{top:Ot.y,left:Ot.x,width:Math.min(Math.max(Ot.width,$g),rt.width)}:void 0},Je.key);return Zt("div",{className:"af-grid af-gap-4 lg:af-grid-cols-[minmax(0,1fr)_300px]",children:[Zt("div",{className:"af-min-w-0 af-space-y-3",children:[N?.kind==="subject"?je(qg,{draft:N.base,busy:A.busy,error:A.error,onCancel:X,onDone:xe=>void ve(N.base,{...xe,blocks:N.base.blocks},[xe.subject,xe.preheader??""].join(`
|
|
8
|
-
`))}):ke?je("button",{type:"button","data-testid":"subject-line",onClick:()=>{Te.current||(_(null),oe({kind:"subject",base:g}))},className:"af-block af-w-full af-rounded-md af-border af-border-dashed af-px-3 af-py-2 af-text-left hover:af-border-primary",children:je(Zd,{draft:g})}):je("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:je(Zd,{draft:g})}),s&&Zt(Ne,{tone:"info",children:[Zt("p",{children:["This email is scheduled",s.sendsAt?` to send ${new Date(s.sendsAt).toLocaleString()}`:"",", so it can't change. Unschedule it to edit, then schedule it again."]}),je(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:!f||s.busy,onClick:()=>void s.onUnschedule(),children:"Unschedule to edit"}),s.error&&je("p",{className:"af-mt-1 af-text-destructive",children:s.error})]}),w!==null&&Zt(Ne,{tone:"warning",children:[je("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."}),je("textarea",{readOnly:!0,"aria-label":"Your unsaved text",value:w,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"}),je(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>k(null),children:"Dismiss"})]}),T&&je("div",{"data-testid":"template-hint",children:je(Ne,{children:T==="header"?Zt(ul,{children:['The header is part of the "',it,'" template. Switch templates on the right.']}):Zt(ul,{children:["Every email ends with this footer. Your business name and address come from"," ",je(ks,{onClick:()=>o("sender"),children:"Settings"}),"."]})})}),pe&&c&&je(Ne,{tone:"warning",children:"This template tried to open another page in the preview, so the preview can't be edited here."}),p?Zt("div",{className:"af-relative",children:[je("iframe",{ref:ce,title:"Email preview",sandbox:ke?"allow-scripts":"",srcDoc:p.html,onLoad:ke?xe=>Ct(xe,p.html):void 0,style:{height:rt.height},className:"af-block af-w-full af-rounded-md af-border af-bg-white"},ke?"editable":"read-only"),ke&&z&&!N&&je("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:Hg(rl(z.rect,rt)),children:Ug[g.blocks[z.section]?.type??"text"]}),Ot&&vt]}):v?Zt(Ne,{tone:"warning",children:[v.text,je(ir,{reason:v.code})]}):je(J,{className:"af-h-40 af-w-full"}),!Ot&&vt,ke&&!N&&Zt("div",{className:"af-space-y-2",children:[je(y,{type:"button",variant:"outline",size:"sm",onClick:()=>W(xe=>!xe),"aria-expanded":M,children:"+ Add a section"}),M&&je("div",{"data-testid":"add-section-menu",className:"af-flex af-flex-wrap af-gap-2",children:["text","heading","button","image",...sa?["cart"]:[]].map(xe=>je(y,{type:"button",size:"sm",variant:"secondary",onClick:()=>{let ot=Le.current!==null?Le.current+1:g.blocks.length;W(!1),_(null),oe({kind:"section",base:g,index:ot,block:zd(xe),isNew:!0,anchor:null,key:++ye.current})},children:il[xe]},xe))})]}),je("p",{className:"af-text-center af-text-xs af-text-muted-foreground",children:"Header and footer come from your template."})]}),Zt("div",{className:"af-space-y-3",children:[Zt("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[je(y,{type:"button",variant:"outline",size:"sm",disabled:!f||de.busy,onClick:async()=>{S(null);let xe=await de.run("testSendDraft",{draftId:e});xe.ok&&S(xe.result?.sent_to??"your email")},children:"Send a test to me"}),h&&Zt(Ne,{tone:"success",children:["Test sent to ",h,"."]}),de.error&&je(Ne,{tone:"error",children:de.error}),p&&!s&&t?.({draft:g,preview:p,reload:()=>O()})]}),je(Kd,{draft:g,disabled:!c||N!==null,onChanged:async()=>{await O(),a?.()}}),n&&f&&je(y,{type:"button",variant:"outline",className:"af-w-full",onClick:()=>n(`Update the "${g.subject}" email to `),children:"\u2728 Change this email with the editor"})]})]})}function Zd({draft:e}){return Zt(ul,{children:[je("span",{className:"af-text-xs af-text-muted-foreground",children:"Subject "}),je("span",{className:"af-font-medium",children:e.subject||"(no subject)"}),e.preheader&&Zt("span",{className:"af-text-sm af-text-muted-foreground",children:[" \u2014 ",e.preheader]})]})}function qg({draft:e,busy:t,error:a,onDone:s,onCancel:n}){let[r,i]=ze.useState(e.subject),[l,f]=ze.useState(e.preheader??"");return Zt("form",{className:"af-space-y-2 af-rounded-md af-border af-p-3",onSubmit:d=>{d.preventDefault(),s({subject:r,preheader:l.trim()||null})},children:[Zt("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Subject",je(te,{"aria-label":"Subject",value:r,maxLength:200,autoFocus:!0,onChange:d=>i(d.target.value)})]}),Zt("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)",je(te,{"aria-label":"Preview text",value:l,maxLength:200,onChange:d=>f(d.target.value)})]}),a&&je(Ne,{tone:"error",children:a}),Zt("div",{className:"af-flex af-justify-end af-gap-2",children:[je(y,{type:"button",variant:"outline",size:"sm",disabled:t,onClick:n,children:"Cancel"}),je(y,{type:"submit",size:"sm",disabled:t,children:"Done"})]})]})}import{jsx as Re,jsxs as At}from"react/jsx-runtime";var Wg={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function Xd({openDraftId:e,onOpenDraft:t,onAskAssistant:a,onPickImage:s}){let{siteId:n,canWrite:r,refreshKey:i}=nt(),[l,f]=wt.useState(0),d=l+i,o=dr({siteId:n,kind:"broadcast",refreshKey:d}),c=cr({siteId:n,refreshKey:d}),b=Dt(),g=Dt(),m=Wi(o.data??[],c.data??[]),p=o.data?.filter(u=>!m.has(u.id))??null;if(e){let u=c.data?.find(v=>v.draft_id===e&&v.status==="scheduled");return At("div",{className:"af-space-y-4",children:[At(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>t(null),children:[Re(jg,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),!c.data&&!c.error||!o.data&&!o.error?Re(J,{className:"af-h-40 af-w-full"}):m.has(e)?Re(Ne,{children:"This email has been sent, so it can't change. Duplicate it from the list to send it again."}):Re(Yd,{draftId:e,onSaved:()=>f(v=>v+1),renderCommit:v=>Re(Yg,{...v,onCommitted:()=>f(x=>x+1)}),scheduled:u?{sendsAt:u.scheduled_at,busy:b.busy,error:b.error,onUnschedule:async()=>{(await b.run("cancelBroadcast",{sendId:u.id})).ok&&f(x=>x+1)}}:void 0,onAskAssistant:a,onPickImage:s})]})}return At("div",{children:[Re(tn,{children:"Drafts"}),o.error?Re(Nt,{message:"Couldn't load drafts.",onRetry:()=>void o.refetch()}):p?p.length===0?Re(ha,{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:p.map(u=>At("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:u.subject||"(no subject)"}),Re(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(u.id),children:"Review"})]},u.id))}):Re(J,{className:"af-h-10 af-w-full"}),Re(tn,{children:"Sent and scheduled"}),b.error&&Re(Ne,{tone:"error",children:b.error}),g.error&&Re(Ne,{tone:"error",children:g.error}),c.error?Re(Nt,{message:"Couldn't load broadcasts.",onRetry:()=>void c.refetch()}):c.data?c.data.length===0?Re(ha,{children:"Nothing sent yet."}):Re("ul",{className:"af-divide-y af-rounded-md af-border",children:c.data.map(u=>Re(Gg,{broadcast:u,canCancel:r&&(u.status==="scheduled"||u.status==="unscheduled"||u.status==="sending"),busy:b.busy||g.busy,onCancel:async()=>{(await b.run("cancelBroadcast",{sendId:u.id})).ok&&f(x=>x+1)},onDuplicate:r&&u.draft_id&&tl(u)?async()=>{let v=await g.run("duplicateDraft",{draftId:u.draft_id});v.ok&&(f(x=>x+1),t(v.result.id))}:void 0},u.id))}):Re(J,{className:"af-h-10 af-w-full"})]})}function Gg({broadcast:e,canCancel:t,busy:a,onCancel:s,onDuplicate:n}){return At("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[At("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}),At("div",{className:"af-flex af-items-center af-gap-2",children:[Re(ee,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Wg[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"})]})]}),At("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",Fe(e.recipients.planned)," recipients \xB7 ",Fe(e.stats.delivered)," delivered \xB7 ",Fe(e.stats.opened)," opened \xB7"," ",Fe(e.stats.clicked)," clicked \xB7 ",Fe(e.stats.bounced)," bounced \xB7 ",Fe(e.stats.complained)," complaints \xB7"," ",Fe(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&Re("div",{className:"af-text-xs af-text-muted-foreground",children:sr(e.status_reason)})]})}var Qd=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function Jd(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:Qd(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:s?Kg(a):"",suggested:t!==null||a!==null,timePassed:a!==null&&!s}}function Kg(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 Zg=(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 Yg({draft:e,preview:t,reload:a,onCommitted:s}){let{api:n}=H(),{siteId:r,canWrite:i,settings:l,refreshKey:f}=nt(),[d,o]=wt.useState(null),[c,b]=wt.useState(!1),[g,m]=wt.useState(null),[p,u]=wt.useState(()=>Jd(e)),[v,x]=wt.useState(p.tagIds),[R,P]=wt.useState(p.match),[h,S]=wt.useState(p.scheduleAt),[N,C]=wt.useState(0),w=!Zg({tagIds:v,match:R,scheduleAt:h},p),k=Qd(e);wt.useEffect(()=>{if(k===p.key||e.id===p.draftId&&w)return;let X=Jd(e);u(X),x(X.tagIds),P(X.match),S(X.scheduleAt),C(0)},[k,e,p,w]);let T=wt.useMemo(()=>d?new Set(d.map(X=>X.id)):null,[d]),_=T!==null&&v.every(X=>T.has(X));wt.useEffect(()=>{if(!T||v.every(ve=>T.has(ve)))return;let X=ve=>ve.filter(Me=>T.has(Me));C(ve=>ve+v.length-X(v).length),x(X(v)),u(ve=>({...ve,tagIds:X(ve.tagIds)}))},[T,v]);let[z,Z]=wt.useState(null),[U,ae]=wt.useState(null),[le,fe]=wt.useState(null),M=Dt();wt.useEffect(()=>{n.getMarketingTags(r).then(X=>{o(X),b(!1)},()=>{o(null),b(!0)}),n.getMarketingContactStats(r).then(m,()=>m(null))},[n,r,f]);let W=h?new Date(h).toISOString():null,A=JSON.stringify([v,R,W]),de=z?.plan??null,ce=z!==null&&z.key===A,Le=wt.useRef(0),ye=wt.useCallback(async()=>{let X=++Le.current;ae(null);try{let ve=await n.estimateBroadcast(r,{targeting:{tag_ids:v,match:R},scheduled_at:W});X===Le.current&&Z({key:A,plan:ve})}catch(ve){if(X!==Le.current)return;Z(null),ae(or(ve))}},[n,r,v,R,W,A,f]),Te=wt.useRef(!1);wt.useEffect(()=>{if(!_&&v.length>0)return;if(!Te.current){Te.current=!0,ye();return}let X=setTimeout(()=>void ye(),300);return()=>clearTimeout(X)},[ye,_,v.length]);let Oe=l&&!l.readiness.can_send?sr(l.readiness.reason):null,oe=de!==null&&!de.fits,st=g?Math.max(0,g.by_status.subscribed-g.mailable):null,E=g&&de&&st!==null?Math.max(0,g.total-de.recipients-st):null,O=!i||M.busy||!de||!ce||oe||de.recipients===0||Oe!==null||c&&v.length>0,B=async()=>{fe(null);let X=await M.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:v,match:R},scheduled_at:W});if(X.ok){fe({tone:"success",text:W?"Scheduled.":"Sending now."}),s();return}vn(X.error,"version_conflict")?(M.setError(null),await a(),fe({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):vn(X.error,"over_allowance")&&await ye()},we=X=>x(ve=>ve.includes(X)?ve.filter(Me=>Me!==X):[...ve,X]);return At("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[p.suggested&&!w&&Re(Ne,{children:"Suggested by your assistant \u2014 review before sending."}),Re(tn,{children:"Who gets it"}),c&&Re(Ne,{tone:"warning",children:v.length>0?"Couldn't load your tags, so this targeted send can't go out yet. Refresh to try again.":"Couldn't load your tags. Refresh to target by tag."}),N>0&&Re(Ne,{tone:"warning",children:N===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),d&&d.length>0?At("div",{className:"af-space-y-2",children:[Re("div",{className:"af-flex af-flex-wrap af-gap-2",children:d.map(X=>At("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[Re("input",{type:"checkbox",checked:v.includes(X.id),onChange:()=>we(X.id)}),X.label]},X.id))}),v.length>1&&At("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",At("select",{"aria-label":"Tag match",value:R,onChange:X=>P(X.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"})]})]}),v.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."}),At("label",{className:"af-block af-space-y-1",children:[Re("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),Re(te,{"aria-label":"Schedule time",type:"datetime-local",value:h,onChange:X=>S(X.target.value)})]}),p.timePassed&&!h&&Re(Ne,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),U?At(Ne,{tone:"error",children:["Couldn't work out the audience. ",U]}):de?At("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[At("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[Re(fl,{label:"Will receive it",value:de.recipients}),Re(fl,{label:"Suppressed (bounced or complained)",value:st}),Re(fl,{label:"Not included",value:E})]}),At("p",{className:"af-text-muted-foreground",children:[Fe(de.allowance.remaining)," of ",Fe(de.allowance.monthly)," emails left this month."]}),de.sample_size!==null&&At(Ne,{children:["We'll send to ",Fe(de.sample_size)," people first and check for bounces before sending the rest."]}),de.ramp_days.length>1&&At(Ne,{children:["Your domain is new, so this goes out over ",de.ramp_days.length," days:"," ",de.ramp_days.map(X=>`${Fe(X.recipients)} on ${X.date}`).join(", "),"."]})]}):Re(J,{className:"af-h-12 af-w-full"}),oe&&de&&At(Ne,{tone:"warning",children:["This send needs ",Fe(de.recipients)," emails, but only ",Fe(de.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),Oe&&At(Ne,{tone:"warning",children:[Oe,Re(ir,{reason:l?.readiness.reason})]}),le&&Re(Ne,{tone:le.tone,children:le.text}),M.error&&Re(Ne,{tone:"error",children:M.error}),Re(y,{type:"button",disabled:O,onClick:()=>void B(),children:W?"Schedule":"Send now"})]})}function fl({label:e,value:t}){return At("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":Fe(t)})]})}import*as ka from"react";import{Check as nu,FileText as fv,ShieldCheck as mv}from"lucide-react";import*as Es from"react";import{ArrowRight as Jg,Check as eu,ChevronDown as Xg,Globe as Qg,Lock as ev,Mail as Qi,PenLine as tv,Sparkles as av}from"lucide-react";import{Fragment as Xi,jsx as K,jsxs as ge}from"react/jsx-runtime";var nv=[{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."}],sv="hello";function pl(e){return`${sv}@${e}`}function tu({onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,onTurnOn:s,siteDomain:n,businessName:r}){let{api:i}=H(),{siteId:l,settings:f,canWrite:d,refreshKey:o,refetchSettings:c}=nt(),b=Kt(()=>i.getMarketingContactStats(l),`${l}|${o}`,l),[g,m]=Es.useState(!1),[p,u]=Es.useState(null);if(!f)return null;let v=b.data?.by_status.subscribed??0,x={siteDomain:n,businessName:r};return rv(f)?K(gl,{settings:f,site:x,waiting:v,children:d?s&&ge("div",{className:"af-space-y-2",children:[ge(y,{disabled:g,onClick:async()=>{m(!0),u(null);try{await s(),await c()}catch(R){u(R instanceof Error?R.message:"Couldn't turn on email. Try again.")}finally{m(!1)}},children:["Get started ",K(Jg,{className:"af-ml-2 af-h-4 af-w-4","aria-hidden":!0})]}),p&&K(Ne,{tone:"error",children:p})]}):K("p",{className:"af-text-sm af-text-muted-foreground",children:"Only the site owner can set up email."})}):K(iv,{settings:f,site:x,waiting:v,onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a})}function rv(e){return e.readiness.reason==="sending_not_enabled"}function gl({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:ge("div",{className:"af-grid af-items-center af-gap-10 md:af-grid-cols-[1fr_18rem]",children:[ge("div",{children:[ge("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(Qi,{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:nv.map((n,r)=>ge("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}),ge("p",{className:"af-text-sm",children:[ge("span",{className:"af-font-medium",children:[n.title,"."]})," ",K("span",{className:"af-text-muted-foreground",children:n.body})]})]},n.title))}),a>0&&ge("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:[ge("span",{className:"af-font-semibold",children:[Fe(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(eo,{settings:e,site:t,className:"af-rotate-1"})]})})}function au({onUpgradePlan:e}){return ge("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(ev,{className:"af-h-5 af-w-5 af-shrink-0 af-text-violet-700","aria-hidden":!0}),ge("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 iv({settings:e,site:t,waiting:a,onStartDomainSetup:s,onConnectDomain:n,onAskAssistant:r}){let{refetchSettings:i,canWrite:l}=nt(),[f,d]=Es.useState(null),o=p=>d(u=>u===p?null:p),{siteDomain:c}=t,b=Br(e),g=c===null&&!e.domain.sending_domain,m=!!e.postal_address;return ge("div",{className:"af-mx-auto af-max-w-4xl af-py-4",children:[ge("div",{className:"af-mb-6 af-flex af-items-start af-justify-between af-gap-6",children:[ge("div",{children:[K("h3",{className:"af-text-xl af-font-semibold",children:"Set up email"}),ge("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Newsletters to your subscribers, sent from ",c??"your own domain","."]})]}),a>0&&ge("div",{className:"af-text-right",children:[K("div",{className:"af-text-2xl af-font-semibold",children:Fe(a)}),ge("div",{className:"af-text-xs af-text-muted-foreground",children:[a===1?"subscriber":"subscribers"," waiting"]})]})]}),!l&&K(Ne,{className:"af-mb-4",children:"Only the site owner can finish setup."}),ge("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_16rem]",children:[ge("div",{className:"af-space-y-4",children:[ge(ml,{title:c??"Your domain",sub:"One domain for your website and your email.",children:[c&&K(Tn,{icon:Qg,label:"Website",value:c,status:K(Cn,{tone:"green",children:"Live"})}),g?K(Tn,{icon:Qi,label:"Email sending",value:"Needs a custom domain",status:K(Cn,{tone:"gray",children:"Not available"}),action:n&&l?{label:"Connect domain",onClick:n}:void 0}):ge(Tn,{icon:Qi,label:"Email sending",value:e.domain.sending_domain??(c?`news.${c}`:"news.yourdomain.com"),status:vl(e),action:!b&&l?{label:e.domain.sending_domain?"Details":"Set up",onClick:()=>o("sending")}:void 0,expanded:f==="sending",children:[!e.domain.sending_domain&&K("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:"Emails go out from a subdomain of your site's domain, so they reach inboxes and are clearly from you. If we manage your domain's DNS we add the records; otherwise you'll get a few to copy into your DNS provider."}),K(bl,{settings:e,canWrite:l,onStartDomainSetup:s,onChanged:i})]})]}),K(ml,{title:"Sender",sub:"Who your emails are from. The mailing address is legally required in every email.",children:K(Tn,{icon:tv,label:m?e.business_name??"Sender":"Not set",value:e.postal_address??"Name, mailing address and reply-to",status:m?K(Cn,{tone:"green",children:"Done"}):K(Cn,{tone:"gray",children:"Needed"}),action:l?{label:m?"Edit":"Add",onClick:()=>o("sender")}:void 0,expanded:f==="sender",children:K(ov,{settings:e,businessName:t.businessName,onSaved:async()=>{await i(),d(null)}})})}),K(ml,{title:"How people join your list",sub:"Only people who asked to hear from you get your emails.",children:K(uv,{onAskAssistant:l?r:void 0})})]}),ge("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(eo,{settings:e,site:t})]})]})]})}function ml({title:e,sub:t,children:a}){return ge("section",{className:"af-rounded-xl af-border af-bg-background",children:[ge("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 Tn({icon:e,marker:t,label:a,value:s,mono:n=!0,hint:r,status:i,action:l,expanded:f=!1,children:d}){return ge("div",{className:"af-rounded-lg af-border af-bg-muted/30",children:[ge("div",{className:"af-flex af-items-center af-gap-3 af-p-3",children:[t?ge("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}),ge("span",{className:"af-sr-only",children:["Shown at ",t," in the preview"]})]}):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})}),ge("div",{className:"af-min-w-0 af-flex-1",children:[K("div",{className:"af-text-xs af-text-muted-foreground",children:a}),K("div",{className:G("af-truncate af-text-sm",n&&"af-font-mono"),children:s}),r&&K("div",{className:"af-text-xs af-text-muted-foreground",children:r})]}),i,l&&ge(y,{size:"sm",variant:f?"secondary":"outline","aria-expanded":d?f:void 0,onClick:l.onClick,children:[l.label,d&&K(Xg,{className:G("af-ml-1 af-h-3.5 af-w-3.5 af-transition-transform",f&&"af-rotate-180"),"aria-hidden":!0})]})]}),f&&d&&K("div",{className:"af-border-t af-bg-background af-p-4",children:d})]})}function Cn({tone:e,children:t}){return K("span",{className:G("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 Br(e){return e.domain.status==="verified"&&e.domain.dmarc_status==="ok"}function vl(e){let{sending_domain:t,status:a}=e.domain;return!t||a==="none"?K(Cn,{tone:"gray",children:"Not set up"}):a==="verified"?Br(e)?K(Cn,{tone:"green",children:"Live"}):K(Cn,{tone:"amber",children:"DMARC record missing"}):a==="failed"?K(Cn,{tone:"red",children:"Records not found"}):K(Cn,{tone:"amber",children:"Waiting for DNS"})}function ov({settings:e,businessName:t,onSaved:a}){let{canWrite:s}=nt(),[n,r]=Es.useState(e.business_name??t??""),[i,l]=Es.useState(e.postal_address??""),[f,d]=Es.useState(e.reply_to??""),o=Dt();return ge("form",{className:"af-space-y-3",onSubmit:async c=>{c.preventDefault(),(await o.run("updateSettings",{business_name:n.trim()||null,postal_address:i.trim()||null,reply_to:f.trim()||null,double_opt_in:e.double_opt_in})).ok&&await a()},children:[K(lv,{name:n,address:i}),ge("label",{className:"af-block af-space-y-1",children:[K("span",{className:"af-text-sm af-font-medium",children:"Sender name"}),K(te,{"aria-label":"Business name",value:n,disabled:!s,onChange:c=>r(c.target.value)})]}),ge("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:c=>l(c.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."})]}),ge("label",{className:"af-block af-space-y-1",children:[K("span",{className:"af-text-sm af-font-medium",children:"Replies go to (optional)"}),K(te,{"aria-label":"Reply-to email",type:"email",value:f,disabled:!s,onChange:c=>d(c.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(Ne,{tone:"error",children:o.error}),s&&K(y,{type:"submit",size:"sm",disabled:o.busy||!i.trim(),children:"Save sender details"})]})}function lv({name:e,address:t}){return ge("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"}),ge("div",{children:["\xA9 ",new Date().getFullYear()," ",K("span",{className:"af-font-medium af-text-foreground",children:e.trim()||"Your business"})]}),K("div",{className:G(!t.trim()&&"af-italic af-text-amber-700"),children:t.trim()||"No mailing address yet"}),ge("div",{children:[K("span",{className:"af-underline",children:"Manage preferences"})," | ",K("span",{className:"af-underline",children:"Unsubscribe"})]})]})}var cv={1:"From",2:"Subject and body",3:"Footer"};function eo({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"),f={backgroundColor:e?.brand.color??"hsl(var(--primary))"},d=r!==void 0?r.trim()||null:e?.postal_address,o=(c,b,g)=>s?ge("div",{"data-preview-region":c,"data-highlighted":n===c,className:G("af-relative af-rounded-md af-transition-shadow",n===c&&"af-ring-2 af-ring-primary af-ring-offset-2",b),children:[ge("span",{className:"af-absolute -af-left-3 -af-top-2 af-flex af-h-5 af-w-5 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-[10px] af-font-semibold af-text-background",children:[K("span",{"aria-hidden":!0,children:c}),ge("span",{className:"af-sr-only",children:[c,". ",cv[c],":"]})]}),g]}):K("div",{className:b,children:g});return ge("div",{className:G("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",ge(Xi,{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:f,children:i.slice(0,1).toUpperCase()}),ge("div",{className:"af-min-w-0",children:[K("div",{className:"af-truncate af-text-sm af-font-semibold",children:i}),ge("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:["<",pl(l),">"]}),K("div",{className:"af-text-xs af-text-muted-foreground",children:"to me"})]})]})),o(2,"af-mt-4 af-space-y-2",ge(Xi,{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",ge(Xi,{children:[K("div",{children:d??K("span",{className:"af-italic af-text-amber-700",children:"Mailing address goes here"})}),K("div",{className:"af-underline",children:"Unsubscribe"})]}))]})}var dv="Add a newsletter signup to my footer";function uv({onAskAssistant:e}){let t=hl();if(!t.data)return null;let{signups:a,optIns:s,others:n}=yl(t.data);return ge("div",{className:"af-space-y-3",children:[a.length===0?ge("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(Qi,{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&&ge(y,{type:"button",size:"sm",className:"af-mt-1",onClick:()=>e(dv),children:[K(av,{className:"af-mr-1.5 af-h-3.5 af-w-3.5","aria-hidden":!0}),"Add signup form"]})]}):ge("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[K(eu,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),ge("div",{className:"af-min-w-0 af-flex-1",children:[K("span",{className:"af-font-medium",children:"Signup form is live"}),ge("span",{className:"af-text-muted-foreground",children:[" \xB7 ",a.map(r=>r.name).join(", ")]})]})]}),s.length>0&&ge("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[K(eu,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),ge("div",{className:"af-min-w-0 af-flex-1",children:[K("span",{className:"af-font-medium",children:"Opt-in checkbox"}),ge("span",{className:"af-text-muted-foreground",children:[" \xB7 ",s.map(r=>r.name).join(", ")]})]})]}),a.length===0&&n.length>0&&ge("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&&ge(Xi,{children:[" ",K("button",{type:"button",className:"af-font-medium af-text-foreground af-underline af-underline-offset-2",onClick:()=>e(xl(n)),children:"Add the checkbox"})]})]})]})}import{Fragment as Sv,jsx as ue,jsxs as ea}from"react/jsx-runtime";var to="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 pv(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 wl({onStartDomainSetup:e,onAskAssistant:t}){let{settings:a,refetchSettings:s,canWrite:n,settingsSection:r}=nt(),[i,l]=ka.useState(null),[f,d]=ka.useState(null),[o,c]=ka.useState(""),b=a!==null;if(ka.useEffect(()=>{b&&r&&document.getElementById(Dr(r))?.scrollIntoView?.({block:"start"})},[b,r]),!a)return ue(J,{className:"af-h-40 af-w-full"});let g=h=>d(S=>S===h?null:h),m=()=>d(null),p=async()=>{await s(),m()},u=(h,S,N)=>({id:N,"data-settings-row":h,onMouseEnter:()=>l(S),onMouseLeave:()=>l(null),onFocus:()=>l(S),onBlur:()=>l(null)}),v=Br(a),{sending_domain:x,status:R}=a.domain,P=h=>n?{expanded:f===h}:{};return ue("div",{className:"af-@container",children:ea("div",{className:"af-grid af-items-start af-gap-6 @2xl:af-grid-cols-[minmax(0,17rem)_minmax(0,1fr)]",children:[ea("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(eo,{settings:a,site:{},numbered:!0,highlight:i,postalAddress:f==="address"?o:void 0}),ue(xv,{settings:a})]}),ea("div",{children:[ue(tn,{children:"From"}),ea("div",{className:"af-space-y-2",children:[ue("div",{...u("Sending domain",1,Dr("domain")),children:ue(Tn,{marker:1,label:"Sending from",value:x?pl(x):"No sending domain yet",status:vl(a),action:!v&&n?{label:x?R==="verified"||R==="failed"?"Fix":"Details":"Set up",onClick:()=>g("domain")}:void 0,...P("domain"),children:ue(bl,{settings:a,canWrite:n,onStartDomainSetup:e,onChanged:s})})}),ue("div",{...u("Sender name and replies",1),children:ue(Tn,{marker:1,label:"Sender name and replies",mono:!1,value:`${a.business_name??"No sender name"} \xB7 replies to ${a.reply_to??"your account email"}`,action:n?{label:"Edit",onClick:()=>g("sender")}:void 0,...P("sender"),children:ue(gv,{settings:a,onSaved:p,onCancel:m})})})]}),ue(tn,{children:"Brand"}),ue("div",{...u("Brand color and logo",2),children:ue(Tn,{marker:2,label:"Brand color and logo",value:`${a.brand.color}, ${a.brand.logo_url?"with your logo":"no logo"}`,action:n?{label:"Edit",onClick:()=>g("brand")}:void 0,...P("brand"),children:ue(vv,{settings:a,onSaved:p,onCancel:m})})}),ue(tn,{children:"Footer"}),ue("div",{...u("Mailing address",3,Dr("sender")),children:ue(Tn,{marker:3,label:"Mailing address",mono:!1,value:a.postal_address??"Not set",hint:"Anti-spam law requires it at the bottom of every email. A PO box works.",status:a.postal_address?void 0:ue(Cn,{tone:"amber",children:"Needed"}),action:n?{label:a.postal_address?"Edit":"Add",onClick:()=>{c(a.postal_address??""),g("address")}}:void 0,...P("address"),children:ue(bv,{settings:a,draft:o,onDraft:c,onSaved:p,onCancel:m})})}),ea("div",{id:Dr("signups"),children:[ue(tn,{children:"Who gets it"}),ea("div",{className:"af-space-y-2",children:[ue("div",{...u("Double opt-in",null),children:ue(hv,{settings:a,canWrite:n,onSaved:s})}),ue(wv,{onAskAssistant:n?t:void 0})]})]})]})]})})}function no(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 Sl({busy:e,error:t,canSave:a=!0,onSave:s,onCancel:n,children:r}){return ea("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),await s()},children:[r,t&&ue(Ne,{tone:"error",children:t}),ea("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 gv({settings:e,onSaved:t,onCancel:a}){let[s,n]=ka.useState(e.business_name??""),[r,i]=ka.useState(e.reply_to??""),l=Dt();return ea(Sl,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",no(e,{business_name:s.trim()||null,reply_to:r.trim()||null}))).ok&&await t()},children:[ue(ao,{label:"Sender name",children:ue(te,{"aria-label":"Business name",value:s,onChange:f=>n(f.target.value)})}),ue(ao,{label:"Replies go to (your account email or an address on your domain)",children:ue(te,{"aria-label":"Reply-to email",type:"email",value:r,onChange:f=>i(f.target.value)})})]})}function vv({settings:e,onSaved:t,onCancel:a}){let[s,n]=ka.useState(e.brand.color),[r,i]=ka.useState(e.brand.logo_url??""),l=Dt();return ue(Sl,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",no(e,{brand:{color:s,logo_url:r.trim()||null}}))).ok&&await t()},children:ea("div",{className:"af-flex af-flex-wrap af-gap-3",children:[ue(ao,{label:"Brand color",children:ue(te,{"aria-label":"Brand color",type:"color",className:"af-h-9 af-w-16 af-p-1",value:s,onChange:f=>n(f.target.value)})}),ue(ao,{label:"Logo URL (https)",children:ue(te,{"aria-label":"Logo URL",value:r,onChange:f=>i(f.target.value)})})]})})}function bv({settings:e,draft:t,onDraft:a,onSaved:s,onCancel:n}){let r=Dt();return ue(Sl,{busy:r.busy,error:r.error,canSave:!!t.trim(),onCancel:n,onSave:async()=>{(await r.run("updateSettings",no(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 hv({settings:e,canWrite:t,onSaved:a}){let[s,n]=ka.useState(null),[r,i]=ka.useState(!1),l=Dt(),f=s??e.double_opt_in;return ea("div",{className:"af-space-y-2",children:[ue(Tn,{icon:mv,label:"Double opt-in",mono:!1,value:f?"New subscribers confirm by email first":"New subscribers join straight away",status:ea("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:to,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:to}),ue("input",{"aria-label":"Double opt-in",type:"checkbox",role:"switch",checked:f,disabled:!t||l.busy,onChange:async d=>{let o=d.target.checked;n(o),(await l.run("updateSettings",no(e,{double_opt_in:o}))).ok&&await a(),n(null)}})]})}),l.error&&ue(Ne,{tone:"error",children:l.error})]})}function bl({settings:e,canWrite:t,onStartDomainSetup:a,onChanged:s}){let[n,r]=ka.useState(null),[i,l]=ka.useState(!1),[f,d]=ka.useState(null),o=Br(e);return ea("div",{children:[ue("p",{className:"af-text-sm",children:pv(e)}),!o&&a&&ue(y,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||i,onClick:async()=>{l(!0),d(null);try{r(await a()),await s()}catch(c){d(c instanceof Error?c.message:"Couldn't start domain setup.")}finally{l(!1)}},children:e.domain.sending_domain?"Check domain setup":"Set up sending domain"}),f&&ue(Ne,{tone:"error",className:"af-mt-2",children:f}),n?.records&&n.records.length>0&&ea("div",{className:"af-mt-3 af-space-y-1",children:[ue("p",{className:"af-text-sm",children:"Add these records at your domain provider:"}),ea("table",{className:"af-w-full af-text-left af-text-xs",children:[ue("thead",{children:ea("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:n.records.map((c,b)=>ea("tr",{className:"af-border-t af-align-top",children:[ue("td",{className:"af-py-1 af-pr-2",children:c.type}),ue("td",{className:"af-break-all af-py-1 af-pr-2",children:c.name}),ue("td",{className:"af-break-all af-py-1 af-pr-2",children:c.value}),ue("td",{className:"af-py-1",children:c.priority??""})]},b))})]})]}),n&&ue(yv,{result:n})]})}function yv({result:e}){return e.status==="no_domain"?ue(Ne,{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(Ne,{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 xv({settings:e}){let{monthly:t,sent:a,reserved:s}=e.allowance,n=a+s;return ea("p",{className:"af-text-xs af-text-muted-foreground",children:[Fe(n)," of ",Fe(t)," emails used this month (",Fe(Math.max(0,t-n))," left). Receipts and form notifications don't count."]})}function hl(){let{api:e}=H(),{siteId:t,refreshKey:a}=nt();return Kt(async()=>Promise.all((await e.getForms()).map(s=>e.getForm(s.id))),`${t}|${a}`,t)}function yl(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 xl(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 wv({onAskAssistant:e}){let t=hl();if(!t.data||t.data.length===0)return null;let{signups:a,optIns:s,others:n}=yl(t.data),r=[{id:"signup",label:"Signup forms",note:"Submitting one subscribes the visitor.",forms:a,icon:nu},{id:"opt_in",label:'Forms with a "Send me news" checkbox',note:"Visitors who tick the box join your list.",forms:s,icon:nu},{id:"other",label:"Other forms",note:"These don't add anyone to your list.",forms:n,icon:fv,action:a.length===0&&e?{label:"Add the checkbox",onClick:()=>e(xl(n))}:void 0}];return ue(Sv,{children:r.filter(i=>i.forms.length>0).map(i=>ue("div",{"data-form-group":i.id,children:ue(Tn,{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 ao({label:e,children:t}){return ea("label",{className:"af-block af-space-y-1",children:[ue("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}import*as so from"react";import{jsx as la,jsxs as Is}from"react/jsx-runtime";function ru({templateId:e,onOpenTemplate:t,onOpenDraft:a,onAskAssistant:s}){let{api:n}=H(),{siteId:r,canWrite:i,refreshKey:l}=nt(),[f,d]=so.useState(0),o=f+l,c=Kt(()=>n.getEmailTemplates(r),`${r}|${o}`,r),b=so.useCallback(()=>d(u=>u+1),[]),g=i?s:void 0;if(e){let u=e===zn?null:c.data?.find(v=>v.id===e);if(u!==void 0)return la(Gd,{template:u,onBack:()=>t(null),onOpenTemplate:t,onOpenDraft:a,onAskAssistant:g,reload:b,refreshKey:o},e);if(c.isLoading)return la(J,{className:"af-h-96 af-w-full"})}let m=c.data?.filter(u=>u.status!=="archived")??[],p=c.data?.filter(u=>u.status==="archived")??[];return Is("div",{children:[Is("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[la("h3",{className:"af-text-sm af-font-semibold",children:"Templates"}),g&&la(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(Zi.create),children:"\u2728 New template with the editor"})]}),Is(su,{children:[la(Nl,{template:null,onOpen:()=>t(zn)}),m.map(u=>la(Nl,{template:u,onOpen:()=>t(u.id)},u.id))]}),c.error&&!c.data?la("div",{className:"af-mt-3",children:la(Nt,{message:"Couldn't load your templates.",onRetry:()=>void c.refetch()})}):!c.data&&la(J,{className:"af-mt-3 af-h-10 af-w-full"}),p.length>0&&Is("div",{"data-testid":"archived-templates",children:[la(tn,{children:"Archived"}),la(su,{children:p.map(u=>la(Nl,{template:u,onOpen:()=>t(u.id)},u.id))})]})]})}function su({children:e}){return la("ul",{className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:e})}function Nv(e){let t=[dl(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 Nl({template:e,onOpen:t}){let a=e?.name??"Standard",s=e&&Nv(e);return Is("li",{"data-testid":"template-card",className:"af-relative af-overflow-hidden af-rounded-md af-border hover:af-border-primary",children:[la(Yi,{templateId:e?.id??zn,version:e?.updated_at??"builtin",className:"af-h-40 af-border-b",frame:{width:600,height:400,scale:.4}}),Is("div",{className:"af-space-y-1 af-p-2",children:[Is("div",{className:"af-flex af-items-center af-gap-2",children:[la("span",{"data-testid":"template-name",className:"af-grow af-truncate af-text-sm af-font-medium",children:a}),la(cl,{template:e})]}),s&&la("p",{className:"af-text-xs af-text-muted-foreground",children:s})]}),la("button",{type:"button","aria-label":`Open ${a}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}import{Fragment as Iv,jsx as bt,jsxs as Fr}from"react/jsx-runtime";var Rv=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"templates",label:"Templates"},{id:"settings",label:"Settings"}];function ps(e,t={}){return{tab:e,draftId:null,templateId:null,...t}}var iu=e=>!!(e.tab||e.draftId||e.templateId);function ou(e){return e.draftId?ps("broadcasts"):e.templateId?ps("templates",{templateId:e.templateId}):ps(e.tab==="template"?"templates":e.tab==="automations"||!e.tab?"audience":e.tab)}var _v={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function lu(e){return bt(Pv,{...e},e.siteId)}function Pv({siteId:e,isOwnerSide:t,needsPaidPlan:a,initialDraftId:s,initialTab:n,templateId:r,showViewNonce:i,onOrgAction:l,onRequestReview:f,onStartDomainSetup:d,onBackToWebsite:o,onUpgradePlan:c,onConnectDomain:b,onAskAssistant:g,onPickImage:m,onTurnOn:p,siteDomain:u,businessName:v,onOpenStoreSettings:x,refreshKey:R=0,className:P}){let{api:h}=H(),S=Kt(()=>h.getMarketingSettings(e),`${e}|${R}`,e),N={tab:n,draftId:s,templateId:r},[C,w]=ta.useState(()=>ou(N)),[k,T]=ta.useState(s??null),[_,z]=ta.useState(iu(N)),[Z,U]=ta.useState(null),[ae,le]=ta.useState(!1),fe=ta.useCallback(()=>z(!1),[]),M=ta.useCallback(oe=>{w(ps("settings")),U(oe??null)},[]),W=oe=>{w(ps(oe)),U(null)},A=ta.useCallback(oe=>w(ps("broadcasts",{draftId:oe})),[]),de=ta.useCallback(oe=>w(ps("templates",{templateId:oe})),[]),ce=!_&&S.data!==null&&kv(S.data),Le=S.data&&!S.error?Cv(S.data):null,ye=JSON.stringify([i??null,n??null,s??null,r??null]),Te=ta.useRef(ye);ta.useEffect(()=>{if(ye===Te.current||ae)return;Te.current=ye;let oe={tab:n,draftId:s,templateId:r};iu(oe)&&(w(ou(oe)),T(oe.draftId??null),U(null),z(!0))},[ye,ae,n,s,r]),ta.useEffect(()=>{if(!k||a)return;let oe=!0,st=E=>{oe&&(w(ps("broadcasts",{draftId:E})),T(null))};return h.getEmailDraft(e,k).then(E=>st(E.kind==="broadcast"?E.id:null),()=>st(null)),()=>{oe=!1}},[h,e,k,a]);let Oe=ta.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:l,settings:S.data,refetchSettings:S.refetch,refreshKey:R,openSetup:fe,openSettings:M,settingsSection:Z,onOpenStoreSettings:x,setInlineEditOpen:le}),[e,t,l,S.data,S.refetch,R,fe,M,Z,x]);return a?bt(Ft,{title:"Email Marketing",onBackToWebsite:o,className:P,children:bt(gl,{settings:S.data,site:{siteDomain:u,businessName:v},children:bt(au,{onUpgradePlan:c})})}):bt(Ft,{title:"Email Marketing",onBackToWebsite:o,className:P,children:bt(el.Provider,{value:Oe,children:ce?bt(tu,{onStartDomainSetup:d,onConnectDomain:b,onAskAssistant:g,onTurnOn:p,siteDomain:u,businessName:v}):Fr(Iv,{children:[S.error&&!S.data&&bt(Nt,{message:"Couldn't load email settings.",onRetry:()=>void S.refetch()}),Le&&bt(Ev,{reason:Le,pauseReason:S.data?.paused.reason??null,onRequestReview:f}),!t&&bt(Ne,{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:Rv.map(oe=>Fr("button",{type:"button",role:"tab","aria-selected":C.tab===oe.id,onClick:()=>W(oe.id),className:G("af-border-b-2 af-px-3 af-py-2 af-text-sm",C.tab===oe.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:[oe.label,oe.id==="settings"&&Le&&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"})]},oe.id))}),bt("div",{role:"tabpanel",children:k?bt(J,{className:"af-h-24 af-w-full"}):C.tab==="audience"?bt(Md,{}):C.tab==="broadcasts"?bt(Xd,{openDraftId:C.draftId,onOpenDraft:A,onAskAssistant:g,onPickImage:m}):C.tab==="templates"?bt(ru,{templateId:C.templateId,onOpenTemplate:de,onOpenDraft:A,onAskAssistant:g}):bt(wl,{onStartDomainSetup:d,onAskAssistant:g})})]})})})}function kv(e){return!e.paused.paused_at&&!e.readiness.can_send&&Er.has(e.readiness.reason??"")}function Cv(e){if(e.paused.paused_at)return"paused";let t=e.readiness.reason;return!e.readiness.can_send&&t&&Er.has(t)?t:null}var Tv={domain_not_verified:"domain",dmarc_missing:"domain",postal_address_missing:"sender"};function Ev({reason:e,pauseReason:t,onRequestReview:a}){let{openSetup:s,openSettings:n}=nt(),[r,i]=ta.useState("idle");if(e==="paused")return bt("div",{"data-testid":"email-hold",className:"af-mb-3",children:Fr(Ne,{tone:"warning",children:[bt("div",{className:"af-font-medium",children:"Sending is paused."}),Fr("p",{children:[_v[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=Tv[e];return bt("div",{"data-testid":"email-hold",className:"af-mb-3",children:Fr(Ne,{tone:"warning",children:["Sending is on hold. ",sr(e)," ",l?bt(ks,{onClick:()=>n(l),children:"Fix in Settings"}):bt(ks,{onClick:s,children:"Finish setup"})]})})}import*as aa from"react";var Dv=2e3,pa=()=>({data:null,error:null,isLoading:!0});function ur(e,{refreshKey:t,breakdowns:a=[],filters:s=[]}={}){let{api:n}=H(),[r,i]=aa.useState(pa),[l,f]=aa.useState(pa),[d,o]=aa.useState(pa),[c,b]=aa.useState(pa),[g,m]=aa.useState(pa),p=M=>Object.fromEntries(M.map(W=>[W,pa()])),[u,v]=aa.useState(()=>p(a)),x=aa.useRef(0),R=aa.useRef(0),P=aa.useRef("idle"),h=a.join(","),S=ts()??"",N=JSON.stringify(s),C=`${e}:${h}:${N}:${S}`,[w,k]=aa.useState({api:n,fetchIdentity:C});(w.api!==n||w.fetchIdentity!==C)&&(k({api:n,fetchIdentity:C}),x.current+=1,i(pa),f(pa),o(pa),b(pa),v(p(h?h.split(","):[])));let T=`${e}:${String(t??"")}:${S}`,[_,z]=aa.useState({api:n,conversionsIdentity:T});(_.api!==n||_.conversionsIdentity!==T)&&(z({api:n,conversionsIdentity:T}),R.current+=1,P.current="idle",m(pa));let Z=aa.useCallback(async M=>{let W=++x.current,A=h?h.split(","):[];i(pa),f(pa),o(pa),b(pa),v(Object.fromEntries(A.map(E=>[E,pa()])));let de=P.current!=="pending"&&(M?.force===!0||P.current==="idle"),ce=(E,O)=>O.then(B=>{W===x.current&&E({data:B,error:null,isLoading:!1})},B=>{W===x.current&&E({data:null,error:B instanceof Error?B:new Error("Failed to fetch report"),isLoading:!1})}),Le=n.getAnalyticsStatus(),ye=ce(i,Le),Te=Symbol("status-timeout"),Oe,oe=await Promise.race([Le.then(E=>E,()=>null),new Promise(E=>{Oe=setTimeout(()=>E(Te),Dv)})]);if(clearTimeout(Oe),W!==x.current)return;if(oe===Te&&i({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),oe!==null&&oe!==Te&&(oe.collecting!==!0||oe.first_seen===null&&!oe.first_seen_unavailable||oe.first_seen!==null&&oe.first_seen_in_reports===!1)){let E={data:null,error:null,isLoading:!1};f(E),o(E),b(E),v(Object.fromEntries(A.map(O=>[O,{...E}]))),de&&(m(E),P.current="done"),await ye;return}await Promise.all([oe===Te?Promise.resolve():ye,ce(f,n.getAnalyticsSummary(e,s)),ce(o,n.getAnalyticsTimeseries(e,s)),ce(b,n.getAnalyticsChannels(e,s)),de?(()=>{P.current="pending";let E=++R.current;return m(pa),n.getAnalyticsConversions(e).then(O=>{E===R.current&&(m({data:O,error:null,isLoading:!1}),P.current="done")},O=>{E===R.current&&(m({data:null,error:O instanceof Error?O:new Error("Failed to fetch report"),isLoading:!1}),P.current="done")})})():Promise.resolve(),...A.map(E=>n.getAnalyticsBreakdown(E,e,s).then(O=>{W===x.current&&v(B=>({...B,[E]:{data:O,error:null,isLoading:!1}}))},O=>{W===x.current&&v(B=>({...B,[E]:{data:null,error:O instanceof Error?O:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,N,T,S]),U=aa.useCallback(async()=>{let M=x.current;try{let W=await n.getAnalyticsStatus();if(M!==x.current)return;i({data:W,error:null,isLoading:!1})}catch(W){if(M!==x.current)return;i(A=>({data:A.data,error:W instanceof Error?W:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),ae=aa.useCallback(()=>Z({force:!0}),[Z]);aa.useEffect(()=>{Z()},[Z,t]);let le=r.isLoading||l.isLoading||d.isLoading||c.isLoading||g.isLoading||Object.values(u).some(M=>M.isLoading),fe=[d,l,c,g,...Object.values(u)].map(M=>M.data?.status==="ok"?M.data.timezone:void 0).find(M=>M!==void 0);return{status:r,summary:l,timeseries:d,channels:c,conversions:g,breakdowns:u,reportedZone:fe,isLoading:le,refetch:ae,refetchStatus:U}}import*as na from"react";var Rl=3e4,_l=3;function ro(e={}){let t="collecting"in e,{collecting:a,statusFailed:s=!1,identity:n}=e,{api:r}=H(),[i,l]=na.useState(null),[f,d]=na.useState(null),[o,c]=na.useState(!1),[b,g]=na.useState(null),[m,p]=na.useState(!1),[u,v]=na.useState(!0),[x,R]=na.useState(0),P=na.useRef(0),h=na.useRef(0),S=na.useRef(void 0);a!==void 0&&(S.current=a);let N=t?S.current===!0||S.current===void 0&&s:!0,[C,w]=na.useState({api:r,identity:n}),k=n!==void 0&&n!==C.identity;(C.api!==r||k)&&(S.current=void 0,w({api:r,identity:n}),h.current+=1,P.current=0,l(null),d(null),c(!1),g(null),p(!1),v(!0),R(0));let T=na.useRef(()=>{}),_=na.useRef(null),z=na.useCallback(async()=>{if(_.current!==null&&_.current===h.current)return;let Z=++h.current;_.current=Z;try{let U=await r.getAnalyticsRealtime();if(Z!==h.current)return;if(U.status==="unreachable"){p(!0),c(!0),v(!1),R(ae=>ae+1);return}P.current=0,p(!1),l(U.data.current_visitors),d(U.as_of),c(!1),g(null),v(!1),R(ae=>ae+1)}catch(U){if(Z!==h.current)return;P.current+=1,v(!1),R(ae=>ae+1),c(!0),P.current>=_l&&g(U instanceof Error?U:new Error("Realtime unavailable"))}finally{_.current===Z&&(_.current=null)}},[r]);return T.current=()=>void z(),na.useEffect(()=>{let Z,U=()=>{Z===void 0&&(Z=setInterval(()=>T.current(),Rl))},ae=()=>{Z!==void 0&&(clearInterval(Z),Z=void 0)},le=()=>{typeof document<"u"&&document.hidden?ae():(T.current(),U())};return N?((typeof document>"u"||!document.hidden)&&(T.current(),U()),document?.addEventListener("visibilitychange",le),()=>{ae(),document?.removeEventListener("visibilitychange",le),h.current+=1}):()=>{document?.removeEventListener("visibilitychange",le)}},[C.api,C.identity,N]),{currentVisitors:i,asOf:f,isStale:o,error:b,isUnreachable:m,isInitialLoad:u,polls:x}}import*as Lt from"react";import*as du from"react";import{jsx as Pl,jsxs as cu}from"react/jsx-runtime";function Av(){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 kl({value:e,chosen:t,onChange:a}){let s=pr(),n=t===null&&s!==null&&e===s,r=du.useMemo(()=>{let i=Av();return i.includes(e)?i:[e,...i]},[e]);return cu("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[Pl("span",{className:"af-sr-only",children:"Reporting timezone"}),cu("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:[Pl("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(i=>Pl("option",{value:i,children:i.replace(/_/g," ")},i))]})]})}var io=(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 Mr from"react";var Lv=3e4;function oo({status:e,holdingForFirstData:t,refetchStatus:a,refetch:s}){Mr.useEffect(()=>{if(!t)return;let r,i=()=>{r===void 0&&(r=setInterval(()=>void a(),Lv))},l=()=>{r!==void 0&&(clearInterval(r),r=void 0)},f=()=>{typeof document<"u"&&document.hidden?l():(a(),i())};return(typeof document>"u"||!document.hidden)&&i(),document?.addEventListener("visibilitychange",f),()=>{l(),document?.removeEventListener("visibilitychange",f)}},[t,a]);let n=Mr.useRef(void 0);Mr.useEffect(()=>{if(!e){n.current=void 0;return}let r=n.current;n.current=t,r===!0&&!t&&s()},[e,t,s])}import*as As from"react";var Ov=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ca(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?Ca(i*s):`${i}${n}`}return String(e)}function fr(e){return`${(e*100).toFixed(1)}%`}function Ur(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 fu(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`:Ur(t)}function mu(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function pu(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 $r(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function gu(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 Cl(e){let t=Number(e.slice(5,7)),a=Number(e.slice(8,10));return`${Ov[t-1]} ${a}`}function uu(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Bv(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function vu(e,t,a="UTC"){let s=new Map(t.map(i=>[i.date,i])),n=[],r=uu(e.to,a);for(let i=uu(e.from,a);i<r;i=Bv(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 bu(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 Mv,jsx as gs,jsxs as Fv}from"react/jsx-runtime";function hu({what:e="This report",onRetry:t,collecting:a}){return Fv("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:[gs("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),gs("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?gs("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 lo({what:e="No data"}){return gs("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 es({sourced:e,error:t,isLoading:a,what:s,onRetry:n,collecting:r,children:i}){return a?gs("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?gs(hu,{what:s,onRetry:n,collecting:r}):!e||e.status==="unreachable"?gs(hu,{what:s,onRetry:n,collecting:r}):gs(Mv,{children:i(e.data)})}import{Fragment as Uv,jsx as Ha,jsxs as Ds}from"react/jsx-runtime";function Tl({rows:e,dimension:t,metric:a,metricLabel:s,secondary:n,emptyCopy:r="No data for this period",onFilter:i,canFilter:l,maxRows:f=9}){let[d,o]=As.useState(!1);if(e.length===0)return Ha(lo,{what:r});let c=e.reduce((m,p)=>Math.max(m,Number(p[a]??0)),0)||1,b=Math.max(0,e.length-f),g=d?e:e.slice(0,f);return Ds(Uv,{children:[Ds("table",{className:"af-w-full af-text-sm",children:[Ha("thead",{children:Ds("tr",{className:"af-text-xs af-text-muted-foreground",children:[Ha("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),Ha("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),Ha("tbody",{children:g.map((m,p)=>{let u=Number(m[a]??0),v=m[t]??null,x=$r(v),R=n?m[n]:null,P=v!==null&&(l?l(v,R):!0);return Ds("tr",{className:"af-border-t af-border-border",children:[Ds("td",{className:"af-relative af-py-1.5 af-pr-2",children:[Ha("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,u/c*100)}%`}}),v!==null&&i&&P?Ha("button",{type:"button",onClick:()=>i(v,R),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}):Ha("span",{className:"af-relative af-break-words af-text-foreground",children:x}),R?Ha("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:R}):null]}),Ha("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Ca(u)})]},`${x}-${R??""}-${p}`)})})]}),b>0?Ha("button",{type:"button",onClick:()=>o(m=>!m),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:d?"Show fewer":`Show all ${e.length}`}):null]})}function Vr({title:e,tabs:t,defaultTabId:a,headerRight:s}){let[n,r]=As.useState(a),i=t.find(g=>g.id===n)??t[0],l=As.useId(),f=g=>`${l}-tab-${g}`,d=g=>`${l}-panel-${g}`,o=As.useRef(null),c=(g,m)=>{g.preventDefault();let p=(m+t.length)%t.length;r(t[p].id),o.current?.querySelectorAll('[role="tab"]')?.[p]?.focus()};return Ds("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[Ds("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:[Ha("div",{ref:o,role:"tablist","aria-label":e,onKeyDown:g=>{let m=t.findIndex(p=>p.id===n);g.key==="ArrowRight"&&c(g,m+1),g.key==="ArrowLeft"&&c(g,m-1),g.key==="Home"&&c(g,0),g.key==="End"&&c(g,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(g=>Ha("button",{id:f(g.id),role:"tab",type:"button","aria-selected":g.id===n,"aria-controls":d(g.id),tabIndex:g.id===n?0:-1,onClick:()=>r(g.id),className:g.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:g.label},g.id))}),s]}),i?Ha("div",{id:d(i.id),role:"tabpanel","aria-labelledby":f(i.id),tabIndex:0,className:"af-px-3 af-py-2",children:i.render()},i.id):null]})}import*as za from"react";import*as vs from"@radix-ui/react-popover";var Ls=3,Os=100;import{jsx as Ht,jsxs as qn}from"react/jsx-runtime";var Hr={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"},$v=Object.keys(Hr);function yu(e){let t=Hr[e.dimension],a=e.operator==="is_not"?"is not":"is",s=e.values.map(n=>$r(n)).join(" or ");return`${t} ${a} ${s}`}function El(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>Os||s.length===e[a].values.length?e:e.map((n,r)=>r===a?{...n,values:s}:n)}return t.values.length>Os||e.length>=Ls?e:[...e,t]}function Vv(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 xu(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>Os||e.length>=Ls?e:[...e,t]}function Hv(e){return{dimension:e,operator:"is",search:"",picked:[]}}function wu(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=Vv(e.byDimension,a);for(let[r,i]of Object.entries(s)){let l=e.foldsByLabel.get(r)??new Set;for(let f of i)l.add(f);e.foldsByLabel.set(r,l)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([r,i])=>[r,[...i]]))}}function Su(e){let{filters:t,onChange:a}=e,s=t.length>=Ls;return za.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:[Ht("span",{className:"af-text-foreground",children:yu(n)}),Ht("button",{type:"button","aria-label":`Remove filter ${yu(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"}`)),Ht(zv,{...e,disabled:s}),t.length>0?Ht("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 zv({filters:e,onChange:t,suggestions:a,resetKey:s,disabled:n,expandValues:r}){let[i,l]=za.useState(!1),f=za.useRef(null),[d,o]=za.useState(null);za.useEffect(()=>{o(f.current?.closest(".aifeatures-admin")??null)},[]);let[c,b]=za.useState(null),[g,m]=za.useState("is"),[p,u]=za.useState(""),[v,x]=za.useState([]);za.useEffect(()=>{i||(b(null),m("is"),u(""),x([]))},[i]);let R=za.useRef(s);R.current!==s&&(R.current=s,i&&l(!1),c!==null&&b(null),v.length>0&&x([]),p!==""&&u(""),g!=="is"&&m("is"));let P=k=>{let T=Hv(k);b(T.dimension),x(T.picked),u(T.search),m(T.operator)},S=(c?a[c]??[]:[]).filter(k=>k.toLowerCase().includes(p.trim().toLowerCase())),N=c===null||v.length===0?null:El(e,{dimension:c,operator:g,values:r?r(c,v):v}),C=N!==null&&N!==e,w=()=>{let k=N;!k||k===e||(t(k),l(!1))};return qn(vs.Root,{open:i,onOpenChange:l,children:[Ht(vs.Trigger,{asChild:!0,children:Ht("button",{ref:f,type:"button",disabled:!1,title:n?`At most ${Ls} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),Ht(vs.Portal,{container:d,children:Ht(vs.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:c===null?qn("div",{children:[Ht("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),Ht("div",{className:"af-max-h-96 af-overflow-y-auto",children:$v.filter(k=>a[k]!==void 0).map(k=>{let T=a[k]?.length??0,_=!e.some(z=>z.dimension===k)&&e.length>=Ls;return qn("button",{type:"button",onClick:()=>P(k),disabled:T===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:[Ht("span",{children:Hr[k]}),Ht("span",{className:"af-text-muted-foreground",children:T===0?"no data":_?"no room":T})]},k)})})]}):qn("div",{children:[qn("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Ht("button",{type:"button",onClick:()=>P(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),Ht("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Hr[c]}),qn("select",{"aria-label":"Operator",value:g,onChange:k=>m(k.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[Ht("option",{value:"is",children:"is"}),Ht("option",{value:"is_not",children:"is not"})]})]}),Ht("input",{type:"text",value:p,onChange:k=>u(k.target.value),placeholder:"Search\u2026","aria-label":`Search ${Hr[c]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),Ht("div",{className:"af-max-h-48 af-overflow-y-auto",children:S.length===0?qn("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",p,"\u201D."]}):S.map(k=>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:[Ht("input",{type:"checkbox",checked:v.includes(k),disabled:!v.includes(k)&&v.length>=Os,onChange:T=>x(_=>T.target.checked?[..._,k]:_.filter(z=>z!==k))}),Ht("span",{className:"af-break-all",children:$r(k)})]},k))}),Ht("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:v.length<=1?"Apply filter":v.length>=Os?`Apply filter (${v.length} values \u2014 the maximum)`:`Apply filter (${v.length} values)`})]})})})]})}import{Fragment as Wv,jsx as Ta,jsxs as co}from"react/jsx-runtime";var qv=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Ca,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Ca,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Ca,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:fr,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Ur,chart:"visit_duration_seconds"}];function jv({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 Ta("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 Nu({summary:e,selected:t,onSelect:a}){return Ta("div",{className:"af-@container",children:Ta("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:qv.map(s=>{let n=s.chart===t,r=a!==void 0,i=co(Wv,{children:[Ta("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),co("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Ta("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?Ta(jv,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?Ta("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):Ta("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:i},s.key)})})})}function Il({currentVisitors:e,asOf:t,isStale:a,isUnreachable:s,isInitialLoad:n=!1,scopeIsSiteWide:r=!1}){if(n&&!s)return co("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:[Ta("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Ta("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return Ta("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let i=t?gu(t):"freshness unknown",l=r?" across the whole site, not the current filter,":"",f=a?`${e} current visitors${l} ${i} (not updating)`:`${e} current visitors${l} ${i}`;return co("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:f,children:[Ta("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"}),Ta("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Ta("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),Ta("span",{className:"af-sr-only",children:f})]})}import*as _u from"react";import{Star as Gv}from"lucide-react";import{Fragment as Ru,jsx as ca,jsxs as Bs}from"react/jsx-runtime";function uo(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function fo({rows:e,denominator:t,windowPrecedesCollection:a=!1,coverageUnknown:s=!1,emptyCopy:n="No conversions in this period",maxRows:r=9,primaryConversion:i}){let[l,f]=_u.useState(!1),d=e.filter(u=>!u.implicit||u.visitors>0||u.events>0||uo(u,i)),o=a?ca("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?ca("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null;if(d.length===0)return Bs(Ru,{children:[ca(lo,{what:n}),o]});let c=d.slice(0,r),b=i?d.find(u=>uo(u,i)):void 0,g=b&&!c.includes(b)?d.filter(u=>c.includes(u)||u===b).slice(0,Math.max(0,r-1)).concat(b):c,m=l?e:g,p=Math.max(0,e.length-g.length);return Bs(Ru,{children:[Bs("table",{className:"af-w-full af-text-sm",children:[ca("thead",{children:Bs("tr",{className:"af-text-xs af-text-muted-foreground",children:[ca("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),ca("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),ca("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),ca("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),ca("tbody",{children:m.map((u,v)=>Bs("tr",{className:"af-border-t af-border-border","aria-current":uo(u,i)?"true":void 0,children:[ca("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:uo(u,i)?Bs("span",{className:"af-flex af-items-center af-gap-1.5",children:[ca(Gv,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),ca("span",{className:"af-font-medium af-text-foreground",children:u.goal}),ca("span",{className:"af-sr-only",children:"(your main conversion)"})]}):u.goal}),ca("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ca(u.visitors)}),ca("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ca(u.events)}),ca("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:u.conversion_rate===null?ca("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):fr(u.conversion_rate)})]},`${u.goal}-${v}`))})]}),p>0?ca("button",{type:"button",onClick:()=>f(u=>!u),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,Bs("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Ca(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),o]})}import{Area as Kv,AreaChart as Zv,CartesianGrid as Yv,ResponsiveContainer as Jv,Tooltip as Xv,XAxis as Qv,YAxis as eb}from"recharts";import{jsx as Ea,jsxs as zr}from"react/jsx-runtime";var mo={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Al={visitors:Ca,visits:Ca,pageviews:Ca,views_per_visit:e=>e.toFixed(2),bounce_rate:fr,visit_duration_seconds:Ur},tb=31,ab=new Set(["visitors","visits","pageviews"]),nb={...Al,bounce_rate:mu,visit_duration_seconds:fu},Dl=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],sb=[5,10,15,30,60,120,300,600,900,1800,3600,7200],rb=[.01,.02,.05,.1,.2,.25,.5,1],ib=[.25,.5,1,2,5,10,25,50],ob={visitors:Dl,visits:Dl,pageviews:Dl,views_per_visit:ib,bounce_rate:rb,visit_duration_seconds:sb};function lb({active:e,payload:t,label:a,metric:s}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return zr("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:[Ea("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:mo[s]}),zr("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[Ea("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),Ea("span",{className:"af-text-muted-foreground",children:bu(String(a))}),Ea("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Al[s](Number(n[s]??0))})]})]})}function po({rows:e,window:t,metric:a,timeZone:s="UTC",height:n=260}){let r=vu(t,e,s),i=Al[a],l=nb[a],f=pu(r.reduce((o,c)=>Math.max(o,Number(c[a]??0)),0),ob[a]),d=`${mo[a]} by day: ${r.map(o=>`${Cl(o.date)}: ${i(Number(o[a]??0))}`).join("; ")}.`;return zr("figure",{"aria-label":`${mo[a]} over time`,className:"af-m-0",children:[Ea(Jv,{width:"100%",height:n,children:zr(Zv,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[Ea("defs",{children:zr("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[Ea("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),Ea("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),Ea(Yv,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Ea(Qv,{dataKey:"date",tickFormatter:Cl,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Ea(eb,{allowDecimals:!ab.has(a),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...f?{ticks:f,domain:[0,f[f.length-1]]}:{},tickFormatter:o=>l(o),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Ea(Xv,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Ea(lb,{metric:a})}),Ea(Kv,{type:"linear",dataKey:a,name:mo[a],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=tb?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),Ea("figcaption",{className:"af-sr-only",children:d})]})}import{Fragment as Ll,jsx as Ae,jsxs as Sa}from"react/jsx-runtime";var cb="2026-08-13",db=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],ub=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function fb({filters:e,onFiltersChange:t,refreshKey:a,onBackToWebsite:s,primaryConversion:n,className:r,published:i,lastPublishedAt:l}){let[f,d]=Lt.useState(30),[o,c]=Lt.useState(()=>yo()),b=e!==void 0&&t!==void 0,[g,m]=Lt.useState(e??[]),{api:p}=H(),[u,v]=Lt.useState(p);u!==p&&(v(p),!b&&g.length>0&&m([]));let x=b?e:g,R=Lt.useCallback(B=>{t&&t(B),b||m(B)},[t,b]),P=Lt.useCallback((B,we,X)=>{let ve=Array.isArray(we)?we:[we];if(ve.length===0)return null;let Me=El(x,{dimension:B,operator:"is",values:ve});if(X&&(!X.value||(Me=xu(Me,{dimension:X.dimension,operator:"is",values:[X.value]}),!Me.find(Ct=>Ct.dimension===X.dimension&&Ct.operator!=="is_not")?.values.includes(X.value))))return null;let ht=Me.find(Ke=>Ke.dimension===B&&Ke.operator!=="is_not");return ve.every(Ke=>ht?.values.includes(Ke))?JSON.stringify(Me)===JSON.stringify(x)?null:Me:null},[x]),h=Lt.useCallback((B,we,X)=>P(B,we,X)!==null,[P]),S=Lt.useCallback((B,we,X)=>{let ve=P(B,we,X);ve&&R(ve)},[P,R]),[N,C]=Lt.useState("visitors"),w=ur(f,{refreshKey:a,breakdowns:ub,filters:x}),k=w.status.data,T=w.reportedZone??k?.timezone,_=T??o??pr()??"UTC",{notCollecting:z,awaitingFirstVisit:Z,firstVisitTooRecent:U,holdingForFirstData:ae}=io(k,{published:i}),le=i===!1,fe=ro({collecting:Z||z?!1:k?.collecting,statusFailed:w.status.error!=null,identity:k?.analytics_id}),M=Lt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),W=Lt.useMemo(()=>{let B=w.breakdowns.sources?.data,we={};if(!B||B.status!=="ok")return we;for(let X of B.data){let ve=X.source,Me=X.sources;typeof ve=="string"&&Array.isArray(Me)&&Me.length>0&&(we[ve]=Me)}return we},[w.breakdowns.sources?.data]),A=Lt.useMemo(()=>{let B=(ve,Me)=>{let ht=w.breakdowns[ve]?.data;return!ht||ht.status!=="ok"?[]:[...new Set(ht.data.map(Ke=>Ke[Me]).filter(Ke=>typeof Ke=="string"&&Ke!==""))]};return{channel:w.channels.data?.status==="ok"?[...new Set(w.channels.data.data.map(ve=>ve.channel))]:[],source:B("sources","source"),campaign:B("utm/campaign","campaign"),page:B("pages","pathname"),entry_page:B("entry-pages","pathname"),exit_page:B("exit-pages","pathname"),country:B("countries","country"),browser:B("browsers","browser"),os:B("operating-systems","os"),device:B("devices","device")}},[w.breakdowns,w.channels.data]),[de,ce]=Lt.useState({}),Le=JSON.stringify(A),[ye,Te]=Lt.useState(new Map),Oe=JSON.stringify(W);Lt.useEffect(()=>{let{suggestions:B,folds:we}=wu(M.current,{api:p,period:f},JSON.parse(Le),JSON.parse(Oe));ce(B),Te(we)},[Le,Oe,p,f]);let oe=Lt.useCallback((B,we)=>B!=="source"?we:[...new Set(we.flatMap(X=>{let ve=[...ye.get(X)??[],...W[X]??[]];return ve.length>0?ve:[X]}))],[ye,W]),st=Lt.useMemo(()=>{let B=w.conversions.error;return B instanceof Yt&&B.details?.code==="goals_exceed_report_budget"?B.message:null},[w.conversions.error]),E=Lt.useMemo(()=>{let B=[w.summary,w.timeseries,w.channels,...Object.values(w.breakdowns)];for(let we of B){let X=we?.error;if(X instanceof Yt&&X.details?.code==="filter_unsupported")return X.message}return null},[w.summary,w.timeseries,w.channels,w.breakdowns]),O=(B,we,X,ve,Me,ht,Ke,Ct,pe)=>()=>{let ke=w.breakdowns[B];return Ae(es,{sourced:ke?.data??null,error:ke?.error,isLoading:ke?.isLoading,what:we,collecting:k?.collecting,onRetry:w.refetch,children:rt=>{let Je=zt=>Ct?oe(Ct,[zt]):zt;return Ae(Tl,{rows:rt,dimension:X,metric:ve,metricLabel:Me,secondary:ht,emptyCopy:x.length>0?"No data for this filter":Ke,canFilter:Ct?(zt,Ot)=>h(Ct,Je(zt),pe?{dimension:pe,value:Ot}:void 0):()=>!1,onFilter:Ct?(zt,Ot)=>S(Ct,Je(zt),pe?{dimension:pe,value:Ot}:void 0):void 0})}})};if(oo({status:k,holdingForFirstData:ae,refetchStatus:w.refetchStatus,refetch:w.refetch}),z){let B=!!l&&String(l).slice(0,10)<cb;return Ae(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:Sa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),Ae("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:le?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":B?"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 Z?Ae(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:Sa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),Ae("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?Sa(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:[Ae("div",{className:"af-mb-3 af-flex af-justify-end",children:Ae(kl,{value:_,chosen:o,onChange:B=>{xo(B),c(B)}})}),Sa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),Sa("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",k?.timezone?` ${k.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),Ae("div",{className:"af-mt-4 af-flex af-justify-center",children:Ae(Il,{currentVisitors:fe.currentVisitors,asOf:fe.asOf,isStale:fe.isStale,isUnreachable:fe.isUnreachable||fe.error!==null,isInitialLoad:fe.isInitialLoad})})]})]}):Ae(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:Sa("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Sa("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Ae("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:db.map(B=>Ae("button",{type:"button","aria-pressed":B.value===f,onClick:()=>d(B.value),className:B.value===f?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:B.label},B.value))}),Ae(kl,{value:_,chosen:o,onChange:B=>{xo(B),c(B)}}),Ae(Il,{currentVisitors:fe.currentVisitors,asOf:fe.asOf,isStale:fe.isStale,isUnreachable:fe.isUnreachable||fe.error!==null,isInitialLoad:fe.isInitialLoad,scopeIsSiteWide:x.length>0})]}),Ae(Su,{filters:x,onChange:R,suggestions:de,expandValues:oe,resetKey:p}),E?Sa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),Ae("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:E}),Ae("button",{type:"button",onClick:()=>R([]),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&&k?.timezone_defaulted?Ae("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:Sa(Ll,{children:[Ae(es,{sourced:w.summary.data,error:w.summary.error,isLoading:w.summary.isLoading,what:"The traffic summary",collecting:k?.collecting,onRetry:w.refetch,children:B=>Sa(Ll,{children:[Ae(Nu,{summary:B,selected:N,onSelect:C}),B.previous_unavailable?Sa("p",{className:"af-text-xs af-text-muted-foreground",children:[B.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]})}),Ae("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:Ae(es,{sourced:w.timeseries.data,error:w.timeseries.error,isLoading:w.timeseries.isLoading,what:"The visitors chart",collecting:k?.collecting,onRetry:w.refetch,children:B=>{let we=w.timeseries.data?.status==="ok"?w.timeseries.data.window:{from:"",to:""};return Ae(po,{rows:B,window:we,metric:N,timeZone:T??"UTC"})}})}),Sa("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[Ae(Vr,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>Ae(es,{sourced:w.channels.data,error:w.channels.error,isLoading:w.channels.isLoading,what:"Channels",collecting:k?.collecting,onRetry:w.refetch,children:B=>Ae(Tl,{rows:B,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:we=>h("channel",we),onFilter:we=>S("channel",we)})})},{id:"sources",label:"Sources",render:O("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:O("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),Ae(Vr,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:O("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:O("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:O("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),Ae(Vr,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:O("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:O("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:O("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),Ae(Vr,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:O("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:O("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:O("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),Sa("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[Ae("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:Ae("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),Sa("div",{className:"af-px-3 af-py-2",children:[x.length>0?Sa("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,st!==null?Sa("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:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),Ae("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:st})]}):Ae(es,{sourced:w.conversions.data,error:w.conversions.error,isLoading:w.conversions.isLoading,what:"Conversions",collecting:k?.collecting,onRetry:w.refetch,children:B=>{let we=w.conversions.data?.status==="ok"?w.conversions.data:null;return Ae(Ll,{children:Ae(fo,{rows:B,primaryConversion:n,denominator:we?.denominator??0,windowPrecedesCollection:we?.window_precedes_collection??!1,coverageUnknown:we?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import*as Lu from"react";import{Phone as Iu,Mail as Bl,ShoppingBag as vb,ExternalLink as bb,MessageCircle as hb,Download as yb,Target as Ou}from"lucide-react";import*as bn from"react";import{Check as Ol,ChevronLeft as mb,Loader2 as Pu}from"lucide-react";import{jsx as gt,jsxs as da}from"react/jsx-runtime";var ku=90,Cu=100;function pb(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Tu(e){return!!e.label&&e.label!==e.target}function gb(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 qr(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Eu({current:e,onChange:t,onClose:a}){let{api:s}=H(),[n,r]=bn.useState(null),[i,l]=bn.useState(!1),[f,d]=bn.useState({at:"goals"}),[o,c]=bn.useState(null),[b,g]=bn.useState(null),[m,p]=bn.useState(!1),[u,v]=bn.useState(null),x=bn.useRef(0);bn.useEffect(()=>{let S=!0;return r(null),l(!1),d({at:"goals"}),c(null),g(null),p(!1),v(null),x.current+=1,s.getAnalyticsConversions(ku).then(N=>{if(S){if(N.status!=="ok"){l(!0);return}r(N.data)}}).catch(()=>{S&&l(!0)}),()=>{S=!1}},[s]);let R=S=>{d({at:"targets",row:S}),c(null),g(null),p(!1),v(null);let N=++x.current;s.getAnalyticsGoalTargets(S.goal,ku,Cu).then(C=>{if(N===x.current){if(C.status!=="ok"){g("failed");return}c(C.data),p(C.truncated===!0),v(C.coverage??null)}}).catch(C=>{if(N!==x.current)return;let w=C instanceof Yt?C.details?.code:void 0;g(w==="goal_has_no_targets"?"no-values":"failed")})},P=S=>{t(S),a()};if(i)return gt("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 da("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[gt(Pu,{className:"af-h-4 af-w-4 af-animate-spin"}),gt("span",{children:"Loading your conversions\u2026"})]});if(f.at==="targets"){let S=f.row,N=new Map;for(let C of o??[])N.set(C.label,(N.get(C.label)??0)+1);return da("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:[gt("header",{className:"af-flex af-items-center af-gap-1",children:da(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>d({at:"goals"}),children:[gt(mb,{className:"af-h-4 af-w-4"}),gt("span",{children:"All conversions"})]})}),da("button",{type:"button","aria-current":e&&qr(S,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:()=>P({goal:S.goal,implicit:S.implicit}),children:[e&&qr(S,e)&&!e.target&>(Ol,{className:"af-h-4 af-w-4 af-shrink-0"}),da("span",{children:["Any ",S.goal.toLowerCase()]})]}),b==="no-values"&>("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"&&da("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[gt("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),gt(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(S),children:"Try again"})]}),!o&&b===null&&da("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:[gt(Pu,{className:"af-h-4 af-w-4 af-animate-spin"}),gt("span",{children:"Loading\u2026"})]}),o&>("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:gb(o.length,u,m)}),m&&da("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Cu,". If what you want isn\u2019t here, pick the conversion itself instead."]}),o?.some(Tu)&>("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&&qr(S,e)&&e.target===C.target),k=N.get(C.label)>1;return Tu(C)?da("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:[da("span",{className:"af-min-w-0",children:[gt("span",{className:"af-block af-truncate",children:C.label}),k&>("span",{className:"af-block af-truncate af-text-xs",children:C.target})]}),gt("span",{className:"af-shrink-0 af-text-xs",children:C.visitors.toLocaleString()})]},C.target):da("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:()=>P({goal:S.goal,implicit:S.implicit,target:C.target,...C.label&&C.label!==C.target?{label:C.label}:{}}),children:[da("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[w&>(Ol,{className:"af-h-4 af-w-4 af-shrink-0"}),da("span",{className:"af-min-w-0",children:[gt("span",{className:"af-block af-truncate",children:C.label}),k&>("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:C.target})]})]}),gt("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:C.visitors.toLocaleString()})]},C.target)})]})}let h=e?.goal&&!n.some(S=>qr(S,e));return da("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&&da("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&>("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(S=>{let N=e?qr(S,e):!1;return da("div",{className:"af-flex af-items-center af-gap-1",children:[da("button",{type:"button","aria-current":N?"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:()=>P({goal:S.goal,implicit:S.implicit}),children:[da("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[N&>(Ol,{className:"af-h-4 af-w-4 af-shrink-0"}),gt("span",{className:"af-truncate",children:S.goal})]}),gt("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:S.visitors.toLocaleString()})]}),pb(S)&>(y,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${S.goal}`,onClick:()=>R(S),children:"Narrow"})]},S.goal)}),e?.goal&>("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:()=>P(null),children:"No main conversion"})]})}import{Fragment as Nb,jsx as Fs,jsxs as Au}from"react/jsx-runtime";function xb(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 wb(e){if(Fl(e,"whatsapp"))return!0;let t=xb(e);return t===null?!1:["wa.me","whatsapp.com"].some(a=>t===a||t.endsWith(`.${a}`))}function Fl(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var Du=[{goal:"Contact",target:e=>Fl(e,"tel"),icon:Iu,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Fl(e,"mailto"),icon:Bl,line:"This site is set up to get you emails."},{goal:"Contact",icon:Iu,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>wb(e),icon:hb,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:bb,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Bl,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Bl,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:vb,line:"This site is set up to sell."},{goal:"File Download",icon:yb,line:"This site is set up to get your file downloaded."}];function Bu(e){let{goal:t,target:a}=e;return e.implicit!==!0?null:(a?Du.find(n=>n.goal===t&&n.target?.(a)):void 0)??Du.find(n=>n.goal===t&&!n.target)??null}function Sb(e){return Bu(e)?.icon??Ou}function Fu({primaryConversion:e,onChange:t}){let[a,s]=Lu.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?Bu(e):null,i=e?.label?.trim(),l=e?Sb(e):Ou,f=e?.goal?i?`Your main conversion is ${i}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",d=Au(Nb,{children:[Fs(l,{className:"af-h-4 af-w-4 af-shrink-0"}),Fs("span",{children:f})]});return t?Au(vi,{open:a,onOpenChange:s,children:[Fs(bi,{asChild:!0,children:Fs("button",{type:"button",className:"af-flex af-items-center af-gap-2 af-rounded af-text-left af-text-sm af-text-muted-foreground hover:af-text-foreground focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:d})}),Fs(Nr,{align:"start",className:"af-w-80 af-p-1",children:a&&Fs(Eu,{current:e,onChange:t,onClose:()=>s(!1)})})]}):Fs("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:d})}import{Fragment as Rb,jsx as bs,jsxs as go}from"react/jsx-runtime";function Mu({refreshKey:e,onViewAll:t,primaryConversion:a}){let s=ur(7,{refreshKey:e,breakdowns:[]}),n=s.status.data??void 0,{nothingToReport:r,notCollecting:i,holdingForFirstData:l}=io(n);return oo({status:n,holdingForFirstData:l,refetchStatus:s.refetchStatus,refetch:s.refetch}),go("section",{className:"af-rounded-md af-border af-p-3",children:[go("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[bs("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&bs(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?bs("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."}):go(Rb,{children:[bs(es,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:s.refetch,children:f=>{let d=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return bs(po,{rows:f,window:d?.window??{from:"",to:""},metric:"visitors",timeZone:d?.timezone,height:140})}}),go("div",{className:"af-mt-3",children:[bs("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),bs(es,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:s.refetch,children:f=>{let d=s.conversions.data?.status==="ok"?s.conversions.data:null;return bs(fo,{rows:f,primaryConversion:a,denominator:d?.denominator??0,windowPrecedesCollection:d?.window_precedes_collection??!1,coverageUnknown:d?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as En,jsxs as jr}from"react/jsx-runtime";var Ml=5;function Ul({title:e,viewAllLabel:t,onViewAll:a}){return jr("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[En("h3",{className:"af-text-sm af-font-medium",children:e}),a&&En(y,{type:"button",variant:"ghost",size:"sm",onClick:a,children:t})]})}function _b({refreshKey:e,onBackToWebsite:t,primaryConversion:a,onChangePrimaryConversion:s,onOpenSurface:n,needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l}){let f=Xs({refreshKey:e}),d=(f.summary?.products.count??0)>0||(f.summary?.commerce?.storefront_orders??!1),o=d||(f.summary?.commerce?.invoicing??!1);return En(Ft,{title:"Dashboard",onBackToWebsite:t,children:jr("div",{className:"af-flex af-flex-col af-gap-4",children:[En(Fu,{primaryConversion:a,onChange:s}),En(Mu,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:a}),jr("section",{className:"af-rounded-md af-border af-p-3",children:[En(Ul,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),En(Mi,{refreshKey:e,maxRows:Ml,onViewAll:n&&(()=>n("leads"))})]}),d&&jr("section",{className:"af-rounded-md af-border af-p-3",children:[En(Ul,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),En(os,{refreshKey:e,maxRows:Ml,onViewAll:n&&(()=>n("orders"))})]}),o&&jr("section",{className:"af-rounded-md af-border af-p-3",children:[En(Ul,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),En(cs,{refreshKey:e,maxRows:Ml,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l})]})]})})}export{rr as AUDIENCE_PAGE_SIZE,Yt as AifeaturesApiError,Vu as AifeaturesProvider,fb as AnalyticsView,Ki as ContactImport,_i as CustomerDetail,Pi as CustomersList,to as DOUBLE_OPT_IN_HELP,_b as DashboardView,Qo as EMAIL_ORG_ACTIONS,Od as EMAIL_READINESS_TEXT,lu as EmailView,va as ExportCsvButton,ci as FormSettings,ri as FormSubmissions,cc as FormsDashboard,Yr as FormsList,al as IMPORT_ATTESTATION,Uo as InvoiceDetail,Rr as InvoiceLabelBadge,qi as InvoiceSettingsPanel,cs as InvoicesList,Ld as InvoicesView,Mi as LeadsView,Ls as MAX_ANALYTICS_FILTERS,Os as MAX_ANALYTICS_FILTER_VALUES,Dd as NotificationRecipientsSettings,wi as OrderDetail,Ss as OrderStatusBadge,os as OrdersList,zc as OrdersView,$c as PaymentsDashboard,Ks as PaymentsSetup,pi as ProductSettings,fi as ProductsList,Jc as ProductsView,Vs as PromosPanel,_l as REALTIME_FAILURES_BEFORE_ERROR,Rl as REALTIME_POLL_MS,$o as RetainerStatusBadge,Gs as RetainersPanel,Td as StoreSettings,ti as SubmissionDetail,ud as SubscriptionsView,mi as VariantsEditor,Ft as ViewShell,oi as WebhookDeliveries,li as WebhookSettings,Cg as buildEmailOrgRequest,Jn as chargedTotal,wo as createApiClient,sr as emailReadinessText,Y as formatPrice,kg as isEmailOrgAction,cn as isZeroDecimalCurrency,Et as toMajorUnits,ua as toMinorUnits,H as useAifeatures,H as useAifeaturesContext,ur as useAnalytics,ji as useAudience,cr as useBroadcasts,Xs as useBusinessSummary,si as useCsvExport,Ri as useCustomers,dr as useEmailDrafts,ii as useEventDestinations,Us as useForms,js as useInvoices,gi as useOrders,rs as usePaymentsStatus,Bi as usePeople,Fi as usePerson,Zs as useProducts,ro as useRealtimeVisitors,Ys as useRetainers,fs as useSiteSettings,Qr as useSubmissions,Ui 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 bv={...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:c,className:d}){let[o,u]=Us.useState(e),[b,v]=Us.useState(!1),m=p=>u(x=>({...x,...p})),g=Us.useRef(null);Us.useEffect(()=>g.current?.focus(),[]);let f=p=>{p&&!g.current&&(g.current=p)};return ka("form",{"data-testid":"section-editor",style:c,className:d,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(se,{ref:f,"aria-label":"Heading",value:o.text,maxLength:200,onChange:p=>m({text:p.target.value})}),o.type==="text"&&ka("textarea",{ref:f,"aria-label":"Text",className:"af-min-h-[120px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-font-mono af-text-sm",value:o.text,maxLength:5e3,onChange: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(se,{ref:f,"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(se,{"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:f,type:"button",variant:"outline",size:"sm",disabled:b,onClick:async()=>{v(!0);try{let p=await n();p&&u(x=>({...x,url:p.url,alt:p.alt??(x.type==="image"?x.alt:"")}))}finally{v(!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(se,{ref:f,"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(se,{"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(se,{ref:f,"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:bv[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 hv}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(te,{variant:"secondary",children:"Archived"}):e.locked?Ze(te,{variant:"secondary",children:"In use"}):null:Ze(te,{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(hv,{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(yv,{template:e,onOpenTemplate:a,onAskAssistant:n,reload:r}),Ze(xv,{templateId:e?.id??null,onOpenDraft:s,refreshKey:i})]})]})]})}function yv({template:e,onOpenTemplate:t,onAskAssistant:a,reload:s}){let{canWrite:n}=Ke(),r=vt(),[i,l]=mu.useState(null),c=e?.name??"Standard",d=async(f,p)=>{let x=await r.run(f,p);l(null),x.ok&&f==="deleteEmailTemplate"&&t(null),!x.ok&&Ga(x.error,"template_in_use")&&r.setError("Emails use this template now."),s()},o=async f=>{let p=await r.run("copyEmailTemplate",{templateId:f.id});p.ok&&(t(p.result.id),s())},u=f=>Ze(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:r.busy,onClick:()=>void o(f),children:"Make a copy"}),b=Ze(y,{type:"button",variant:"ghost",size:"sm",disabled:r.busy,onClick:()=>l("delete"),children:"Delete"}),v=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[f,p,x]=i==="delete"?["Delete this template?","Delete",()=>d("deleteEmailTemplate",{templateId:e.id})]:["Archive this template?","Archive",()=>d("archiveEmailTemplate",{templateId:e.id})];m=ha(_l,{children:[Ze("p",{className:"af-text-sm",children:f}),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 d("unarchiveEmailTemplate",{templateId:e.id}),children:"Unarchive"}),u(e)]}):e.locked?m=ha("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_archive&&v,u(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&&v]})]}):m=a&&Ze(y,{type:"button",size:"sm",onClick:()=>a(co.copyStandard),children:"Make a copy"});let g=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:c}),Ze(kl,{template:e})]}),g&&Ze("p",{className:"af-text-xs af-text-muted-foreground",children:g}),r.error&&Ze(ue,{tone:"error",children:r.error}),m]})}function xv({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(u=>(u.template?.id??null)===e)??null,l=r.data??[],c=oo(n.data??[],l),d=new Set(l.flatMap(u=>u.draft_id&&u.status==="scheduled"?[u.draft_id]:[])),o=u=>c.has(u)?"Sent":d.has(u)?"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(u=>{let b=o(u.id),v=ha(_l,{children:[Ze("span",{className:"af-block af-truncate af-text-sm",children:u.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:v}):Ze("button",{type:"button",onClick:()=>t(u.id),className:"af-w-full af-rounded-md af-px-2 af-py-1 af-text-left hover:af-bg-muted",children:v})},u.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(),c=e.template?.id??Jn,d=c===Jn,o=(i.data??[]).filter(g=>g.status==="active"),u=o.find(g=>g.id===c),b=d?"Standard":e.template?.name??u?.name??"",v=d?"builtin":u?.updated_at??"current",m=async g=>{if(g===c)return;let f=await l.run("setDraftTemplate",{draftId:e.id,template_id:g===Jn?null:g,expected_version:e.version});f.ok?await a():Ga(f.error,"template_missing_cart")?l.setError("This email shows the shopper's cart, and that template has no cart section. Pick another template, or keep this one."):Ga(f.error,"version_conflict")?(l.setError("This email changed meanwhile. We've loaded the latest version; switch again if you still want to."),await a()):Ga(f.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:c,version:v,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:c,disabled:t||l.busy,onChange:g=>void m(g.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(g=>Vs("option",{value:g.id,children:g.name},g.id)),!d&&!u&&Vs("option",{value:c,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(ua,{onClick:s,children:"Back to the automation"})})]})}import{Fragment as Cl,jsx as qe,jsxs as Xt}from"react/jsx-runtime";var wv={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"},Sv=320,Nv=600,Rv=e=>({top:Math.max(0,e.y-24),left:e.x});function _v(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:c}=H(),{siteId:d,canWrite:o,refreshKey:u,openSettings:b}=Ke(),v=o&&!r,m=We.useRef(v);m.current=v;let[g,f]=We.useState(null),[p,x]=We.useState(null),[S,k]=We.useState(null),[h,N]=We.useState(null),[R,P]=We.useState(null),[w,C]=We.useState(null),[E,_]=We.useState(null),[j,q]=We.useState(null),[U,ae]=We.useState(null),[ce,fe]=We.useState({}),[T,V]=We.useState(qr.initial),[A,ne]=We.useState(!1),ie=vt(),Fe=vt(),Se=We.useRef(null),Ae=We.useRef(null),Ye=We.useRef(0),Re=We.useRef(!1),Xe=We.useRef(!1),I=We.useCallback(ye=>{Re.current=ye!==null,C(ye)},[]);su(w!==null);let M=We.useRef(g);M.current=g;let B=We.useRef(0),ee=We.useCallback(async(ye={})=>{let Rt=++B.current,$=m.current,Pe=()=>$?c.previewEmailDraft(d,e,{editable:!0}):c.previewEmailDraft(d,e),[zt,Rn]=await Promise.allSettled([c.getEmailDraft(d,e),Pe()]),X=Rn,oa=()=>zt.status==="fulfilled"&&X.status==="fulfilled"&&X.value.version!==zt.value.version;if(oa()&&Rt===B.current&&([X]=await Promise.allSettled([Pe()])),Rt===B.current){if(ye.background&&Re.current){Xe.current=!0;return}if(N(null),k(null),zt.status==="rejected"){N(hr(zt.reason));return}f(zt.value),X.status==="fulfilled"?x({...X.value,editable:$&&!oa()}):(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}))}},[c,d,e]);We.useEffect(()=>{f(null),x(null),ee()},[ee]);let J=We.useRef(v);We.useEffect(()=>{J.current!==v&&(J.current=v,v||I(null),ee())},[v,ee,I]);let pe=We.useRef(u);We.useEffect(()=>{if(u!==pe.current){if(pe.current=u,Re.current){Xe.current=!0;return}ee({background:!0})}},[u,ee]);let Ue=()=>{I(null),ie.setError(null),Xe.current&&(Xe.current=!1,ee())},ft=async(ye,Rt,$)=>{let Pe=await ie.run("updateDraft",{draftId:e,expected_version:ye.version,...Rt});Pe.ok?(_(null),Ae.current=null,Xe.current=!1,I(null),await ee(),n?.()):Ga(Pe.error,"version_conflict")&&(ie.setError(null),_($),Xe.current=!1,I(null),await ee())},Qe=We.useRef({frame:null,html:null,count:0}),[Et,be]=We.useState(null),Me=(ye,Rt)=>{let $=Qe.current;$.frame!==ye.currentTarget||$.html!==Rt?Qe.current={frame:ye.currentTarget,html:Rt,count:1}:++$.count>1&&be(Rt)},yt=p!==null&&Et===p.html,It=v&&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":ae(Pe.section===null?null:{section:Pe.section,rect:Pe.rect});return;case"focus":Ae.current=Pe.section;return;case"open":if(Ae.current=Pe.section,Re.current)return;q(null),ne(!1),I({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]));fe(Rn=>_v(Rn,zt)?Rn:zt)}return;case"template":Re.current||q(Pe.region);return}};return window.addEventListener("message",ye),()=>window.removeEventListener("message",ye)},[It,I]),h)return Xt(ue,{tone:"error",children:["Couldn't load this email. ",h]});if(!g)return qe(G,{className:"af-h-40 af-w-full"});let Mt={width:Se.current?.clientWidth||Nv,height:It?T:qr.initial},et=w?.kind==="section"?w:null,ea=(()=>{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=ea?Sl(ea,Mt):null,wt=s??g.kind==="recovery",Ja=g.template?.name??"Standard",Mn=et&&qe(fu,{block:et.block,isNew:et.isNew,busy:ie.busy,error:ie.error,onPickImage:l,onCancel:Ue,onRemove:()=>{let{base:ye}=et;ft(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);ft(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,Sv),Mt.width)}:void 0},et.key);return Xt("div",{className:"af-grid af-gap-4 lg:af-grid-cols-[minmax(0,1fr)_300px]",children:[Xt("div",{className:"af-min-w-0 af-space-y-3",children:[w?.kind==="subject"?qe(kv,{draft:w.base,busy:ie.busy,error:ie.error,onCancel:Ue,onDone:ye=>void ft(w.base,{...ye,blocks:w.base.blocks},[ye.subject,ye.preheader??""].join(`
|
|
8
|
+
`))}):It?qe("button",{type:"button","data-testid":"subject-line",onClick:()=>{Re.current||(q(null),I({kind:"subject",base:g}))},className:"af-block af-w-full af-rounded-md af-border af-border-dashed af-px-3 af-py-2 af-text-left hover:af-border-primary",children:qe(yu,{draft:g})}):qe("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:qe(yu,{draft:g})}),r&&Xt(ue,{tone:"info",children:[Xt("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})]}),E!==null&&Xt(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:E,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"})]}),j&&qe("div",{"data-testid":"template-hint",children:qe(ue,{children:j==="header"?Xt(Cl,{children:['The header is part of the "',Ja,'" template. Switch templates on the right.']}):Xt(Cl,{children:["Every email ends with this footer. Your business name and address come from"," ",qe(ua,{onClick:()=>b("sender"),children:"Settings"}),"."]})})}),yt&&v&&qe(ue,{tone:"warning",children:"This template tried to open another page in the preview, so the preview can't be edited here."}),p?Xt("div",{className:"af-relative",children:[qe("iframe",{ref:Se,title:"Email preview",sandbox:It?"allow-scripts":"",srcDoc:p.html,onLoad:It?ye=>Me(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:Rv(Sl(U.rect,Mt)),children:wv[g.blocks[U.section]?.type??"text"]}),Je&&Mn]}):S?Xt(ue,{tone:"warning",children:[S.text,qe(br,{reason:S.code})]}):qe(G,{className:"af-h-40 af-w-full"}),!Je&&Mn,It&&!w&&Xt("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=Ae.current!==null?Ae.current+1:g.blocks.length;ne(!1),q(null),I({kind:"section",base:g,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."})]}),Xt("div",{className:"af-space-y-3",children:[Xt("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||Fe.busy,onClick:async()=>{P(null);let ye=await Fe.run("testSendDraft",{draftId:e});ye.ok&&P(ye.result?.sent_to??"your email")},children:"Send a test to me"}),R&&Xt(ue,{tone:"success",children:["Test sent to ",R,"."]}),Fe.error&&qe(ue,{tone:"error",children:Fe.error}),p&&!r&&t?.({draft:g,preview:p,reload:()=>ee()}),a&&qe(hu,{...a})]}),qe(vu,{draft:g,disabled:!v||w!==null,onChanged:async()=>{await ee(),n?.()}}),i&&o&&qe(y,{type:"button",variant:"outline",className:"af-w-full",onClick:()=>i(`Update the "${g.subject}" email to `),children:"\u2728 Change this email with the editor"})]})]})}function yu({draft:e}){return Xt(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&&Xt("span",{className:"af-text-sm af-text-muted-foreground",children:[" \u2014 ",e.preheader]})]})}function kv({draft:e,busy:t,error:a,onDone:s,onCancel:n}){let[r,i]=We.useState(e.subject),[l,c]=We.useState(e.preheader??"");return Xt("form",{className:"af-space-y-2 af-rounded-md af-border af-p-3",onSubmit:d=>{d.preventDefault(),s({subject:r,preheader:l.trim()||null})},children:[Xt("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Subject",qe(se,{"aria-label":"Subject",value:r,maxLength:200,autoFocus:!0,onChange:d=>i(d.target.value)})]}),Xt("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(se,{"aria-label":"Preview text",value:l,maxLength:200,onChange:d=>c(d.target.value)})]}),a&&qe(ue,{tone:"error",children:a}),Xt("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 _e,jsxs as Bt}from"react/jsx-runtime";var Cv={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,c]=Nt.useState(0),d=l+i,o=xr({siteId:n,kind:"broadcast",refreshKey:d}),u=yr({siteId:n,refreshKey:d}),b=vt(),v=vt(),m=oo(o.data??[],u.data??[]),g=o.data?.filter(f=>!m.has(f.id))??null;if(e){let f=u.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:[_e(Pv,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),!u.data&&!u.error||!o.data&&!o.error?_e(G,{className:"af-h-40 af-w-full"}):m.has(e)?_e(ue,{children:"This email has been sent, so it can't change. Duplicate it from the list to send it again."}):_e(po,{draftId:e,onSaved:()=>c(p=>p+1),renderCommit:p=>_e(Av,{...p,onCommitted:()=>c(x=>x+1)}),scheduled:f?{sendsAt:f.scheduled_at,busy:b.busy,error:b.error,onUnschedule:async()=>{(await b.run("cancelBroadcast",{sendId:f.id})).ok&&c(x=>x+1)}}:void 0,onAskAssistant:a,onPickImage:s})]})}return Bt("div",{children:[_e(_a,{children:"Drafts"}),o.error?_e(xt,{message:"Couldn't load drafts.",onRetry:()=>void o.refetch()}):g?g.length===0?_e(la,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):_e("ul",{"data-testid":"drafts",className:"af-divide-y af-rounded-md af-border",children:g.map(f=>Bt("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[_e("span",{className:"af-truncate af-text-sm",children:f.subject||"(no subject)"}),_e(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(f.id),children:"Review"})]},f.id))}):_e(G,{className:"af-h-10 af-w-full"}),_e(_a,{children:"Sent and scheduled"}),b.error&&_e(ue,{tone:"error",children:b.error}),v.error&&_e(ue,{tone:"error",children:v.error}),u.error?_e(xt,{message:"Couldn't load broadcasts.",onRetry:()=>void u.refetch()}):u.data?u.data.length===0?_e(la,{children:"Nothing sent yet."}):_e("ul",{className:"af-divide-y af-rounded-md af-border",children:u.data.map(f=>_e(Tv,{broadcast:f,canCancel:r&&(f.status==="scheduled"||f.status==="unscheduled"||f.status==="sending"),busy:b.busy||v.busy,onCancel:async()=>{(await b.run("cancelBroadcast",{sendId:f.id})).ok&&c(x=>x+1)},onDuplicate:r&&f.draft_id&&hl(f)?async()=>{let p=await v.run("duplicateDraft",{draftId:f.draft_id});p.ok&&(c(x=>x+1),t(p.result.id))}:void 0},f.id))}):_e(G,{className:"af-h-10 af-w-full"})]})}function Tv({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:[_e("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:[_e(te,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Cv[e.status]}),t&&_e(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:s,children:"Cancel"}),n&&_e(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 `:"",Ie(e.recipients.planned)," recipients \xB7 ",Ie(e.stats.delivered)," delivered \xB7 ",Ie(e.stats.opened)," opened \xB7"," ",Ie(e.stats.clicked)," clicked \xB7 ",Ie(e.stats.bounced)," bounced \xB7 ",Ie(e.stats.complained)," complaints \xB7"," ",Ie(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&_e("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?Ev(a):"",suggested:t!==null||a!==null,timePassed:a!==null&&!s}}function Ev(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 Iv=(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 Av({draft:e,preview:t,reload:a,onCommitted:s}){let{api:n}=H(),{siteId:r,canWrite:i,settings:l,refreshKey:c}=Ke(),[d,o]=Nt.useState(null),[u,b]=Nt.useState(!1),[v,m]=Nt.useState(null),[g,f]=Nt.useState(()=>xu(e)),[p,x]=Nt.useState(g.tagIds),[S,k]=Nt.useState(g.match),[h,N]=Nt.useState(g.scheduleAt),[R,P]=Nt.useState(0),w=!Iv({tagIds:p,match:S,scheduleAt:h},g),C=Su(e);Nt.useEffect(()=>{if(C===g.key||e.id===g.draftId&&w)return;let J=xu(e);f(J),x(J.tagIds),k(J.match),N(J.scheduleAt),P(0)},[C,e,g,w]);let E=Nt.useMemo(()=>d?new Set(d.map(J=>J.id)):null,[d]),_=E!==null&&p.every(J=>E.has(J));Nt.useEffect(()=>{if(!E||p.every(pe=>E.has(pe)))return;let J=pe=>pe.filter(Ue=>E.has(Ue));P(pe=>pe+p.length-J(p).length),x(J(p)),f(pe=>({...pe,tagIds:J(pe.tagIds)}))},[E,p]);let[j,q]=Nt.useState(null),[U,ae]=Nt.useState(null),[ce,fe]=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,c]);let V=h?new Date(h).toISOString():null,A=JSON.stringify([p,S,V]),ne=j?.plan??null,ie=j!==null&&j.key===A,Fe=Nt.useRef(0),Se=Nt.useCallback(async()=>{let J=++Fe.current;ae(null);try{let pe=await n.estimateBroadcast(r,{targeting:{tag_ids:p,match:S},scheduled_at:V});J===Fe.current&&q({key:A,plan:pe})}catch(pe){if(J!==Fe.current)return;q(null),ae(hr(pe))}},[n,r,p,S,V,A,c]),Ae=Nt.useRef(!1);Nt.useEffect(()=>{if(!_&&p.length>0)return;if(!Ae.current){Ae.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,Re=ne!==null&&!ne.fits,Xe=v?Math.max(0,v.by_status.subscribed-v.mailable):null,I=v&&ne&&Xe!==null?Math.max(0,v.total-ne.recipients-Xe):null,M=!i||T.busy||!ne||!ie||Re||ne.recipients===0||Ye!==null||u&&p.length>0,B=async()=>{fe(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){fe({tone:"success",text:V?"Scheduled.":"Sending now."}),s();return}Ga(J.error,"version_conflict")?(T.setError(null),await a(),fe({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()},ee=J=>x(pe=>pe.includes(J)?pe.filter(Ue=>Ue!==J):[...pe,J]);return Bt("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[g.suggested&&!w&&_e(ue,{children:"Suggested by your assistant \u2014 review before sending."}),_e(_a,{children:"Who gets it"}),u&&_e(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&&_e(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."}),d&&d.length>0?Bt("div",{className:"af-space-y-2",children:[_e("div",{className:"af-flex af-flex-wrap af-gap-2",children:d.map(J=>Bt("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[_e("input",{type:"checkbox",checked:p.includes(J.id),onChange:()=>ee(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:[_e("option",{value:"any",children:"any of these tags"}),_e("option",{value:"all",children:"all of these tags"})]})]}),p.length===0&&_e("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):_e("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:[_e("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),_e(se,{"aria-label":"Schedule time",type:"datetime-local",value:h,onChange:J=>N(J.target.value)})]}),g.timePassed&&!h&&_e(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:[_e(Tl,{label:"Will receive it",value:ne.recipients}),_e(Tl,{label:"Suppressed (bounced or complained)",value:Xe}),_e(Tl,{label:"Not included",value:I})]}),Bt("p",{className:"af-text-muted-foreground",children:[Ie(ne.allowance.remaining)," of ",Ie(ne.allowance.monthly)," emails left this month."]}),ne.sample_size!==null&&Bt(ue,{children:["We'll send to ",Ie(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=>`${Ie(J.recipients)} on ${J.date}`).join(", "),"."]})]}):_e(G,{className:"af-h-12 af-w-full"}),Re&&ne&&Bt(ue,{tone:"warning",children:["This send needs ",Ie(ne.recipients)," emails, but only ",Ie(ne.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),Ye&&Bt(ue,{tone:"warning",children:[Ye,_e(br,{reason:l?.readiness.reason})]}),ce&&_e(ue,{tone:ce.tone,children:ce.text}),T.error&&_e(ue,{tone:"error",children:T.error}),_e(y,{type:"button",disabled:M,onClick:()=>void B(),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:[_e("div",{className:"af-text-xs af-text-muted-foreground",children:e}),_e("div",{className:"af-font-semibold",children:t===null?"\u2014":Ie(t)})]})}import*as cn from"react";import{Check as ku,FileText as Kv,ShieldCheck as Zv}from"lucide-react";import*as Hs from"react";import{ArrowRight as Dv,Check as Nu,ChevronDown as Ov,Globe as Lv,Lock as Bv,Mail as vo,PenLine as Fv,Sparkles as Mv}from"lucide-react";import{Fragment as go,jsx as Y,jsxs as he}from"react/jsx-runtime";var $v=[{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."}],Uv="hello";function Il(e){return`${Uv}@${e}`}function Ru({onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,onTurnOn:s,siteDomain:n,businessName:r}){let{api:i}=H(),{siteId:l,settings:c,canWrite:d,refreshKey:o,refetchSettings:u}=Ke(),b=Lt(()=>i.getMarketingContactStats(l),`${l}|${o}`,l),[v,m]=Hs.useState(!1),[g,f]=Hs.useState(null);if(!c)return null;let p=b.data?.by_status.subscribed??0,x={siteDomain:n,businessName:r};return Vv(c)?Y(Al,{settings:c,site:x,waiting:p,children:d?s&&he("div",{className:"af-space-y-2",children:[he(y,{disabled:v,onClick:async()=>{m(!0),f(null);try{await s(),await u()}catch(S){f(S instanceof Error?S.message:"Couldn't turn on email. Try again.")}finally{m(!1)}},children:["Get started ",Y(Dv,{className:"af-ml-2 af-h-4 af-w-4","aria-hidden":!0})]}),g&&Y(ue,{tone:"error",children:g})]}):Y("p",{className:"af-text-sm af-text-muted-foreground",children:"Only the site owner can set up email."})}):Y(Hv,{settings:c,site:x,waiting:p,onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a})}function Vv(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:$v.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:[Ie(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(Bv,{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 Hv({settings:e,site:t,waiting:a,onStartDomainSetup:s,onConnectDomain:n,onAskAssistant:r}){let{refetchSettings:i,canWrite:l}=Ke(),[c,d]=Hs.useState(null),o=g=>d(f=>f===g?null:g),{siteDomain:u}=t,b=Wr(e),v=u===null&&!e.domain.sending_domain,m=!!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 ",u??"your own domain","."]})]}),a>0&&he("div",{className:"af-text-right",children:[Y("div",{className:"af-text-2xl af-font-semibold",children:Ie(a)}),he("div",{className:"af-text-xs af-text-muted-foreground",children:[a===1?"subscriber":"subscribers"," waiting"]})]})]}),!l&&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:u??"Your domain",sub:"One domain for your website and your email.",children:[u&&Y(Bn,{icon:Lv,label:"Website",value:u,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&&l?{label:"Connect domain",onClick:n}:void 0}):he(Bn,{icon:vo,label:"Email sending",value:e.domain.sending_domain??(u?`news.${u}`:"news.yourdomain.com"),status:Dl(e),action:!b&&l?{label:e.domain.sending_domain?"Details":"Set up",onClick:()=>o("sending")}:void 0,expanded:c==="sending",children:[!e.domain.sending_domain&&Y("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:"Emails go out from a subdomain of your site's domain, so they reach inboxes and are clearly from you. If we manage your domain's DNS we add the records; otherwise you'll get a few to copy into your DNS provider."}),Y(Ol,{settings:e,canWrite:l,onStartDomainSetup:s,onChanged:i})]})]}),Y(El,{title:"Sender",sub:"Who your emails are from. The mailing address is legally required in every email.",children:Y(Bn,{icon:Fv,label:m?e.business_name??"Sender":"Not set",value:e.postal_address??"Name, mailing address and reply-to",status:m?Y(Ln,{tone:"green",children:"Done"}):Y(Ln,{tone:"gray",children:"Needed"}),action:l?{label:m?"Edit":"Add",onClick:()=>o("sender")}:void 0,expanded:c==="sender",children:Y(zv,{settings:e,businessName:t.businessName,onSaved:async()=>{await i(),d(null)}})})}),Y(El,{title:"How people join your list",sub:"Only people who asked to hear from you get your emails.",children:Y(Gv,{onAskAssistant:l?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:c,expanded:d=!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,c&&he(y,{size:"sm",variant:d?"secondary":"outline","aria-expanded":o?d:void 0,onClick:c.onClick,children:[c.label,o&&Y(Ov,{className:W("af-ml-1 af-h-3.5 af-w-3.5 af-transition-transform",d&&"af-rotate-180"),"aria-hidden":!0})]})]}),d&&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 zv({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??""),[c,d]=Hs.useState(e.reply_to??""),o=vt();return he("form",{className:"af-space-y-3",onSubmit:async u=>{u.preventDefault(),(await o.run("updateSettings",{business_name:n.trim()||null,postal_address:i.trim()||null,reply_to:c.trim()||null,double_opt_in:e.double_opt_in})).ok&&await a()},children:[Y(jv,{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(se,{"aria-label":"Business name",value:n,disabled:!s,onChange:u=>r(u.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:u=>l(u.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(se,{"aria-label":"Reply-to email",type:"email",value:c,disabled:!s,onChange:u=>d(u.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 jv({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 qv={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"),c={backgroundColor:e?.brand.color??"hsl(var(--primary))"},d=r!==void 0?r.trim()||null:e?.postal_address,o=(u,b,v)=>s?he("div",{"data-preview-region":u,"data-highlighted":n===u,className:W("af-relative af-rounded-md af-pl-7 af-transition-shadow",n===u&&"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:u}),he("span",{className:"af-sr-only",children:[u,". ",qv[u],":"]})]}),v]}):Y("div",{className:b,children:v});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:c,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:d??Y("span",{className:"af-italic af-text-amber-700",children:"Mailing address goes here"})}),Y("div",{className:"af-underline",children:"Unsubscribe"})]}))]})}var Wv="Add a newsletter signup to my footer";function Gv({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(Wv),children:[Y(Mv,{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 nb,jsx as ve,jsxs as fa}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}){let{settings:a,refetchSettings:s,canWrite:n,settingsSection:r,onOpenBrandSettings:i}=Ke(),[l,c]=cn.useState(null),[d,o]=cn.useState(null),[u,b]=cn.useState(""),v=a!==null;if(cn.useEffect(()=>{v&&r&&document.getElementById(Hr(r))?.scrollIntoView?.({block:"start"})},[v,r]),!a)return ve(G,{className:"af-h-40 af-w-full"});let m=N=>o(R=>R===N?null:N),g=()=>o(null),f=async()=>{await s(),g()},p=(N,R,P)=>({id:P,"data-settings-row":N,onMouseEnter:()=>c(R),onMouseLeave:()=>c(null),onFocus:()=>c(R),onBlur:()=>c(null)}),x=Wr(a),{sending_domain:S,status:k}=a.domain,h=N=>n?{expanded:d===N}:{};return ve("div",{className:"af-@container",children:fa("div",{className:"af-grid af-items-start af-gap-6 @2xl:af-grid-cols-[minmax(0,17rem)_minmax(0,1fr)]",children:[fa("aside",{className:"af-space-y-3 af-pl-3",children:[ve("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails look like this"}),ve(bo,{settings:a,site:{},numbered:!0,highlight:l,postalAddress:d==="address"?u:void 0}),ve(tb,{settings:a})]}),fa("div",{children:[ve(_a,{children:"From"}),fa("div",{className:"af-space-y-2",children:[ve("div",{...p("Sending domain",1,Hr("domain")),children:ve(Bn,{markerSpace:!0,label:"Sending from",value:S?Il(S):"No sending domain yet",status:Dl(a),action:!x&&n?{label:S?k==="verified"||k==="failed"?"Fix":"Details":"Set up",onClick:()=>m("domain")}:void 0,...h("domain"),children:ve(Ol,{settings:a,canWrite:n,onStartDomainSetup:e,onChanged:s})})}),ve("div",{...p("Sender name and replies",1),children:ve(Bn,{marker:1,label:"Sender name and replies",mono:!1,value:`${a.business_name??"No sender name"} \xB7 replies to ${a.reply_to??"your account email"}`,action:n?{label:"Edit",onClick:()=>m("sender")}:void 0,...h("sender"),children:ve(Jv,{settings:a,onSaved:f,onCancel:g})})})]}),ve(_a,{children:"Brand"}),ve("div",{...p("Logo",2),children:ve(Bn,{marker:2,label:"Logo",mono:!1,value:a.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:i?{label:"Brand settings",onClick:i}:void 0})}),ve(_a,{children:"Footer"}),ve("div",{...p("Mailing address",3,Hr("sender")),children:ve(Bn,{marker:3,label:"Mailing address",mono:!1,value:a.postal_address??"Not set",hint:"Anti-spam law requires it at the bottom of every email. A PO box works.",status:a.postal_address?void 0:ve(Ln,{tone:"amber",children:"Needed"}),action:n?{label:a.postal_address?"Edit":"Add",onClick:()=>{b(a.postal_address??""),m("address")}}:void 0,...h("address"),children:ve(Xv,{settings:a,draft:u,onDraft:b,onSaved:f,onCancel:g})})}),fa("div",{id:Hr("signups"),children:[ve(_a,{children:"Who gets it"}),fa("div",{className:"af-space-y-2",children:[ve("div",{...p("Double opt-in",null),children:ve(Qv,{settings:a,canWrite:n,onSaved:s})}),ve(ab,{onAskAssistant:n?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 Cu({busy:e,error:t,canSave:a=!0,onSave:s,onCancel:n,children:r}){return fa("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),await s()},children:[r,t&&ve(ue,{tone:"error",children:t}),fa("div",{className:"af-flex af-gap-2",children:[ve(y,{type:"submit",size:"sm",disabled:e||!a,children:"Save"}),ve(y,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Cancel"})]})]})}function Jv({settings:e,onSaved:t,onCancel:a}){let[s,n]=cn.useState(e.business_name??""),[r,i]=cn.useState(e.reply_to??""),l=vt();return fa(Cu,{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:[ve(Pu,{label:"Sender name",children:ve(se,{"aria-label":"Business name",value:s,onChange:c=>n(c.target.value)})}),ve(Pu,{label:"Replies go to (your account email or an address on your domain)",children:ve(se,{"aria-label":"Reply-to email",type:"email",value:r,onChange:c=>i(c.target.value)})})]})}function Xv({settings:e,draft:t,onDraft:a,onSaved:s,onCancel:n}){let r=vt();return ve(Cu,{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:ve("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]=cn.useState(null),[r,i]=cn.useState(!1),l=vt(),c=s??e.double_opt_in;return fa("div",{className:"af-space-y-2",children:[ve(Bn,{icon:Zv,label:"Double opt-in",mono:!1,value:c?"New subscribers confirm by email first":"New subscribers join straight away",status:fa("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[ve("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:"?"}),ve("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}),ve("input",{"aria-label":"Double opt-in",type:"checkbox",role:"switch",checked:c,disabled:!t||l.busy,onChange:async d=>{let o=d.target.checked;n(o),(await l.run("updateSettings",$l(e,{double_opt_in:o}))).ok&&await a(),n(null)}})]})}),l.error&&ve(ue,{tone:"error",children:l.error})]})}function Ol({settings:e,canWrite:t,onStartDomainSetup:a,onChanged:s}){let[n,r]=cn.useState(null),[i,l]=cn.useState(!1),[c,d]=cn.useState(null),o=Wr(e);return fa("div",{children:[ve("p",{className:"af-text-sm",children:Yv(e)}),!o&&a&&ve(y,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||i,onClick:async()=>{l(!0),d(null);try{r(await a()),await s()}catch(u){d(u instanceof Error?u.message:"Couldn't start domain setup.")}finally{l(!1)}},children:e.domain.sending_domain?"Check domain setup":"Set up sending domain"}),c&&ve(ue,{tone:"error",className:"af-mt-2",children:c}),n?.records&&n.records.length>0&&fa("div",{className:"af-mt-3 af-space-y-1",children:[ve("p",{className:"af-text-sm",children:"Add these records at your domain provider:"}),fa("table",{className:"af-w-full af-text-left af-text-xs",children:[ve("thead",{children:fa("tr",{children:[ve("th",{className:"af-py-1 af-pr-2",children:"Type"}),ve("th",{className:"af-py-1 af-pr-2",children:"Name"}),ve("th",{className:"af-py-1 af-pr-2",children:"Value"}),ve("th",{className:"af-py-1",children:"Priority"})]})}),ve("tbody",{children:n.records.map((u,b)=>fa("tr",{className:"af-border-t af-align-top",children:[ve("td",{className:"af-py-1 af-pr-2",children:u.type}),ve("td",{className:"af-break-all af-py-1 af-pr-2",children:u.name}),ve("td",{className:"af-break-all af-py-1 af-pr-2",children:u.value}),ve("td",{className:"af-py-1",children:u.priority??""})]},b))})]})]}),n&&ve(eb,{result:n})]})}function eb({result:e}){return e.status==="no_domain"?ve(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"?ve(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:ve("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 tb({settings:e}){let{monthly:t,sent:a,reserved:s}=e.allowance,n=a+s;return fa("p",{className:"af-text-xs af-text-muted-foreground",children:[Ie(n)," of ",Ie(t)," emails used this month (",Ie(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 ab({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:Kv,action:a.length===0&&e?{label:"Add the checkbox",onClick:()=>e(Fl(n))}:void 0}];return ve(nb,{children:r.filter(i=>i.forms.length>0).map(i=>ve("div",{"data-form-group":i.id,children:ve(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 fa("label",{className:"af-block af-space-y-1",children:[ve("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 Eu({templateId:e,onOpenTemplate:t,onOpenDraft:a,onAskAssistant:s}){let{api:n}=H(),{siteId:r,canWrite:i,refreshKey:l}=Ke(),[c,d]=yo.useState(0),o=c+l,u=Lt(()=>n.getEmailTemplates(r),`${r}|${o}`,r),b=yo.useCallback(()=>d(f=>f+1),[]),v=i?s:void 0;if(e){let f=e===Jn?null:u.data?.find(p=>p.id===e);if(f!==void 0)return ma(gu,{template:f,onBack:()=>t(null),onOpenTemplate:t,onOpenDraft:a,onAskAssistant:v,reload:b,refreshKey:o},e);if(u.isLoading)return ma(G,{className:"af-h-96 af-w-full"})}let m=u.data?.filter(f=>f.status!=="archived")??[],g=u.data?.filter(f=>f.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"}),v&&ma(y,{type:"button",variant:"outline",size:"sm",onClick:()=>v(co.create),children:"\u2728 New template with the editor"})]}),zs(Tu,{children:[ma(Ul,{template:null,onOpen:()=>t(Jn)}),m.map(f=>ma(Ul,{template:f,onOpen:()=>t(f.id)},f.id))]}),u.error&&!u.data?ma("div",{className:"af-mt-3",children:ma(xt,{message:"Couldn't load your templates.",onRetry:()=>void u.refetch()})}):!u.data&&ma(G,{className:"af-mt-3 af-h-10 af-w-full"}),g.length>0&&zs("div",{"data-testid":"archived-templates",children:[ma(_a,{children:"Archived"}),ma(Tu,{children:g.map(f=>ma(Ul,{template:f,onOpen:()=>t(f.id)},f.id))})]})]})}function Tu({children:e}){return ma("ul",{className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:e})}function sb(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&&sb(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 Ka from"react";import{ArrowDown as rb,ArrowUp as ib,Clock as Du,Mail as Ou,Plus as ob,Trash2 as lb,Zap as cb}from"lucide-react";import{Fragment as zl,jsx as ke,jsxs as Ht}from"react/jsx-runtime";var db=365*24,ub=[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,Iu=64,fb=24,Gr={trigger:72,send:104,wait:64,waitEditing:196,exit:44};function mb(e,t){let a=[],s=0,n=r=>{a.push({...r,y:s}),s+=r.height+Iu};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-Iu}}var Lu=Ka.createContext(null);function Yr(){let e=Ka.useContext(Lu);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 Bu(e){let{automation:t,onChangeSteps:a}=e,s=t.steps,[n,r]=Ka.useState(null),[i,l]=Ka.useState(null),[c,d]=Ka.useState(null),o=(m,g)=>{d(null),r(null),l(null),a(m,g)},u=wo(s),b={...e,insertAt:n,setInsertAt:m=>{d(null),r(m)},editingWait:i,setEditingWait:l,insertWait:m=>{if(!u.slice(m).some(g=>g.type==="send")){r(null),d("A wait after the last email does nothing, so it wasn't added.");return}o([...u.slice(0,m),{type:"wait",wait_hours:24},...u.slice(m)],"Add a 1 day wait")},setWait:(m,g)=>o(u.map((f,p)=>p===m?{type:"wait",wait_hours:g}:f),`Change ${Vl(s,m)} to ${_s(g)}`),move:(m,g)=>{let f=[...u];[f[m],f[m+g]]=[f[m+g],f[m]],o(f,`Move ${Vl(s,m)} ${g<0?"up":"down"}`)},remove:m=>o(u.filter((g,f)=>f!==m),`Remove ${Vl(s,m)}`)},v=mb(s,i);return Ht(Lu.Provider,{value:b,children:[c&&ke(ue,{className:"af-mb-2",children:c}),ke("div",{"data-testid":"automation-canvas",className:"af-rounded-md af-border af-bg-muted/40",style:{height:v.height+2*fb},children:ke(Ka.Suspense,{fallback:ke(G,{className:"af-h-full af-w-full"}),children:ke(pb,{layout:v,steps:s})})})]})}var pb=Ka.lazy(async()=>({default:gb(await import("@xyflow/react"))}));function gb(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:[ke(e.Handle,{type:"target",position:e.Position.Top,isConnectable:!1,className:"!af-opacity-0"}),ke(e.Handle,{type:"source",position:e.Position.Bottom,isConnectable:!1,className:"!af-opacity-0"})]}),s=l=>Ht(zl,{children:[l,ke(a,{})]}),n={trigger:()=>s(ke(Au,{kind:"trigger"})),send:({data:l})=>s(ke(vb,{index:l.index,step:l.step})),wait:({data:l})=>s(ke(bb,{index:l.index,step:l.step})),exit:()=>s(ke(Au,{kind:"exit"}))};function r({id:l,sourceX:c,sourceY:d,targetX:o,targetY:u,data:b}){let[v,m,g]=e.getStraightPath({sourceX:c,sourceY:d,targetX:o,targetY:u});return Ht(zl,{children:[ke(e.BaseEdge,{id:l,path:v}),ke(e.EdgeLabelRenderer,{children:ke("div",{className:"nodrag nopan af-pointer-events-auto af-absolute",style:{transform:`translate(-50%, -50%) translate(${m}px, ${g}px)`},children:ke(yb,{index:b.insertAt})})})]})}let i={insert:r};return function({layout:c,steps:d}){let o=c.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:d[b.index]}:{index:-1,step:null},draggable:!1,selectable:!1,connectable:!1,focusable:!1})),u=c.nodes.slice(1).map((b,v)=>({id:`${c.nodes[v].id}->${b.id}`,source:c.nodes[v].id,target:b.id,type:"insert",data:{insertAt:v},selectable:!1,focusable:!1}));return ke(e.ReactFlow,{nodes:o,edges:u,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 Au({kind:e}){let{automation:t}=Yr();return e==="exit"?ke("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:[ke(cb,{className:"af-h-4 af-w-4 af-shrink-0"}),Ht("div",{className:"af-min-w-0",children:[ke("div",{className:"af-text-xs af-text-muted-foreground",children:"Trigger"}),ke("div",{className:"af-truncate af-text-sm af-font-medium",children:Kr[t.trigger_type].title})]})]})}function Fu({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:[ke(Hl,{label:`Move ${t} up`,disabled:e===0,onClick:()=>n(e,-1),children:ke(ib,{})}),ke(Hl,{label:`Move ${t} down`,disabled:e===i,onClick:()=>n(e,1),children:ke(rb,{})}),ke(Hl,{label:`Remove ${t}`,onClick:()=>r(e),children:ke(lb,{})})]})}function Hl({label:e,disabled:t,onClick:a,children:s}){return ke(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 vb({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:[ke(Ou,{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]}),ke("div",{className:"af-truncate af-text-sm af-font-medium",children:t.subject||"(no subject)"})]}),a.status==="on"&&t.live&&ke(te,{variant:"success",children:"Live"}),ke(Fu,{index:e,label:`email ${r}`})]}),ke("p",{"data-testid":"canvas-email-stats",className:"af-text-xs af-text-muted-foreground",children:i?`Sent ${Ie(i.sent)} \xB7 Opened ${Ie(i.opened)} \xB7 Clicked ${Ie(i.clicked)}`:"Not sent yet"})]})}function bb({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:[ke(Du,{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)]}),ke(Fu,{index:e,label:i})]}),l&&ke(hb,{hours:t.wait_hours,onSave:c=>r(e,c),onCancel:()=>n(null)})]})}function hb({hours:e,onSave:t,onCancel:a}){let s=e%24===0,[n,r]=Ka.useState(String(s?e/24:e)),[i,l]=Ka.useState(s?"days":"hours"),c=Number(n)*(i==="days"?24:1),d=Number.isInteger(c)&&c>=1&&c<=db;return Ht("div",{"data-testid":"wait-editor",className:"nodrag af-space-y-2",children:[ke("div",{className:"af-flex af-flex-wrap af-gap-1",children:ub.map(o=>ke(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(),d&&t(c)},children:[ke(se,{"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:[ke("option",{value:"hours",children:"hours"}),ke("option",{value:"days",children:"days"})]}),ke(y,{type:"submit",size:"sm",className:"af-h-7 af-px-2",disabled:!d,children:"Save"}),ke(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:a,children:"Cancel"})]}),!d&&ke("p",{className:"af-text-xs af-text-destructive",children:"A wait is 1 hour to 365 days."})]})}function yb({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:[ke("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:ke(ob,{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:[ke(Du,{})," Wait"]}),Ht(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:()=>{s(null),r(e)},children:[ke(Ou,{})," Email"]})]})]})}import{Fragment as js,jsx as me,jsxs as at}from"react/jsx-runtime";var xb="Create an automation that ",wb={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 Mu({automation:e}){let[t,a]=e.status==="on"?e.available?["success","On"]:["warning","Unavailable"]:["secondary",e.status==="draft"?"Draft":"Off"];return me(te,{"data-testid":"automation-state",variant:t,children:a})}function Sb(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(d=>d.step_key===a):void 0,c=null;return e==="postal_address_missing"?c=me(ua,{onClick:()=>n("sender"),children:"Add it in Settings"}):e==="checkout_consent_off"&&i?c=me(ua,{onClick:i,children:"Open Store settings"}):e==="email_empty"&&l?.type==="send"&&s?c=me(ua,{onClick:()=>s(l.draft_id),children:"Open the email"}):e==="domain_not_verified"||e==="dmarc_missing"?c=me(ua,{onClick:()=>n("domain"),children:"Fix in Settings"}):e==="sending_not_enabled"&&(c=me(ua,{onClick:r,children:"Finish setup"})),at(js,{children:[Sb(e,t,a),c&&at(js,{children:[" ",c]})]})}function $u({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(c=>c.id===e);if(l)return me(_b,{automation:l,reload:a.refetch,onBack:()=>t(null),onAskAssistant:i,onPickImage:n},l.id);if(!a.data&&!a.error)return me(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:[me("h3",{className:"af-text-sm af-font-semibold",children:"Automations"}),i&&me(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i(xb),children:"\u2728 New automation with the editor"})]}),a.error&&!a.data?me(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:[me(_a,{children:"Suggested"}),me("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=>me(Rb,{suggestion:l,list:a.data,reload:a.refetch,onOpenAutomation:t},l))})]}),me(_a,{children:"Your automations"}),a.data.automations.length===0?me(la,{children:"No automations yet. Turn on a suggestion above, or ask the editor to build one."}):me("ul",{"data-testid":"automations",className:"af-divide-y af-rounded-md af-border",children:a.data.automations.map(l=>me(Nb,{automation:l,onOpen:()=>t(l.id)},l.id))})]}):me(G,{className:"af-h-24 af-w-full"})]})}function Uu(e){return[Kr[e.trigger_type].title,...e.steps.map(t=>t.type==="send"?"Email":`Wait ${_s(t.wait_hours)}`)].join(" \u2192 ")}function Vu(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 Nb({automation:e,onOpen:t}){let a=Object.values(Vu(e)),s=n=>Ie(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:[me("span",{className:"af-truncate af-text-sm af-font-medium",children:e.name}),me(Mu,{automation:e})]}),me("p",{"data-testid":"automation-chain",className:"af-truncate af-text-xs af-text-muted-foreground",children:Uu(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")]})]}),me(jl,{className:"af-h-4 af-w-4 af-shrink-0 af-text-muted-foreground"}),me("button",{type:"button","aria-label":`Open ${e.name}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}function Rb({suggestion:e,list:t,reload:a,onOpenAutomation:s}){let{api:n}=H(),{siteId:r,canWrite:i,onOpenStoreSettings:l}=Ke(),c=vt(),[d,o]=dn.useState(!1),[u,b]=dn.useState(null),v=wb[e],m=t.automations.find(x=>x.trigger_type===v.trigger&&x.list_tag_id===null),g=e==="recovery"&&t.capabilities.checkout_consent==="off_available",f=async()=>{o(!1),b(null);let x=await c.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(c.setError(null),S=await n.getAutomation(r,N).catch(()=>null),!S)return void a()}let k=await c.run("turnOnAutomation",{automationId:S.id,expected_version:S.version});k.ok||(c.setError(null),b({code:Rs(k.error),stepKey:ql(k.error)})),await a()},p=()=>m?me("p",{className:"af-text-sm",children:me(ua,{onClick:()=>s(m.id),children:"Open the automation"})}):i?d?at("div",{className:"af-space-y-2",children:[at("p",{className:"af-text-sm",children:['Turn on "',v.title,'"? It sends ',Ms(v.emails,"email")," to each person who ",Kr[v.trigger].phrase,"."]}),at("div",{className:"af-flex af-gap-2",children:[me(y,{type:"button",variant:"outline",size:"sm",onClick:()=>o(!1),children:"Cancel"}),me(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:c.busy,onClick:()=>void f(),children:"Turn on"})]})]}):g?at("div",{className:"af-space-y-1",children:[me("p",{className:"af-text-xs af-text-muted-foreground",children:"Needs the marketing consent box at checkout, in Store settings."}),me(y,{type:"button",size:"sm",disabled:!l,onClick:()=>l?.(),children:"Turn on"})]}):me("div",{children:me(y,{type:"button",size:"sm",disabled:c.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:[me("span",{"data-testid":"suggestion-title",className:"af-grow af-text-sm af-font-medium",children:v.title}),m&&me(te,{variant:"secondary",children:"Added"})]}),me("p",{className:"af-text-xs af-text-muted-foreground",children:v.description}),u&&at(ue,{tone:"warning",children:["Not turned on. ",me(Jr,{code:u.code,automation:m,stepKey:u.stepKey})]}),c.error&&me(ue,{tone:"error",children:c.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 _b({automation:e,reload:t,onBack:a,onAskAssistant:s,onPickImage:n}){let{api:r}=H(),{siteId:i,canWrite:l}=Ke(),c=Vu(e),d=vt(),o=vt(),u=vt(),[b,v]=dn.useState(null),[m,g]=dn.useState(null),[f,p]=dn.useState(null),[x,S]=dn.useState(null),[k,h]=dn.useState(null),[N,R]=dn.useState(!1),P=e.status==="on",w=e.steps.filter(T=>T.type==="send").length,C=async T=>{R(!0);try{await T()}finally{R(!1)}},E=(T,V)=>C(async()=>{p(null),S(null);let A=await d.run("updateAutomation",{automationId:e.id,expected_version:e.version,steps:T});if(!A.ok){let ne=Rs(A.error);ne==="version_conflict"?(d.setError(null),p(V)):(ne==="email_empty"||ne==="postal_address_missing")&&(d.setError(null),S({code:ne,stepKey:ql(A.error)}))}await t()}),_=T=>C(async()=>{let V=await d.run("createDraft",{kind:"automation",automation_id:e.id,subject:"",blocks:[]});if(!V.ok)return;let A=V.result.id;if(P)return h({draftId:A,joinAt:T});let ne=wo(e.steps);await E([...ne.slice(0,T),{type:"send",draft_id:A},...ne.slice(T)],"Add an email")}),j=dn.useRef(Promise.resolve()),q=T=>{let V=j.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(Ae=>Ae.type==="send"&&Ae.draft_id===T.draftId))return h({draftId:T.draftId});let ie=wo(ne.steps),Fe=Math.min(T.joinAt,ie.length);(await u.run("updateAutomation",{automationId:e.id,expected_version:ne.version,steps:[...ie.slice(0,Fe),{type:"send",draft_id:T.draftId},...ie.slice(Fe)]})).ok&&h({draftId:T.draftId}),await t()});return j.current=V.catch(()=>{}),V},U=async T=>{v(null),g(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),g({code:Rs(A.error),stepKey:ql(A.error)})),A.ok&&T==="deleteAutomation"&&a(),await t()},ae=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:[me(ua,{onClick:a,children:"Automations"}),me(jl,{className:"af-h-3.5 af-w-3.5"}),T===void 0?me("span",{className:"af-font-medium af-text-foreground",children:e.name}):at(js,{children:[me(ua,{onClick:()=>h(null),children:e.name}),me(jl,{className:"af-h-3.5 af-w-3.5"}),me("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:[ae(T>=0?`Email ${Zr(e.steps,T)}`:"New email"),me(po,{draftId:k.draftId,allowCart:e.trigger_type==="abandoned_checkout",automationStep:{live:P&&!V,joinsOnSave:P&&V,notice:u.error&&at(ue,{tone:"error",children:["Couldn't add this email to the automation. ",u.error]}),onBackToCanvas:()=>h(null)},onSaved:()=>{k.joinAt!==void 0?q({draftId:k.draftId,joinAt:k.joinAt}):t()},onAskAssistant:s,onPickImage:n},k.draftId)]})}let ce=e.blocked_by[0]??null,fe=P&&!e.available;return at("div",{className:"af-space-y-3",children:[ae(),at("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[me("h3",{"data-testid":"automation-title",className:"af-grow af-truncate af-text-base af-font-semibold",children:e.name}),me(Mu,{automation:e}),l&&!b&&me(js,{children:P?me(y,{type:"button",variant:"outline",size:"sm",disabled:o.busy,onClick:()=>v("off"),children:"Turn off"}):at(js,{children:[me(y,{type:"button",variant:"ghost",size:"sm",disabled:o.busy,onClick:()=>v("delete"),children:"Delete"}),me(y,{type:"button",size:"sm",disabled:o.busy,onClick:()=>v("on"),children:"Turn on"})]})})]}),me("p",{className:"af-text-xs af-text-muted-foreground",children:Uu(e)}),b&&at("div",{"data-testid":"automation-confirm",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[me("p",{className:"af-text-sm",children:So[b].message(e,w)}),at("div",{className:"af-flex af-gap-2",children:[me(y,{type:"button",variant:"outline",size:"sm",onClick:()=>v(null),children:"Cancel"}),me(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:[me("span",{className:"af-font-medium",children:"Not turned on."})," ",me(Jr,{code:m.code,automation:e,stepKey:m.stepKey,onOpenEmail:T=>h({draftId:T})})]}),o.error&&me(ue,{tone:"error",children:o.error}),fe?at(ue,{tone:"warning",children:[me("span",{className:"af-font-medium",children:"Unavailable."})," ",me(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:[P?"Not sending right now.":"Won't send yet."," ",me(Jr,{code:ce,automation:e})]}),P&&!fe&&at(ue,{tone:"success",children:[me("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."]}),f&&at(ue,{tone:"warning",children:["This automation changed while you were editing, so your change wasn't saved: ",me("span",{className:"af-font-medium",children:f}),". Here is the latest version; make the change again if you still want it."]}),x&&at(ue,{tone:"warning",children:["Not saved. ",me(Jr,{code:x.code,automation:e,stepKey:x.stepKey,onOpenEmail:T=>h({draftId:T})})]}),d.error&&me(ue,{tone:"error",children:d.error}),me(Bu,{automation:e,statsByStep:c,editable:l&&!d.busy&&!N,onChangeSteps:(T,V)=>void E(T,V),onInsertEmail:T=>void _(T),onOpenEmail:T=>h({draftId:T})})]})}import{Fragment as Db,jsx as bt,jsxs as Xr}from"react/jsx-runtime";var kb=[{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 Hu=e=>!!(e.tab||e.draftId||e.templateId||e.automationId);function zu(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 Pb={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function ju(e){return bt(Cb,{...e},e.siteId)}function Cb({siteId:e,isOwnerSide:t,needsPaidPlan:a,initialDraftId:s,initialTab:n,initialAutomationId:r,templateId:i,showViewNonce:l,onOrgAction:c,onRequestReview:d,onStartDomainSetup:o,onBackToWebsite:u,onUpgradePlan:b,onConnectDomain:v,onAskAssistant:m,onPickImage:g,onTurnOn:f,siteDomain:p,businessName:x,onOpenStoreSettings:S,onOpenBrandSettings:k,refreshKey:h=0,className:N}){let{api:R}=H(),P=Lt(()=>R.getMarketingSettings(e),`${e}|${h}`,e),w=Lt(()=>R.getAutomations(e),`${e}|${h}`,e),C={tab:n,draftId:s,templateId:i,automationId:r},[E,_]=Qt.useState(()=>zu(C)),[j,q]=Qt.useState(s??null),[U,ae]=Qt.useState(Hu(C)),[ce,fe]=Qt.useState(null),[T,V]=Qt.useState(!1),A=Qt.useCallback(()=>ae(!1),[]),ne=Qt.useCallback(ee=>{_(Xn("settings")),fe(ee??null)},[]),ie=ee=>{_(Xn(ee)),fe(null)},Fe=Qt.useCallback(ee=>_(Xn("broadcasts",{draftId:ee})),[]),Se=Qt.useCallback(ee=>_(Xn("templates",{templateId:ee})),[]),Ae=Qt.useCallback(ee=>_(Xn("automations",{automationId:ee})),[]),Ye=!U&&P.data!==null&&Tb(P.data),Re=E.tab,Xe=P.data&&!P.error?Eb(P.data):null,I=JSON.stringify([l??null,n??null,s??null,i??null,r??null]),M=Qt.useRef(I);Qt.useEffect(()=>{if(I===M.current||T)return;M.current=I;let ee={tab:n,draftId:s,templateId:i,automationId:r};Hu(ee)&&(_(zu(ee)),q(ee.draftId??null),fe(null),ae(!0))},[I,T,n,s,i,r]),Qt.useEffect(()=>{if(!j||a)return;let ee=!0,J=pe=>{ee&&(_(Xn("broadcasts",{draftId:pe})),q(null))};return R.getEmailDraft(e,j).then(pe=>J(pe.kind==="broadcast"?pe.id:null),()=>J(null)),()=>{ee=!1}},[R,e,j,a]);let B=Qt.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:c,settings:P.data,refetchSettings:P.refetch,refreshKey:h,openSetup:A,openSettings:ne,settingsSection:ce,onOpenStoreSettings:S,onOpenBrandSettings:k,setInlineEditOpen:V}),[e,t,c,P.data,P.refetch,h,A,ne,ce,S,k]);return a?bt(Ut,{title:"Email Marketing",onBackToWebsite:u,className:N,children:bt(Al,{settings:P.data,site:{siteDomain:p,businessName:x},children:bt(_u,{onUpgradePlan:b})})}):bt(Ut,{title:"Email Marketing",onBackToWebsite:u,className:N,children:bt(bl.Provider,{value:B,children:Ye?bt(Ru,{onStartDomainSetup:o,onConnectDomain:v,onAskAssistant:m,onTurnOn:f,siteDomain:p,businessName:x}):Xr(Db,{children:[P.error&&!P.data&&bt(xt,{message:"Couldn't load email settings.",onRetry:()=>void P.refetch()}),Xe&&bt(Ab,{reason:Xe,pauseReason:P.data?.paused.reason??null,onRequestReview:d}),!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:kb.map(ee=>Xr("button",{type:"button",role:"tab","aria-selected":Re===ee.id,onClick:()=>ie(ee.id),className:W("af-border-b-2 af-px-3 af-py-2 af-text-sm",Re===ee.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:[ee.label,ee.id==="settings"&&Xe&&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"})]},ee.id))}),bt("div",{role:"tabpanel",children:j?bt(G,{className:"af-h-24 af-w-full"}):Re==="audience"?bt(iu,{}):Re==="broadcasts"?bt(wu,{openDraftId:E.draftId,onOpenDraft:Fe,onAskAssistant:m,onPickImage:g}):Re==="automations"?bt($u,{automationId:E.automationId,onOpenAutomation:Ae,list:w,onAskAssistant:m,onPickImage:g}):Re==="templates"?bt(Eu,{templateId:E.templateId,onOpenTemplate:Se,onOpenDraft:Fe,onAskAssistant:m}):bt(Ml,{onStartDomainSetup:o,onAskAssistant:m})})]})})})}function Tb(e){return!e.paused.paused_at&&!e.readiness.can_send&&Ur.has(e.readiness.reason??"")}function Eb(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 Ib={domain_not_verified:"domain",dmarc_missing:"domain",postal_address_missing:"sender"};function Ab({reason:e,pauseReason:t,onRequestReview:a}){let{openSetup:s,openSettings:n}=Ke(),[r,i]=Qt.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:[Pb[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=Ib[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(ua,{onClick:()=>n(l),children:"Fix in Settings"}):bt(ua,{onClick:s,children:"Finish setup"})]})})}import*as ra from"react";var Ob=2e3,ya=()=>({data:null,error:null,isLoading:!0});function wr(e,{refreshKey:t,breakdowns:a=[],filters:s=[]}={}){let{api:n}=H(),[r,i]=ra.useState(ya),[l,c]=ra.useState(ya),[d,o]=ra.useState(ya),[u,b]=ra.useState(ya),[v,m]=ra.useState(ya),g=T=>Object.fromEntries(T.map(V=>[V,ya()])),[f,p]=ra.useState(()=>g(a)),x=ra.useRef(0),S=ra.useRef(0),k=ra.useRef("idle"),h=a.join(","),N=us()??"",R=JSON.stringify(s),P=`${e}:${h}:${R}:${N}`,[w,C]=ra.useState({api:n,fetchIdentity:P});(w.api!==n||w.fetchIdentity!==P)&&(C({api:n,fetchIdentity:P}),x.current+=1,i(ya),c(ya),o(ya),b(ya),p(g(h?h.split(","):[])));let E=`${e}:${String(t??"")}:${N}`,[_,j]=ra.useState({api:n,conversionsIdentity:E});(_.api!==n||_.conversionsIdentity!==E)&&(j({api:n,conversionsIdentity:E}),S.current+=1,k.current="idle",m(ya));let q=ra.useCallback(async T=>{let V=++x.current,A=h?h.split(","):[];i(ya),c(ya),o(ya),b(ya),p(Object.fromEntries(A.map(I=>[I,ya()])));let ne=k.current!=="pending"&&(T?.force===!0||k.current==="idle"),ie=(I,M)=>M.then(B=>{V===x.current&&I({data:B,error:null,isLoading:!1})},B=>{V===x.current&&I({data:null,error:B instanceof Error?B:new Error("Failed to fetch report"),isLoading:!1})}),Fe=n.getAnalyticsStatus(),Se=ie(i,Fe),Ae=Symbol("status-timeout"),Ye,Re=await Promise.race([Fe.then(I=>I,()=>null),new Promise(I=>{Ye=setTimeout(()=>I(Ae),Ob)})]);if(clearTimeout(Ye),V!==x.current)return;if(Re===Ae&&i({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Re!==null&&Re!==Ae&&(Re.collecting!==!0||Re.first_seen===null&&!Re.first_seen_unavailable||Re.first_seen!==null&&Re.first_seen_in_reports===!1)){let I={data:null,error:null,isLoading:!1};c(I),o(I),b(I),p(Object.fromEntries(A.map(M=>[M,{...I}]))),ne&&(m(I),k.current="done"),await Se;return}await Promise.all([Re===Ae?Promise.resolve():Se,ie(c,n.getAnalyticsSummary(e,s)),ie(o,n.getAnalyticsTimeseries(e,s)),ie(b,n.getAnalyticsChannels(e,s)),ne?(()=>{k.current="pending";let I=++S.current;return m(ya),n.getAnalyticsConversions(e).then(M=>{I===S.current&&(m({data:M,error:null,isLoading:!1}),k.current="done")},M=>{I===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(I=>n.getAnalyticsBreakdown(I,e,s).then(M=>{V===x.current&&p(B=>({...B,[I]:{data:M,error:null,isLoading:!1}}))},M=>{V===x.current&&p(B=>({...B,[I]:{data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,R,E,N]),U=ra.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]),ae=ra.useCallback(()=>q({force:!0}),[q]);ra.useEffect(()=>{q()},[q,t]);let ce=r.isLoading||l.isLoading||d.isLoading||u.isLoading||v.isLoading||Object.values(f).some(T=>T.isLoading),fe=[d,l,u,v,...Object.values(f)].map(T=>T.data?.status==="ok"?T.data.timezone:void 0).find(T=>T!==void 0);return{status:r,summary:l,timeseries:d,channels:u,conversions:v,breakdowns:f,reportedZone:fe,isLoading:ce,refetch:ae,refetchStatus:U}}import*as ia 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]=ia.useState(null),[c,d]=ia.useState(null),[o,u]=ia.useState(!1),[b,v]=ia.useState(null),[m,g]=ia.useState(!1),[f,p]=ia.useState(!0),[x,S]=ia.useState(0),k=ia.useRef(0),h=ia.useRef(0),N=ia.useRef(void 0);a!==void 0&&(N.current=a);let R=t?N.current===!0||N.current===void 0&&s:!0,[P,w]=ia.useState({api:r,identity:n}),C=n!==void 0&&n!==P.identity;(P.api!==r||C)&&(N.current=void 0,w({api:r,identity:n}),h.current+=1,k.current=0,l(null),d(null),u(!1),v(null),g(!1),p(!0),S(0));let E=ia.useRef(()=>{}),_=ia.useRef(null),j=ia.useCallback(async()=>{if(_.current!==null&&_.current===h.current)return;let q=++h.current;_.current=q;try{let U=await r.getAnalyticsRealtime();if(q!==h.current)return;if(U.status==="unreachable"){g(!0),u(!0),p(!1),S(ae=>ae+1);return}k.current=0,g(!1),l(U.data.current_visitors),d(U.as_of),u(!1),v(null),p(!1),S(ae=>ae+1)}catch(U){if(q!==h.current)return;k.current+=1,p(!1),S(ae=>ae+1),u(!0),k.current>=Gl&&v(U instanceof Error?U:new Error("Realtime unavailable"))}finally{_.current===q&&(_.current=null)}},[r]);return E.current=()=>void j(),ia.useEffect(()=>{let q,U=()=>{q===void 0&&(q=setInterval(()=>E.current(),Wl))},ae=()=>{q!==void 0&&(clearInterval(q),q=void 0)},ce=()=>{typeof document<"u"&&document.hidden?ae():(E.current(),U())};return R?((typeof document>"u"||!document.hidden)&&(E.current(),U()),document?.addEventListener("visibilitychange",ce),()=>{ae(),document?.removeEventListener("visibilitychange",ce),h.current+=1}):()=>{document?.removeEventListener("visibilitychange",ce)}},[P.api,P.identity,R]),{currentVisitors:i,asOf:c,isStale:o,error:b,isUnreachable:m,isInitialLoad:f,polls:x}}import*as Ft from"react";import*as Wu from"react";import{jsx as Kl,jsxs as qu}from"react/jsx-runtime";function Lb(){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=Wu.useMemo(()=>{let i=Lb();return i.includes(e)?i:[e,...i]},[e]);return qu("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"}),qu("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 Bb=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(),Bb))},l=()=>{r!==void 0&&(clearInterval(r),r=void 0)},c=()=>{typeof document<"u"&&document.hidden?l():(a(),i())};return(typeof document>"u"||!document.hidden)&&i(),document?.addEventListener("visibilitychange",c),()=>{l(),document?.removeEventListener("visibilitychange",c)}},[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 Fb=["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 Ku(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 Zu(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Yu(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 Ju(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`${Fb[t-1]} ${a}`}function Gu(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Mb(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Xu(e,t,a="UTC"){let s=new Map(t.map(i=>[i.date,i])),n=[],r=Gu(e.to,a);for(let i=Gu(e.from,a);i<r;i=Mb(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 Qu(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 Ub,jsx as ks,jsxs as $b}from"react/jsx-runtime";function ef({what:e="This report",onRetry:t,collecting:a}){return $b("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(ef,{what:s,onRetry:n,collecting:r}):!e||e.status==="unreachable"?ks(ef,{what:s,onRetry:n,collecting:r}):ks(Ub,{children:i(e.data)})}import{Fragment as Vb,jsx as Za,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:c=9}){let[d,o]=Ws.useState(!1);if(e.length===0)return Za(ko,{what:r});let u=e.reduce((m,g)=>Math.max(m,Number(g[a]??0)),0)||1,b=Math.max(0,e.length-c),v=d?e:e.slice(0,c);return qs(Vb,{children:[qs("table",{className:"af-w-full af-text-sm",children:[Za("thead",{children:qs("tr",{className:"af-text-xs af-text-muted-foreground",children:[Za("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),Za("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),Za("tbody",{children:v.map((m,g)=>{let f=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:[Za("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,f/u*100)}%`}}),p!==null&&i&&k?Za("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}):Za("span",{className:"af-relative af-break-words af-text-foreground",children:x}),S?Za("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:S}):null]}),Za("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Aa(f)})]},`${x}-${S??""}-${g}`)})})]}),b>0?Za("button",{type:"button",onClick:()=>o(m=>!m),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:d?"Show fewer":`Show all ${e.length}`}):null]})}function ai({title:e,tabs:t,defaultTabId:a,headerRight:s}){let[n,r]=Ws.useState(a),i=t.find(v=>v.id===n)??t[0],l=Ws.useId(),c=v=>`${l}-tab-${v}`,d=v=>`${l}-panel-${v}`,o=Ws.useRef(null),u=(v,m)=>{v.preventDefault();let g=(m+t.length)%t.length;r(t[g].id),o.current?.querySelectorAll('[role="tab"]')?.[g]?.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:[Za("div",{ref:o,role:"tablist","aria-label":e,onKeyDown:v=>{let m=t.findIndex(g=>g.id===n);v.key==="ArrowRight"&&u(v,m+1),v.key==="ArrowLeft"&&u(v,m-1),v.key==="Home"&&u(v,0),v.key==="End"&&u(v,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(v=>Za("button",{id:c(v.id),role:"tab",type:"button","aria-selected":v.id===n,"aria-controls":d(v.id),tabIndex:v.id===n?0:-1,onClick:()=>r(v.id),className:v.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:v.label},v.id))}),s]}),i?Za("div",{id:d(i.id),role:"tabpanel","aria-labelledby":c(i.id),tabIndex:0,className:"af-px-3 af-py-2",children:i.render()},i.id):null]})}import*as Ya from"react";import*as Ps from"@radix-ui/react-popover";var Gs=3,Ks=100;import{jsx as Gt,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"},Hb=Object.keys(ni);function tf(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 zb(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 af(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 jb(e){return{dimension:e,operator:"is",search:"",picked:[]}}function nf(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=zb(e.byDimension,a);for(let[r,i]of Object.entries(s)){let l=e.foldsByLabel.get(r)??new Set;for(let c of i)l.add(c);e.foldsByLabel.set(r,l)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([r,i])=>[r,[...i]]))}}function sf(e){let{filters:t,onChange:a}=e,s=t.length>=Gs;return Ya.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:[Gt("span",{className:"af-text-foreground",children:tf(n)}),Gt("button",{type:"button","aria-label":`Remove filter ${tf(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"}`)),Gt(qb,{...e,disabled:s}),t.length>0?Gt("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 qb({filters:e,onChange:t,suggestions:a,resetKey:s,disabled:n,expandValues:r}){let[i,l]=Ya.useState(!1),c=Ya.useRef(null),[d,o]=Ya.useState(null);Ya.useEffect(()=>{o(c.current?.closest(".aifeatures-admin")??null)},[]);let[u,b]=Ya.useState(null),[v,m]=Ya.useState("is"),[g,f]=Ya.useState(""),[p,x]=Ya.useState([]);Ya.useEffect(()=>{i||(b(null),m("is"),f(""),x([]))},[i]);let S=Ya.useRef(s);S.current!==s&&(S.current=s,i&&l(!1),u!==null&&b(null),p.length>0&&x([]),g!==""&&f(""),v!=="is"&&m("is"));let k=C=>{let E=jb(C);b(E.dimension),x(E.picked),f(E.search),m(E.operator)},N=(u?a[u]??[]:[]).filter(C=>C.toLowerCase().includes(g.trim().toLowerCase())),R=u===null||p.length===0?null:Xl(e,{dimension:u,operator:v,values:r?r(u,p):p}),P=R!==null&&R!==e,w=()=>{let C=R;!C||C===e||(t(C),l(!1))};return Qn(Ps.Root,{open:i,onOpenChange:l,children:[Gt(Ps.Trigger,{asChild:!0,children:Gt("button",{ref:c,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"})}),Gt(Ps.Portal,{container:d,children:Gt(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:u===null?Qn("div",{children:[Gt("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),Gt("div",{className:"af-max-h-96 af-overflow-y-auto",children:Hb.filter(C=>a[C]!==void 0).map(C=>{let E=a[C]?.length??0,_=!e.some(j=>j.dimension===C)&&e.length>=Gs;return Qn("button",{type:"button",onClick:()=>k(C),disabled:E===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:[Gt("span",{children:ni[C]}),Gt("span",{className:"af-text-muted-foreground",children:E===0?"no data":_?"no room":E})]},C)})})]}):Qn("div",{children:[Qn("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Gt("button",{type:"button",onClick:()=>k(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),Gt("span",{className:"af-text-xs af-font-medium af-text-foreground",children:ni[u]}),Qn("select",{"aria-label":"Operator",value:v,onChange:C=>m(C.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:[Gt("option",{value:"is",children:"is"}),Gt("option",{value:"is_not",children:"is not"})]})]}),Gt("input",{type:"text",value:g,onChange:C=>f(C.target.value),placeholder:"Search\u2026","aria-label":`Search ${ni[u]}`,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"}),Gt("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",g,"\u201D."]}):N.map(C=>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:[Gt("input",{type:"checkbox",checked:p.includes(C),disabled:!p.includes(C)&&p.length>=Ks,onChange:E=>x(_=>E.target.checked?[..._,C]:_.filter(j=>j!==C))}),Gt("span",{className:"af-break-all",children:ti(C)})]},C))}),Gt("button",{type:"button",onClick:w,disabled:!P,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 Kb,jsx as Da,jsxs as Po}from"react/jsx-runtime";var Wb=[{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 Gb({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 rf({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:Wb.map(s=>{let n=s.chart===t,r=a!==void 0,i=Po(Kb,{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(Gb,{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?Ju(t):"freshness unknown",l=r?" across the whole site, not the current filter,":"",c=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:c,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:c})]})}import*as lf from"react";import{Star as Zb}from"lucide-react";import{Fragment as of,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,c]=lf.useState(!1),d=e.filter(f=>!f.implicit||f.visitors>0||f.events>0||Co(f,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(d.length===0)return Zs(of,{children:[pa(ko,{what:n}),o]});let u=d.slice(0,r),b=i?d.find(f=>Co(f,i)):void 0,v=b&&!u.includes(b)?d.filter(f=>u.includes(f)||f===b).slice(0,Math.max(0,r-1)).concat(b):u,m=l?e:v,g=Math.max(0,e.length-v.length);return Zs(of,{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((f,p)=>Zs("tr",{className:"af-border-t af-border-border","aria-current":Co(f,i)?"true":void 0,children:[pa("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Co(f,i)?Zs("span",{className:"af-flex af-items-center af-gap-1.5",children:[pa(Zb,{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:f.goal}),pa("span",{className:"af-sr-only",children:"(your main conversion)"})]}):f.goal}),pa("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Aa(f.visitors)}),pa("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Aa(f.events)}),pa("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:f.conversion_rate===null?pa("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Sr(f.conversion_rate)})]},`${f.goal}-${p}`))})]}),g>0?pa("button",{type:"button",onClick:()=>c(f=>!f),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length} goals`}):null,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 Yb,AreaChart as Jb,CartesianGrid as Xb,ResponsiveContainer as Qb,Tooltip as eh,XAxis as th,YAxis as ah}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},nh=31,sh=new Set(["visitors","visits","pageviews"]),rh={...tc,bounce_rate:Zu,visit_duration_seconds:Ku},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],ih=[5,10,15,30,60,120,300,600,900,1800,3600,7200],oh=[.01,.02,.05,.1,.2,.25,.5,1],lh=[.25,.5,1,2,5,10,25,50],ch={visitors:ec,visits:ec,pageviews:ec,views_per_visit:lh,bounce_rate:oh,visit_duration_seconds:ih};function dh({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:Qu(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=Xu(t,e,s),i=tc[a],l=rh[a],c=Yu(r.reduce((o,u)=>Math.max(o,Number(u[a]??0)),0),ch[a]),d=`${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(Qb,{width:"100%",height:n,children:si(Jb,{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(Xb,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Oa(th,{dataKey:"date",tickFormatter:Yl,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Oa(ah,{allowDecimals:!sh.has(a),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...c?{ticks:c,domain:[0,c[c.length-1]]}:{},tickFormatter:o=>l(o),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Oa(eh,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Oa(dh,{metric:a})}),Oa(Yb,{type:"linear",dataKey:a,name:Eo[a],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=nh?{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:d})]})}import{Fragment as ac,jsx as Be,jsxs as Pa}from"react/jsx-runtime";var uh="2026-08-13",fh=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],mh=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function ph({filters:e,onFiltersChange:t,refreshKey:a,onBackToWebsite:s,primaryConversion:n,className:r,published:i,lastPublishedAt:l}){let[c,d]=Ft.useState(30),[o,u]=Ft.useState(()=>Bo()),b=e!==void 0&&t!==void 0,[v,m]=Ft.useState(e??[]),{api:g}=H(),[f,p]=Ft.useState(g);f!==g&&(p(g),!b&&v.length>0&&m([]));let x=b?e:v,S=Ft.useCallback(B=>{t&&t(B),b||m(B)},[t,b]),k=Ft.useCallback((B,ee,J)=>{let pe=Array.isArray(ee)?ee:[ee];if(pe.length===0)return null;let Ue=Xl(x,{dimension:B,operator:"is",values:pe});if(J&&(!J.value||(Ue=af(Ue,{dimension:J.dimension,operator:"is",values:[J.value]}),!Ue.find(Et=>Et.dimension===J.dimension&&Et.operator!=="is_not")?.values.includes(J.value))))return null;let ft=Ue.find(Qe=>Qe.dimension===B&&Qe.operator!=="is_not");return pe.every(Qe=>ft?.values.includes(Qe))?JSON.stringify(Ue)===JSON.stringify(x)?null:Ue:null},[x]),h=Ft.useCallback((B,ee,J)=>k(B,ee,J)!==null,[k]),N=Ft.useCallback((B,ee,J)=>{let pe=k(B,ee,J);pe&&S(pe)},[k,S]),[R,P]=Ft.useState("visitors"),w=wr(c,{refreshKey:a,breakdowns:mh,filters:x}),C=w.status.data,E=w.reportedZone??C?.timezone,_=E??o??Rr()??"UTC",{notCollecting:j,awaitingFirstVisit:q,firstVisitTooRecent:U,holdingForFirstData:ae}=Ro(C,{published:i}),ce=i===!1,fe=No({collecting:q||j?!1:C?.collecting,statusFailed:w.status.error!=null,identity:C?.analytics_id}),T=Ft.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),V=Ft.useMemo(()=>{let B=w.breakdowns.sources?.data,ee={};if(!B||B.status!=="ok")return ee;for(let J of B.data){let pe=J.source,Ue=J.sources;typeof pe=="string"&&Array.isArray(Ue)&&Ue.length>0&&(ee[pe]=Ue)}return ee},[w.breakdowns.sources?.data]),A=Ft.useMemo(()=>{let B=(pe,Ue)=>{let ft=w.breakdowns[pe]?.data;return!ft||ft.status!=="ok"?[]:[...new Set(ft.data.map(Qe=>Qe[Ue]).filter(Qe=>typeof Qe=="string"&&Qe!==""))]};return{channel:w.channels.data?.status==="ok"?[...new Set(w.channels.data.data.map(pe=>pe.channel))]:[],source:B("sources","source"),campaign:B("utm/campaign","campaign"),page:B("pages","pathname"),entry_page:B("entry-pages","pathname"),exit_page:B("exit-pages","pathname"),country:B("countries","country"),browser:B("browsers","browser"),os:B("operating-systems","os"),device:B("devices","device")}},[w.breakdowns,w.channels.data]),[ne,ie]=Ft.useState({}),Fe=JSON.stringify(A),[Se,Ae]=Ft.useState(new Map),Ye=JSON.stringify(V);Ft.useEffect(()=>{let{suggestions:B,folds:ee}=nf(T.current,{api:g,period:c},JSON.parse(Fe),JSON.parse(Ye));ie(B),Ae(ee)},[Fe,Ye,g,c]);let Re=Ft.useCallback((B,ee)=>B!=="source"?ee:[...new Set(ee.flatMap(J=>{let pe=[...Se.get(J)??[],...V[J]??[]];return pe.length>0?pe:[J]}))],[Se,V]),Xe=Ft.useMemo(()=>{let B=w.conversions.error;return B instanceof ta&&B.details?.code==="goals_exceed_report_budget"?B.message:null},[w.conversions.error]),I=Ft.useMemo(()=>{let B=[w.summary,w.timeseries,w.channels,...Object.values(w.breakdowns)];for(let ee of B){let J=ee?.error;if(J instanceof ta&&J.details?.code==="filter_unsupported")return J.message}return null},[w.summary,w.timeseries,w.channels,w.breakdowns]),M=(B,ee,J,pe,Ue,ft,Qe,Et,be)=>()=>{let Me=w.breakdowns[B];return Be(ds,{sourced:Me?.data??null,error:Me?.error,isLoading:Me?.isLoading,what:ee,collecting:C?.collecting,onRetry:w.refetch,children:yt=>{let It=Mt=>Et?Re(Et,[Mt]):Mt;return Be(Jl,{rows:yt,dimension:J,metric:pe,metricLabel:Ue,secondary:ft,emptyCopy:x.length>0?"No data for this filter":Qe,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:C,holdingForFirstData:ae,refetchStatus:w.refetchStatus,refetch:w.refetch}),j){let B=!!l&&String(l).slice(0,10)<uh;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.":B?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return q?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:B=>{Fo(B),u(B)}})}),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",C?.timezone?` ${C.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:fe.currentVisitors,asOf:fe.asOf,isStale:fe.isStale,isUnreachable:fe.isUnreachable||fe.error!==null,isInitialLoad:fe.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:fh.map(B=>Be("button",{type:"button","aria-pressed":B.value===c,onClick:()=>d(B.value),className:B.value===c?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:B.label},B.value))}),Be(Zl,{value:_,chosen:o,onChange:B=>{Fo(B),u(B)}}),Be(Ql,{currentVisitors:fe.currentVisitors,asOf:fe.asOf,isStale:fe.isStale,isUnreachable:fe.isUnreachable||fe.error!==null,isInitialLoad:fe.isInitialLoad,scopeIsSiteWide:x.length>0})]}),Be(sf,{filters:x,onChange:S,suggestions:ne,expandValues:Re,resetKey:g}),I?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:I}),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,!I&&C?.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,I?null:Pa(ac,{children:[Be(ds,{sourced:w.summary.data,error:w.summary.error,isLoading:w.summary.isLoading,what:"The traffic summary",collecting:C?.collecting,onRetry:w.refetch,children:B=>Pa(ac,{children:[Be(rf,{summary:B,selected:R,onSelect:P}),B.previous_unavailable?Pa("p",{className:"af-text-xs af-text-muted-foreground",children:[B.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:C?.collecting,onRetry:w.refetch,children:B=>{let ee=w.timeseries.data?.status==="ok"?w.timeseries.data.window:{from:"",to:""};return Be(Io,{rows:B,window:ee,metric:R,timeZone:E??"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:C?.collecting,onRetry:w.refetch,children:B=>Be(Jl,{rows:B,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:ee=>h("channel",ee),onFilter:ee=>N("channel",ee)})})},{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,Xe!==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:Xe})]}):Be(ds,{sourced:w.conversions.data,error:w.conversions.error,isLoading:w.conversions.isLoading,what:"Conversions",collecting:C?.collecting,onRetry:w.refetch,children:B=>{let ee=w.conversions.data?.status==="ok"?w.conversions.data:null;return Be(ac,{children:Be(To,{rows:B,primaryConversion:n,denominator:ee?.denominator??0,windowPrecedesCollection:ee?.window_precedes_collection??!1,coverageUnknown:ee?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import*as bf from"react";import{Phone as pf,Mail as sc,ShoppingBag as hh,ExternalLink as yh,MessageCircle as xh,Download as wh,Target as hf}from"lucide-react";import*as Nn from"react";import{Check as nc,ChevronLeft as gh,Loader2 as cf}from"lucide-react";import{jsx as ht,jsxs as ga}from"react/jsx-runtime";var df=90,uf=100;function vh(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function ff(e){return!!e.label&&e.label!==e.target}function bh(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 mf({current:e,onChange:t,onClose:a}){let{api:s}=H(),[n,r]=Nn.useState(null),[i,l]=Nn.useState(!1),[c,d]=Nn.useState({at:"goals"}),[o,u]=Nn.useState(null),[b,v]=Nn.useState(null),[m,g]=Nn.useState(!1),[f,p]=Nn.useState(null),x=Nn.useRef(0);Nn.useEffect(()=>{let N=!0;return r(null),l(!1),d({at:"goals"}),u(null),v(null),g(!1),p(null),x.current+=1,s.getAnalyticsConversions(df).then(R=>{if(N){if(R.status!=="ok"){l(!0);return}r(R.data)}}).catch(()=>{N&&l(!0)}),()=>{N=!1}},[s]);let S=N=>{d({at:"targets",row:N}),u(null),v(null),g(!1),p(null);let R=++x.current;s.getAnalyticsGoalTargets(N.goal,df,uf).then(P=>{if(R===x.current){if(P.status!=="ok"){v("failed");return}u(P.data),g(P.truncated===!0),p(P.coverage??null)}}).catch(P=>{if(R!==x.current)return;let w=P instanceof ta?P.details?.code:void 0;v(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(cf,{className:"af-h-4 af-w-4 af-animate-spin"}),ht("span",{children:"Loading your conversions\u2026"})]});if(c.at==="targets"){let N=c.row,R=new Map;for(let P of o??[])R.set(P.label,(R.get(P.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:()=>d({at:"goals"}),children:[ht(gh,{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(cf,{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:bh(o.length,f,m)}),m&&ga("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",uf,". If what you want isn\u2019t here, pick the conversion itself instead."]}),o?.some(ff)&&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(P=>{let w=!!(e&&ri(N,e)&&e.target===P.target),C=R.get(P.label)>1;return ff(P)?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:P.label}),C&&ht("span",{className:"af-block af-truncate af-text-xs",children:P.target})]}),ht("span",{className:"af-shrink-0 af-text-xs",children:P.visitors.toLocaleString()})]},P.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:P.target,...P.label&&P.label!==P.target?{label:P.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:P.label}),C&&ht("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:P.target})]})]}),ht("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:P.visitors.toLocaleString()})]},P.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()})]}),vh(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 _h,jsx as Ys,jsxs as vf}from"react/jsx-runtime";function Sh(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 Nh(e){if(rc(e,"whatsapp"))return!0;let t=Sh(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 gf=[{goal:"Contact",target:e=>rc(e,"tel"),icon:pf,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:pf,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Nh(e),icon:xh,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:yh,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:hh,line:"This site is set up to sell."},{goal:"File Download",icon:wh,line:"This site is set up to get your file downloaded."}];function yf(e){let{goal:t,target:a}=e;return e.implicit!==!0?null:(a?gf.find(n=>n.goal===t&&n.target?.(a)):void 0)??gf.find(n=>n.goal===t&&!n.target)??null}function Rh(e){return yf(e)?.icon??hf}function xf({primaryConversion:e,onChange:t}){let[a,s]=bf.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?yf(e):null,i=e?.label?.trim(),l=e?Rh(e):hf,c=e?.goal?i?`Your main conversion is ${i}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",d=vf(_h,{children:[Ys(l,{className:"af-h-4 af-w-4 af-shrink-0"}),Ys("span",{children:c})]});return t?vf(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:d})}),Ys(Dr,{align:"start",className:"af-w-80 af-p-1",children:a&&Ys(mf,{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:d})}import{Fragment as kh,jsx as Cs,jsxs as Ao}from"react/jsx-runtime";function wf({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(kh,{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:c=>{let d=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return Cs(Io,{rows:c,window:d?.window??{from:"",to:""},metric:"visitors",timeZone:d?.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:c=>{let d=s.conversions.data?.status==="ok"?s.conversions.data:null;return Cs(To,{rows:c,primaryConversion:a,denominator:d?.denominator??0,windowPrecedesCollection:d?.window_precedes_collection??!1,coverageUnknown:d?.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 Ph({refreshKey:e,onBackToWebsite:t,primaryConversion:a,onChangePrimaryConversion:s,onOpenSurface:n,needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l}){let c=dr({refreshKey:e}),d=(c.summary?.products.count??0)>0||(c.summary?.commerce?.storefront_orders??!1),o=d||(c.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(xf,{primaryConversion:a,onChange:s}),Fn(wf,{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"))})]}),d&&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,ta as AifeaturesApiError,Rf as AifeaturesProvider,ph as AnalyticsView,lo as ContactImport,Ui as CustomerDetail,Vi as CustomersList,ho as DOUBLE_OPT_IN_HELP,Ph as DashboardView,vl as EMAIL_ORG_ACTIONS,nu as EMAIL_READINESS_TEXT,ju 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,dv as buildEmailOrgRequest,is as chargedTotal,Mo as createApiClient,Ns as emailReadinessText,Q as formatPrice,cv 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};
|