@aifeatures/admin-react 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  "use client";
2
- "use strict";var Pu=Object.create;var gi=Object.defineProperty;var Cu=Object.getOwnPropertyDescriptor;var Tu=Object.getOwnPropertyNames;var Eu=Object.getPrototypeOf,Iu=Object.prototype.hasOwnProperty;var Au=(e,t)=>{for(var a in t)gi(e,a,{get:t[a],enumerable:!0})},Hl=(e,t,a,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Tu(t))!Iu.call(e,n)&&n!==a&&gi(e,n,{get:()=>t[n],enumerable:!(s=Cu(t,n))||s.enumerable});return e};var le=(e,t,a)=>(a=e!=null?Pu(Eu(e)):{},Hl(t||!e||!e.__esModule?gi(a,"default",{value:e,enumerable:!0}):a,e)),Du=e=>Hl(gi({},"__esModule",{value:!0}),e);var Vp={};Au(Vp,{AUDIENCE_PAGE_SIZE:()=>Ms,AifeaturesApiError:()=>Gt,AifeaturesProvider:()=>Gl,AnalyticsView:()=>gu,ContactImport:()=>Jr,CustomerDetail:()=>$r,CustomersList:()=>Ur,DOUBLE_OPT_IN_HELP:()=>ai,DashboardView:()=>_u,EMAIL_ORG_ACTIONS:()=>Xi,EMAIL_READINESS_TEXT:()=>tl,EmailView:()=>kl,ExportCsvButton:()=>ma,FormSettings:()=>Tr,FormSubmissions:()=>Rr,FormsDashboard:()=>Co,FormsList:()=>hr,IMPORT_ATTESTATION:()=>eo,InvoiceDetail:()=>$i,InvoiceLabelBadge:()=>ar,InvoiceSettingsPanel:()=>Gr,InvoicesList:()=>ts,InvoicesView:()=>el,LeadsView:()=>jr,MAX_ANALYTICS_FILTERS:()=>ys,MAX_ANALYTICS_FILTER_VALUES:()=>xs,NotificationRecipientsSettings:()=>Qo,OrderDetail:()=>Fr,OrderStatusBadge:()=>ms,OrdersList:()=>Qn,OrdersView:()=>Ho,PaymentsDashboard:()=>Vo,PaymentsSetup:()=>Is,ProductSettings:()=>Dr,ProductsList:()=>Ir,ProductsView:()=>zo,PromosPanel:()=>_s,REALTIME_FAILURES_BEFORE_ERROR:()=>po,REALTIME_POLL_MS:()=>mo,RetainerStatusBadge:()=>Vi,RetainersPanel:()=>Es,StoreSettings:()=>Xo,SubmissionDetail:()=>Sr,SubscriptionsView:()=>Wo,VariantsEditor:()=>Ar,ViewShell:()=>Ft,WebhookDeliveries:()=>Pr,WebhookSettings:()=>Cr,buildEmailOrgRequest:()=>yd,chargedTotal:()=>Ln,createApiClient:()=>hi,emailReadinessText:()=>ss,formatPrice:()=>se,isEmailOrgAction:()=>hd,isZeroDecimalCurrency:()=>Xa,toMajorUnits:()=>Et,toMinorUnits:()=>oa,useAifeatures:()=>G,useAifeaturesContext:()=>G,useAnalytics:()=>Ws,useAudience:()=>Zr,useBroadcasts:()=>Vs,useBusinessSummary:()=>Os,useCsvExport:()=>Nr,useCustomers:()=>Mr,useEmailDrafts:()=>Hs,useEventDestinations:()=>_r,useForms:()=>Ss,useInvoices:()=>Ts,useOrders:()=>Or,usePaymentsStatus:()=>Yn,usePeople:()=>Hr,usePerson:()=>zr,useProducts:()=>As,useRealtimeVisitors:()=>li,useRetainers:()=>Ds,useSiteSettings:()=>as,useSubmissions:()=>xr,useSubscriptions:()=>qr});module.exports=Du(Vp);var cs=le(require("react"),1);var No="aifeatures:analytics:timezone",Ro;function pr(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function zl(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function os(){return _o()??pr()}function _o(){if(Ro!==void 0)return Ro;try{let e=window.localStorage.getItem(No);return zl(e)?e:null}catch{return null}}function ko(e){if(!(e!==null&&!zl(e))){Ro=e;try{e===null?window.localStorage.removeItem(No):window.localStorage.setItem(No,e)}catch{}}}function vi(e,t){let a=new URLSearchParams({period:String(e)}),s=os();return s&&a.set("timezone",s),t&&t.length>0&&a.set("filters",JSON.stringify(t)),a.toString()}var Gt=class extends Error{constructor(a,s,n){super(a);this.status=s;this.details=n;this.name="AifeaturesApiError"}};function bi(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 jl(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 ql(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 hi(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 Gt(bi(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 Gt(bi(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(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,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 Gt(bi(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 Gt(bi(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=jl(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",jl(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=ql(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",ql(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=os();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?${vi(n,r)}`)},async getAnalyticsTimeseries(n,r){return a(`/api/v1/analytics/timeseries?${vi(n,r)}`)},async getAnalyticsRealtime(){return a("/api/v1/analytics/realtime")},async getAnalyticsChannels(n,r){return a(`/api/v1/analytics/channels?${vi(n,r)}`)},async getAnalyticsConversions(n){return a((()=>{let r=new URLSearchParams({period:String(n)}),i=os();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=os();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}?${vi(r,i)}`)},async getBusinessSummary(n){let r=new URLSearchParams;r.set("tz_offset_minutes",String(n.tzOffsetMinutes));let i=os();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(`${Ta(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(`${Ta(n)}/contacts${l?`?${l}`:""}`)},async getMarketingContactStats(n){return a(`${Ta(n)}/contacts/stats`)},async getMarketingTags(n){return(await a(`${Ta(n)}/contact-tags`)).tags},async getEmailDrafts(n,r){let i=r?`?kind=${r}`:"";return(await a(`${Ta(n)}/marketing/drafts${i}`)).drafts},async getEmailDraft(n,r){return a(`${Ta(n)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(n,r,i){let l=i?.editable?"?mode=editable":"";return a(`${Ta(n)}/marketing/drafts/${encodeURIComponent(r)}/preview${l}`)},async getEmailTemplates(n){return(await a(`${Ta(n)}/marketing/templates`)).templates},async previewEmailTemplate(n,r,i){let l=i?`?draft_id=${encodeURIComponent(i)}`:"";return a(`${Ta(n)}/marketing/templates/${encodeURIComponent(r)}/preview${l}`)},async getBroadcasts(n){return(await a(`${Ta(n)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(n,r){return a(`${Ta(n)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getAutomations(n){return a(`${Ta(n)}/marketing/automations`)},async getAutomation(n,r){return a(`${Ta(n)}/marketing/automations/${encodeURIComponent(r)}`)},async getAutomationStats(n,r){return(await a(`${Ta(n)}/marketing/automations/${encodeURIComponent(r)}/stats`)).steps}}}function Ta(e){return`/api/v1/sites/${encodeURIComponent(e)}`}var ls=require("react/jsx-runtime"),Wl=cs.createContext(null);function Ou(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 Gl({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:n}){let r=cs.useMemo(()=>Ou(e),[e]),i=cs.useMemo(()=>hi(e,t),[e,t]),l=cs.useMemo(()=>({siteToken:e,apiUrl:t,api:i}),[e,t,i]);return r?(0,ls.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:(0,ls.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,ls.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,ls.jsx)("p",{className:"af-text-sm af-text-destructive",children:r})]})}):(0,ls.jsx)(Wl.Provider,{value:l,children:(0,ls.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:n})})}function G(){let e=cs.useContext(Wl);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var Zn=le(require("react"),1),Js=require("lucide-react");var yi=le(require("react"),1),wn=le(require("@radix-ui/react-tabs"),1);var Kl=require("clsx"),Zl=require("tailwind-merge"),Lu=(0,Zl.extendTailwindMerge)({prefix:"af-"});function Q(...e){return Lu((0,Kl.clsx)(e))}var wi=require("react/jsx-runtime"),xi=wn.Root,vr=yi.forwardRef(({className:e,...t},a)=>(0,wi.jsx)(wn.List,{ref:a,className:Q("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));vr.displayName=wn.List.displayName;var Sn=yi.forwardRef(({className:e,...t},a)=>(0,wi.jsx)(wn.Trigger,{ref:a,className:Q("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));Sn.displayName=wn.Trigger.displayName;var Nn=yi.forwardRef(({className:e,...t},a)=>(0,wi.jsx)(wn.Content,{ref:a,className:Q("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));Nn.displayName=wn.Content.displayName;var Yl=le(require("react"),1),Jl=require("@radix-ui/react-slot"),Xl=require("class-variance-authority");var Ql=require("react/jsx-runtime"),Bu=(0,Xl.cva)("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),y=Yl.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...n},r)=>(0,Ql.jsx)(s?Jl.Slot:"button",{className:Q(Bu({variant:t,size:a,className:e})),ref:r,...n}));y.displayName="Button";var br=require("lucide-react");var Gn=le(require("react"),1);var An=require("react/jsx-runtime"),ut=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,An.jsx)("table",{ref:a,className:Q("af-w-full af-caption-bottom af-text-sm",e),...t})}));ut.displayName="Table";var ft=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("thead",{ref:a,className:Q("[&_tr]:af-border-b",e),...t}));ft.displayName="TableHeader";var mt=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("tbody",{ref:a,className:Q("[&_tr:last-child]:af-border-0",e),...t}));mt.displayName="TableBody";var Fu=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("tfoot",{ref:a,className:Q("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Fu.displayName="TableFooter";var $e=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("tr",{ref:a,className:Q("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));$e.displayName="TableRow";var te=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("th",{ref:a,className:Q("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));te.displayName="TableHead";var ae=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("td",{ref:a,className:Q("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));ae.displayName="TableCell";var Mu=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("caption",{ref:a,className:Q("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Mu.displayName="TableCaption";var Rn=le(require("react"),1);function Ss(){let{api:e}=G(),[t,a]=Rn.useState([]),[s,n]=Rn.useState(!0),[r,i]=Rn.useState(null),l=Rn.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]);Rn.useEffect(()=>{l()},[l]);let c=Rn.useCallback(async u=>{let b=await e.createForm(u);return a(v=>[...v,b]),b},[e]),d=Rn.useCallback(async(u,b)=>{let v=await e.updateForm(u,b);return a(m=>m.map(p=>p.id===u?v:p)),v},[e]),o=Rn.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}}var _t=require("react/jsx-runtime");function hr({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:n}=Ss();return s?(0,_t.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,_t.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,_t.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,_t.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):a.length===0?(0,_t.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,_t.jsx)(br.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,_t.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,_t.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,_t.jsx)("div",{className:t,children:(0,_t.jsxs)(ut,{children:[(0,_t.jsx)(ft,{children:(0,_t.jsxs)($e,{children:[(0,_t.jsx)(te,{children:"Name"}),(0,_t.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,_t.jsx)(mt,{children:a.map(r=>(0,_t.jsxs)($e,{children:[(0,_t.jsx)(ae,{className:"af-font-medium",children:r.name}),(0,_t.jsx)(ae,{className:"af-text-right",children:(0,_t.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,_t.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[(0,_t.jsx)(br.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,_t.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[(0,_t.jsx)(br.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}var ac=require("lucide-react");var ec=require("class-variance-authority");var tc=require("react/jsx-runtime"),$u=(0,ec.cva)("af-inline-flex af-items-center af-rounded-md af-border af-px-2.5 af-py-0.5 af-text-xs af-font-semibold af-transition-colors focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2",{variants:{variant:{default:"af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",secondary:"af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",destructive:"af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",outline:"af-text-foreground",success:"af-border-transparent af-bg-green-100 af-text-green-800",warning:"af-border-transparent af-bg-yellow-100 af-text-yellow-800"}},defaultVariants:{variant:"default"}});function ie({className:e,variant:t,...a}){return(0,tc.jsx)("div",{className:Q($u({variant:t}),e),...a})}var Ha=require("react/jsx-runtime"),Uu={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 Si(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 Po(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function Vu(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 yr({deliveries:e,label:t="Email needs attention"}){return Po(e)?(0,Ha.jsxs)("span",{className:"af-mt-1 af-flex af-items-center af-gap-1 af-text-xs af-font-normal af-text-amber-800 dark:af-text-amber-300",children:[(0,Ha.jsx)(ac.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Dn({deliveries:e,problemsOnly:t=!1,className:a=""}){let s=(e??[]).filter(n=>!t||Po([n]));return s.length?(0,Ha.jsx)("div",{className:`af-space-y-3 ${a}`,"aria-label":"Email delivery",children:s.map(n=>{let r=Si(n),i=Vu(n);return(0,Ha.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Ha.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Ha.jsx)("span",{className:"af-font-medium",children:Uu[n.kind]??"Email notification"}),(0,Ha.jsx)(ie,{variant:r.variant,children:r.label})]}),(0,Ha.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&Po([n])&&(0,Ha.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This status applies to the message sent to this group. It does not mean every recipient had a delivery problem."}),r.detail&&(0,Ha.jsx)("p",{className:"af-mt-1",children:r.detail}),i&&(0,Ha.jsx)("p",{className:"af-mt-1",children:i})]},n.id)})}):null}var us=le(require("react"),1),dn=require("lucide-react");var ds=le(require("react"),1),Ze=le(require("@radix-ui/react-select"),1),Ns=require("lucide-react");var jt=require("react/jsx-runtime"),on=Ze.Root;var ln=Ze.Value,za=ds.forwardRef(({className:e,children:t,...a},s)=>(0,jt.jsxs)(Ze.Trigger,{ref:s,className:Q("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...a,children:[t,(0,jt.jsx)(Ze.Icon,{asChild:!0,children:(0,jt.jsx)(Ns.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));za.displayName=Ze.Trigger.displayName;var nc=ds.forwardRef(({className:e,...t},a)=>(0,jt.jsx)(Ze.ScrollUpButton,{ref:a,className:Q("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,jt.jsx)(Ns.ChevronUp,{className:"af-h-4 af-w-4"})}));nc.displayName=Ze.ScrollUpButton.displayName;var sc=ds.forwardRef(({className:e,...t},a)=>(0,jt.jsx)(Ze.ScrollDownButton,{ref:a,className:Q("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,jt.jsx)(Ns.ChevronDown,{className:"af-h-4 af-w-4"})}));sc.displayName=Ze.ScrollDownButton.displayName;var ja=ds.forwardRef(({className:e,children:t,position:a="popper",...s},n)=>(0,jt.jsx)(Ze.Portal,{children:(0,jt.jsxs)(Ze.Content,{ref:n,className:Q("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:a,...s,children:[(0,jt.jsx)(nc,{}),(0,jt.jsx)(Ze.Viewport,{className:Q("af-p-1",a==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,jt.jsx)(sc,{})]})}));ja.displayName=Ze.Content.displayName;var Hu=ds.forwardRef(({className:e,...t},a)=>(0,jt.jsx)(Ze.Label,{ref:a,className:Q("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));Hu.displayName=Ze.Label.displayName;var kt=ds.forwardRef(({className:e,children:t,...a},s)=>(0,jt.jsxs)(Ze.Item,{ref:s,className:Q("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...a,children:[(0,jt.jsx)("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:(0,jt.jsx)(Ze.ItemIndicator,{children:(0,jt.jsx)(Ns.Check,{className:"af-h-4 af-w-4"})})}),(0,jt.jsx)(Ze.ItemText,{children:t})]}));kt.displayName=Ze.Item.displayName;var zu=ds.forwardRef(({className:e,...t},a)=>(0,jt.jsx)(Ze.Separator,{ref:a,className:Q("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));zu.displayName=Ze.Separator.displayName;var Na=le(require("react"),1);function xr({formId:e,initialPageSize:t=25}){let{api:a}=G(),[s,n]=Na.useState([]),[r,i]=Na.useState(0),[l,c]=Na.useState(!0),[d,o]=Na.useState(null),[u,b]=Na.useState(0),[v,m]=Na.useState(t),p=Na.useRef(0),f=Na.useCallback(async()=>{if(!e)return;let T=++p.current;try{c(!0),o(null);let h={limit:v,offset:u*v},P=await a.getSubmissions(e,h);if(T!==p.current)return;if(P.submissions.length===0&&u>0){b(Math.max(0,Math.ceil(P.total/v)-1));return}n(P.submissions),i(P.total)}catch(h){if(T!==p.current)return;o(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{T===p.current&&c(!1)}},[a,e,u,v]);Na.useEffect(()=>{f()},[f]);let g=Na.useRef(f);g.current=f;let x=Na.useCallback(async T=>{await a.deleteSubmission(T),g.current()},[a]),k=Math.ceil(r/v);return{submissions:s,total:r,isLoading:l,error:d,page:u,pageSize:v,hasNextPage:u<k-1,hasPreviousPage:u>0,setPage:b,setPageSize:T=>{m(T),b(0)},refetch:f,deleteSubmission:x}}var Ni=le(require("react"),1),oc=require("lucide-react");var wr=le(require("react"),1),ea=le(require("@radix-ui/react-dialog"),1),rc=require("lucide-react");var Ea=require("react/jsx-runtime"),cn=ea.Root;var ju=ea.Portal;var ic=wr.forwardRef(({className:e,...t},a)=>(0,Ea.jsx)(ea.Overlay,{ref:a,className:Q("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));ic.displayName=ea.Overlay.displayName;var qa=wr.forwardRef(({className:e,children:t,...a},s)=>(0,Ea.jsx)(ju,{children:(0,Ea.jsxs)("div",{className:"aifeatures-admin",children:[(0,Ea.jsx)(ic,{}),(0,Ea.jsxs)(ea.Content,{ref:s,className:Q("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...a,children:[t,(0,Ea.jsxs)(ea.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[(0,Ea.jsx)(rc.X,{className:"af-h-4 af-w-4"}),(0,Ea.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));qa.displayName=ea.Content.displayName;var Wa=({className:e,...t})=>(0,Ea.jsx)("div",{className:Q("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Wa.displayName="DialogHeader";var Ga=({className:e,...t})=>(0,Ea.jsx)("div",{className:Q("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ga.displayName="DialogFooter";var Ka=wr.forwardRef(({className:e,...t},a)=>(0,Ea.jsx)(ea.Title,{ref:a,className:Q("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Ka.displayName=ea.Title.displayName;var Za=wr.forwardRef(({className:e,...t},a)=>(0,Ea.jsx)(ea.Description,{ref:a,className:Q("af-text-sm af-text-muted-foreground",e),...t}));Za.displayName=ea.Description.displayName;var va=require("react/jsx-runtime");function Zs({onDelete:e,iconOnly:t}){let[a,s]=Ni.useState(!1),[n,r]=Ni.useState(!1),[i,l]=Ni.useState(null);return(0,va.jsxs)(va.Fragment,{children:[(0,va.jsxs)(y,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{l(null),s(!0)},children:[(0,va.jsx)(oc.Trash2,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),(0,va.jsx)(cn,{open:a,onOpenChange:d=>{!d&&!n&&s(!1)},children:(0,va.jsxs)(qa,{children:[(0,va.jsxs)(Wa,{children:[(0,va.jsx)(Ka,{children:"Delete this submission?"}),(0,va.jsx)(Za,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),i&&(0,va.jsx)("p",{className:"af-text-sm af-text-destructive",children:i}),(0,va.jsxs)(Ga,{children:[(0,va.jsx)(y,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),(0,va.jsx)(y,{variant:"destructive",onClick:async()=>{r(!0),l(null);try{await e(),s(!1)}catch(d){l(d instanceof Error?d.message:"Failed to delete submission")}finally{r(!1)}},disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}var cc=le(require("react"),1),ba=require("lucide-react");var Le=require("react/jsx-runtime");function lc(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function qu(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 Sr({submission:e,onBack:t,onDelete:a}){let{api:s}=G(),[n,r]=cc.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(0,Le.jsxs)("div",{children:[(0,Le.jsxs)("div",{className:"af-mb-6",children:[(0,Le.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,Le.jsx)(ba.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,Le.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Le.jsxs)("div",{children:[(0,Le.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,Le.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",lc(e.metadata.submitted_at)]})]}),a&&(0,Le.jsx)(Zs,{onDelete:a})]})]}),(0,Le.jsxs)("div",{className:"af-space-y-6",children:[(0,Le.jsx)(Dn,{deliveries:e.email_deliveries}),(0,Le.jsxs)("div",{children:[(0,Le.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,Le.jsxs)("div",{className:"af-space-y-3",children:[c.map(([d,o])=>(0,Le.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,Le.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:d.replace(/_/g," ")}),(0,Le.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof o=="string"&&o.includes(`
3
- `)?(0,Le.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:o}):String(o)})]},d)),c.length===0&&(0,Le.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,Le.jsxs)("div",{children:[(0,Le.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,Le.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((d,o)=>(0,Le.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Le.jsx)(ba.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,Le.jsx)("span",{className:"af-text-sm",children:d.name}),(0,Le.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",qu(d.size),")"]})]}),(0,Le.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>l(d),disabled:n===i(d),children:[n===i(d)?(0,Le.jsx)(ba.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Le.jsx)(ba.Download,{className:"af-h-4 af-w-4 af-mr-1"}),n===i(d)?"Downloading...":"Download"]})]},o))})]}),(0,Le.jsxs)("div",{children:[(0,Le.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,Le.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Le.jsx)(ba.Clock,{className:"af-h-4 af-w-4"}),(0,Le.jsx)("span",{children:lc(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Le.jsx)(ba.Globe,{className:"af-h-4 af-w-4"}),(0,Le.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,Le.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,Le.jsx)(ba.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,Le.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Le.jsx)(ba.Mail,{className:"af-h-4 af-w-4"}),(0,Le.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var uc=require("lucide-react");var Rs=le(require("react"),1);var Wu=/^\+[1-9]\d{1,14}$/;function dc(e){let t=e==null?"":String(e),a=!Wu.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 Ri(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function _i(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 Nr({fetchCsv:e,filename:t}){let[a,s]=Rs.useState(!1),[n,r]=Rs.useState(null),i=Rs.useRef(!1);return{exportCsv:Rs.useCallback(async()=>{if(!i.current){i.current=!0,s(!0),r(null);try{let c=await e();_i(c,Ri(t))}catch(c){r(c instanceof Error?c:new Error("Export failed"))}finally{i.current=!1,s(!1)}}},[e,t]),exporting:a,error:n}}var Ys=require("react/jsx-runtime");function ma({fetchCsv:e,filename:t,label:a="Export CSV",disabled:s,className:n}){let{exportCsv:r,exporting:i,error:l}=Nr({fetchCsv:e,filename:t});return(0,Ys.jsxs)("span",{className:n,children:[(0,Ys.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||i,"aria-busy":i,children:[(0,Ys.jsx)(uc.Download,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Exporting\u2026":a]}),l&&(0,Ys.jsx)("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}var Re=require("react/jsx-runtime");function Gu(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Ku(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 Zu=["message","comments","comment","inquiry","question","details","body","notes"];function Yu(e){let t=Object.entries(e).filter(([r,i])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof i=="string"&&i.trim()),a=new Map(t.map(([r,i])=>[r.toLowerCase(),i])),n=(Zu.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 Rr({formId:e,className:t,defaultSubmissionId:a,submissionId:s,onSelectSubmission:n}){let{api:r}=G(),{submissions:i,total:l,isLoading:c,error:d,page:o,pageSize:u,hasNextPage:b,hasPreviousPage:v,setPage:m,setPageSize:p,deleteSubmission:f}=xr({formId:e}),g=us.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[x,k]=us.useState(a??null),T=n?s??null:x,h=n??k,P=q=>!!q&&q.id===T&&q.form_id===e,_=i.find(P),[E,w]=us.useState(null),I=P(E)?E:null,[O,C]=us.useState(null);if(us.useEffect(()=>{if(C(null),!T||_||I)return;let q=!1;return r.getSubmission(T).then(de=>{if(!q){if(de.form_id!==e){C("This submission could not be found.");return}w(de)}}).catch(()=>{q||C("This submission could not be found.")}),()=>{q=!0}},[r,e,T,_,I]),T){let q=_??I;return q?(0,Re.jsx)("div",{className:t,children:(0,Re.jsx)(Sr,{submission:q,onBack:()=>h(null),onDelete:async()=>{await f(q.id),h(null)}})}):O?(0,Re.jsxs)("div",{className:t,children:[(0,Re.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>h(null),className:"af-mb-2 af--ml-2",children:[(0,Re.jsx)(dn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,Re.jsx)("p",{className:"af-text-sm af-text-destructive",children:O})]}):(0,Re.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Re.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(c)return(0,Re.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Re.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(d)return(0,Re.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Re.jsxs)("div",{className:"af-text-destructive",children:["Error: ",d.message]})});if(i.length===0&&o===0)return(0,Re.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,Re.jsx)(dn.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Re.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,Re.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let Y=o*u+1,X=Math.min((o+1)*u,l);return(0,Re.jsxs)("div",{className:t,children:[(0,Re.jsx)("div",{className:"af-mb-2 af-flex af-justify-end",children:(0,Re.jsx)(ma,{fetchCsv:g,filename:"submissions"})}),(0,Re.jsxs)(ut,{children:[(0,Re.jsx)(ft,{children:(0,Re.jsxs)($e,{children:[(0,Re.jsx)(te,{children:"Email"}),(0,Re.jsx)(te,{children:"Preview"}),(0,Re.jsx)(te,{children:"Date"}),(0,Re.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,Re.jsx)(mt,{children:i.map(q=>{let de=Ku(q.data),ge=Yu(q.data);return(0,Re.jsxs)($e,{children:[(0,Re.jsxs)(ae,{className:"af-font-medium",children:[(0,Re.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[de||(0,Re.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),q.attachments.length>0&&(0,Re.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${q.attachments.length} attachment(s)`,children:[(0,Re.jsx)(dn.Paperclip,{className:"af-h-3 af-w-3"}),(0,Re.jsx)("span",{className:"af-text-xs",children:q.attachments.length})]})]}),(0,Re.jsx)(yr,{deliveries:q.email_deliveries,label:"Notification email needs attention"})]}),(0,Re.jsx)(ae,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:ge||(0,Re.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,Re.jsx)(ae,{className:"af-text-muted-foreground",children:Gu(q.metadata.submitted_at)}),(0,Re.jsxs)(ae,{className:"af-text-right",children:[(0,Re.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>h(q.id),title:"View details",children:(0,Re.jsx)(dn.Eye,{className:"af-h-4 af-w-4"})}),(0,Re.jsx)(Zs,{iconOnly:!0,onDelete:()=>f(q.id)})]})]},q.id)})})]}),(0,Re.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,Re.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Re.jsxs)("span",{children:["Showing ",Y,"-",X," of ",l]}),(0,Re.jsxs)(on,{value:String(u),onValueChange:q=>p(Number(q)),children:[(0,Re.jsx)(za,{className:"af-w-[70px] af-h-8",children:(0,Re.jsx)(ln,{})}),(0,Re.jsxs)(ja,{children:[(0,Re.jsx)(kt,{value:"10",children:"10"}),(0,Re.jsx)(kt,{value:"25",children:"25"}),(0,Re.jsx)(kt,{value:"50",children:"50"}),(0,Re.jsx)(kt,{value:"100",children:"100"})]})]}),(0,Re.jsx)("span",{children:"per page"})]}),(0,Re.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Re.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>m(o-1),disabled:!v,children:[(0,Re.jsx)(dn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,Re.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>m(o+1),disabled:!b,children:["Next",(0,Re.jsx)(dn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ja=le(require("react"),1),fs=require("lucide-react");var fc=le(require("react"),1);var mc=require("react/jsx-runtime"),ce=fc.forwardRef(({className:e,type:t,...a},s)=>(0,mc.jsx)("input",{type:t,className:Q("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...a}));ce.displayName="Input";var pc=le(require("react"),1),gc=require("class-variance-authority");var vc=require("react/jsx-runtime"),Ju=(0,gc.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),qe=pc.forwardRef(({className:e,...t},a)=>(0,vc.jsx)("label",{ref:a,className:Q(Ju(),e),...t}));qe.displayName="Label";var un=le(require("react"),1),ha=require("lucide-react");var Ya=le(require("react"),1);function _r(){let{api:e}=G(),[t,a]=Ya.useState([]),[s,n]=Ya.useState(!0),[r,i]=Ya.useState(null),l=Ya.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]);Ya.useEffect(()=>{l()},[l]);let c=Ya.useCallback(async v=>{let m=await e.createEventDestination(v);return a(p=>[m,...p]),m},[e]),d=Ya.useCallback(async(v,m)=>{let p=await e.updateEventDestination(v,m);return a(f=>f.map(g=>g.id===v?p:g)),p},[e]),o=Ya.useCallback(async v=>{await e.deleteEventDestination(v),a(m=>m.filter(p=>p.id!==v))},[e]),u=Ya.useCallback(async v=>{let m=await e.rotateEventDestinationSecret(v);return a(p=>p.map(f=>f.id===v?m:f)),m},[e]),b=Ya.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}}var Kn=le(require("react"),1),kr=require("lucide-react");var ta=require("react/jsx-runtime");function Pr({destinationId:e,limit:t=25,className:a}){let{api:s}=G(),[n,r]=Kn.useState([]),[i,l]=Kn.useState(!0),[c,d]=Kn.useState(null),[o,u]=Kn.useState(null),b=Kn.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]);Kn.useEffect(()=>{b()},[b]);let v=async m=>{try{u(m.id),d(null);let p=await s.retryEventDelivery(e,m.id);r(f=>f.map(g=>g.id===m.id?p:g))}catch(p){d(p instanceof Error?p.message:"Retry failed")}finally{u(null)}};return i?(0,ta.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,ta.jsx)(kr.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):c?(0,ta.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:c}):n.length===0?(0,ta.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):(0,ta.jsx)("div",{className:a,children:(0,ta.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(m=>{let p=m.delivered_at!==null;return(0,ta.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,ta.jsxs)("div",{className:"af-min-w-0",children:[(0,ta.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[p?(0,ta.jsx)(ie,{variant:"secondary",children:m.last_status??200}):(0,ta.jsx)(ie,{variant:"destructive",children:m.last_status??"failed"}),(0,ta.jsx)("span",{className:"af-text-sm af-truncate",children:m.type})]}),(0,ta.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[m.event_id," \xB7 ",m.created_at,m.attempts>0&&` \xB7 ${m.attempts} failed ${m.attempts===1?"attempt":"attempts"}`]}),!p&&m.last_error&&(0,ta.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:m.last_error})]}),(0,ta.jsx)(y,{variant:"ghost",size:"sm",title:"Send this event again",disabled:o===m.id,onClick:()=>v(m),children:o===m.id?(0,ta.jsx)(kr.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,ta.jsx)(kr.RotateCw,{className:"af-h-4 af-w-4"})})]},m.id)})})})}var Ee=require("react/jsx-runtime");function Cr({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}=_r(),[b,v]=un.useState(""),[m,p]=un.useState(!1),[f,g]=un.useState(null),[x,k]=un.useState(null),[T,h]=un.useState(null),[P,_]=un.useState(!1),[E,w]=un.useState(null),[I,O]=un.useState(null),[C,Y]=un.useState(null),X=un.useMemo(()=>n.filter(B=>B.form_id===e),[n,e]),q=async()=>{let B=b.trim();if(B){if(!B.startsWith("https://")){g("Webhook URLs must start with https://");return}try{p(!0),g(null),await l({url:B,form_id:e,...t&&t.length>0?{topics:t}:{}}),v("")}catch(ue){g(ue instanceof Error?ue.message:"Failed to add webhook")}finally{p(!1)}}},de=async B=>{try{O(B.id),g(null),await o(B.id),_(!1),h(await u(B.id))}catch(ue){g(ue instanceof Error?ue.message:"Failed to rotate secret")}finally{O(null)}},ge=async B=>{try{O(B.id),g(null),await c(B.id,{status:"active"})}catch(ue){g(ue instanceof Error?ue.message:"Failed to re-enable")}finally{O(null)}},ye=async()=>{if(E)try{O(E.id),await d(E.id),w(null)}catch(B){g(B instanceof Error?B.message:"Failed to delete")}finally{O(null)}},D=async B=>{if(x===B.id){k(null),h(null);return}try{O(B.id),g(null),_(!1),k(B.id),h(await u(B.id))}catch(ue){k(null),g(ue instanceof Error?ue.message:"Failed to read secret")}finally{O(null)}},W=async()=>{if(T)try{await navigator.clipboard.writeText(T),_(!0)}catch{}};return(0,Ee.jsxs)("div",{className:s,children:[(0,Ee.jsxs)("div",{className:"af-space-y-1",children:[(0,Ee.jsx)(qe,{children:"Webhooks"}),(0,Ee.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:a??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),(0,Ee.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,Ee.jsx)(ce,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:B=>v(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),q())},disabled:m}),(0,Ee.jsxs)(y,{onClick:q,disabled:m||!b.trim(),children:[m?(0,Ee.jsx)(ha.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ee.jsx)(ha.Plus,{className:"af-h-4 af-w-4"}),(0,Ee.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(f||i)&&(0,Ee.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:f||i?.message}),(0,Ee.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[r&&(0,Ee.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Ee.jsx)(ha.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&X.length===0&&(0,Ee.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),X.map(B=>(0,Ee.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,Ee.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Ee.jsxs)("div",{className:"af-min-w-0",children:[(0,Ee.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Ee.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:B.url}),B.status==="disabled"?(0,Ee.jsx)(ie,{variant:"destructive",children:"Disabled"}):(0,Ee.jsx)(ie,{variant:"secondary",children:"Active"})]}),(0,Ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:B.topics.includes("*")?"All events":B.topics.join(", ")})]}),(0,Ee.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,Ee.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>Y(C===B.id?null:B.id),children:C===B.id?"Hide log":"Deliveries"}),(0,Ee.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>D(B),disabled:I===B.id,children:x===B.id?"Hide secret":"Show secret"}),(0,Ee.jsx)(y,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:I===B.id,onClick:()=>w(B),children:(0,Ee.jsx)(ha.Trash2,{className:"af-h-4 af-w-4"})})]})]}),B.status==="disabled"&&(0,Ee.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[(0,Ee.jsx)(ha.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,Ee.jsxs)("div",{className:"af-text-sm",children:[(0,Ee.jsxs)("p",{children:["We stopped sending after repeated failures."," ",B.disabled_reason]}),(0,Ee.jsx)(y,{variant:"outline",size:"sm",className:"af-mt-2",disabled:I===B.id,onClick:()=>ge(B),children:"Re-enable"})]})]}),x===B.id&&T&&(0,Ee.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,Ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Optional. Use this if you want your endpoint to check that a delivery really came from us. Rotating replaces it."}),(0,Ee.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ee.jsx)(ce,{readOnly:!0,value:T,className:"af-font-mono"}),(0,Ee.jsx)(y,{variant:"outline",title:"Copy signing secret",onClick:W,children:P?(0,Ee.jsx)(ha.Check,{className:"af-h-4 af-w-4"}):(0,Ee.jsx)(ha.Copy,{className:"af-h-4 af-w-4"})}),(0,Ee.jsx)(y,{variant:"outline",title:"Rotate signing secret",disabled:I===B.id,onClick:()=>de(B),children:I===B.id?(0,Ee.jsx)(ha.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ee.jsx)(ha.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),C===B.id&&(0,Ee.jsx)(Pr,{destinationId:B.id})]},B.id))]}),(0,Ee.jsx)(cn,{open:!!E,onOpenChange:B=>{!B&&!I&&w(null)},children:(0,Ee.jsxs)(qa,{children:[(0,Ee.jsxs)(Wa,{children:[(0,Ee.jsx)(Ka,{children:"Delete this webhook?"}),(0,Ee.jsxs)(Za,{children:["New submissions will stop being sent to ",E?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),(0,Ee.jsxs)(Ga,{children:[(0,Ee.jsx)(y,{variant:"outline",onClick:()=>w(null),disabled:!!I,children:"Cancel"}),(0,Ee.jsx)(y,{variant:"destructive",onClick:ye,disabled:!!I,children:I?"Deleting...":"Delete"})]})]})})]})}var je=require("react/jsx-runtime");function Tr({form:e,onSaved:t,className:a}){let{updateForm:s}=Ss(),[n,r]=Ja.useState(!1),[i,l]=Ja.useState(null),[c,d]=Ja.useState(null),[o,u]=Ja.useState(e.name),[b,v]=Ja.useState(e.redirect_url||""),[m,p]=Ja.useState(e.email_recipients),[f,g]=Ja.useState("");Ja.useEffect(()=>{u(e.name),v(e.redirect_url||""),p(e.email_recipients),d(null)},[e]);let x=Ja.useCallback(async _=>{try{r(!0),d(null);let E=await s(e.id,_);l(new Date),t?.(E)}catch(E){d(E instanceof Error?E.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);Ja.useEffect(()=>{if(i){let _=setTimeout(()=>l(null),2e3);return()=>clearTimeout(_)}},[i]);let k=async()=>{let _=f.trim().toLowerCase();if(!_)return;if(!_.includes("@")){d("Please enter a valid email address");return}if(m.includes(_)){d("This email is already added");return}let E=[...m,_];p(E),g(""),d(null),await x({email_recipients:E})},T=async _=>{let E=m.filter(w=>w!==_);p(E),await x({email_recipients:E})},h=async()=>{o!==e.name&&await x({name:o})},P=async()=>{let _=b||null;_!==e.redirect_url&&await x({redirect_url:_})};return(0,je.jsxs)("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(n||i)&&(0,je.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,je.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-background af-border af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,je.jsx)(fs.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,je.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,je.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-green-50 af-border af-border-green-200 af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,je.jsx)(fs.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,je.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,je.jsxs)("div",{className:"af-space-y-2",children:[(0,je.jsx)(qe,{htmlFor:"form-name",children:"Form Name"}),(0,je.jsx)(ce,{id:"form-name",value:o,onChange:_=>u(_.target.value),onBlur:h,placeholder:"Contact Form"}),(0,je.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,je.jsxs)("div",{className:"af-space-y-2",children:[(0,je.jsx)(qe,{children:"Email Recipients"}),(0,je.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,je.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[m.map(_=>(0,je.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[_,(0,je.jsx)("button",{type:"button",onClick:()=>T(_),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,je.jsx)(fs.X,{className:"af-h-3 af-w-3"})})]},_)),m.length===0&&(0,je.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,je.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,je.jsx)(ce,{type:"email",value:f,onChange:_=>g(_.target.value),placeholder:"Add email address",onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),k())},disabled:n}),(0,je.jsx)(y,{type:"button",variant:"outline",onClick:k,disabled:!f.trim()||n,children:(0,je.jsx)(fs.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,je.jsxs)("div",{className:"af-space-y-2",children:[(0,je.jsx)(qe,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,je.jsx)(ce,{id:"redirect-url",value:b,onChange:_=>v(_.target.value),onBlur:P,placeholder:"/thank-you"}),(0,je.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Where to send visitors after a successful submission. Use a site path (/thank-you) or a full URL (https://example.com/thank-you). Leave empty for a default success page."})]}),(0,je.jsxs)("div",{className:"af-space-y-2",children:[(0,je.jsx)(qe,{children:"Form Endpoint"}),(0,je.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,je.jsx)("code",{className:"af-flex-1 af-text-xs af-bg-muted af-px-3 af-py-2 af-rounded af-border",children:e.endpoint_url})}),(0,je.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,je.jsxs)("div",{className:"af-space-y-2",children:[(0,je.jsx)(qe,{children:"Captcha Protection"}),(0,je.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,je.jsx)(ie,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,je.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,je.jsx)(Cr,{formId:e.id}),c&&(0,je.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c})]})}var xt=require("react/jsx-runtime");function Co({className:e,location:t,onNavigate:a,submissionId:s}){let{api:n}=G(),[r,i]=Zn.useState({submissionId:s});Zn.useEffect(()=>{s&&i({submissionId:s})},[s]);let l=a?t??{}:r,c=a??i,[d,o]=Zn.useState(null),u=`${l.formId??""}|${l.submissionId??""}`,[b,v]=Zn.useState(null),m=b?.key===u?b.message:null,p=l.formId??(d&&d.submissionId===l.submissionId?d.formId:void 0);Zn.useEffect(()=>{let _=l.submissionId;if(!_||l.formId)return;let E=!1;return n.getSubmission(_).then(w=>{E||(v(null),o({submissionId:_,formId:w.form_id}))}).catch(()=>{E||v({key:u,message:"This submission could not be found."})}),()=>{E=!0}},[n,l.submissionId,l.formId,u]);let[f,g]=Zn.useState(null);Zn.useEffect(()=>{if(!p||f?.id===p)return;let _=!1;return n.getForm(p).then(E=>{_||(v(null),g(E))}).catch(()=>{_||v({key:u,message:"This form could not be found."})}),()=>{_=!0}},[n,p,f?.id,u]);let x=(_,E)=>{g(_),c({formId:_.id,tab:E})},k=()=>c({});if(!l.formId&&!l.submissionId)return(0,xt.jsxs)("div",{className:e,children:[(0,xt.jsxs)("div",{className:"af-mb-6",children:[(0,xt.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,xt.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,xt.jsx)(hr,{onSelectForm:x})]});let h=(0,xt.jsxs)(y,{variant:"ghost",size:"sm",onClick:k,className:"af-mb-2 af--ml-2",children:[(0,xt.jsx)(Js.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(m)return(0,xt.jsxs)("div",{className:e,children:[h,(0,xt.jsx)("p",{className:"af-text-sm af-text-destructive",children:m})]});if(!p||f?.id!==p)return(0,xt.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,xt.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let P=l.submissionId?"submissions":l.tab??"submissions";return(0,xt.jsxs)("div",{className:e,children:[(0,xt.jsxs)("div",{className:"af-mb-6",children:[h,(0,xt.jsx)("h2",{className:"af-text-lg af-font-semibold",children:f.name})]}),(0,xt.jsxs)(xi,{value:P,onValueChange:_=>c({formId:p,tab:_}),children:[(0,xt.jsxs)(vr,{className:"af-mb-4",children:[(0,xt.jsxs)(Sn,{value:"submissions",className:"af-gap-2",children:[(0,xt.jsx)(Js.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,xt.jsxs)(Sn,{value:"settings",className:"af-gap-2",children:[(0,xt.jsx)(Js.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,xt.jsx)(Nn,{value:"submissions",children:(0,xt.jsx)(Rr,{formId:p,submissionId:l.submissionId,onSelectSubmission:_=>c({formId:p,tab:"submissions",submissionId:_??void 0})})}),(0,xt.jsx)(Nn,{value:"settings",children:(0,xt.jsx)(Tr,{form:f,onSaved:g})})]})]})}var ct=le(require("react"),1);var On=le(require("react"),1);function Yn(){let{api:e}=G(),[t,a]=On.useState(null),[s,n]=On.useState(!0),[r,i]=On.useState(null),l=On.useRef(0),c=On.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 On.useEffect(()=>{c()},[c]),{status:t,isLoading:s,error:r,refetch:c}}var Xu=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Xa(e){return Xu.has(e.toLowerCase())}function se(e,t,a){let s=Xa(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Ln(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 oa(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=Xa(t)?a:a*100;return Math.round(s)}function Et(e,t){return Xa(t)?e:e/100}function ki(e){return e.amount_paid??Math.max(0,Ln(e)-(e.credit_applied??0))}var Se=require("react/jsx-runtime");function Er(e){return e instanceof Gt&&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 bc(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${se(e.amount_off,e.currency)} off`:"Discount unavailable"}function _s(){let{api:e,siteToken:t}=G();return(0,Se.jsx)(Qu,{api:e},t)}function Qu({api:e}){let{status:t,error:a}=Yn(),[s,n]=ct.useState([]),[r,i]=ct.useState(null),[l,c]=ct.useState(null),[d,o]=ct.useState(!1),[u,b]=ct.useState(!1),[v,m]=ct.useState(""),[p,f]=ct.useState(null),[g,x]=ct.useState(null),[k,T]=ct.useState(!1),h=ct.useRef(0),P=ct.useCallback(async w=>{let I=++h.current;o(!0),m("");try{let O=await e.getPromos(w);if(I!==h.current)return;n(C=>w?[...C,...O.promos.filter(Y=>!C.some(X=>X.id===Y.id))]:O.promos),i(O.next_cursor),c(O.checkout_enabled)}catch(O){I===h.current&&m(Er(O))}finally{I===h.current&&o(!1)}},[e]);ct.useEffect(()=>(P(),()=>{h.current++}),[P]);async function _(w){let I=++h.current;o(!0),m(""),T(!1);try{let O=await e.getPromo(w);I===h.current&&f(O)}catch(O){I===h.current&&m(Er(O))}finally{I===h.current&&o(!1)}}async function E(){if(p){b(!0),o(!0),m("");try{let w=await e.disablePromo(p.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.");T(!1),await P()}catch(w){m(Er(w))}finally{b(!1),o(!1)}}}return g?(0,Se.jsx)(ef,{currency:t?.currency??void 0,replaces:g.replaces,onCancel:()=>x(null),onSave:async w=>{let I=g.replaces?await e.replacePromo(g.replaces.id,w):await e.createPromo(w),O=await e.getPromo(I.id);if(O.status==="pending"||O.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");f(O),x(null),await P()}}):(0,Se.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,Se.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,Se.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,Se.jsx)(y,{disabled:d||!t?.currency,onClick:()=>{m(""),x({})},children:"Create promo code"})]}),(0,Se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),l===!1&&(0,Se.jsx)("p",{role:"status",className:"af-rounded-md af-border af-p-3 af-text-sm",children:"Checkout code entry is not enabled yet. You can prepare codes, but buyers cannot enter them in our checkout until it is enabled."}),!t?.currency&&(0,Se.jsx)("p",{className:"af-text-sm",children:a?Er(a):"Connect Stripe and set the payment currency before creating codes."}),v&&(0,Se.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[v," ",(0,Se.jsx)(y,{variant:"outline",disabled:d,onClick:()=>p?void _(p.id):void P(),children:"Refresh"})]}),p?(0,Se.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,Se.jsx)(y,{variant:"ghost",disabled:u,onClick:()=>{f(null),T(!1),P()},children:"Back to codes"}),(0,Se.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[p.code," \xB7 ",p.name]}),(0,Se.jsxs)("p",{children:[bc(p)," \xB7 ",p.status]}),(0,Se.jsxs)("p",{className:"af-text-sm",children:[p.times_redeemed==null?"Usage unavailable":`${p.times_redeemed} redemptions`,p.max_redemptions!=null?` / ${p.max_redemptions} maximum`:""]}),(0,Se.jsxs)("p",{className:"af-text-sm",children:[p.minimum_amount!=null&&p.currency?`Minimum order: ${se(p.minimum_amount,p.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,Se.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",p.duration==="repeating"?`${p.duration_in_months} months`:p.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,Se.jsx)("p",{className:"af-text-sm",children:p.expires_at?`Expires ${new Date(p.expires_at).toLocaleString()}`:"No expiry"}),(0,Se.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,Se.jsx)(y,{variant:"outline",disabled:d,onClick:()=>void _(p.id),children:"Refresh details"}),(0,Se.jsx)(y,{variant:"outline",disabled:d||p.status==="pending"||p.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:p}),children:"Replace with new code"}),(0,Se.jsx)(y,{variant:"outline",disabled:d||!["active","pending","unavailable"].includes(p.status),onClick:()=>T(!0),children:p.status==="pending"?"Cancel pending offer":"Disable code"})]}),k&&(0,Se.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,Se.jsxs)("p",{className:"af-text-sm",children:[p.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${p.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,Se.jsx)(y,{disabled:d,onClick:()=>void E(),children:p.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,Se.jsx)(y,{variant:"ghost",disabled:d,onClick:()=>T(!1),children:"Cancel"})]})]}):(0,Se.jsxs)(Se.Fragment,{children:[s.map(w=>(0,Se.jsxs)("button",{type:"button",disabled:d,onClick:()=>void _(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:[(0,Se.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,Se.jsx)("span",{className:"af-font-semibold af-break-all",children:w.code}),(0,Se.jsx)("span",{className:"af-text-sm",children:w.status})]}),(0,Se.jsxs)("div",{className:"af-text-sm",children:[bc(w)," \xB7"," ",w.times_redeemed==null?"Usage unavailable":`${w.times_redeemed} redemptions`]})]},w.id)),!d&&!v&&s.length===0&&(0,Se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),d&&(0,Se.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),r&&(0,Se.jsx)(y,{variant:"outline",disabled:d,onClick:()=>void P(r),children:"Load more"})]})]})}function ef({currency:e,replaces:t,onCancel:a,onSave:s}){let[n,r]=ct.useState(""),[i,l]=ct.useState(t?.name??""),[c,d]=ct.useState(t?.amount_off!=null?"fixed":"percent"),[o,u]=ct.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(Et(t.amount_off,e)):"")),[b,v]=ct.useState(t?.minimum_amount!=null&&e?String(Et(t.minimum_amount,e)):""),[m,p]=ct.useState(()=>{if(!t?.expires_at)return"";let ge=new Date(t.expires_at);return Number.isFinite(ge.getTime())?new Date(ge.getTime()-ge.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[f,g]=ct.useState(t?.max_redemptions?.toString()??""),[x,k]=ct.useState(t?.duration??"once"),[T,h]=ct.useState(t?.duration_in_months?.toString()??"3"),[P,_]=ct.useState(null),[E,w]=ct.useState(!1),[I,O]=ct.useState(""),C=ct.useRef(!1),Y=e&&Xa(e)?"1":"0.01";async function X(ge){if(ge.preventDefault(),C.current)return;O("");let ye=P;if(!ye){if(!e){O("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){O("Choose a different code for the replacement.");return}let D=oa(o,e),W=b?oa(b,e):null;if(c==="fixed"&&(!D||D>999999999999)||b&&(!W||W>999999999999)){O("Enter a positive amount within the supported range.");return}if(m&&new Date(m).getTime()<=Date.now()){O("Choose a future expiry.");return}ye={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:i.trim(),duration:x,...c==="percent"?{percent_off:Number(o)}:{amount_off:D,currency:e},...b?{minimum_amount:W,currency:e}:{},...m?{expires_at:new Date(m).toISOString()}:{},...f?{max_redemptions:Number(f)}:{},...x==="repeating"?{duration_in_months:Number(T)}:{}},_(ye)}C.current=!0,w(!0);try{await s(ye)}catch(D){O(Er(D)),D instanceof Gt&&D.status>=400&&D.status<500&&D.details?.retryable!==!0&&_(null)}finally{C.current=!1,w(!1)}}let q=(ge,ye,D,W={})=>(0,Se.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[ge,(0,Se.jsx)(ce,{"aria-label":ge,value:ye,onChange:B=>D(B.target.value),...W})]}),de="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,Se.jsxs)("form",{onSubmit:X,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,Se.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,Se.jsx)("p",{className:"af-text-sm",children:"Use a different code. The old code will be disabled only after the replacement is created. Existing subscription discounts continue."}),(0,Se.jsxs)("fieldset",{disabled:E||!!P,className:"af-grid af-gap-4",children:[q("Code",n,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),q("Name",i,l,{required:!0,maxLength:40}),(0,Se.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,Se.jsxs)("select",{"aria-label":"Discount type",className:de,value:c,onChange:ge=>d(ge.target.value),children:[(0,Se.jsx)("option",{value:"percent",children:"Percentage"}),(0,Se.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),q("Discount",o,u,{type:"number",required:!0,min:c==="percent"?"0.01":Y,max:c==="percent"?"100":void 0,step:c==="percent"?"0.01":Y}),q("Minimum order amount",b,v,{type:"number",min:Y,step:Y,placeholder:e?.toUpperCase()}),(0,Se.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),q("Expires at (local time)",m,p,{type:"datetime-local",step:1}),q("Maximum redemptions",f,g,{type:"number",min:1,max:1e6,step:1}),(0,Se.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,Se.jsxs)("select",{"aria-label":"Subscription duration",className:de,value:x,onChange:ge=>k(ge.target.value),children:[(0,Se.jsx)("option",{value:"once",children:"First invoice only"}),(0,Se.jsx)("option",{value:"forever",children:"Every invoice"}),(0,Se.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&q("Months",T,h,{type:"number",required:!0,min:1,max:36,step:1})]}),I&&(0,Se.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:I}),P&&!E&&(0,Se.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,Se.jsx)("span",{className:"af-break-all",children:P.request_id})]}),(0,Se.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,Se.jsx)(y,{type:"submit",disabled:E,children:E?"Saving\u2026":P?"Retry same request":t?"Create replacement":"Create code"}),(0,Se.jsx)(y,{type:"button",variant:"ghost",disabled:E||!!P,onClick:a,children:"Cancel"})]})]})}var nr=le(require("react"),1),gn=require("lucide-react");var Pi=le(require("react"),1),Jn=require("lucide-react");var Fe=require("react/jsx-runtime");function tf(e){if(e.allow_custom_amount){let t=e.min_amount!==null?se(e.min_amount,e.currency):"?",a=e.max_amount!==null?se(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":se(e.unit_amount,e.currency)}function af(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Ir({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:n,isLoading:r,error:i,deleteProduct:l}=e,[c,d]=Pi.useState(null),[o,u]=Pi.useState(!1),[b,v]=Pi.useState(null),m=async()=>{if(c)try{u(!0),v(null),await l(c.id),d(null)}catch(p){v(p instanceof Error?p.message:"Failed to delete product")}finally{u(!1)}};return r?(0,Fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Fe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):i?(0,Fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Fe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i.message]})}):n.length===0?(0,Fe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[(0,Fe.jsx)(Jn.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Fe.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,Fe.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,Fe.jsxs)(y,{variant:"outline",onClick:()=>a?.(),children:[(0,Fe.jsx)(Jn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,Fe.jsxs)("div",{className:s,children:[(0,Fe.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,Fe.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[(0,Fe.jsx)(Jn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,Fe.jsxs)(ut,{children:[(0,Fe.jsx)(ft,{children:(0,Fe.jsxs)($e,{children:[(0,Fe.jsx)(te,{children:"Name"}),(0,Fe.jsx)(te,{children:"Price"}),(0,Fe.jsx)(te,{children:"Fulfillment"}),(0,Fe.jsx)(te,{children:"Status"}),(0,Fe.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,Fe.jsx)(mt,{children:n.map(p=>(0,Fe.jsxs)($e,{children:[(0,Fe.jsx)(ae,{className:"af-font-medium",children:p.name}),(0,Fe.jsx)(ae,{children:tf(p)}),(0,Fe.jsx)(ae,{className:"af-text-muted-foreground",children:af(p)}),(0,Fe.jsx)(ae,{children:(0,Fe.jsx)(ie,{variant:p.active?"success":"secondary",children:p.active?"Active":"Inactive"})}),(0,Fe.jsx)(ae,{className:"af-text-right",children:(0,Fe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Fe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>t?.(p),children:[(0,Fe.jsx)(Jn.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,Fe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>{v(null),d(p)},children:[(0,Fe.jsx)(Jn.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},p.id))})]}),(0,Fe.jsx)(cn,{open:!!c,onOpenChange:p=>{!p&&!o&&d(null)},children:(0,Fe.jsxs)(qa,{children:[(0,Fe.jsxs)(Wa,{children:[(0,Fe.jsx)(Ka,{children:"Delete product?"}),(0,Fe.jsxs)(Za,{children:['"',c?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&(0,Fe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),(0,Fe.jsxs)(Ga,{children:[(0,Fe.jsx)(y,{variant:"outline",onClick:()=>d(null),disabled:o,children:"Cancel"}),(0,Fe.jsx)(y,{variant:"destructive",onClick:m,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})}var It=le(require("react"),1),Qa=require("lucide-react");var Kt=le(require("react"),1),fn=require("lucide-react");var M=require("react/jsx-runtime");function To(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Ar({productId:e,currency:t,className:a}){let{api:s}=G(),n=Xa(t)?"1":"0.01",[r,i]=Kt.useState(null),[l,c]=Kt.useState(!0),[d,o]=Kt.useState(null),[u,b]=Kt.useState(null),[v,m]=Kt.useState(!1),p=Kt.useRef(!0);Kt.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);let f=Kt.useCallback(async()=>{try{let L=await s.getProduct(e);if(!p.current)return;i(L)}catch(L){if(!p.current)return;o(L instanceof Error?L.message:"Failed to load product")}finally{p.current&&c(!1)}},[s,e]);Kt.useEffect(()=>{f()},[f]);let g=async L=>{b(null),m(!0);try{await L(),await f()}catch(V){p.current&&b(V instanceof Error?V.message:"Something went wrong")}finally{p.current&&m(!1)}},[x,k]=Kt.useState(""),[T,h]=Kt.useState(""),[P,_]=Kt.useState({}),E=()=>g(async()=>{let L=x.trim(),V=T.split(",").map($=>$.trim()).filter(Boolean);if(!L)throw new Error("Option name is required");if(V.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:L,values:V}),p.current&&(k(""),h(""))}),w=L=>g(async()=>{let V=(P[L.id]??"").trim();if(!V)throw new Error("Enter a value");await s.updateOption(L.id,{add_values:[V]}),p.current&&_($=>({...$,[L.id]:""}))}),I=(L,V)=>g(()=>s.updateOption(L.id,{remove_values:[V]})),O=L=>g(()=>s.deleteOption(L.id)),[C,Y]=Kt.useState(null),[X,q]=Kt.useState(null),[de,ge]=Kt.useState(!1),[ye,D]=Kt.useState(null),W=r?.options??[],B=r?.variants??[],ue=()=>{q(null),Y({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(W.map(L=>[L.id,L.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},me=L=>{q(null);let V=L.inventory?.on_hand??0,$=V<0?"":String(V);Y({variant:L,title:L.title??"",sku:L.sku??"",unitAmount:L.unit_amount!=null?String(Et(L.unit_amount,t)):"",compareAt:L.compare_at_amount!=null?String(Et(L.compare_at_amount,t)):"",active:L.active,optionValues:{},tracked:L.inventory?.tracked??!1,onHand:$,initialOnHand:$,allowBackorder:L.inventory?.allow_backorder??!1})},We=async()=>{if(!C)return;q(null);let L=C.variant?.allow_custom_amount??!1,V=null,$=null;if(!L){if(V=oa(C.unitAmount,t),V===null||V<=0){q("Enter a valid price");return}if(C.compareAt.trim()&&($=oa(C.compareAt,t),$===null||$<=V)){q("Compare-at price must be greater than the price");return}}let xe=C.onHand.trim()!==C.initialOnHand.trim(),H=parseInt(C.onHand,10);if(C.tracked&&xe&&(!Number.isFinite(H)||H<0)){q("On-hand quantity must be zero or more");return}try{if(ge(!0),C.variant)await s.updateVariant(C.variant.id,{title:C.title.trim()||null,sku:C.sku.trim()||null,...L?{}:{unit_amount:V,compare_at_amount:$},active:C.active}),await s.setVariantInventory(C.variant.id,{tracked:C.tracked,on_hand:C.tracked&&xe?H:void 0,allow_backorder:C.allowBackorder});else{let ke={};for(let ze of W){let gt=C.optionValues[ze.id];if(!gt){q(`Choose a ${ze.title}`),ge(!1);return}ke[ze.title]=gt}await s.createVariant(e,{title:C.title.trim()||null,sku:C.sku.trim()||null,unit_amount:V,compare_at_amount:$,active:C.active,option_values:W.length>0?ke:void 0,inventory:C.tracked?{tracked:!0,on_hand:H,allow_backorder:C.allowBackorder}:{tracked:!1,allow_backorder:C.allowBackorder}})}await f(),p.current&&Y(null)}catch(ke){if(p.current&&q(ke instanceof Error?ke.message:"Failed to save variant"),C.variant)try{let ze=await s.getProduct(e);p.current&&i(ze)}catch{}}finally{p.current&&ge(!1)}},Ie=()=>g(async()=>{ye&&(await s.deleteVariant(ye.id),p.current&&D(null))}),He=C?.variant?.allow_custom_amount??!1,et=C?.variant!=null&&C.variant.option_values.length===0&&W.length>0&&!C.variant.active,De=C?.variant?.inventory!=null&&C.variant.inventory.on_hand<0?-C.variant.inventory.on_hand:null;function Ke(L){let V=L.inventory;if(!V||!V.tracked)return(0,M.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let $=V.available??V.on_hand;return $<0?(0,M.jsxs)("span",{children:[-$," backordered"]}):(0,M.jsxs)("span",{children:[$," in stock",V.allow_backorder&&(0,M.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return l?(0,M.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:(0,M.jsx)(fn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):d?(0,M.jsx)("div",{className:a,children:(0,M.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})}):(0,M.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,M.jsxs)("div",{className:"af-space-y-3",children:[(0,M.jsxs)("div",{children:[(0,M.jsx)(qe,{children:"Options"}),(0,M.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),W.length>0&&(0,M.jsx)("div",{className:"af-space-y-3",children:W.map(L=>(0,M.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,M.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,M.jsx)("span",{className:"af-text-sm af-font-medium",children:L.title}),(0,M.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>O(L),disabled:v,children:(0,M.jsx)(fn.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,M.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:L.values.map(V=>(0,M.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[V.value,(0,M.jsx)("button",{type:"button",onClick:()=>I(L,V.value),className:"af-ml-1 hover:af-text-destructive",disabled:v,title:"Remove value",children:(0,M.jsx)(fn.X,{className:"af-h-3 af-w-3"})})]},V.id))}),(0,M.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,M.jsx)(ce,{value:P[L.id]??"",onChange:V=>_($=>({...$,[L.id]:V.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),w(L))},disabled:v}),(0,M.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>w(L),disabled:v||!(P[L.id]??"").trim(),children:(0,M.jsx)(fn.Plus,{className:"af-h-4 af-w-4"})})]})]},L.id))}),(0,M.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(qe,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,M.jsx)(ce,{id:"new-option-title",value:x,onChange:L=>k(L.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:v})]}),(0,M.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,M.jsx)(qe,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,M.jsx)(ce,{id:"new-option-values",value:T,onChange:L=>h(L.target.value),placeholder:"S, M, L",disabled:v})]}),(0,M.jsxs)(y,{type:"button",variant:"outline",onClick:E,disabled:v||!x.trim()||!T.trim(),children:[(0,M.jsx)(fn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,M.jsxs)("div",{className:"af-space-y-3",children:[(0,M.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,M.jsx)(qe,{children:"Variants"}),(0,M.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:ue,disabled:v||W.length===0,children:[(0,M.jsx)(fn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),W.length===0&&(0,M.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),B.length===0?(0,M.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,M.jsxs)(ut,{children:[(0,M.jsx)(ft,{children:(0,M.jsxs)($e,{children:[(0,M.jsx)(te,{children:"Variant"}),(0,M.jsx)(te,{children:"SKU"}),(0,M.jsx)(te,{children:"Price"}),(0,M.jsx)(te,{children:"Stock"}),(0,M.jsx)(te,{children:"Status"}),(0,M.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,M.jsx)(mt,{children:B.map(L=>(0,M.jsxs)($e,{children:[(0,M.jsx)(ae,{className:"af-font-medium",children:To(L)}),(0,M.jsx)(ae,{className:"af-text-muted-foreground",children:L.sku||"-"}),(0,M.jsx)(ae,{children:L.unit_amount!=null?(0,M.jsxs)("span",{children:[L.compare_at_amount!=null&&(0,M.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:se(L.compare_at_amount,L.currency)}),se(L.unit_amount,L.currency)]}):L.allow_custom_amount?(0,M.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,M.jsx)(ae,{children:Ke(L)}),(0,M.jsx)(ae,{children:(0,M.jsx)(ie,{variant:L.active?"success":"secondary",children:L.active?"Active":"Inactive"})}),(0,M.jsx)(ae,{className:"af-text-right",children:(0,M.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,M.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>me(L),disabled:v,children:"Edit"}),(0,M.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>D(L),disabled:v,title:"Delete variant",children:(0,M.jsx)(fn.Trash2,{className:"af-h-4 af-w-4"})})]})})]},L.id))})]})]}),u&&(0,M.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u}),(0,M.jsx)(cn,{open:C!==null,onOpenChange:L=>{!L&&!de&&Y(null)},children:(0,M.jsxs)(qa,{children:[(0,M.jsxs)(Wa,{children:[(0,M.jsx)(Ka,{children:C?.variant?"Edit variant":"Add variant"}),(0,M.jsx)(Za,{children:"Price, markdown, and stock live on the variant."})]}),C&&(0,M.jsxs)("div",{className:"af-space-y-3",children:[C.variant?C.variant.option_values.length>0&&(0,M.jsxs)("div",{className:"af-text-sm",children:[(0,M.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),To(C.variant)]}):W.map(L=>(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(qe,{className:"af-text-xs af-text-muted-foreground",children:L.title}),(0,M.jsxs)(on,{value:C.optionValues[L.id]??"",onValueChange:V=>Y($=>$&&{...$,optionValues:{...$.optionValues,[L.id]:V}}),children:[(0,M.jsx)(za,{children:(0,M.jsx)(ln,{placeholder:`Choose ${L.title}`})}),(0,M.jsx)(ja,{children:L.values.map(V=>(0,M.jsx)(kt,{value:V.value,children:V.value},V.id))})]})]},L.id)),He?(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(qe,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,M.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,M.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsxs)(qe,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,M.jsx)(ce,{id:"variant-price",type:"number",min:"0",step:n,value:C.unitAmount,onChange:L=>Y(V=>V&&{...V,unitAmount:L.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(qe,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,M.jsx)(ce,{id:"variant-compare",type:"number",min:"0",step:n,value:C.compareAt,onChange:L=>Y(V=>V&&{...V,compareAt:L.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(qe,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,M.jsx)(ce,{id:"variant-sku",value:C.sku,onChange:L=>Y(V=>V&&{...V,sku:L.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,M.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,M.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,M.jsx)("input",{type:"checkbox",checked:C.tracked,onChange:L=>Y(V=>V&&{...V,tracked:L.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),C.tracked&&(0,M.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,M.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(qe,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,M.jsx)(ce,{id:"variant-onhand",type:"number",min:"0",step:"1",value:C.onHand,onChange:L=>Y(V=>V&&{...V,onHand:L.target.value}),placeholder:De!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,M.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,M.jsx)("input",{type:"checkbox",checked:C.allowBackorder,onChange:L=>Y(V=>V&&{...V,allowBackorder:L.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),De!=null&&(0,M.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",De," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,M.jsx)("input",{type:"checkbox",checked:C.active,onChange:L=>Y(V=>V&&{...V,active:L.target.checked}),className:"af-h-4 af-w-4",disabled:et}),"Active (buyers can purchase this variant)"]}),et&&(0,M.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),X&&(0,M.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:X})]}),(0,M.jsxs)(Ga,{children:[(0,M.jsx)(y,{variant:"outline",onClick:()=>Y(null),disabled:de,children:"Cancel"}),(0,M.jsxs)(y,{onClick:We,disabled:de,children:[de?(0,M.jsx)(fn.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,C?.variant?"Save":"Add variant"]})]})]})}),(0,M.jsx)(cn,{open:ye!==null,onOpenChange:L=>{!L&&!v&&D(null)},children:(0,M.jsxs)(qa,{children:[(0,M.jsxs)(Wa,{children:[(0,M.jsx)(Ka,{children:"Delete variant?"}),(0,M.jsx)(Za,{children:ye&&`"${To(ye)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,M.jsxs)(Ga,{children:[(0,M.jsx)(y,{variant:"outline",onClick:()=>D(null),disabled:v,children:"Cancel"}),(0,M.jsx)(y,{variant:"destructive",onClick:Ie,disabled:v,children:"Delete"})]})]})})]})}var oe=require("react/jsx-runtime");function nf(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 Dr({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=Xa(o)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[v,m]=It.useState(!1),[p,f]=It.useState(null),g=It.useRef(!0);It.useEffect(()=>(g.current=!0,()=>{g.current=!1}),[]);let[x,k]=It.useState(t?.name??""),[T,h]=It.useState(t?.description??""),[P,_]=It.useState(t?.allow_custom_amount?"custom":"fixed"),[E,w]=It.useState(t?.unit_amount!=null?String(Et(t.unit_amount,o)):""),[I,O]=It.useState(t?.min_amount!=null?String(Et(t.min_amount,o)):""),[C,Y]=It.useState(t?.max_amount!=null?String(Et(t.max_amount,o)):""),[X,q]=It.useState(String(t?.max_quantity??10)),de=It.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,[ge,ye]=It.useState(t?.collect_shipping_address??!1),[D,W]=It.useState(t?.active??!0),[B,ue]=It.useState(t?.images??[]),[me,We]=It.useState(""),[Ie,He]=It.useState(t?.fulfillment??null),[et,De]=It.useState(!1),[Ke,L]=It.useState(""),[V,$]=It.useState(null),xe=It.useRef(null),H=v||et,ke=()=>{let Pe=me.trim();if(Pe){if(B.includes(Pe)){f("This image URL is already added");return}ue(Ge=>[...Ge,Pe]),We(""),f(null)}},ze=Pe=>{ue(Ge=>Ge.filter(yt=>yt!==Pe))},gt=async()=>{if(f(null),!x.trim()){f("Product name is required");return}let Pe=null,Ge=null,yt=null,Lt=!d||P!==de.pricingMode||(P==="fixed"?E!==de.unitAmount:I!==de.minAmount||C!==de.maxAmount),Vt=!d||X!==de.maxQuantity,it=b||P==="fixed";if(!(b||!Lt))if(P==="fixed"){if(Pe=oa(E,o),Pe===null||Pe<=0){f("Enter a valid price");return}}else{if(Ge=oa(I,o),yt=oa(C,o),Ge===null||yt===null){f("Enter valid minimum and maximum amounts");return}if(yt<Ge){f("Maximum amount must be at least the minimum amount");return}}let Qt=parseInt(X,10);if(it&&Vt&&(!Number.isFinite(Qt)||Qt<1)){f("Max quantity must be at least 1");return}try{m(!0);let tt;if(d&&t){let Rt={name:x.trim(),description:T.trim()||null,images:B,collect_shipping_address:ge,active:D};!b&&Lt&&(Rt.allow_custom_amount=P==="custom",P==="fixed"?Rt.unit_amount=Pe:(Rt.min_amount=Ge,Rt.max_amount=yt)),it&&Vt&&(Rt.max_quantity=Qt),tt=await i(t.id,Rt),de.pricingMode=tt.allow_custom_amount?"custom":"fixed",de.unitAmount=tt.unit_amount!=null?String(Et(tt.unit_amount,o)):"",de.minAmount=tt.min_amount!=null?String(Et(tt.min_amount,o)):"",de.maxAmount=tt.max_amount!=null?String(Et(tt.max_amount,o)):"",de.maxQuantity=String(tt.max_quantity)}else{let Rt={name:x.trim(),allow_custom_amount:P==="custom",collect_shipping_address:ge,active:D};T.trim()&&(Rt.description=T.trim()),B.length>0&&(Rt.images=B),P==="fixed"?(Rt.unit_amount=Pe,Rt.max_quantity=Qt):(Rt.min_amount=Ge,Rt.max_amount=yt),tt=await r(Rt)}if(!g.current)return;He(tt.fulfillment),s?.(tt)}catch(tt){if(!g.current)return;f(tt instanceof Error?tt.message:"Failed to save product")}finally{g.current&&m(!1)}},st=async Pe=>{let Ge=Pe.target.files?.[0];if(!(!Ge||!t))try{De(!0),$(null);let yt=await l(t.id,Ge);if(!g.current)return;He(yt.fulfillment),s?.(yt)}catch(yt){if(!g.current)return;$(yt instanceof Error?yt.message:"Failed to upload file")}finally{g.current&&(De(!1),xe.current&&(xe.current.value=""))}},Ot=async()=>{let Pe=Ke.trim();if(!(!Pe||!t))try{De(!0),$(null);let Ge=await c(t.id,Pe);if(!g.current)return;He(Ge.fulfillment),L(""),s?.(Ge)}catch(Ge){if(!g.current)return;$(Ge instanceof Error?Ge.message:"Failed to fetch file")}finally{g.current&&De(!1)}};return(0,oe.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(qe,{htmlFor:"product-name",children:"Name"}),(0,oe.jsx)(ce,{id:"product-name",value:x,onChange:Pe=>k(Pe.target.value),placeholder:"My product"})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(qe,{htmlFor:"product-description",children:"Description"}),(0,oe.jsx)("textarea",{id:"product-description",value:T,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"})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(qe,{children:"Pricing"}),b?(0,oe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):(0,oe.jsxs)(oe.Fragment,{children:[(0,oe.jsxs)(on,{value:P,onValueChange:Pe=>_(Pe),children:[(0,oe.jsx)(za,{className:"af-w-[260px]",children:(0,oe.jsx)(ln,{})}),(0,oe.jsxs)(ja,{children:[(0,oe.jsx)(kt,{value:"fixed",children:"Fixed price"}),(0,oe.jsx)(kt,{value:"custom",children:"Buyer chooses the amount"})]})]}),P==="fixed"?(0,oe.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsxs)(qe,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",o.toUpperCase(),")"]}),(0,oe.jsx)(ce,{id:"product-price",type:"number",min:"0",step:u,value:E,onChange:Pe=>w(Pe.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsxs)(qe,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",o.toUpperCase(),")"]}),(0,oe.jsx)(ce,{id:"product-min-amount",type:"number",min:"0",step:u,value:I,onChange:Pe=>O(Pe.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsxs)(qe,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",o.toUpperCase(),")"]}),(0,oe.jsx)(ce,{id:"product-max-amount",type:"number",min:"0",step:u,value:C,onChange:Pe=>Y(Pe.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,oe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Buyers pick their own amount within these bounds (tip jar, pay-what-you-want). Quantity is always 1."})]}),(0,oe.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",o.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||P==="fixed")&&(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsx)(qe,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,oe.jsx)(ce,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:X,onChange:Pe=>q(Pe.target.value),className:"af-w-[140px]"})]})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(qe,{children:"Images"}),(0,oe.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,oe.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[B.map(Pe=>(0,oe.jsxs)(ie,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,oe.jsx)("span",{className:"af-truncate",children:Pe}),(0,oe.jsx)("button",{type:"button",onClick:()=>ze(Pe),className:"af-ml-1 hover:af-text-destructive",disabled:v,children:(0,oe.jsx)(Qa.X,{className:"af-h-3 af-w-3"})})]},Pe)),B.length===0&&(0,oe.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,oe.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,oe.jsx)(ce,{type:"url",value:me,onChange:Pe=>We(Pe.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:Pe=>{Pe.key==="Enter"&&(Pe.preventDefault(),ke())},disabled:v}),(0,oe.jsx)(y,{type:"button",variant:"outline",onClick:ke,disabled:!me.trim()||v,children:(0,oe.jsx)(Qa.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(qe,{children:"Digital File"}),(0,oe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, Word, Excel, PowerPoint, CSV, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),d?(0,oe.jsxs)("div",{className:"af-space-y-3",children:[Ie?.type==="download"&&(0,oe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,oe.jsx)(Qa.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,oe.jsx)("span",{className:"af-text-sm",children:Ie.filename}),Ie.size!=null&&(0,oe.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",nf(Ie.size),")"]})]}),Ie?.type==="redirect"&&Ie.url&&(0,oe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,oe.jsx)(Qa.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,oe.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Ie.url]})]}),(0,oe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,oe.jsx)("input",{ref:xe,type:"file",onChange:st,className:"af-hidden",disabled:H}),(0,oe.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>xe.current?.click(),disabled:H,children:[et?(0,oe.jsx)(Qa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,oe.jsx)(Qa.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Ie?.type==="download"?"Replace file":"Upload file"]}),(0,oe.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,oe.jsx)(ce,{type:"url",value:Ke,onChange:Pe=>L(Pe.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:et}),(0,oe.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:Ot,disabled:!Ke.trim()||H,children:"Fetch from URL"})]}),V&&(0,oe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:V})]}):(0,oe.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(qe,{children:"Settings"}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,oe.jsx)("input",{type:"checkbox",checked:ge,onChange:Pe=>ye(Pe.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,oe.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,oe.jsx)("input",{type:"checkbox",checked:D,onChange:Pe=>W(Pe.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),d&&t&&(0,oe.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,oe.jsx)(qe,{children:"Options & Variants"}),(0,oe.jsx)(Ar,{productId:t.id,currency:o})]}),p&&(0,oe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:p}),(0,oe.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,oe.jsxs)(y,{type:"button",onClick:gt,disabled:H,children:[v?(0,oe.jsx)(Qa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?"Save changes":"Create product"]})})]})}var aa=le(require("react"),1),en=require("lucide-react");var Bt=le(require("react"),1);var sf=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Or({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=G(),[s,n]=Bt.useState([]),[r,i]=Bt.useState(0),[l,c]=Bt.useState(!0),[d,o]=Bt.useState(null),[u,b]=Bt.useState(0),[v,m]=Bt.useState(e),[p,f]=Bt.useState(void 0),[g,x]=Bt.useState(""),[k,T]=Bt.useState(""),[h,P]=Bt.useState(""),[_,E]=Bt.useState(!1),[w,I]=Bt.useState(!1),[O,C]=Bt.useState(void 0),Y=O?O.join(","):"",X=Bt.useMemo(()=>{if(!Y)return;let D=new Set(Y.split(","));return sf.filter(W=>!D.has(W))},[Y]),q=Bt.useMemo(()=>{let D={};return p?D.status=p:X?D.excludeStatus=X:_||(D.excludeStatus=["pending","expired"]),g.trim()&&(D.customerEmail=g.trim()),k.trim()&&(D.from=k.trim()),h.trim()&&(D.to=h.trim()),w&&(D.unfulfilledOnly=!0),D},[p,X,_,g,k,h,w]),de=Bt.useRef(0),ge=Bt.useCallback(async()=>{let D=++de.current;try{c(!0),o(null);let W={...q,limit:v,offset:u*v},B=await a.getOrders(W);if(D!==de.current)return;n(B.orders),i(B.total)}catch(W){if(D!==de.current)return;o(W instanceof Error?W:new Error("Failed to fetch orders"))}finally{D===de.current&&c(!1)}},[a,u,v,q,t]);Bt.useEffect(()=>{ge()},[ge]);let ye=Math.ceil(r/v);return{orders:s,total:r,isLoading:l,error:d,page:u,pageSize:v,hasNextPage:u<ye-1,hasPreviousPage:u>0,setPage:b,setPageSize:D=>{m(D),b(0)},status:p,setStatus:D=>{f(D),b(0)},statusIn:O,setStatusIn:D=>{C(D&&D.length>0?D:void 0),b(0)},customerEmail:g,setCustomerEmail:D=>{x(D),b(0)},from:k,setFrom:D=>{T(D),b(0)},to:h,setTo:D=>{P(D),b(0)},showAbandoned:_,setShowAbandoned:D=>{E(D),b(0)},unfulfilledOnly:w,setUnfulfilledOnly:D=>{I(D),b(0)},clearFilters:()=>{f(void 0),C(void 0),E(!1),I(!1),x(""),T(""),P(""),b(0)},filters:q,refetch:ge}}var qt=le(require("react"),1),at=require("lucide-react");var hc=le(require("react"),1),Bn=le(require("@radix-ui/react-popover"),1);var Ci=require("react/jsx-runtime"),Ti=Bn.Root,Ei=Bn.Trigger;var Lr=hc.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},n)=>(0,Ci.jsx)(Bn.Portal,{children:(0,Ci.jsx)("div",{className:"aifeatures-admin",children:(0,Ci.jsx)(Bn.Content,{ref:n,align:t,sideOffset:a,className:Q("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...s})})}));Lr.displayName=Bn.Content.displayName;var Br=require("react/jsx-runtime"),rf={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function of(e){return rf[e]??e}function yc(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 ks({status:e,className:t}){return(0,Br.jsx)(ie,{variant:yc(e),className:t,children:of(e)})}function ms({status:e}){return(0,Br.jsx)(ks,{status:e})}function Xs({order:e,className:t}){return e.line_items.some(a=>a.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,Br.jsx)(ie,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Br.jsx)(ie,{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)}`}var S=require("react/jsx-runtime"),Nc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ps="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 lf(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 Ii=24,cf=["paid","partially_refunded"],df=["paid","partially_refunded","disputed"],uf=/^[A-Za-z0-9 _-]*$/,xc=100;function Do(e,t,a,s,n){let r=cf.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 ${Ii} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${Ii} 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<Ii&&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<Ii&&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(0,S.jsxs)("div",{children:[(0,S.jsx)(Dn,{deliveries:[l]}),i&&(0,S.jsx)("div",{className:"af-mt-2",children:i})]});let c=Do(n,a,s,r,t);return(0,S.jsxs)("div",{children:[(0,S.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,S.jsxs)("div",{className:"af-min-w-0",children:[(0,S.jsx)("div",{className:"af-text-sm",children:e}),t&&(0,S.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,S.jsx)(ie,{variant:c.variant,className:"af-shrink-0",children:c.label})]}),c.detail&&(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:c.detail}),i&&(0,S.jsx)("div",{className:"af-mt-2",children:i})]})}function Sc(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=lf(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 ff(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Oo({value:e,label:t,children:a,className:s,size:n="icon"}){let[r,i]=qt.useState(!1);if(!ff())return null;let l=async()=>{try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},c=r?(0,S.jsx)(at.Check,{className:"af-h-3 af-w-3"}):(0,S.jsx)(at.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,S.jsx)(y,{variant:"ghost",size:"icon",className:Q("af-h-6 af-w-6 af-shrink-0",s),onClick:l,title:t,"aria-label":t,children:c}):(0,S.jsxs)(y,{variant:"outline",size:"sm",className:s,onClick:l,"aria-label":t,children:[r?(0,S.jsx)(at.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,S.jsx)(at.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":a]})}function Io({label:e,value:t}){return(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Ps,children:e}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,S.jsx)(Oo,{value:t,label:`Copy ${e}`})]})]})}function mf({src:e}){let[t,a]=qt.useState(!1);return!e||t?(0,S.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-10 af-w-10 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-muted",children:(0,S.jsx)(at.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,S.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>a(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Fn({title:e,action:t,children:a,className:s}){return(0,S.jsxs)("section",{className:Q("af-rounded-lg af-border af-p-4",s),children:[(0,S.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,S.jsx)("h4",{className:Nc,children:e}),t]}),(0,S.jsx)("div",{className:"af-mt-3",children:a})]})}function Ia({label:e,emphasis:t,divider:a,children:s}){return(0,S.jsxs)("div",{className:Q("af-flex af-items-baseline af-justify-between af-gap-6",a&&"af-mt-2 af-border-t af-pt-2"),children:[(0,S.jsx)("span",{className:t?"af-text-base af-font-semibold":Ps,children:e}),(0,S.jsx)("span",{className:Q("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function Ao({onSelect:e,disabled:t,icon:a,children:s}){return(0,S.jsxs)(y,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,S.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function pf(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 ${se(ki(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?Si(a):Do("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?Si(a):Do("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 ${se(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 Fr({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:n=!1,onPrevOrder:r,onNextOrder:i,hasPrevOrder:l=!1,hasNextOrder:c=!1}){let{api:d}=G(),[o,u]=qt.useState(e),[b,v]=qt.useState(null),[m,p]=qt.useState(null),[f,g]=qt.useState(!1),[x,k]=qt.useState(!1),[T,h]=qt.useState(!1),[P,_]=qt.useState(!1),[E,w]=qt.useState(""),[I,O]=qt.useState(!1),[C,Y]=qt.useState(null),[X,q]=qt.useState(!1),[de,ge]=qt.useState(""),[ye,D]=qt.useState([]),[W,B]=qt.useState(!1),[ue,me]=qt.useState(!1),[We,Ie]=qt.useState(null);qt.useEffect(()=>{u(e)},[e]);let He=U=>{let ot=U.id===o.id&&U.email_deliveries===void 0?{...U,email_deliveries:o.email_deliveries}:U;u(ot),s?.(ot)},et=Object.entries(o.metadata??{}),De=Math.max(0,ki(o)-o.amount_refunded),Ke=(o.status==="paid"||o.status==="partially_refunded")&&De>0,L=o.exclusive_tax_total!=null,V=U=>typeof U.amountNet=="number"?U.amountNet+(U.exclusiveTax??0):(typeof U.unitAmount=="number"?U.unitAmount:0)*(typeof U.quantity=="number"&&U.quantity>0?U.quantity:1),$=Math.max(0,(o.shipping_total??0)-(o.shipping_refunded??0)),xe=ye.reduce((U,ot)=>U+V(o.line_items[ot]??{}),0)+(W?$:0),H=o.tax_total??0,ke=Math.max(0,(o.exclusive_tax_total??0)-o.line_items.reduce((U,ot)=>U+(ot.exclusiveTax??0),0)),ze=L?W&&$>0?ke:0:o.automatic_tax&&o.tax_behavior==="exclusive"&&H>0&&o.amount_total+(o.shipping_total??0)>0?Math.min(Math.max(0,H-(o.tax_refunded??0)),Math.round(H*xe/(o.amount_total+(o.shipping_total??0)))):0,gt=o.source==="subscription"&&(o.credit_applied??0)>0&&o.line_items.length===1?Math.min(xe+ze,De):xe+ze,st=ye.length>0||W,Ot=st?gt:oa(de,o.currency),Pe=Xa(o.currency)?"1":"0.01",Ge=async()=>{try{g(!0),v(null),p(null),await d.resendOrderReceipt(o.id);let U=await d.getOrder(o.id);He(U),p("Receipt email queued.")}catch(U){v(U instanceof Error?U.message:"Failed to resend receipt")}finally{g(!1)}},yt=async()=>{try{k(!0),v(null),p(null);let U=await d.resetOrderDownloads(o.id);He(U),h(!1),p("Download count reset.")}catch(U){v(U instanceof Error?U.message:"Failed to reset downloads")}finally{k(!1)}},Lt=o.line_items.some(U=>U.collectShippingAddress===!0&&!U.refunded&&!U.unavailableReason),Vt=typeof o.merchant_fulfilled_at=="string",it=df.includes(o.status)||o.status==="refunded"&&o.line_items.some(U=>U.collectShippingAddress===!0&&U.amountNet===0&&!U.refunded&&!U.unavailableReason),Qt=E.trim(),tt=uf.test(Qt)&&Qt.length<=xc,Rt=async U=>{try{O(!0),Y(null),p(null);let ot=await d.setOrderFulfillment(o.id,{fulfilled:U,...U&&Qt?{trackingNumber:Qt}:{}});He(ot),w(""),p(U?"Marked as shipped.":"Marked as not shipped.")}catch(ot){ot instanceof Gt&&ot.status===409?Y(`This order is ${o.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Y(ot instanceof Error?ot.message:"Failed to update the order")}finally{O(!1)}},Va=()=>{Ie(null),ge(String(Et(De,o.currency))),D([]),B(!1),q(!0)},In=U=>D(ot=>ot.includes(U)?ot.filter(Ca=>Ca!==U):[...ot,U]),Te=async(U,ot)=>{if(a)try{me(!0),Ie(null),await a(o,U,ot);let Ca=await d.getOrder(o.id);He(Ca),q(!1),p("Refund issued.")}catch(Ca){Ie(Ca instanceof Error?Ca.message:"Refund failed")}finally{me(!1)}},Tt=async()=>{if(st){if(gt<=0){Ie("The lines you picked were charged nothing");return}if(gt>De){Ie(`That selection exceeds the refundable remainder (${se(De,o.currency)})`);return}await Te(gt,{...ye.length>0?{line_items:[...ye].sort((ot,Ca)=>ot-Ca)}:{},...W?{shipping:!0}:{}});return}let U=oa(de,o.currency);if(U===null||U<=0){Ie("Enter a valid refund amount");return}if(U>De){Ie(`Amount exceeds the refundable remainder (${se(De,o.currency)})`);return}await Te(U,{amount:U})},z=()=>Te(De,{full:!0}),Oe=!o.subscription_history_only&&o.fulfillment_type==="download",zt=!o.subscription_history_only&&n&&Lt,xn=pf(o),ne=o.shipping_address?Sc(o.shipping_address).join(`
4
- `):"",ia=o.shipping_total!=null,So=o.exclusive_tax_total??(o.automatic_tax&&o.tax_behavior==="exclusive"?o.tax_total??0:0),Fl=o.exclusive_tax_total!=null?Math.max(0,(o.tax_total??0)-So):o.automatic_tax&&o.tax_behavior==="exclusive"?0:o.tax_total??0,Ml=So>0,ku=Fl>0,$l=o.amount_subtotal!=null||ia||Ml||(o.discount_total??0)>0,mr=[];return o.subscription_history_only||mr.push((0,S.jsx)(Ao,{icon:f?(0,S.jsx)(at.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,S.jsx)(at.Mail,{className:"af-h-4 af-w-4"}),disabled:f||o.fulfillment_status!=="fulfilled",onSelect:()=>{_(!1),Ge()},children:"Resend receipt"},"resend")),Oe&&mr.push((0,S.jsx)(Ao,{icon:(0,S.jsx)(at.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{_(!1),h(!0)},children:"Reset download count"},"reset")),Ke&&mr.push((0,S.jsxs)("div",{children:[(0,S.jsx)(Ao,{icon:(0,S.jsx)(at.Undo2,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{_(!1),Va()},children:"Refund\u2026"}),!a&&(0,S.jsx)("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),(0,S.jsxs)("div",{children:[(0,S.jsxs)("div",{className:"af-mb-6",children:[(0,S.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,S.jsx)(at.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,S.jsxs)("div",{className:"af-min-w-0",children:[(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.jsx)("h3",{className:"af-text-xl af-font-semibold",children:Xn(o)}),(0,S.jsx)(ks,{status:o.status}),n&&!o.subscription_history_only&&(0,S.jsx)(Xs,{order:o}),o.is_test&&(0,S.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,S.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Eo(o.created_at)]}),o.is_test&&(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||i)&&(0,S.jsxs)("div",{className:"af-flex af-items-center",children:[(0,S.jsx)(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!l,"aria-label":"Previous order",children:(0,S.jsx)(at.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,S.jsx)(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:(0,S.jsx)(at.ChevronRight,{className:"af-h-4 af-w-4"})})]}),zt&&(Vt?(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",o.merchant_fulfilled_at?` \xB7 ${Eo(o.merchant_fulfilled_at)}`:""]}),it&&(0,S.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>Rt(!1),disabled:I,children:[I?(0,S.jsx)(at.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(at.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):it?(0,S.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,S.jsx)(ce,{value:E,onChange:U=>w(U.target.value),placeholder:"Tracking number (optional)",maxLength:xc,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:I}),(0,S.jsxs)(y,{variant:"default",className:"af-shrink-0",onClick:()=>Rt(!0),disabled:I||!tt,children:[I?(0,S.jsx)(at.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(at.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),mr.length>0&&(0,S.jsxs)(Ti,{open:P,onOpenChange:_,children:[(0,S.jsx)(Ei,{asChild:!0,children:(0,S.jsx)(y,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,S.jsx)(at.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,S.jsx)(Lr,{children:(0,S.jsx)("div",{className:"af-space-y-0.5",children:mr})})]})]})]}),zt&&!Vt&&!tt&&(0,S.jsx)("p",{className:"af-mt-2 af-text-xs af-text-destructive",children:"Tracking numbers can use letters, numbers, spaces, dashes and underscores \u2014 up to 100 characters."}),C&&(0,S.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:C}),m&&(0,S.jsx)("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:m}),b&&(0,S.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:b})]}),(0,S.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,S.jsxs)("div",{className:"af-space-y-6",children:[o.line_items.length>0&&(0,S.jsx)(Fn,{title:"Items",children:(0,S.jsx)("ul",{className:"af-space-y-3",children:o.line_items.map((U,ot)=>{let Ca=typeof U.name=="string"&&U.name?U.name:"Item",Ul=typeof U.quantity=="number"&&U.quantity>0?U.quantity:1,Vl=typeof U.unitAmount=="number";return(0,S.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,S.jsx)(mf,{src:typeof U.imageUrl=="string"&&U.imageUrl?U.imageUrl:void 0}),(0,S.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,S.jsxs)("div",{className:"af-text-sm af-font-medium",children:[Ca,typeof U.variantTitle=="string"&&U.variantTitle&&(0,S.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",U.variantTitle]})]}),(0,S.jsxs)("div",{className:Ps,children:[Ul," \xD7"," ",Vl?se(U.unitAmount,o.currency):"\u2014"]}),U.unavailableReason==="oversold"&&!U.refunded&&(0,S.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:U.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),U.refunded===!0&&(0,S.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:U.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,S.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof U.amountNet=="number"||Vl?se(U.amountNet??U.unitAmount*Ul,o.currency):"\u2014"})]},ot)})})}),et.length>0&&(0,S.jsx)(Fn,{title:"Order details",children:(0,S.jsx)("dl",{className:"af-space-y-2",children:et.map(([U,ot])=>(0,S.jsxs)("div",{children:[(0,S.jsx)("dt",{className:Q(Ps,"af-capitalize"),children:U.replace(/_/g," ")}),(0,S.jsx)("dd",{className:"af-text-sm af-break-words",children:Rc(ot)})]},U))})}),(0,S.jsx)(Fn,{title:"Totals",children:(0,S.jsxs)("div",{className:"af-w-full",children:[$l&&(0,S.jsx)(Ia,{label:"Subtotal",children:se(o.amount_subtotal??o.amount_total+(o.discount_total??0),o.currency)}),(o.discount_total??0)>0&&(0,S.jsxs)(Ia,{label:"Discount",children:["\u2212",se(o.discount_total,o.currency)]}),ia&&(0,S.jsx)(Ia,{label:"Shipping",children:o.shipping_total===0?"Free":se(o.shipping_total??0,o.currency)}),Ml&&(0,S.jsx)(Ia,{label:"Tax",children:se(So,o.currency)}),(0,S.jsx)(Ia,{label:"Total",emphasis:!0,divider:$l,children:se(Ln(o),o.currency)}),(o.credit_applied??0)>0&&(0,S.jsxs)(Ia,{label:"Credit applied",children:["\u2212",se(o.credit_applied,o.currency)]}),o.amount_paid!=null&&(0,S.jsx)(Ia,{label:"Amount paid",children:se(o.amount_paid,o.currency)}),ku&&(0,S.jsx)(Ia,{label:"incl. tax",children:se(Fl,o.currency)}),o.base_currency!=null&&o.base_amount_total!=null&&(0,S.jsxs)(Ia,{label:"Your price",children:[se(o.base_amount_total,o.base_currency),(0,S.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",o.currency.toUpperCase()]})]}),o.amount_refunded>0&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(Ia,{label:"Refunded",children:["\u2212",se(o.amount_refunded,o.currency),(o.shipping_refunded??0)>0&&(0,S.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",se(o.shipping_refunded??0,o.currency)," ","shipping"]})]}),(0,S.jsx)(Ia,{label:"Net",children:(0,S.jsx)("span",{className:"af-font-medium",children:se(Math.max(0,ki(o)-o.amount_refunded),o.currency)})})]})]})}),o.application_fee_state&&(0,S.jsxs)(Fn,{title:"Platform fee",children:[o.application_fee_original!=null&&(0,S.jsx)(Ia,{label:"Collected",children:se(o.application_fee_original,o.application_fee_currency??o.currency)}),o.application_fee_returned!=null&&(0,S.jsx)(Ia,{label:"Returned",children:se(o.application_fee_returned,o.application_fee_currency??o.currency)}),o.application_fee_retained!=null&&(0,S.jsx)(Ia,{label:"Retained",children:se(o.application_fee_retained,o.application_fee_currency??o.currency)}),o.application_fee_state!=="complete"&&(0,S.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:o.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,S.jsx)(Fn,{title:"Timeline",children:(0,S.jsx)("ol",{className:"af-space-y-3",children:xn.map(U=>(0,S.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,S.jsx)("span",{"aria-hidden":"true",className:Q("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",U.tone==="destructive"?"af-bg-destructive":U.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,S.jsxs)("div",{className:"af-min-w-0",children:[(0,S.jsx)("div",{className:"af-text-sm af-break-words",children:U.text}),U.at&&(0,S.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:Eo(U.at)})]})]},U.key))})})]}),(0,S.jsxs)("div",{className:"af-space-y-6",children:[(0,S.jsx)(Fn,{title:"Customer",children:(0,S.jsxs)("div",{className:"af-space-y-2",children:[(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Ps,children:"Email"}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:o.customer_email||(0,S.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),o.customer_email&&(0,S.jsx)(Oo,{value:o.customer_email,label:"Copy email"})]})]}),o.customer_name&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Ps,children:"Name"}),(0,S.jsx)("div",{className:"af-text-sm",children:o.customer_name})]}),o.customer&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Ps,children:"Customer record"}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.jsx)("span",{className:"af-break-all af-text-sm",children:o.customer.name||o.customer.email}),(0,S.jsx)(ie,{variant:"secondary",children:"Linked"})]})]})]})}),o.shipping_address&&(0,S.jsx)(Fn,{title:"Ship to",action:(0,S.jsx)(Oo,{value:ne,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,S.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Sc(o.shipping_address).map((U,ot)=>(0,S.jsx)("div",{children:U},ot))})}),o.subscription_history_only?(0,S.jsx)(Fn,{title:"Subscription history",children:(0,S.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This renewal had no payment due. No items were fulfilled and no purchase receipt was sent."})}):(0,S.jsxs)(Fn,{title:"Emails",children:[(0,S.jsx)(Dn,{deliveries:o.email_deliveries?.filter(U=>!["purchase_receipt","merchant_sale"].includes(U.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,S.jsxs)("div",{className:"af-space-y-4",children:[(0,S.jsx)(wc,{side:"buyer",title:"Receipt to buyer",delivery:o.email_deliveries?.find(U=>U.kind==="purchase_receipt"),recipient:o.customer_email,status:o.buyer_email_status,attempts:o.buyer_email_attempts,orderStatus:o.status,action:(0,S.jsxs)(y,{variant:"outline",size:"sm",onClick:Ge,disabled:f||o.fulfillment_status!=="fulfilled",children:[f?(0,S.jsx)(at.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(at.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,S.jsx)(wc,{side:"merchant",title:"Sale alert to you",delivery:o.email_deliveries?.find(U=>U.kind==="merchant_sale"),recipient:null,status:o.merchant_email_status,attempts:o.merchant_email_attempts,orderStatus:o.status})]})]}),Oe&&(0,S.jsx)(Fn,{title:"Download",children:(0,S.jsxs)("div",{className:"af-space-y-2",children:[(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,S.jsx)(at.Download,{className:"af-h-4 af-w-4"}),(0,S.jsxs)("span",{children:["Downloaded ",o.download_count," time",o.download_count===1?"":"s"]})]}),o.download_url&&(0,S.jsx)("a",{href:o.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,S.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,S.jsx)("summary",{className:Q(Nc,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,S.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,S.jsx)(Io,{label:"Order ID",value:o.id}),o.stripe_checkout_session_id&&(0,S.jsx)(Io,{label:"Checkout session",value:o.stripe_checkout_session_id}),o.stripe_payment_intent_id&&(0,S.jsx)(Io,{label:"Payment",value:o.stripe_payment_intent_id})]})]})]})]}),(0,S.jsx)(cn,{open:T,onOpenChange:U=>{!U&&!x&&h(!1)},children:(0,S.jsxs)(qa,{children:[(0,S.jsxs)(Wa,{children:[(0,S.jsx)(Ka,{children:"Reset download count?"}),(0,S.jsx)(Za,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,S.jsxs)(Ga,{children:[(0,S.jsx)(y,{variant:"outline",onClick:()=>h(!1),disabled:x,children:"Cancel"}),(0,S.jsx)(y,{onClick:yt,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),(0,S.jsx)(cn,{open:X,onOpenChange:U=>{!U&&!ue&&q(!1)},children:(0,S.jsxs)(qa,{children:[(0,S.jsxs)(Wa,{children:[(0,S.jsx)(Ka,{children:"Refund order"}),(0,S.jsxs)(Za,{children:["Refund up to ",se(De,o.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,S.jsxs)("div",{className:"af-space-y-4",children:[(o.line_items.length>0||$>0)&&(0,S.jsxs)("div",{className:"af-space-y-2",children:[(0,S.jsx)(qe,{children:"Items"}),(0,S.jsxs)("div",{className:"af-space-y-2",children:[o.line_items.map((U,ot)=>{let Ca=U.refunded===!0;return(0,S.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,S.jsx)("input",{type:"checkbox",checked:ye.includes(ot),onChange:()=>In(ot),disabled:ue||Ca||!!U.unavailableReason||V(U)<=0,className:"af-h-4 af-w-4"}),(0,S.jsxs)("span",{className:Ca?"af-text-muted-foreground af-line-through":void 0,children:[typeof U.name=="string"&&U.name?U.name:"Item",typeof U.variantTitle=="string"&&U.variantTitle?` \u2014 ${U.variantTitle}`:"",typeof U.quantity=="number"&&U.quantity>1?` \xD7 ${U.quantity}`:""]}),(0,S.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Ca?"Refunded":se(V(U),o.currency)})]},ot)}),$>0&&(0,S.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,S.jsx)("input",{type:"checkbox",checked:W,onChange:U=>B(U.target.checked),disabled:ue,className:"af-h-4 af-w-4"}),(0,S.jsx)("span",{children:"Shipping"}),(0,S.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:se($,o.currency)})]})]})]}),(0,S.jsxs)("div",{className:"af-space-y-2",children:[(0,S.jsxs)(qe,{htmlFor:"refund-amount",children:["Amount (",o.currency.toUpperCase(),")"]}),(0,S.jsx)(ce,{id:"refund-amount",type:"number",min:"0",step:Pe,value:st?String(Et(gt,o.currency)):de,onChange:U=>ge(U.target.value),disabled:ue||st}),st&&(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),We&&(0,S.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:We}),(0,S.jsxs)(Ga,{children:[(0,S.jsx)(y,{variant:"outline",onClick:()=>q(!1),disabled:ue,children:"Cancel"}),(0,S.jsx)(y,{variant:"outline",onClick:z,disabled:ue,children:"Refund everything"}),(0,S.jsx)(y,{variant:"destructive",onClick:Tt,disabled:ue,children:ue?"Refunding...":Ot!==null&&Ot>0?`Refund ${se(Ot,o.currency)}`:"Refund"})]})]})})]})}var Ai=le(require("react"),1),Di=require("lucide-react");var At=require("react/jsx-runtime");function Ft({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:n}){let r=Ai.useRef(null);return Ai.useEffect(()=>{r.current?.focus()},[]),(0,At.jsxs)("div",{className:Q("af-bg-background",n),children:[(0,At.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,At.jsx)("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!a&&(0,At.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,At.jsx)(Di.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,At.jsx)("div",{className:"af-p-4",children:s})]})}function ee({className:e}){return(0,At.jsx)("div",{"aria-hidden":"true",className:Q("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function vt({label:e,children:t,detail:a,valueClassName:s}){return(0,At.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,At.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,At.jsx)("div",{className:Q("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&(0,At.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function wt({message:e,onRetry:t}){return(0,At.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,At.jsx)("span",{children:e}),(0,At.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,At.jsx)(Di.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function la({icon:e,children:t}){return(0,At.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,At.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function Qs({icon:e,heading:t,body:a,action:s,className:n,children:r}){return(0,At.jsxs)("div",{className:Q("af-px-6 af-py-10 af-text-center",n),children:[(0,At.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,At.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,At.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&(0,At.jsx)(y,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}var F=require("react/jsx-runtime"),gf={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},_c={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 Pc(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 Oi(e){return e.customer?.name||e.customer_name||null}function vf({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}=G(),u=Or({refreshKey:a}),{orders:b,total:v,isLoading:m,error:p,page:f,pageSize:g,hasNextPage:x,hasPreviousPage:k,setPage:T,setPageSize:h,customerEmail:P,setCustomerEmail:_,setStatusIn:E,from:w,setFrom:I,to:O,setTo:C,showAbandoned:Y,setShowAbandoned:X,setUnfulfilledOnly:q,filters:de,refetch:ge}=u,ye=aa.useCallback(()=>o.exportOrdersCsv(de),[o,de]),[D,W]=aa.useState("list"),[B,ue]=aa.useState(null),[me,We]=aa.useState(""),[Ie,He]=aa.useState(""),[et,De]=aa.useState(!d&&n?"needs_shipping":"all"),[Ke,L]=aa.useState(!1),[V,$]=aa.useState(!!s&&!d),[xe,H]=aa.useState(null);aa.useEffect(()=>{if(!s||d)return;let ne=!1;return $(!0),H(null),o.getOrder(s).then(ia=>{ne||(ue(ia),W("detail"))}).catch(()=>{ne||H("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{ne||$(!1)}),()=>{ne=!0}},[o,s,d]);let ke=aa.useCallback(ne=>{De(ne);let ia=_c[ne];E(ia.statusIn),q(ia.unfulfilledOnly)},[E,q]);aa.useEffect(()=>{n&&!d&&q(!0)},[]);let ze=aa.useRef(!n);aa.useEffect(()=>{ze.current||m||(ze.current=!0,b.length===0&&ke("all"))},[m,b.length,ke]);let gt=D==="detail"&&!!B;aa.useEffect(()=>{i?.(gt)},[gt,i]);let st=(w?1:0)+(O?1:0)+(Y?1:0),Ot=st>0||!!P||!!Ie,Pe=!!w&&!!O&&w>O,Ge=!d||!!c,yt=ne=>{if(d){c?.();return}ue(ne),W("detail")},Lt=()=>{W("list"),ue(null),ge()},Vt=ne=>{let ia=ne.trim();if(!ia){He(""),P&&_("");return}if(ia.startsWith("#")||/^\d+$/.test(ia)){He(ia),P&&_("");return}He(""),_(ia)},it=()=>{We(""),He(""),_(""),I(""),C(""),X(!1),L(!1)},Qt=Ie.replace(/^#/,"").toLowerCase(),tt=Qt?b.filter(ne=>String(ne.order_number??"")===Qt||ne.id.toLowerCase().startsWith(Qt)):b,Rt=d?tt.slice(0,l):tt,Va=B?b.findIndex(ne=>ne.id===B.id):-1,In=Va>0,Te=Va>=0&&Va<b.length-1;if(V)return(0,F.jsx)("div",{className:t,children:(0,F.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,F.jsx)(en.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(D==="detail"&&B)return(0,F.jsx)("div",{className:t,children:(0,F.jsx)(Fr,{order:B,onBack:Lt,onRefund:e,onOrderUpdated:ne=>ue(ne),allowFulfillment:n,onPrevOrder:In?()=>ue(b[Va-1]):void 0,onNextOrder:Te?()=>ue(b[Va+1]):void 0,hasPrevOrder:In,hasNextOrder:Te},B.id)});let z=(0,F.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[xe&&(0,F.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:xe}),(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,F.jsx)("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(ne=>(0,F.jsx)("button",{type:"button","aria-pressed":et===ne,onClick:()=>ke(ne),className:Q("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",et===ne?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:gf[ne]},ne))}),(0,F.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,F.jsx)(en.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,F.jsx)(ce,{type:"text",value:me,onChange:ne=>We(ne.target.value),onBlur:()=>Vt(me),onKeyDown:ne=>{ne.key==="Enter"&&(ne.preventDefault(),Vt(me))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,F.jsxs)(y,{type:"button",variant:st>0?"secondary":"ghost",size:"sm",onClick:()=>L(ne=>!ne),"aria-expanded":Ke,children:[(0,F.jsx)(en.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",st>0&&(0,F.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:st})]}),Ot&&(0,F.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:it,children:"Clear filters"}),(0,F.jsx)(ma,{fetchCsv:ye,filename:"orders",disabled:!!Ie,className:"af-ml-auto"})]}),(Ke||!!w||!!O)&&(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2",children:[(0,F.jsx)(qe,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,F.jsx)(ce,{id:"orders-from",type:"date",value:w,max:O||void 0,onChange:ne=>I(ne.target.value),className:"af-w-[170px]"}),(0,F.jsx)(qe,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,F.jsx)(ce,{id:"orders-to",type:"date",value:O,min:w||void 0,onChange:ne=>C(ne.target.value),className:"af-w-[170px]"}),!_c[et].statusIn&&(0,F.jsx)(y,{type:"button",variant:Y?"secondary":"ghost",size:"sm",onClick:()=>X(!Y),"aria-pressed":Y,children:Y?"Hide abandoned":"Show abandoned"})]}),Pe&&(0,F.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(m)return(0,F.jsxs)("div",{className:t,children:[d?null:z,(0,F.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(ne=>(0,F.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,F.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,F.jsx)(ee,{className:"af-h-4 af-w-16"}),(0,F.jsx)(ee,{className:"af-h-4 af-w-14"})]}),(0,F.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-40"}),(0,F.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-24"})]},ne))}),(0,F.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,F.jsxs)(ut,{children:[(0,F.jsx)(ft,{children:(0,F.jsxs)($e,{children:[(0,F.jsx)(te,{children:"Order"}),(0,F.jsx)(te,{children:"Date"}),(0,F.jsx)(te,{children:"Customer"}),(0,F.jsx)(te,{children:"Items"}),(0,F.jsx)(te,{className:"af-text-right",children:"Total"}),(0,F.jsx)(te,{children:"Status"}),(0,F.jsx)(te,{className:"af-w-8"})]})}),(0,F.jsx)(mt,{"aria-hidden":"true",children:[0,1,2,3,4].map(ne=>(0,F.jsxs)($e,{children:[(0,F.jsx)(ae,{children:(0,F.jsx)(ee,{className:"af-h-4 af-w-14"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(ee,{className:"af-h-4 af-w-24"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(ee,{className:"af-h-4 af-w-40"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(ee,{className:"af-h-4 af-w-32"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(ee,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(ee,{className:"af-h-5 af-w-16"})}),(0,F.jsx)(ae,{})]},ne))})]})}),(0,F.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(p)return(0,F.jsxs)("div",{className:t,children:[d?null:z,(0,F.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,F.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,F.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>ge(),children:"Try again"})]})]});let Oe=et!=="all";if(tt.length===0&&f===0)return Ot||Oe?(0,F.jsxs)("div",{className:t,children:[!d&&z,(0,F.jsx)(la,{children:"No orders match these filters."})]}):(0,F.jsx)("div",{className:t,children:(0,F.jsx)(Qs,{icon:en.Receipt,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!d&&(0,F.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>X(!0),children:"Show abandoned checkouts"})})});let zt=f*g+1,xn=Math.min((f+1)*g,v);return(0,F.jsxs)("div",{className:t,children:[d?null:z,(0,F.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Rt.map(ne=>(0,F.jsxs)("button",{type:"button",onClick:()=>yt(ne),disabled:!Ge,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ge?" hover:af-bg-muted/50":""}`,children:[(0,F.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,F.jsx)("span",{className:"af-font-medium",children:Xn(ne)}),(0,F.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:se(Ln(ne),ne.currency)})]}),(0,F.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,F.jsxs)("div",{className:"af-truncate af-text-sm",children:[ne.customer_email||(0,F.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Oi(ne)&&(0,F.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Oi(ne)]})]}),(0,F.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Pc(ne)}),ne.amount_refunded>0&&(0,F.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",se(ne.amount_refunded,ne.currency)," refunded"]})]}),(0,F.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,F.jsx)(ks,{status:ne.status}),(0,F.jsx)(yr,{deliveries:ne.email_deliveries}),ne.is_test&&(0,F.jsx)(ie,{variant:"outline",children:"Test"}),n&&(0,F.jsx)(Xs,{order:ne}),(0,F.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:kc(ne.created_at)})]})]},ne.id))}),(0,F.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,F.jsxs)(ut,{children:[(0,F.jsx)(ft,{children:(0,F.jsxs)($e,{children:[(0,F.jsx)(te,{children:"Order"}),(0,F.jsx)(te,{children:"Date"}),(0,F.jsx)(te,{children:"Customer"}),(0,F.jsx)(te,{children:"Items"}),(0,F.jsx)(te,{className:"af-text-right",children:"Total"}),(0,F.jsx)(te,{children:"Status"}),(0,F.jsx)(te,{className:"af-w-8"})]})}),(0,F.jsx)(mt,{children:Rt.map(ne=>(0,F.jsxs)($e,{onClick:Ge?()=>yt(ne):void 0,className:Ge?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,F.jsxs)(ae,{className:"af-whitespace-nowrap af-font-medium",children:[(0,F.jsx)("button",{type:"button",onClick:ia=>{ia.stopPropagation(),yt(ne)},disabled:!Ge,"aria-label":`Open order ${Xn(ne)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ge?" hover:af-underline":""}`,children:Xn(ne)}),ne.is_test&&(0,F.jsx)(ie,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,F.jsx)(ae,{className:"af-whitespace-nowrap af-text-muted-foreground",children:kc(ne.created_at)}),(0,F.jsxs)(ae,{className:"af-max-w-[220px]",children:[(0,F.jsx)("div",{className:"af-truncate",children:ne.customer_email||(0,F.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Oi(ne)&&(0,F.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Oi(ne)})]}),(0,F.jsx)(ae,{className:"af-max-w-[220px]",children:(0,F.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:Pc(ne)})}),(0,F.jsxs)(ae,{className:"af-whitespace-nowrap af-text-right",children:[(0,F.jsx)("div",{className:"af-font-medium af-tabular-nums",children:se(Ln(ne),ne.currency)}),ne.amount_refunded>0&&(0,F.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",se(ne.amount_refunded,ne.currency)," ","refunded"]})]}),(0,F.jsx)(ae,{children:(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,F.jsx)(ks,{status:ne.status}),(0,F.jsx)(yr,{deliveries:ne.email_deliveries}),n&&(0,F.jsx)(Xs,{order:ne})]})}),(0,F.jsx)(ae,{className:"af-w-8 af-text-right",children:(0,F.jsx)(en.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},ne.id))})]})}),d?null:(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,F.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,F.jsx)("span",{children:Qt?`${tt.length} matching this page`:`Showing ${zt}-${xn} of ${v}`}),(0,F.jsxs)(on,{value:String(g),onValueChange:ne=>h(Number(ne)),children:[(0,F.jsx)(za,{className:"af-w-[70px] af-h-8",children:(0,F.jsx)(ln,{})}),(0,F.jsxs)(ja,{children:[(0,F.jsx)(kt,{value:"10",children:"10"}),(0,F.jsx)(kt,{value:"25",children:"25"}),(0,F.jsx)(kt,{value:"50",children:"50"}),(0,F.jsx)(kt,{value:"100",children:"100"})]})]}),(0,F.jsx)("span",{children:"per page"})]}),(0,F.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,F.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>T(f-1),disabled:!k,children:[(0,F.jsx)(en.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,F.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>T(f+1),disabled:!x,children:["Next",(0,F.jsx)(en.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function Qn(e){return(0,F.jsx)(vf,{...e},e.maxRows==null?"full":"compact")}var er=le(require("react"),1),Mn=require("lucide-react");var Aa=le(require("react"),1);function Mr({initialPageSize:e=25}={}){let{api:t}=G(),[a,s]=Aa.useState([]),[n,r]=Aa.useState(0),[i,l]=Aa.useState(!0),[c,d]=Aa.useState(null),[o,u]=Aa.useState(0),[b,v]=Aa.useState(e),[m,p]=Aa.useState(""),f=Aa.useRef(0),g=Aa.useCallback(async()=>{let k=++f.current;try{l(!0),d(null);let T={limit:b,offset:o*b};m.trim()&&(T.email=m.trim());let h=await t.getCustomers(T);if(k!==f.current)return;s(h.customers),r(h.total)}catch(T){if(k!==f.current)return;d(T instanceof Error?T:new Error("Failed to fetch customers"))}finally{k===f.current&&l(!1)}},[t,o,b,m]);Aa.useEffect(()=>{g()},[g]);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:k=>{v(k),u(0)},email:m,setEmail:k=>{p(k),u(0)},refetch:g}}var Cs=le(require("react"),1),Li=require("lucide-react");var Ae=require("react/jsx-runtime");function Cc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function bf(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 $r({customer:e,onBack:t,className:a}){let{api:s}=G(),[n,r]=Cs.useState(null),[i,l]=Cs.useState([]),[c,d]=Cs.useState(!0),[o,u]=Cs.useState(null);Cs.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(([p,f])=>{m||(r(p),l(f.orders))}).catch(p=>{m||u(p instanceof Error?p.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(0,Ae.jsxs)("div",{className:a,children:[(0,Ae.jsxs)("div",{className:"af-mb-6",children:[(0,Ae.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,Ae.jsx)(Li.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,Ae.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,Ae.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Cc(e.created_at)]})]}),c?(0,Ae.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,Ae.jsx)(Li.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):o?(0,Ae.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o}):(0,Ae.jsxs)("div",{className:"af-space-y-6",children:[(0,Ae.jsx)(Dn,{deliveries:n?.email_deliveries}),(0,Ae.jsxs)("div",{children:[(0,Ae.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,Ae.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,Ae.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,Ae.jsx)("span",{children:e.email})]}),e.name&&(0,Ae.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,Ae.jsx)("span",{children:e.name})]}),e.phone&&(0,Ae.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,Ae.jsx)("span",{children:e.phone})]}),(0,Ae.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,Ae.jsx)("span",{children:v})]})]})]}),b.length>0&&(0,Ae.jsxs)("div",{children:[(0,Ae.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,Ae.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(m=>(0,Ae.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[m.is_default&&(0,Ae.jsx)(ie,{variant:"secondary",className:"af-mb-1",children:"Default"}),bf(m).map((p,f)=>(0,Ae.jsx)("div",{children:p},f))]},m.id))})]}),(0,Ae.jsxs)("div",{children:[(0,Ae.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),i.length===0?(0,Ae.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,Ae.jsxs)(ut,{children:[(0,Ae.jsx)(ft,{children:(0,Ae.jsxs)($e,{children:[(0,Ae.jsx)(te,{children:"Date"}),(0,Ae.jsx)(te,{children:"Amount"}),(0,Ae.jsx)(te,{children:"Status"})]})}),(0,Ae.jsx)(mt,{children:i.map(m=>(0,Ae.jsxs)($e,{children:[(0,Ae.jsx)(ae,{className:"af-text-muted-foreground",children:Cc(m.created_at)}),(0,Ae.jsx)(ae,{children:se(Ln(m),m.currency)}),(0,Ae.jsx)(ae,{children:(0,Ae.jsx)(ms,{status:m.status})})]},m.id))})]})]})]})]})}var _e=require("react/jsx-runtime");function hf(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 Ur({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}=Mr(),{api:m}=G(),p=er.useCallback(()=>m.exportCustomersCsv(),[m]),[f,g]=er.useState("list"),[x,k]=er.useState(null),[T,h]=er.useState(""),P=O=>{k(O),g("detail")},_=()=>{g("list"),k(null),v()};if(f==="detail"&&x)return(0,_e.jsx)("div",{className:e,children:(0,_e.jsx)($r,{customer:x,onBack:_})});let E=(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,_e.jsx)(ce,{type:"email",value:T,onChange:O=>h(O.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),b(T.trim()))}}),(0,_e.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>b(T.trim()),children:[(0,_e.jsx)(Mn.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),u&&(0,_e.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),b("")},children:"Clear"}),(0,_e.jsx)(ma,{fetchCsv:p,filename:"customers",className:"af-ml-auto"})]});if(s)return(0,_e.jsxs)("div",{className:e,children:[E,(0,_e.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,_e.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,_e.jsxs)("div",{className:e,children:[E,(0,_e.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,_e.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&r===0)return(0,_e.jsxs)("div",{className:e,children:[u&&E,(0,_e.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,_e.jsx)(Mn.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,_e.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:u?"No customers match that email.":(0,_e.jsxs)(_e.Fragment,{children:["No customers yet.",(0,_e.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let w=r*i+1,I=Math.min((r+1)*i,a);return(0,_e.jsxs)("div",{className:e,children:[E,(0,_e.jsxs)(ut,{children:[(0,_e.jsx)(ft,{children:(0,_e.jsxs)($e,{children:[(0,_e.jsx)(te,{children:"Email"}),(0,_e.jsx)(te,{children:"Name"}),(0,_e.jsx)(te,{children:"Phone"}),(0,_e.jsx)(te,{children:"Customer since"}),(0,_e.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,_e.jsx)(mt,{children:t.map(O=>(0,_e.jsxs)($e,{children:[(0,_e.jsx)(ae,{className:"af-font-medium",children:O.email}),(0,_e.jsx)(ae,{children:O.name||(0,_e.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,_e.jsx)(ae,{children:O.phone||(0,_e.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,_e.jsx)(ae,{className:"af-text-muted-foreground",children:hf(O.created_at)}),(0,_e.jsx)(ae,{className:"af-text-right",children:(0,_e.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>P(O),title:"View customer",children:(0,_e.jsx)(Mn.Eye,{className:"af-h-4 af-w-4"})})})]},O.id))})]}),(0,_e.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,_e.jsxs)("span",{children:["Showing ",w,"-",I," of ",a]}),(0,_e.jsxs)(on,{value:String(i),onValueChange:O=>o(Number(O)),children:[(0,_e.jsx)(za,{className:"af-w-[70px] af-h-8",children:(0,_e.jsx)(ln,{})}),(0,_e.jsxs)(ja,{children:[(0,_e.jsx)(kt,{value:"10",children:"10"}),(0,_e.jsx)(kt,{value:"25",children:"25"}),(0,_e.jsx)(kt,{value:"50",children:"50"}),(0,_e.jsx)(kt,{value:"100",children:"100"})]})]}),(0,_e.jsx)("span",{children:"per page"})]}),(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_e.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>d(r-1),disabled:!c,children:[(0,_e.jsx)(Mn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,_e.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>d(r+1),disabled:!l,children:["Next",(0,_e.jsx)(Mn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ye=le(require("react"),1),Yt=require("lucide-react");var Zt=le(require("react"),1);function Ts({initialPageSize:e=25,refreshKey:t,includeAggregates:a=!1}={}){let{api:s}=G(),[n,r]=Zt.useState([]),[i,l]=Zt.useState(0),[c,d]=Zt.useState(null),[o,u]=Zt.useState(!0),[b,v]=Zt.useState(null),[m,p]=Zt.useState(0),[f,g]=Zt.useState(e),[x,k]=Zt.useState(void 0),[T,h]=Zt.useState(""),[P,_]=Zt.useState(""),[E,w]=Zt.useState(""),[I,O]=Zt.useState(""),[C,Y]=Zt.useState(""),X=x?x.join(","):"",q=Zt.useRef(0),de=Zt.useCallback(async()=>{let ye=++q.current;u(!0),v(null);try{let D={labels:X?X.split(","):void 0,customerEmail:T||void 0,q:P||void 0,from:E||void 0,to:I||void 0,retainerId:C||void 0,includeAggregates:a,limit:f,offset:m*f},W=await s.getInvoices(D);if(ye!==q.current)return;if(m>0&&m*f>=W.total){p(Math.max(0,Math.ceil(W.total/f)-1));return}r(W.invoices),l(W.total),a&&d(W.aggregates??null)}catch(D){if(ye!==q.current)return;v(D instanceof Error?D:new Error("Failed to fetch invoices"))}finally{ye===q.current&&u(!1)}},[s,X,T,P,E,I,C,m,f,a]);Zt.useEffect(()=>{de()},[de,t]);let ge=ye=>D=>{p(0),ye(D)};return{invoices:n,total:i,aggregates:c,isLoading:o,error:b,page:m,pageSize:f,hasNextPage:(m+1)*f<i,hasPreviousPage:m>0,setPage:p,setPageSize:ge(g),labels:x,setLabels:ge(k),customerEmail:T,setCustomerEmail:ge(h),q:P,setQ:ge(_),from:E,setFrom:ge(w),to:I,setTo:ge(O),retainerId:C,setRetainerId:ge(Y),clearFilters:()=>{p(0),k(void 0),h(""),_(""),w(""),O(""),Y("")},refetch:de}}var N=require("react/jsx-runtime"),yf={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`:yf[e.label]??e.label}function xf(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"},wf={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function ar({invoice:e,className:t}){return(0,N.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,N.jsx)(ie,{variant:xf(e.label),className:t,children:Mo(e)}),e.collection_method==="charge_automatically"&&(0,N.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"})]})}function Mi({delivery:e,className:t}){if(!e)return null;let a=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,N.jsx)(ie,{variant:a,className:t,children:Fo[e.state]??e.state})}function tr(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function pn(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 Tc={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Bi={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},Lo=100,Bo=5e3;async function Sf(e,t){let a=[],s=0;for(let n=0;n<Bo;n+=Lo){let r=await e.getInvoices({...t,limit:Lo,offset:n});if(s=r.total,a.push(...r.invoices),r.invoices.length<Lo||a.length>=s)break}return{invoices:a.slice(0,Bo),total:s,truncated:s>a.length||s>Bo}}function Ic(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,tr(s),Mo(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),se(s.amount_subtotal,s.currency),se(s.tax_total,s.currency),se(s.amount_total,s.currency),s.amount_due===null?"":se(s.amount_due,s.currency),s.amount_paid===null?"":se(s.amount_paid,s.currency),se(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?"":se(s.discount_total,s.currency),s.collection_method??""]);return[t,...a].map(s=>s.map(dc).join(",")).join(`
5
- `)}function Nf(e){_i(new Blob([Ic(e)],{type:"text/csv;charset=utf-8"}),Ri("invoices"))}function Rf({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}=G(),{invoices:v,total:m,isLoading:p,error:f,page:g,pageSize:x,hasNextPage:k,hasPreviousPage:T,setPage:h,labels:P,setLabels:_,customerEmail:E,setCustomerEmail:w,q:I,setQ:O,from:C,setFrom:Y,to:X,setTo:q,retainerId:de,setRetainerId:ge,refetch:ye}=Ts({refreshKey:t}),[D,W]=Ye.useState(typeof d=="number"?"all":"open"),[B,ue]=Ye.useState(""),[me,We]=Ye.useState(null),Ie=Ye.useRef(0),He=!u||!!o,et=Ye.useCallback(z=>{if(u){o?.();return}Ie.current++,Ke(!1),We(z)},[u,o]),[De,Ke]=Ye.useState(!1),[L,V]=Ye.useState(0),[$,xe]=Ye.useState(null),[H,ke]=Ye.useState(!1),[ze,gt]=Ye.useState(0);Ye.useEffect(()=>{We(z=>{if(!z)return z;let Oe=v.find(zt=>zt.id===z.id);return Oe&&Oe!==z?Oe:z})},[v]);let[st,Ot]=Ye.useState(!1),[Pe,Ge]=Ye.useState(null),yt=async()=>{if(!st){Ot(!0),Ge(null);try{let{invoices:z,total:Oe,truncated:zt}=await Sf(b,{labels:P,customerEmail:E,q:I,from:C,to:X,retainerId:de});Nf(z),Ge(zt?`Exported the first ${z.length.toLocaleString()} of ${Oe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ge("Couldn't export \u2014 try again.")}finally{Ot(!1)}}},Lt=!E&&!I&&!C&&!X&&!de,[Vt,it]=Ye.useState(null);Ye.useEffect(()=>{if(p||m>0||!Lt||D!=="open")return;let z=!1;return b.getInvoices({limit:1}).then(Oe=>{z||it(Oe.total>0)}).catch(()=>{z||it(!0)}),()=>{z=!0}},[b,p,m,Lt,D,t]),Ye.useEffect(()=>{_(u?Bi.all:Bi.open)},[]),Ye.useEffect(()=>{let z=l?.id??"";z!==de&&(ge(z),z&&(W("all"),_(Bi.all),w(""),O(""),ue(""),Y(""),q("")))},[l?.id]),Ye.useEffect(()=>{let z=!1;return ke(!1),b.getInvoiceSettings().then(Oe=>{z||xe({payments_active:Oe.payments_active,blocked:Oe.blocked})}).catch(()=>{z||ke(!0)}),()=>{z=!0}},[b,t,ze]),Ye.useEffect(()=>{if(!a||u)return;let z=!1,Oe=Ie.current;return Ke(!1),b.getInvoice(a).then(zt=>{!z&&Oe===Ie.current&&We(zt)}).catch(()=>{!z&&Oe===Ie.current&&Ke(!0)}),()=>{z=!0}},[b,a,L,u]),Ye.useEffect(()=>{s?.(me!==null)},[me,s]);let Qt=z=>{W(z),_(Bi[z])},tt=z=>{let Oe=z.trim();if(!Oe){I&&O(""),E&&w("");return}if(Oe.includes("@")){I&&O(""),w(Oe);return}E&&w(""),O(Oe.replace(/^#/,""))},Rt=v,Va=u?Rt.slice(0,d):Rt,In=De&&(0,N.jsxs)("div",{role:"alert",className:"af-mb-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't open the requested invoice. ",(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>V(z=>z+1),children:"Retry opening invoice"})]});if(me)return(0,N.jsxs)("div",{className:e,children:[In,(0,N.jsx)($i,{invoice:me,refreshKey:t,onBack:()=>{et(null),ye()}},me.id)]});let Te=(0,N.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[H&&(0,N.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>gt(z=>z+1),children:"Retry setup check"})]}),In,$?.blocked&&(0,N.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",$.blocked.reason?`: ${$.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),l&&(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,N.jsxs)(ie,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",l.label]}),c&&(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:c,children:"Clear schedule filter"})]}),(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,N.jsx)("div",{role:"group","aria-label":"Invoice views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Object.keys(Tc).map(z=>(0,N.jsx)("button",{type:"button","aria-pressed":D===z,onClick:()=>Qt(z),className:Q("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",D===z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Tc[z]},z))}),(0,N.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,N.jsx)(Yt.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,N.jsx)(ce,{type:"text",value:B,onChange:z=>ue(z.target.value),onBlur:()=>tt(B),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),tt(B))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,N.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,N.jsx)(qe,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,N.jsx)(ce,{id:"invoices-from",type:"date",value:C,max:X||void 0,onChange:z=>Y(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,N.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,N.jsx)(qe,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,N.jsx)(ce,{id:"invoices-to",type:"date",value:X,min:C||void 0,onChange:z=>q(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,N.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void yt(),disabled:st||p||!!f||m===0,"aria-busy":st,children:[(0,N.jsx)(Yt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),st?"Exporting\u2026":"Export CSV (all matching)"]})]}),Pe&&(0,N.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:Pe})]});return p?(0,N.jsxs)("div",{className:e,children:[u?null:Te,(0,N.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(z=>(0,N.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,N.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,N.jsx)(ee,{className:"af-h-4 af-w-20"}),(0,N.jsx)(ee,{className:"af-h-4 af-w-16"})]}),(0,N.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-40"})]},z))})]}):f?(0,N.jsxs)("div",{className:e,children:[u?null:Te,(0,N.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>void ye(),children:"Retry"})]})]}):m===0&&Lt&&(D==="all"||Vt===!1)&&(D==="open"||D==="all")?$?.blocked?(0,N.jsxs)("div",{className:e,children:[u?null:Te,(0,N.jsx)(Fi,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):i?(0,N.jsxs)("div",{className:e,children:[u?null:Te,(0,N.jsx)(Fi,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):$&&!$.payments_active?(0,N.jsxs)("div",{className:e,children:[u?null:Te,(0,N.jsx)(Fi,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):(0,N.jsxs)("div",{className:e,children:[u?null:Te,(0,N.jsx)(Fi,{heading:"No invoices yet",body:!$||H?"Once invoice setup is ready, you can send invoices from the chat.":"Ask in the chat to send an invoice to a client for your services."})]}):(0,N.jsxs)("div",{className:e,children:[u?null:Te,Va.length===0?(0,N.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:"No invoices match."}):(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Va.map(z=>(0,N.jsxs)("button",{type:"button",onClick:()=>et(z),disabled:!He,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${He?" hover:af-bg-muted/50":""}`,children:[(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,N.jsx)("span",{className:"af-font-medium",children:tr(z)}),(0,N.jsx)(ar,{invoice:z})]}),(0,N.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:z.customer_name??z.customer_email??"\u2014"}),z.delivery&&(0,N.jsx)("div",{className:"af-mt-1",children:(0,N.jsx)(Mi,{delivery:z.delivery})}),(0,N.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[(0,N.jsx)("span",{children:z.collection_method==="charge_automatically"?"Automatic collection":z.due_at?`Due ${pn(z.due_at)}`:"Due on receipt"}),(0,N.jsx)("span",{className:"af-font-medium af-tabular-nums",children:se(z.amount_due??z.amount_total,z.currency)})]})]},z.id))}),(0,N.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,N.jsxs)(ut,{children:[(0,N.jsx)(ft,{children:(0,N.jsxs)($e,{children:[(0,N.jsx)(te,{children:"Invoice"}),(0,N.jsx)(te,{children:"Created"}),(0,N.jsx)(te,{children:"Customer"}),(0,N.jsx)(te,{children:"Due"}),(0,N.jsx)(te,{className:"af-text-right",children:"Amount"}),(0,N.jsx)(te,{children:"Status"}),(0,N.jsx)(te,{children:"Delivery"}),(0,N.jsx)(te,{className:"af-w-8"})]})}),(0,N.jsx)(mt,{children:Va.map(z=>(0,N.jsxs)($e,{className:He?"af-cursor-pointer":void 0,onClick:He?()=>et(z):void 0,children:[(0,N.jsx)(ae,{className:"af-font-medium",children:(0,N.jsx)("button",{type:"button",disabled:!He,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${He?" hover:af-underline":""}`,onClick:Oe=>{Oe.stopPropagation(),et(z)},"aria-label":`Open invoice ${tr(z)}`,children:tr(z)})}),(0,N.jsx)(ae,{children:pn(z.created_at)}),(0,N.jsxs)(ae,{children:[(0,N.jsx)("div",{children:z.customer_name??"\u2014"}),(0,N.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:z.customer_email})]}),(0,N.jsx)(ae,{children:z.collection_method==="charge_automatically"?"Automatic":z.due_at?pn(z.due_at):"On receipt"}),(0,N.jsx)(ae,{className:"af-text-right af-tabular-nums",children:se(z.amount_due??z.amount_total,z.currency)}),(0,N.jsx)(ae,{children:(0,N.jsx)(ar,{invoice:z})}),(0,N.jsx)(ae,{children:(0,N.jsx)(Mi,{delivery:z.delivery})}),(0,N.jsx)(ae,{children:(0,N.jsx)(Yt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},z.id))})]})}),u?null:(0,N.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,N.jsxs)("span",{children:[m," invoice",m===1?"":"s"]}),(0,N.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,N.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(g-1),disabled:!T,"aria-label":"Previous page",children:(0,N.jsx)(Yt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,N.jsxs)("span",{className:"af-tabular-nums",children:[g*x+1,"\u2013",Math.min((g+1)*x,m)]}),(0,N.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(g+1),disabled:!k,"aria-label":"Next page",children:(0,N.jsx)(Yt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Fi({heading:e,body:t,action:a}){return(0,N.jsx)(Qs,{icon:Yt.FileText,heading:e,body:t,action:a})}function ts(e){return(0,N.jsx)(Rf,{...e},e.maxRows==null?"full":"compact")}var es="af-text-xs af-text-muted-foreground";function Ec(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function $i({invoice:e,onBack:t,refreshKey:a,className:s}){let{api:n}=G(),r=Ye.useRef(null);Ye.useEffect(()=>{r.current?.focus()},[e.id]);let[i,l]=Ye.useState(!1),[c,d]=Ye.useState(null),[o,u]=Ye.useState(!1),[b,v]=Ye.useState(!1),m=Ye.useRef(0),[p,f]=Ye.useState(null),[g,x]=Ye.useState(!1),[k,T]=Ye.useState(0);Ye.useEffect(()=>{let C=!1;return x(!1),n.getInvoice(e.id).then(Y=>{C||f({source:e,value:Y})}).catch(()=>{C||x(!0)}),()=>{C=!0}},[n,e,a,k]);let h=p?.source===e?p.value:e,P=h.collection_method==="charge_automatically";Ye.useEffect(()=>(m.current++,d(null),u(!1),v(!1),l(!1),()=>{m.current++}),[n,h,a]);let _=C=>C==null?"\u2014":se(C,h.currency),E=async()=>{if(!(!h.pay_url||!Ec()))try{await navigator.clipboard.writeText(h.pay_url),l(!0),setTimeout(()=>l(!1),1500)}catch{}},w=async()=>{if(c){d(null);return}let C=++m.current;v(!1),u(!0);try{let Y=await n.getInvoicePreview(h.id);C===m.current&&d(Y)}catch{C===m.current&&v(!0)}finally{C===m.current&&u(!1)}},I=h.bill_to,O=I?[I.company,I.name,I.address?.line1,I.address?.line2,[I.address?.city,I.address?.state,I.address?.postal_code].filter(Boolean).join(", "),I.address?.country,I.tax_id?`${I.tax_id.value}`:null,I.po_number?`PO ${I.po_number}`:null,I.service_period?`Service period: ${I.service_period}`:null].filter(C=>!!C&&C.length>0):[];return(0,N.jsxs)("div",{className:s,children:[(0,N.jsxs)("div",{className:"af-mb-4",children:[(0,N.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,N.jsx)(Yt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,N.jsxs)("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",tr(h)]}),(0,N.jsx)(ar,{invoice:h}),(0,N.jsx)(Mi,{delivery:h.delivery})]}),(0,N.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[h.customer_name??h.customer_email,h.customer_name&&h.customer_email?` \xB7 ${h.customer_email}`:""]})]}),g&&(0,N.jsxs)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't refresh this invoice. These details may be out of date. ",(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>T(C=>C+1),children:"Retry details"})]}),h.label==="failed"&&(0,N.jsx)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),h.label==="creating"&&(0,N.jsx)("p",{role:"status",className:"af-mb-4 af-text-sm af-text-muted-foreground",children:"This invoice is still being created. Its final details will appear when it is ready."}),(0,N.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,N.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,N.jsxs)(ut,{children:[(0,N.jsx)(ft,{children:(0,N.jsxs)($e,{children:[(0,N.jsx)(te,{children:"Description"}),(0,N.jsx)(te,{className:"af-text-right",children:"Qty"}),(0,N.jsx)(te,{className:"af-text-right",children:"Amount"})]})}),(0,N.jsx)(mt,{children:h.line_items.map((C,Y)=>(0,N.jsxs)($e,{children:[(0,N.jsx)(ae,{style:{overflowWrap:"anywhere"},children:C.description}),(0,N.jsx)(ae,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:C.quantity}),(0,N.jsx)(ae,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_(C.amount)})]},Y))})]}),(0,N.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,N.jsx)(ps,{label:"Subtotal",value:_(h.amount_subtotal)}),(h.discount_total??0)>0&&(0,N.jsx)(ps,{label:"Discount",value:`-${_(h.discount_total)}`}),h.tax_total>0&&(0,N.jsx)(ps,{label:h.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:_(h.tax_total)}),(0,N.jsx)(ps,{label:"Total",value:_(h.amount_total),strong:!0}),h.credit_applied>0&&(0,N.jsx)(ps,{label:"Credit applied",value:`-${_(h.credit_applied)}`}),h.amount_due!==null&&h.amount_due!==h.amount_total&&(0,N.jsx)(ps,{label:"Amount due",value:_(h.amount_due),strong:!0}),h.amount_paid!==null&&h.amount_paid>0&&(0,N.jsx)(ps,{label:"Amount paid",value:_(h.amount_paid)}),h.amount_refunded>0&&(0,N.jsx)(ps,{label:"Refunded",value:_(h.amount_refunded)})]}),h.credit_notes?.length>0&&(0,N.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,N.jsx)("div",{className:es,children:"Credit notes"}),h.credit_notes.map(C=>(0,N.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,N.jsxs)("span",{className:"af-text-muted-foreground",children:[pn(C.created_at)," \xB7 ",C.origin==="dashboard"?"issued in Stripe":"refund",C.stripe_credit_note_id?"":" \xB7 being created"]}),(0,N.jsxs)("span",{className:"af-tabular-nums",children:["-",se(C.amount,C.currency)]})]},C.id))]})]}),(h.note||h.footer)&&(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[h.note&&(0,N.jsxs)("div",{children:[(0,N.jsx)("div",{className:es,children:"Note"}),(0,N.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:h.note})]}),h.footer&&(0,N.jsxs)("div",{children:[(0,N.jsx)("div",{className:es,children:"Footer"}),(0,N.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:h.footer})]})]}),c&&!P&&(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,N.jsxs)("div",{className:Q(es,"af-break-words"),children:["Email preview \u2014 ",c.subject]}),(0,N.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,N.jsx)("iframe",{title:"Invoice email preview",srcDoc:c.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,N.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,N.jsx)(mn,{label:"Created",value:pn(h.created_at)}),(0,N.jsx)(mn,{label:"Due",value:h.collection_method==="charge_automatically"?"Managed in Stripe":h.due_at?pn(h.due_at):"On receipt"}),h.paid_at&&(0,N.jsx)(mn,{label:"Paid",value:pn(h.paid_at)}),h.payment_method&&(0,N.jsx)(mn,{label:"Paid by",value:h.paid_out_of_band?`${h.payment_method} (recorded outside Stripe)`:h.payment_method}),h.payment_state!=="none"&&(0,N.jsx)(mn,{label:"Payment",value:h.payment_state==="processing"?"Processing":h.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),h.delivery&&(0,N.jsx)(mn,{label:"Delivery",value:`${Fo[h.delivery.state]} \xB7 ${h.delivery.recipient}`}),h.marked_uncollectible_at&&(0,N.jsx)(mn,{label:"Written off",value:pn(h.marked_uncollectible_at)}),h.correction_reason&&(0,N.jsx)(mn,{label:"Correction",value:h.correction_reason}),h.replaced_by_order_id&&(0,N.jsx)(mn,{label:"Replaced by",value:h.replaced_by_order_id}),h.collection_method==="charge_automatically"?(0,N.jsx)(mn,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):h.retainer_id&&(0,N.jsx)(mn,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),h.replaces_order_id&&(0,N.jsx)(mn,{label:"Replaces",value:h.replaces_order_id})]}),(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,N.jsx)("div",{className:es,children:"Reminders"}),P?(0,N.jsx)("div",{children:"View automatic payment reminders in Stripe."}):h.reminders.disabled?(0,N.jsx)("div",{children:"Off for this invoice."}):h.reminders.paused_until?(0,N.jsxs)("div",{children:["Paused until ",pn(h.reminders.paused_until),"."]}):h.reminders.next_at?(0,N.jsxs)("div",{children:["Next on ",pn(h.reminders.next_at),"."]}):h.reminders.final_sent_at?(0,N.jsxs)("div",{children:["Final reminder sent ",pn(h.reminders.final_sent_at),"."]}):(0,N.jsx)("div",{children:"None scheduled."}),!P&&(0,N.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",h.reminders.schedule.length===0?"none":h.reminders.schedule.map(C=>C<0?`${-C}d before`:C===0?"due day":`${C}d after`).join(", ")]})]}),h.communications&&h.communications.length>0&&(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,N.jsx)("div",{className:es,children:"Email delivery history"}),h.communications.map(C=>(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,N.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[wf[C.kind]??C.kind,C.kind==="reminder"&&C.slot!==null?` #${C.slot}`:"",(0,N.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",C.recipient]})]}),(0,N.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Fo[C.state]??C.state," \xB7 ",pn(C.state_at??C.created_at)]})]},C.id))]}),O.length>0&&(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,N.jsx)("div",{className:es,children:"Bill to"}),O.map((C,Y)=>(0,N.jsx)("div",{className:"af-break-words",children:C},Y))]}),(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[h.pay_url&&(0,N.jsxs)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void E(),disabled:!Ec(),children:[(0,N.jsx)(Yt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Copied":P?"Copy invoice link":"Copy pay link"]}),h.pdf_url&&(0,N.jsx)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,N.jsxs)("a",{href:h.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,N.jsx)(Yt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!P&&(0,N.jsxs)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void w(),disabled:o,children:[o?(0,N.jsx)(Yt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,N.jsx)(Yt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),c?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!P&&(0,N.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),h.pay_url&&(0,N.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:h.pay_url}),(0,N.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:P?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function mn({label:e,value:t}){return(0,N.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,N.jsx)("span",{className:Q(es,"af-shrink-0"),children:e}),(0,N.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function ps({label:e,value:t,strong:a}){return(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,N.jsx)("dt",{className:Q(es,a&&"af-font-medium af-text-foreground"),children:e}),(0,N.jsx)("dd",{className:Q("af-tabular-nums",a&&"af-font-semibold"),children:t})]})}var Dc=require("lucide-react");var nt=require("react/jsx-runtime"),_f={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Ac={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function kf(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 Oc(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>Ac[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>Ac[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":_f[e.status]}function Lc(e){let t=e.interval==="year"?"every year":"every month";return`${se(e.amount,e.currency)} ${t}`}function Pf(e){return e.status==="canceled"?`Ended ${Ui(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Ui(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 ${Ui(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Ui(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Ui(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 Vi({retainer:e,className:t}){return(0,nt.jsx)(ie,{variant:kf(e.status),className:Q("af-max-w-full af-whitespace-normal af-break-words",t),children:Oc(e)})}function Es({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 p=i!==void 0?Math.max(0,i-e.length):0;return(0,nt.jsxs)("section",{className:Q("af-mb-6",v),"aria-label":"Recurring invoices",children:[(0,nt.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,nt.jsx)(Dc.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,nt.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,nt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),m&&(0,nt.jsx)(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&&(0,nt.jsx)(ma,{fetchCsv:b,filename:"retainers",className:m?void 0:"af-ml-auto"})]}),a?(0,nt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",(0,nt.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?(0,nt.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(f=>(0,nt.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,nt.jsx)(ee,{className:"af-h-4 af-w-48"}),(0,nt.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-32"})]},f))}):e.length===0?(0,nt.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:o?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,nt.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(f=>{let g=r===f.id;return(0,nt.jsxs)("li",{className:Q("af-rounded-md af-border af-p-3",g&&"af-border-primary af-bg-muted/40"),children:[(0,nt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,nt.jsxs)("div",{className:"af-min-w-0",children:[(0,nt.jsx)("div",{className:"af-truncate af-font-medium",children:f.customer_name??f.customer_email??"\u2014"}),(0,nt.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:f.description})]}),(0,nt.jsx)(Vi,{retainer:f})]}),f.collection_method==="charge_automatically"?(0,nt.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,nt.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"}),(0,nt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Automatic charging is enabled in Stripe. View or change the billing terms there. To edit this schedule from the chat, switch it back to sending invoices in Stripe."})]}):(0,nt.jsx)("div",{className:"af-mt-2 af-text-sm",children:Lc(f)}),(0,nt.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-text-xs af-text-muted-foreground",children:[(0,nt.jsxs)("span",{children:[Pf(f)," \xB7 ",f.cycles.count===0?"no invoices yet":`${f.cycles.paid} paid${f.cycles.open>0?`, ${f.cycles.open} open`:""}`]}),f.cycles.count>0&&(0,nt.jsx)(y,{type:"button",variant:g?"secondary":"ghost",size:"sm",onClick:()=>n(f),"aria-pressed":g,children:g?"Showing invoices":"View invoices"})]}),f.status==="failed"&&f.operation?.last_error&&(0,nt.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",f.operation.last_error,". Ask in the chat to try again."]})]},f.id)})}),!t&&!a&&p>0&&d&&(0,nt.jsx)("div",{className:"af-mt-2",children:(0,nt.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:d,disabled:c,children:c?"Loading\u2026":`Load more (${p} more)`})})]})}var Bc=le(require("react"),1),tn=require("lucide-react");var Ue=require("react/jsx-runtime");function Is({onConnectStripe:e,onUpgradePlan:t,whenActive:a,className:s}){let{status:n,isLoading:r,error:i,refetch:l}=Yn(),[c,d]=Bc.useState(!1),o=async()=>{d(!0);try{await l()}finally{d(!1)}};return r&&!n?(0,Ue.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ue.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!n?(0,Ue.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ue.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):n.status==="active"?a!==void 0?(0,Ue.jsx)("div",{className:s,children:a}):(0,Ue.jsx)("div",{className:s,children:(0,Ue.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-green-50 af-border af-border-green-200 af-rounded-lg af-p-4",children:[(0,Ue.jsx)(tn.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Ue.jsxs)("div",{children:[(0,Ue.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Ue.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",n.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,Ue.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[n.reason==="needs_stripe"&&(0,Ue.jsxs)("div",{className:"af-space-y-3",children:[(0,Ue.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ue.jsx)(tn.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ue.jsxs)("div",{children:[(0,Ue.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Ue.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"It only takes a few minutes. You'll enter your details with Stripe, who handle the payments, and money from sales goes straight to your own bank."})]})]}),e?(0,Ue.jsxs)(y,{onClick:e,children:[(0,Ue.jsx)(tn.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),n.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Ue.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),n.reason==="needs_paid_plan"&&(0,Ue.jsxs)("div",{className:"af-space-y-3",children:[(0,Ue.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ue.jsx)(tn.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ue.jsxs)("div",{children:[(0,Ue.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Ue.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your products are saved as drafts. Upgrade to a paid plan to start accepting payments on your site."})]})]}),t?(0,Ue.jsx)(y,{onClick:t,children:"Upgrade plan"}):(0,Ue.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),n.reason==="account_disabled"&&(0,Ue.jsxs)("div",{className:"af-space-y-3",children:[(0,Ue.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-yellow-50 af-border af-border-yellow-200 af-rounded-lg af-p-4",children:[(0,Ue.jsx)(tn.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Ue.jsxs)("div",{children:[(0,Ue.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),n.stripe_account_connected?(0,Ue.jsx)("p",{className:"af-text-sm af-text-yellow-800",children:"Your Stripe account can't currently accept charges. Check your Stripe account for outstanding requirements or notifications \u2014 once Stripe re-enables charges, payments resume here automatically."}):(0,Ue.jsx)("p",{className:"af-text-sm af-text-yellow-800",children:"Payments are currently paused for this site. If you think this is a mistake, get in touch with support and we'll look into it with you."})]})]}),(0,Ue.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&n.stripe_account_connected&&(0,Ue.jsxs)(y,{onClick:e,children:[(0,Ue.jsx)(tn.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Ue.jsxs)(y,{variant:"outline",onClick:o,disabled:c,children:[c?(0,Ue.jsx)(tn.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Ue.jsx)(tn.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var Ra=le(require("react"),1);function $o(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function As({includeStats:e=!1,refreshKey:t}={}){let{api:a}=G(),[s,n]=Ra.useState([]),[r,i]=Ra.useState(!0),[l,c]=Ra.useState(null),d=Ra.useRef(0),o=Ra.useCallback(async()=>{let f=++d.current;try{i(!0),c(null);let g=await a.getProducts(e?{include:"stats"}:{});if(f!==d.current)return;n(g)}catch(g){if(f!==d.current)return;c(g instanceof Error?g:new Error("Failed to fetch products"))}finally{f===d.current&&i(!1)}},[a,e,t]);Ra.useEffect(()=>{o()},[o]);let u=Ra.useCallback(async f=>{let g=await a.createProduct(f);return n(x=>[g,...x]),g},[a]),b=Ra.useCallback(async(f,g)=>{let x=await a.updateProduct(f,g);return n(k=>$o(k,f,x)),x},[a]),v=Ra.useCallback(async f=>{await a.deleteProduct(f),n(g=>g.filter(x=>x.id!==f))},[a]),m=Ra.useCallback(async(f,g)=>{let x=await a.attachProductFile(f,g);return n(k=>$o(k,f,x)),x},[a]),p=Ra.useCallback(async(f,g)=>{let x=await a.attachProductFileFromUrl(f,g);return n(k=>$o(k,f,x)),x},[a]);return{products:s,isLoading:r,error:l,refetch:o,createProduct:u,updateProduct:b,deleteProduct:v,attachProductFile:m,attachProductFileFromUrl:p}}var _a=le(require("react"),1);var Uo=["creating","active","paused","canceling"],Cf=["canceled","failed"],Tf={statuses:Uo},Ef={};function Ds({refreshKey:e,includeEnded:t=!1,limit:a=50}={}){let{api:s}=G(),[n,r]=_a.useState([]),[i,l]=_a.useState(0),[c,d]=_a.useState(0),[o,u]=_a.useState(!0),[b,v]=_a.useState(!1),[m,p]=_a.useState(null),[f,g]=_a.useState(t),x=_a.useRef(0),k=_a.useCallback(async()=>{let h=++x.current;u(!0),v(!1),p(null);try{let P=await s.getRetainers({statuses:f?void 0:Uo,limit:a,offset:0});if(h!==x.current)return;if(r(P.retainers),l(P.total),!f&&P.total===0){let _=await s.getRetainers({statuses:Cf,limit:1,offset:0});if(h!==x.current)return;d(_.total)}else d(0)}catch(P){if(h!==x.current)return;p(P instanceof Error?P:new Error("Failed to fetch retainers"))}finally{h===x.current&&u(!1)}},[s,f,a]);_a.useEffect(()=>{k()},[k,e]);let T=_a.useCallback(async()=>{if(o||b||n.length>=i)return;let h=x.current;v(!0);try{let P=await s.getRetainers({statuses:f?void 0:Uo,limit:a,offset:n.length});if(h!==x.current)return;r(_=>{let E=new Set(_.map(w=>w.id));return[..._,...P.retainers.filter(w=>!E.has(w.id))]}),l(P.total)}catch(P){if(h!==x.current)return;p(P instanceof Error?P: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:g,loadMore:T,refetch:k,filters:f?Ef:Tf}}var Me=require("react/jsx-runtime");function Vo({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:n}){let[r,i]=nr.useState(t),[l,c]=nr.useState("list"),[d,o]=nr.useState(null),u=As(),{status:b,error:v}=Yn(),m=b?.currency,p=k=>{o(k),c("edit")},f=()=>{o(null),c("create")},g=()=>{c("list"),o(null)},x=k=>{o(k),c("edit")};return(0,Me.jsxs)("div",{className:e,children:[(0,Me.jsxs)("div",{className:"af-mb-6",children:[(0,Me.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Me.jsxs)(xi,{value:r,onValueChange:k=>i(k),children:[(0,Me.jsxs)(vr,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Me.jsxs)(Sn,{value:"products",className:"af-gap-2",children:[(0,Me.jsx)(gn.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Me.jsxs)(Sn,{value:"orders",className:"af-gap-2",children:[(0,Me.jsx)(gn.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Me.jsxs)(Sn,{value:"invoices",className:"af-gap-2",children:[(0,Me.jsx)(gn.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Me.jsxs)(Sn,{value:"customers",className:"af-gap-2",children:[(0,Me.jsx)(gn.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Me.jsx)(Sn,{value:"promos",children:"Promo codes"}),(0,Me.jsxs)(Sn,{value:"setup",className:"af-gap-2",children:[(0,Me.jsx)(gn.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Me.jsx)(Nn,{value:"products",children:l==="list"?(0,Me.jsx)(Ir,{productsState:u,onSelectProduct:p,onCreateProduct:f}):(0,Me.jsxs)("div",{children:[(0,Me.jsxs)("div",{className:"af-mb-6",children:[(0,Me.jsxs)(y,{variant:"ghost",size:"sm",onClick:g,className:"af-mb-2 af--ml-2",children:[(0,Me.jsx)(gn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Me.jsx)("h3",{className:"af-text-lg af-font-semibold",children:l==="create"?"New Product":d?.name})]}),l==="create"&&!m?(0,Me.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:v?(0,Me.jsxs)("div",{className:"af-text-destructive",children:["Error: ",v.message]}):(0,Me.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Me.jsx)(Dr,{productsState:u,product:l==="edit"?d:null,currency:m??"usd",onSaved:x},l==="edit"?d?.id??"edit":"new")]})}),(0,Me.jsx)(Nn,{value:"orders",children:(0,Me.jsx)(Qn,{onRefund:s})}),(0,Me.jsx)(Nn,{value:"invoices",children:(0,Me.jsx)(If,{onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),(0,Me.jsx)(Nn,{value:"customers",children:(0,Me.jsx)(Ur,{})}),(0,Me.jsx)(Nn,{value:"promos",children:(0,Me.jsx)(_s,{})}),(0,Me.jsx)(Nn,{value:"setup",children:(0,Me.jsx)(Is,{onConnectStripe:a,onUpgradePlan:n})})]})]})}function If({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a}){let s=Ds(),[n,r]=nr.useState(null),[i,l]=nr.useState(!1);return(0,Me.jsxs)(Me.Fragment,{children:[!i&&(0,Me.jsx)(Es,{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}),(0,Me.jsx)(ts,{onDetailOpenChange:l,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}var Mc=le(require("react"),1);var $n=le(require("react"),1);function Os({refreshKey:e}={}){let{api:t}=G(),[a,s]=$n.useState(null),[n,r]=$n.useState(!0),[i,l]=$n.useState(null),c=$n.useRef(0),d=$n.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 $n.useEffect(()=>{d()},[d]),{summary:a,isLoading:n,error:i,refetch:d}}var bt=require("react/jsx-runtime");function Fc(e,t){if(e.settled.complete)return{headline:se(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:se(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${se(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:se(0,t),extra:[]}}function Ho({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:n,className:r}){let{summary:i,isLoading:l,error:c,refetch:d}=Os({refreshKey:e}),[o,u]=Mc.useState(!1),b=(0,bt.jsx)("div",{className:"af-mb-6",children:c&&!i?(0,bt.jsx)(wt,{message:"Couldn't load your revenue summary.",onRetry:()=>d()}):(0,bt.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:l||!i?(0,bt.jsxs)(bt.Fragment,{children:[(0,bt.jsx)(vt,{label:"This week",children:(0,bt.jsx)(ee,{className:"af-h-6 af-w-24"})}),(0,bt.jsx)(vt,{label:"Today",children:(0,bt.jsx)(ee,{className:"af-h-6 af-w-24"})}),(0,bt.jsx)(vt,{label:"Needs attention",children:(0,bt.jsx)(ee,{className:"af-h-6 af-w-10"})})]}):(0,bt.jsx)(bt.Fragment,{children:(()=>{let v=Fc(i.revenue.d7,i.currency),m=Fc(i.revenue.today,i.currency);return(0,bt.jsxs)(bt.Fragment,{children:[(0,bt.jsx)(vt,{label:"This week",detail:v.extra.length>0?(0,bt.jsx)("div",{children:v.extra.map(p=>(0,bt.jsx)("div",{children:p},p))}):void 0,children:v.headline}),(0,bt.jsx)(vt,{label:"Today",detail:m.extra.length>0?(0,bt.jsx)("div",{children:m.extra.map(p=>(0,bt.jsx)("div",{children:p},p))}):void 0,children:m.headline}),(0,bt.jsx)(vt,{label:"Needs attention",valueClassName:i.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:i.needs_attention.count===0?"All clear":i.needs_attention.items[0]?.title??void 0,children:i.needs_attention.count})]})})()})})});return(0,bt.jsxs)(Ft,{title:"Orders",onBackToWebsite:n,hideBackButton:o,className:r,children:[b,(0,bt.jsx)(Qn,{refreshKey:e,initialOrderId:t,onDetailOpenChange:u,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var vn=le(require("react"),1),sr=require("lucide-react");var Un=le(require("react"),1),Gi=require("lucide-react");var ca=require("react/jsx-runtime"),$c="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",gs="af-text-xs af-text-muted-foreground",Hi="af-text-sm af-font-medium af-tabular-nums",Af=3;function Df(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 (${se(c,a)} \u2013 ${se(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?se(n,a):`${se(n,a)} \u2013 ${se(r,a)}`,l=t?.compare_at_amount??null;return{text:i,compareAt:l!==null&&l>r?se(l,a):null}}function zi({product:e,className:t}){let a=Df(e);return(0,ca.jsxs)("div",{className:t,children:[(0,ca.jsx)("span",{className:Hi,children:a.text}),a.compareAt&&(0,ca.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function ji({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,ca.jsx)(ie,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,ca.jsxs)(ie,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,ca.jsx)(ie,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,ca.jsxs)(ie,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,ca.jsx)(ie,{variant:"warning",children:"Low stock"}):null}function qi(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Wi(e){return e.map(t=>se(t.amount,t.currency)).join(" + ")}function Uc(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${se(e.min_amount,e.currency)} \u2013 ${se(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":se(e.unit_amount,e.currency)}function Vc({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,ca.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?(0,ca.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ca.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,a)}),(0,ca.jsx)(ie,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?(0,ca.jsx)(ie,{variant:"destructive",children:"Out of stock"}):(0,ca.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ca.jsx)("span",{className:"af-tabular-nums",children:a}),a<=Af&&(0,ca.jsx)(ie,{variant:"warning",children:"Low"})]})}var fe=require("react/jsx-runtime");function Vr({title:e,children:t,className:a}){return(0,fe.jsxs)("section",{className:Q("af-rounded-lg af-border af-p-4",a),children:[(0,fe.jsx)("h4",{className:$c,children:e}),(0,fe.jsx)("div",{className:"af-mt-3",children:t})]})}function Hc({src:e,className:t}){let[a,s]=Un.useState(!1);return Un.useEffect(()=>s(!1),[e]),!e||a?(0,fe.jsx)("div",{"aria-hidden":"true",className:Q("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,fe.jsx)(Gi.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,fe.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:Q("af-object-cover",t)})}function zc({product:e,showStats:t=!1,onBack:a}){let{api:s}=G(),[n,r]=Un.useState(null),[i,l]=Un.useState(!0),[c,d]=Un.useState(null),[o,u]=Un.useState(0),[b,v]=Un.useState(0);Un.useEffect(()=>{let h=!1;return l(!0),d(null),s.getProduct(e.id).then(P=>{h||r(P)}).catch(P=>{h||d(P instanceof Error?P:new Error("Failed to load product"))}).finally(()=>{h||l(!1)}),()=>{h=!0}},[s,e.id,o]);let m=n?{...e,...n}:e,p=m.images.length>0?m.images:e.images,f=p[b]??p[0],g=qi(m),x=t?m.stats:void 0,k=n?.variants??[],T=k.length>1;return(0,fe.jsxs)("div",{children:[(0,fe.jsxs)("div",{className:"af-mb-6",children:[(0,fe.jsxs)(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,fe.jsx)(Gi.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,fe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,fe.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:m.name}),(0,fe.jsx)(ie,{variant:m.active?"success":"secondary",children:m.active?"Active":"Draft"}),(0,fe.jsx)(ji,{product:m})]}),(0,fe.jsx)(zi,{product:m,className:"af-mt-1"}),!m.active&&(0,fe.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),(0,fe.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,fe.jsxs)("div",{className:"af-space-y-2",children:[(0,fe.jsx)(Hc,{src:f,className:"af-h-48 af-w-full af-rounded-md af-border"}),p.length>1&&(0,fe.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:p.map((h,P)=>(0,fe.jsx)("button",{type:"button",onClick:()=>v(P),"aria-label":`Show photo ${P+1} of ${p.length}`,"aria-pressed":P===b,className:Q("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",P===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,fe.jsx)(Hc,{src:h,className:"af-h-12 af-w-12 af-rounded-md"})},`${h}-${P}`))})]}),(0,fe.jsxs)("div",{className:"af-space-y-6",children:[m.description&&(0,fe.jsx)(Vr,{title:"Description",children:(0,fe.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:m.description})}),i?(0,fe.jsxs)(Vr,{title:"Variants",children:[(0,fe.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(h=>(0,fe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,fe.jsx)(ee,{className:"af-h-4 af-w-28"}),(0,fe.jsx)(ee,{className:"af-h-4 af-w-20"}),(0,fe.jsx)(ee,{className:"af-h-4 af-w-16"})]},h))}),(0,fe.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):c?(0,fe.jsx)(wt,{message:"Couldn't load this product's variants.",onRetry:()=>u(h=>h+1)}):T?(0,fe.jsx)(Vr,{title:`Variants \xB7 ${k.length}`,children:(0,fe.jsx)("div",{className:"af-overflow-x-auto",children:(0,fe.jsxs)(ut,{children:[(0,fe.jsx)(ft,{children:(0,fe.jsxs)($e,{children:[(0,fe.jsx)(te,{children:"Variant"}),(0,fe.jsx)(te,{children:"SKU"}),(0,fe.jsx)(te,{className:"af-text-right",children:"Price"}),(0,fe.jsx)(te,{children:"Stock"})]})}),(0,fe.jsx)(mt,{children:k.map(h=>(0,fe.jsxs)($e,{children:[(0,fe.jsxs)(ae,{className:"af-font-medium",children:[h.title||h.option_values.map(P=>P.value).join(" / ")||"\u2014",!h.active&&(0,fe.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,fe.jsx)(ae,{className:"af-text-muted-foreground",children:h.sku?(0,fe.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:h.sku}):"\u2014"}),(0,fe.jsxs)(ae,{className:"af-whitespace-nowrap af-text-right",children:[(0,fe.jsx)("div",{className:Hi,children:Uc(h)}),h.compare_at_amount!==null&&h.unit_amount!==null&&h.compare_at_amount>h.unit_amount&&(0,fe.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:se(h.compare_at_amount,h.currency)})]}),(0,fe.jsx)(ae,{className:"af-text-sm",children:(0,fe.jsx)(Vc,{variant:h})})]},h.id))})]})})}):null,(0,fe.jsx)(Vr,{title:"Details",children:(0,fe.jsxs)("dl",{className:"af-space-y-2",children:[(0,fe.jsxs)("div",{children:[(0,fe.jsx)("dt",{className:gs,children:"Delivery"}),(0,fe.jsx)("dd",{className:"af-text-sm",children:g==="Digital download"?m.fulfillment.filename??"Digital download":g??"Nothing to deliver"})]}),m.fulfillment.type==="redirect"&&m.fulfillment.url&&(0,fe.jsxs)("div",{children:[(0,fe.jsx)("dt",{className:gs,children:"Sends buyers to"}),(0,fe.jsx)("dd",{className:"af-break-all af-text-sm",children:m.fulfillment.url})]}),(0,fe.jsxs)("div",{children:[(0,fe.jsx)("dt",{className:gs,children:"Shipping address"}),(0,fe.jsx)("dd",{className:"af-text-sm",children:m.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,fe.jsxs)("div",{children:[(0,fe.jsx)("dt",{className:gs,children:"Most one buyer can order"}),(0,fe.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:m.max_quantity})]})]})}),x&&(0,fe.jsx)(Vr,{title:"Last 30 days",children:(0,fe.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,fe.jsxs)("div",{children:[(0,fe.jsx)("dt",{className:gs,children:"Units sold"}),(0,fe.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),(0,fe.jsxs)("div",{children:[(0,fe.jsx)("dt",{className:gs,children:"Orders"}),(0,fe.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),(0,fe.jsxs)("div",{children:[(0,fe.jsx)("dt",{className:gs,children:"Gross"}),(0,fe.jsx)("dd",{className:Hi,children:x.gross.length>0?Wi(x.gross):"\u2014"})]})]})}),(0,fe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var J=require("react/jsx-runtime"),Of={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Lf=["all","active","draft","low_stock","out_of_stock"];function jc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function qc(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Bf(e){return e.inventory?.out_of_stock??!1}function Ff(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return qc(e);case"out_of_stock":return Bf(e);default:return!0}}function Mf({product:e,showStats:t,onOpen:a}){let s=e.images[0],n=t?e.stats:void 0,r=qi(e),i=e.variant_count??0;return(0,J.jsxs)("button",{type:"button",onClick:a,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?(0,J.jsx)("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,J.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:(0,J.jsx)(sr.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,J.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,J.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,J.jsxs)("div",{className:"af-min-w-0",children:[(0,J.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,J.jsx)(zi,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,J.jsx)(ie,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,J.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,J.jsx)(ji,{product:e}),i>1&&(0,J.jsxs)(ie,{variant:"outline",children:[i," variants"]}),r&&(0,J.jsx)(ie,{variant:"outline",children:r})]}),n&&(0,J.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Wi(n.gross)}`:""," ",(0,J.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function $f(){return(0,J.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:[0,1,2,3,4,5].map(e=>(0,J.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,J.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,J.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,J.jsx)(ee,{className:"af-w-32"}),(0,J.jsx)(ee,{className:"af-w-16"}),(0,J.jsx)(ee,{className:"af-h-5 af-w-24"})]})]},e))})}function zo({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:n,isLoading:r,error:i,refetch:l}=As({includeStats:t,refreshKey:e}),[c,d]=vn.useState(!1),[o,u]=vn.useState(null),[b,v]=vn.useState("all"),{api:m}=G(),p=vn.useCallback(()=>m.exportProductsCsv(),[m]),[f,g]=vn.useState(""),[x,k]=vn.useState("newest"),T=vn.useMemo(()=>{if(!t)return null;let X=null;for(let q of n)!q.stats||q.stats.units_sold===0||(!X||q.stats.units_sold>(X.stats?.units_sold??0))&&(X=q);return X},[n,t]),h=vn.useMemo(()=>n.filter(qc).length,[n]),P=f.trim().toLowerCase(),_=vn.useMemo(()=>{let q=[...n.filter(de=>Ff(de,b)&&(!P||de.name.toLowerCase().includes(P)))];return x==="name"?q.sort((de,ge)=>de.name.localeCompare(ge.name)):x==="best_selling"?q.sort((de,ge)=>(ge.stats?.units_sold??0)-(de.stats?.units_sold??0)):q.sort((de,ge)=>jc(ge.created_at)-jc(de.created_at)),q},[n,b,P,x]),E=b!=="all"||!!P,w=()=>{v("all"),g("")},I=r||i!==null&&n.length===0,O=(0,J.jsx)("div",{className:"af-mb-6",children:(0,J.jsx)("div",{className:Q("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:I?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(vt,{label:"Products",children:(0,J.jsx)(ee,{className:"af-h-6 af-w-10"})}),t?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(vt,{label:"Best seller",children:(0,J.jsx)(ee,{className:"af-h-6 af-w-28"})}),(0,J.jsx)(vt,{label:"Low stock",children:(0,J.jsx)(ee,{className:"af-h-6 af-w-10"})})]}):(0,J.jsx)(vt,{label:"Active",children:(0,J.jsx)(ee,{className:"af-h-6 af-w-10"})})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(vt,{label:"Products",children:n.length}),t?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(vt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:T?`${T.stats?.units_sold??0} sold, last 30 days`:void 0,children:T?(0,J.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:T.name}):(0,J.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,J.jsx)(vt,{label:"Low stock",children:h})]}):(0,J.jsx)(vt,{label:"Active",children:n.filter(X=>X.active).length})]})})}),C=(0,J.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,J.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,J.jsx)("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Lf.map(X=>(0,J.jsx)("button",{type:"button","aria-pressed":b===X,onClick:()=>v(X),className:Q("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",b===X?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Of[X]},X))}),(0,J.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,J.jsx)(sr.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,J.jsx)(ce,{type:"text",value:f,onChange:X=>g(X.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,J.jsxs)(on,{value:x,onValueChange:X=>k(X),children:[(0,J.jsx)(za,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,J.jsx)(ln,{})}),(0,J.jsxs)(ja,{children:[(0,J.jsx)(kt,{value:"newest",children:"Newest"}),(0,J.jsx)(kt,{value:"name",children:"Name A\u2013Z"}),t&&(0,J.jsx)(kt,{value:"best_selling",children:"Best selling"})]})]}),E&&(0,J.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:w,children:"Clear filters"}),(0,J.jsx)(ma,{fetchCsv:p,filename:"products",label:E?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&n.length===0?(0,J.jsx)(ee,{className:"af-h-4 af-w-28"}):(0,J.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:E?`${_.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),Y;return o?Y=(0,J.jsx)(zc,{product:o,showStats:t,onBack:()=>{u(null),l()}},o.id):r&&n.length===0?Y=(0,J.jsxs)(J.Fragment,{children:[C,(0,J.jsx)($f,{}),(0,J.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):i&&n.length===0?Y=(0,J.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,J.jsx)(wt,{message:"Couldn't load your products.",onRetry:()=>l()})}):n.length===0?Y=(0,J.jsxs)(la,{icon:(0,J.jsx)(sr.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,J.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):Y=(0,J.jsxs)(J.Fragment,{children:[C,i&&(0,J.jsx)("div",{className:"af-mb-4",children:(0,J.jsx)(wt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>l()})}),_.length===0?(0,J.jsxs)(la,{children:["No products match these filters.",(0,J.jsx)("br",{}),(0,J.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:w,children:"Show all products"})]}):(0,J.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:_.map(X=>(0,J.jsx)(Mf,{product:X,showStats:t,onOpen:()=>u(X)},X.id))})]}),(0,J.jsx)(Ft,{title:"Products",onBackToWebsite:a,hideBackButton:!!o,className:s,children:c?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(y,{variant:"ghost",onClick:()=>d(!1),children:"Back to products"}),(0,J.jsx)(_s,{})]}):(0,J.jsxs)(J.Fragment,{children:[!o&&(0,J.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,J.jsx)(y,{variant:"outline",onClick:()=>d(!0),children:"Promo codes"})}),!o&&O,Y]})})}var Oa=le(require("react"),1),Wt=require("lucide-react");var Da=le(require("react"),1);function Hr({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=G(),[s,n]=Da.useState([]),[r,i]=Da.useState(!0),[l,c]=Da.useState(null),[d,o]=Da.useState(0),[u]=Da.useState(e),[b,v]=Da.useState(""),[m,p]=Da.useState(void 0),f=Da.useRef(0),g=Da.useCallback(async({afterRemoval:x=!1}={})=>{let k=++f.current;try{i(!0),c(null);let T={limit:u,offset:d*u};b.trim()&&(T.q=b.trim()),m&&(T.source=m);let h=await a.getPeople(T);if(k!==f.current)return;if(x&&h.people.length===0&&d>0){o(d-1);return}n(h.people)}catch(T){if(k!==f.current)return;c(T instanceof Error?T:new Error("Failed to fetch people"))}finally{k===f.current&&i(!1)}},[a,d,u,b,m,t]);return Da.useEffect(()=>{g()},[g]),{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=>{p(x),o(0)},refetch:()=>g(),refetchAfterRemoval:()=>g({afterRemoval:!0})}}var Vn=le(require("react"),1);function zr(e,{refreshKey:t}={}){let{api:a}=G(),[s,n]=Vn.useState(null),[r,i]=Vn.useState(e!==null),[l,c]=Vn.useState(null),d=Vn.useRef(0),o=Vn.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 Vn.useEffect(()=>{o()},[o]),{person:s,isLoading:r,error:l,refetch:o}}var R=require("react/jsx-runtime"),jo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Uf="af-text-xs af-text-muted-foreground";function rr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function qo(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function Vf(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Hf({value:e,label:t}){let[a,s]=Oa.useState(!1);return Vf()?(0,R.jsxs)(y,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[a?(0,R.jsx)(Wt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,R.jsx)(Wt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function Wc(e){return(0,R.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,R.jsxs)(ie,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,R.jsx)(ie,{variant:"secondary",children:"Contact form"})]})}function Gc(e){return e.name?e.name:e.email?e.email:(0,R.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var zf=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,jf=40;function qf(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),s=t.find(([n,r])=>zf.test(n)&&typeof r=="string"&&r.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=jf).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 Wf(e){return e.replace(/_/g," ")}function Gf(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Kf({data:e}){let{message:t,rest:a}=qf(e);return t===null&&a.length===0?(0,R.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,R.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,R.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),a.length>0&&(0,R.jsx)("dl",{className:"af-space-y-1",children:a.map(([s,n])=>(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,R.jsx)("dt",{className:Q(Uf,"af-w-28 af-shrink-0 af-capitalize"),children:Wf(s)}),(0,R.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Gf(n)})]},s))})]})}function Zc({formName:e,createdAt:t,data:a,onDelete:s}){return(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)(ie,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,R.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,R.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:rr(t)}),(0,R.jsx)(Zs,{iconOnly:!0,onDelete:s})]}),(0,R.jsx)(Kf,{data:a})]})}function Zf(e){return e.charged_total??e.amount_total}function Yf({email:e,refreshKey:t,onBack:a,onRemoved:s}){let{api:n}=G(),{person:r,isLoading:i,error:l,refetch:c}=zr(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=qo(e,r?.submissions[0]?.form_name);return(0,R.jsxs)("div",{children:[(0,R.jsxs)("div",{className:"af-mb-6",children:[(0,R.jsxs)(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,R.jsx)(Wt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,R.jsxs)("div",{className:"af-min-w-0",children:[i?(0,R.jsx)(ee,{className:"af-h-7 af-w-48"}):(0,R.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),(0,R.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,R.jsx)(Hf,{value:e,label:"Copy email address"})]})]}),(0,R.jsx)(y,{asChild:!0,children:(0,R.jsxs)("a",{href:o,children:[(0,R.jsx)(Wt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),i?(0,R.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(u=>(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsx)(ee,{className:"af-w-40"}),(0,R.jsx)(ee,{className:"af-mt-2 af-w-64"})]},u)),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):l||!r?(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(wt,{message:"Couldn't load this person.",onRetry:()=>c()})}):(0,R.jsxs)("div",{className:"af-space-y-6",children:[r.customer&&(0,R.jsxs)("div",{children:[(0,R.jsx)("h4",{className:Q(jo,"af-mb-3"),children:"Customer"}),(0,R.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&(0,R.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,R.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,R.jsx)("dd",{children:r.customer.name})]}),r.customer.phone&&(0,R.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,R.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,R.jsx)("dd",{children:r.customer.phone})]}),(0,R.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,R.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,R.jsx)("dd",{children:rr(r.customer.created_at)})]})]})]}),r.orders.length>0&&(0,R.jsxs)("div",{children:[(0,R.jsx)("h4",{className:Q(jo,"af-mb-3"),children:"Purchases"}),(0,R.jsx)("div",{className:"af-overflow-x-auto",children:(0,R.jsxs)(ut,{children:[(0,R.jsx)(ft,{children:(0,R.jsxs)($e,{children:[(0,R.jsx)(te,{children:"Order"}),(0,R.jsx)(te,{children:"Date"}),(0,R.jsx)(te,{className:"af-text-right",children:"Total"}),(0,R.jsx)(te,{children:"Status"})]})}),(0,R.jsx)(mt,{children:r.orders.map(u=>(0,R.jsxs)($e,{children:[(0,R.jsx)(ae,{className:"af-whitespace-nowrap af-font-medium",children:Xn(u)}),(0,R.jsx)(ae,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rr(u.created_at)}),(0,R.jsx)(ae,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:se(Zf(u),u.currency)}),(0,R.jsx)(ae,{children:(0,R.jsx)(ms,{status:u.status})})]},u.id))})]})}),(0,R.jsx)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),r.submissions.length>0&&(0,R.jsxs)("div",{children:[(0,R.jsx)("h4",{className:Q(jo,"af-mb-3"),children:"Messages"}),(0,R.jsx)("div",{className:"af-space-y-3",children:r.submissions.map(u=>(0,R.jsx)(Zc,{formName:u.form_name,createdAt:u.created_at,data:u.data,onDelete:()=>d(u.id)},u.id))})]})]})]})}function Jf({submissionId:e,onBack:t,onRemoved:a}){let{api:s}=G(),[n,r]=Oa.useState(null),[i,l]=Oa.useState(!0),[c,d]=Oa.useState(null),[o,u]=Oa.useState(0);return Oa.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]),(0,R.jsxs)("div",{children:[(0,R.jsxs)("div",{className:"af-mb-6",children:[(0,R.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,R.jsx)(Wt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,R.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,R.jsx)(ee,{className:"af-mt-1 af-h-4 af-w-32"}):n&&(0,R.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:rr(n.metadata.submitted_at)})]}),i?(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,R.jsx)(ee,{className:"af-w-40"}),(0,R.jsx)(ee,{className:"af-mt-2 af-w-64"}),(0,R.jsx)(ee,{className:"af-mt-2 af-w-52"}),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):c||!n?(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(wt,{message:"Couldn't load this submission.",onRetry:()=>u(b=>b+1)})}):(0,R.jsxs)("div",{className:"af-space-y-3",children:[(0,R.jsx)(Zc,{formName:null,createdAt:n.metadata.submitted_at,data:n.data,onDelete:async()=>{await s.deleteSubmission(e),a(),t()}}),(0,R.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"No email address came with this submission, so there is nobody to reply to."})]})]})}var Xf={all:"All",customers:"Customers",leads:"Leads"},Qf=["all","customers","leads"],Kc={all:void 0,customers:"customer",leads:"lead"};function em({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:p,source:f,setSource:g,refetch:x,refetchAfterRemoval:k}=Hr({refreshKey:e}),[T,h]=Oa.useState({kind:"list"}),[P,_]=Oa.useState(""),E=f==="customer"?"customers":f==="lead"?"leads":"all",w=W=>{Kc[W]!==f&&g(Kc[W])},{api:I}=G(),O=Oa.useCallback(()=>I.exportPeopleCsv({...m?{q:m}:{},...f?{source:f}:{}}),[I,m,f]),C=!r||!!n,Y=W=>{if(r){n?.();return}W.email?h({kind:"person",email:W.email}):W.submission_id&&h({kind:"submission",submissionId:W.submission_id})},X=Oa.useRef(!1),q=()=>{X.current=!0},de=()=>{h({kind:"list"}),X.current?(X.current=!1,k()):x()},ge=W=>{let B=W.trim();B!==m&&p(B)},ye=r?i.slice(0,s):i,D;if(T.kind==="person")D=(0,R.jsx)(Yf,{email:T.email,refreshKey:e,onBack:de,onRemoved:q});else if(T.kind==="submission")D=(0,R.jsx)(Jf,{submissionId:T.submissionId,onBack:de,onRemoved:q});else{let W=(0,R.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Qf.map(B=>(0,R.jsx)("button",{type:"button","aria-pressed":E===B,onClick:()=>w(B),className:Q("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",E===B?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Xf[B]},B))}),(0,R.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,R.jsx)(Wt.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,R.jsx)(ce,{type:"text",value:P,onChange:B=>_(B.target.value),onBlur:()=>ge(P),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),ge(P))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),m&&(0,R.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{_(""),p("")},children:"Clear search"}),(0,R.jsx)(ma,{fetchCsv:O,filename:"people",className:"af-ml-auto"})]});if(l)D=(0,R.jsxs)("div",{children:[r?null:W,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(B=>(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,R.jsx)(ee,{className:"af-h-4 af-w-32"}),(0,R.jsx)(ee,{className:"af-h-4 af-w-16"})]}),(0,R.jsx)(ee,{className:"af-mt-2 af-h-5 af-w-28"}),(0,R.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-56"})]},B))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(ut,{children:[(0,R.jsx)(ft,{children:(0,R.jsxs)($e,{children:[(0,R.jsx)(te,{children:"Person"}),(0,R.jsx)(te,{children:"Came from"}),(0,R.jsx)(te,{children:"Latest message"}),(0,R.jsx)(te,{children:"Last activity"}),(0,R.jsx)(te,{className:"af-w-8"}),(0,R.jsx)(te,{className:"af-w-8"})]})}),(0,R.jsx)(mt,{"aria-hidden":"true",children:[0,1,2,3,4].map(B=>(0,R.jsxs)($e,{children:[(0,R.jsx)(ae,{children:(0,R.jsx)(ee,{className:"af-h-4 af-w-40"})}),(0,R.jsx)(ae,{children:(0,R.jsx)(ee,{className:"af-h-5 af-w-24"})}),(0,R.jsx)(ae,{children:(0,R.jsx)(ee,{className:"af-h-4 af-w-56"})}),(0,R.jsx)(ae,{children:(0,R.jsx)(ee,{className:"af-h-4 af-w-24"})}),(0,R.jsx)(ae,{}),(0,R.jsx)(ae,{})]},B))})]})}),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(c)D=(0,R.jsxs)("div",{children:[r?null:W,(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(wt,{message:"Couldn't load your leads.",onRetry:()=>x()})})]});else if(ye.length===0&&d===0){let B=!!m||E!=="all";D=(0,R.jsxs)("div",{children:[B&&W,B?(0,R.jsx)(la,{children:m?"Nobody matches that search.":E==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,R.jsx)(Qs,{icon:Wt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(i.length===0)D=(0,R.jsxs)("div",{children:[r?null:W,(0,R.jsx)(la,{children:"No more results."}),(0,R.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,R.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>v(d-1),children:[(0,R.jsx)(Wt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let B=d*o+1,ue=d*o+i.length;D=(0,R.jsxs)("div",{children:[r?null:W,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ye.map((me,We)=>(0,R.jsxs)("div",{onClick:C?()=>Y(me):void 0,className:`af-rounded-md af-border af-p-3${C?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,R.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,R.jsxs)("div",{className:"af-min-w-0",children:[(0,R.jsx)("button",{type:"button",onClick:Ie=>{Ie.stopPropagation(),Y(me)},disabled:!C,"aria-label":`Open ${me.name||me.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${C?" hover:af-underline":""}`,children:Gc(me)}),me.name&&me.email&&(0,R.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:me.email})]}),(0,R.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,R.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:rr(me.last_activity_at)}),me.email&&(0,R.jsx)(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,R.jsx)("a",{href:qo(me.email),onClick:Ie=>Ie.stopPropagation(),"aria-label":`Email ${me.email}`,children:(0,R.jsx)(Wt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,R.jsx)("div",{className:"af-mt-2",children:Wc(me)}),me.latest_message_excerpt&&(0,R.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:me.latest_message_excerpt})]},me.email??me.submission_id??We))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(ut,{children:[(0,R.jsx)(ft,{children:(0,R.jsxs)($e,{children:[(0,R.jsx)(te,{children:"Person"}),(0,R.jsx)(te,{children:"Came from"}),(0,R.jsx)(te,{children:"Latest message"}),(0,R.jsx)(te,{children:"Last activity"}),(0,R.jsx)(te,{className:"af-w-8",children:(0,R.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,R.jsx)(te,{className:"af-w-8"})]})}),(0,R.jsx)(mt,{children:ye.map((me,We)=>(0,R.jsxs)($e,{onClick:C?()=>Y(me):void 0,className:C?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,R.jsxs)(ae,{className:"af-max-w-[260px] af-font-medium",children:[(0,R.jsx)("button",{type:"button",onClick:Ie=>{Ie.stopPropagation(),Y(me)},disabled:!C,"aria-label":`Open ${me.name||me.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${C?" hover:af-underline":""}`,children:Gc(me)}),me.name&&me.email&&(0,R.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:me.email})]}),(0,R.jsx)(ae,{children:Wc(me)}),(0,R.jsx)(ae,{className:"af-max-w-[320px]",children:me.latest_message_excerpt?(0,R.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:me.latest_message_excerpt}):(0,R.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,R.jsx)(ae,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rr(me.last_activity_at)}),(0,R.jsx)(ae,{className:"af-w-8",children:me.email&&(0,R.jsx)(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,R.jsx)("a",{href:qo(me.email),onClick:Ie=>Ie.stopPropagation(),"aria-label":`Email ${me.email}`,children:(0,R.jsx)(Wt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,R.jsx)(ae,{className:"af-w-8 af-text-right",children:(0,R.jsx)(Wt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},me.email??me.submission_id??We))})]})}),!r&&(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,R.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${B}-${ue}`}),(0,R.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,R.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>v(d-1),disabled:!b,children:[(0,R.jsx)(Wt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,R.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>v(d+1),disabled:!u,children:["Next",(0,R.jsx)(Wt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?(0,R.jsx)("div",{className:a,children:D}):(0,R.jsx)(Ft,{title:"Leads",onBackToWebsite:t,hideBackButton:T.kind!=="list",className:a,children:D})}function jr(e){return(0,R.jsx)(em,{...e},e.maxRows==null?"full":"compact")}var ed=le(require("react"),1),Ls=require("lucide-react");var La=le(require("react"),1);function qr({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=G(),[s,n]=La.useState([]),[r,i]=La.useState(0),[l,c]=La.useState(!0),[d,o]=La.useState(null),[u,b]=La.useState(0),[v,m]=La.useState(e),[p,f]=La.useState(void 0),g=La.useRef(0),x=La.useCallback(async()=>{let T=++g.current;try{c(!0),o(null);let h={limit:v,offset:u*v};p&&(h.status=p);let P=await a.getSubscriptions(h);if(T!==g.current)return;n(P.subscriptions),i(P.total)}catch(h){if(T!==g.current)return;o(h instanceof Error?h:new Error("Failed to fetch subscriptions"))}finally{T===g.current&&c(!1)}},[a,u,v,p,t]);La.useEffect(()=>{x()},[x]);let k=Math.ceil(r/v);return{subscriptions:s,total:r,isLoading:l,error:d,page:u,pageSize:v,hasNextPage:u<k-1,hasPreviousPage:u>0,setPage:b,setPageSize:T=>{m(T),b(0)},status:p,setStatus:T=>{f(T),b(0)},refetch:x}}var K=require("react/jsx-runtime");function Yc(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 Jc({sub:e}){return e.status==="canceled"?(0,K.jsx)(ie,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,K.jsx)(ie,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,K.jsx)(ie,{variant:"warning",children:"Scheduled to cancel"}):(0,K.jsx)(ie,{variant:"success",children:"Active"}):(0,K.jsx)(ie,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function tm(e,t){let a=se(t,e.currency);return e.plan_interval_count===1?`${a} / ${e.plan_interval}`:`${a} every ${e.plan_interval_count} ${e.plan_interval}s`}function Xc({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,K.jsxs)("div",{children:[(0,K.jsx)("div",{className:"af-font-medium af-tabular-nums",children:tm(e,e.current_amount)}),t&&(0,K.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",se(e.plan_amount,e.currency)]})]})}function Qc(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Yc(e.current_period_end)}`:"Ends at period end":e.current_period_end?Yc(e.current_period_end):"\u2014"}function Wo({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}=qr({refreshKey:e}),{api:m}=G(),p=ed.useCallback(()=>m.exportSubscriptionsCsv(b?{status:b}:{}),[m,b]),f;if(r)f=(0,K.jsxs)("div",{children:[(0,K.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(g=>(0,K.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,K.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,K.jsx)(ee,{className:"af-h-4 af-w-40"}),(0,K.jsx)(ee,{className:"af-h-4 af-w-20"})]}),(0,K.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-32"}),(0,K.jsx)(ee,{className:"af-mt-2 af-h-5 af-w-24"})]},g))}),(0,K.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,K.jsxs)(ut,{children:[(0,K.jsx)(ft,{children:(0,K.jsxs)($e,{children:[(0,K.jsx)(te,{children:"Subscriber"}),(0,K.jsx)(te,{children:"Plan"}),(0,K.jsx)(te,{className:"af-text-right",children:"Amount"}),(0,K.jsx)(te,{children:"Renews"}),(0,K.jsx)(te,{children:"Status"})]})}),(0,K.jsx)(mt,{"aria-hidden":"true",children:[0,1,2,3,4].map(g=>(0,K.jsxs)($e,{children:[(0,K.jsx)(ae,{children:(0,K.jsx)(ee,{className:"af-h-4 af-w-44"})}),(0,K.jsx)(ae,{children:(0,K.jsx)(ee,{className:"af-h-4 af-w-32"})}),(0,K.jsx)(ae,{className:"af-text-right",children:(0,K.jsx)(ee,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,K.jsx)(ae,{children:(0,K.jsx)(ee,{className:"af-h-4 af-w-24"})}),(0,K.jsx)(ae,{children:(0,K.jsx)(ee,{className:"af-h-5 af-w-20"})})]},g))})]})}),(0,K.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(i)f=(0,K.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,K.jsx)(wt,{message:"Couldn't load your subscriptions.",onRetry:()=>v()})});else if(s.length===0&&l===0)f=(0,K.jsx)(la,{icon:(0,K.jsx)(Ls.Repeat,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(s.length===0)f=(0,K.jsxs)("div",{children:[(0,K.jsx)(la,{children:"No more results."}),(0,K.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,K.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>u(l-1),children:[(0,K.jsx)(Ls.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let g=l*c+1,x=l*c+s.length;f=(0,K.jsxs)("div",{children:[(0,K.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,K.jsx)(ma,{fetchCsv:p,filename:"subscriptions"})}),(0,K.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(k=>(0,K.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,K.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,K.jsxs)("div",{className:"af-min-w-0",children:[(0,K.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:k.customer_email||(0,K.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,K.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:k.plan_title||"Untitled plan"})]}),(0,K.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,K.jsx)(Xc,{sub:k})})]}),(0,K.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,K.jsx)(Jc,{sub:k}),k.is_test&&(0,K.jsx)(ie,{variant:"outline",children:"Test"}),(0,K.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Qc(k)})]}),(0,K.jsx)(Dn,{deliveries:k.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},k.id))}),(0,K.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,K.jsxs)(ut,{children:[(0,K.jsx)(ft,{children:(0,K.jsxs)($e,{children:[(0,K.jsx)(te,{children:"Subscriber"}),(0,K.jsx)(te,{children:"Plan"}),(0,K.jsx)(te,{className:"af-text-right",children:"Amount"}),(0,K.jsx)(te,{children:"Renews"}),(0,K.jsx)(te,{children:"Status"})]})}),(0,K.jsx)(mt,{children:s.map(k=>(0,K.jsxs)($e,{children:[(0,K.jsx)(ae,{className:"af-max-w-[240px]",children:(0,K.jsx)("div",{className:"af-truncate af-font-medium",children:k.customer_email||(0,K.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,K.jsx)(ae,{className:"af-max-w-[220px]",children:(0,K.jsx)("div",{className:"af-truncate",children:k.plan_title||(0,K.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,K.jsx)(ae,{className:"af-whitespace-nowrap af-text-right",children:(0,K.jsx)(Xc,{sub:k})}),(0,K.jsx)(ae,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Qc(k)}),(0,K.jsxs)(ae,{children:[(0,K.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,K.jsx)(Jc,{sub:k}),k.is_test&&(0,K.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,K.jsx)(Dn,{deliveries:k.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},k.id))})]})}),(0,K.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,K.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${g}-${x} of ${n}`}),(0,K.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,K.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>u(l-1),disabled:!o,children:[(0,K.jsx)(Ls.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,K.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>u(l+1),disabled:!d,children:["Next",(0,K.jsx)(Ls.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,K.jsx)(Ft,{title:"Subscriptions",onBackToWebsite:t,className:a,children:f})}var zn=le(require("react"),1),gd=require("lucide-react");var ya=le(require("react"),1);var Ki=le(require("react"),1),Bs=typeof window>"u"?Ki.useEffect:Ki.useLayoutEffect;var Zi=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},am=(e,t)=>e instanceof Error?e:new Error(t);function nm(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 td(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function as({siteId:e,refreshKey:t,onSaveInvoiceSettings:a}){let{api:s}=G(),[n,r]=ya.useState(null),[i,l]=ya.useState(!0),[c,d]=ya.useState(null),o=ya.useRef(null),[u,b]=ya.useState(()=>td(s,e)),v=u.api!==s||u.siteId!==e,m=u;v&&(m=td(s,e),b(m),r(null),l(!0),d(null));let p=ya.useRef(m);Bs(()=>{p.current!==m&&(p.current=m,o.current=null)},[m]);let f=(w,I)=>p.current===w&&I>w.applied,g=(w,I,O)=>f(w,I)?(w.applied=I,o.current=O,r(O),l(!1),!0):!1,x=async w=>{for(;w.writing;)await w.idle;let I=++w.seq;try{let O=await w.api.getSite(w.siteId);return g(w,I,O)&&d(null),{seq:I,error:null}}catch(O){return{seq:I,error:am(O,"Failed to load store settings")}}},k=(w,I)=>{let O=async()=>{if(p.current!==w)throw new Error("Not saved: the store switched to another site first.");w.writing=!0,w.idle=new Promise(Y=>{w.markIdle=Y});try{return await I(++w.seq)}finally{w.writing=!1,w.markIdle()}},C=w.queue.then(O,O);return w.queue=C.catch(()=>{}),C},T=ya.useCallback(async()=>{let w=await x(m);w.error&&f(m,w.seq)&&(d(w.error),l(!1))},[m]);ya.useEffect(()=>{T()},[T,t]);let h=ya.useCallback(w=>k(m,async I=>{let O=await m.api.updateSite(m.siteId,w),{currency_restatement:C,...Y}=O;return g(m,I,Y)&&d(X=>X instanceof Zi?X:null),O}),[m]),P=ya.useRef(a);Bs(()=>{P.current=a});let _=ya.useCallback(async(w,I)=>{await k(m,()=>w());let O=await x(m);return O.error&&f(m,O.seq)&&o.current&&(g(m,O.seq,{...o.current,...I}),d(new Zi(`Saved, but couldn't refresh settings: ${O.error.message}`))),p.current===m?o.current:null},[m]),E=ya.useCallback(w=>{let I=P.current;return _(()=>I(w),nm(w))},[_]);return{site:v?null:n,isLoading:v||i,error:v?null:c,refetch:T,updateSite:h,saveInvoiceSettings:a?E:null}}var na=le(require("react"),1),Zo=require("lucide-react");var Dt=require("react/jsx-runtime");function Yi(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",ad="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",nd="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 Ba({children:e}){return(0,Dt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Wr({children:e}){return(0,Dt.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var Hn=na.forwardRef(function({id:t,title:a,description:s,children:n},r){let i=`af-store-${t}-title`;return(0,Dt.jsxs)("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":i,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[(0,Dt.jsxs)("div",{className:"af-space-y-1",children:[(0,Dt.jsx)("h3",{id:i,className:"af-text-sm af-font-semibold",children:a}),s&&(0,Dt.jsx)(Ba,{children:s})]}),n]})});function Ji({label:e,description:t,checked:a,onSave:s,disabled:n=!1,disabledReason:r}){let[i,l]=na.useState(null),[c,d]=na.useState(null),o=i??a,u=async b=>{l(b),d(null);try{await s(b)}catch(v){d(Yi(v))}finally{l(null)}};return(0,Dt.jsxs)("div",{className:"af-space-y-1",children:[(0,Dt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,Dt.jsx)("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"}),(0,Dt.jsxs)("span",{className:"af-space-y-0.5",children:[(0,Dt.jsxs)("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,i!==null&&(0,Dt.jsx)(Zo.Loader2,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&(0,Dt.jsx)(Ba,{children:t})]})]}),(n&&r||c)&&(0,Dt.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[n&&r&&(0,Dt.jsx)(Ba,{children:r}),c&&(0,Dt.jsx)(Wr,{children:c})]})]})}var Ko=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Go=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function sm(e,t,a,s=[]){if(!Go(e)||!Go(t)||!Go(a))return{draft:Ko(e,t)?a:e,dropped:[]};let n=[],r={...a};for(let i of Object.keys(a))Ko(e[i],t[i])||(s.includes(i)?n.push(i):r[i]=e[i]);return{draft:r,dropped:n}}function ir(e,t){let a=JSON.stringify(e),[s,n]=na.useState(e),[r,i]=na.useState([]),l=na.useRef(e),c=na.useRef(e),d=na.useRef(s);Bs(()=>{c.current=e,d.current=s});let o=na.useRef(t?.when);na.useEffect(()=>{let b=Object.is(o.current,t?.when)?[]:t?.fields??[];if(o.current=t?.when,Ko(l.current,c.current)&&b.length===0)return;let v=sm(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=na.useCallback(b=>{n(b??c.current),i([])},[]);return{draft:s,setDraft:n,dirty:JSON.stringify(s)!==a,reset:u,dropped:r}}function or({dirty:e,saving:t,error:a,onSave:s,onDiscard:n}){return e?(0,Dt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Dt.jsxs)(y,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&(0,Dt.jsx)(Zo.Loader2,{className:"af-animate-spin"}),"Save"]}),(0,Dt.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:n,children:"Discard"}),a&&(0,Dt.jsx)("p",{role:"alert",className:Q("af-text-sm af-text-destructive"),children:a})]}):null}function lr(){let[e,t]=na.useState(!1),[a,s]=na.useState(null),n=na.useCallback(async r=>{t(!0),s(null);try{await r()}catch(i){s(Yi(i))}finally{t(!1)}},[]);return{saving:e,error:a,setError:s,run:n}}function sd({what:e}){return(0,Dt.jsxs)(Ba,{children:["Only the site owner can change ",e,"."]})}var bn=le(require("react"),1),Fs=require("lucide-react");var Z=require("react/jsx-runtime"),Jo=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ld({site:e,updateSite:t}){return(0,Z.jsxs)("div",{className:"af-space-y-4",children:[(0,Z.jsx)(Ji,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:a=>t({collect_phone_at_checkout:a})}),e.checkout_marketing_consent!==void 0&&(0,Z.jsx)(Ji,{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 rd(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 cd({site:e,updateSite:t,refetch:a,providerSlot:s,currencyChanging:n=!1}){let{draft:r,setDraft:i,dirty:l,reset:c,dropped:d}=ir(rd(e),{when:e.currency,fields:["rates","threshold"]}),{saving:o,error:u,setError:b,run:v}=lr(),m=e.currency.toUpperCase(),p=()=>v(async()=>{let g={},x=[...new Set(r.countries.split(/[\s,]+/).map(w=>w.trim().toUpperCase()).filter(Boolean))],k=x.find(w=>!/^[A-Z]{2}$/.test(w));if(k)throw new Error(`"${k}" isn't a two-letter country code (e.g. US, CA).`);let T=x.length?x:null;Jo(T,e.shipping_countries)||(g.shipping_countries=T);let h=[];for(let w of r.rates){let I=w.label.trim(),O=oa(w.amount,e.currency);if(!I)throw new Error("Every rate needs a name.");if(w.amount.trim()===""||O===null)throw new Error(`Enter a price for "${I}" (0 for free).`);h.push({label:I,amount:O})}let P=h.length?h:null;Jo(P,e.shipping_rates)||(g.shipping_rates=P);let _=null;if(r.threshold.trim()!==""&&(_=oa(r.threshold,e.currency),_===null||_===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(_!==e.free_shipping_over&&(g.free_shipping_over=_),Object.keys(g).length===0){c();return}("shipping_rates"in g||"free_shipping_over"in g)&&(g.expected_currency=e.currency);let E;try{E=await t(g)}catch(w){throw w instanceof Gt&&w.details?.code==="currency_changed"&&await a?.(),w}c(rd(E))}),f=(g,x)=>i({...r,rates:r.rates.map((k,T)=>T===g?{...k,...x}:k)});return(0,Z.jsxs)("fieldset",{disabled:o||n,className:"af-space-y-4",children:[(0,Z.jsxs)("label",{className:_n,children:["Countries you ship to",(0,Z.jsx)(ce,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:g=>i({...r,countries:g.target.value})}),(0,Z.jsx)(Ba,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsxs)("p",{className:"af-text-sm",children:["Flat shipping rates (",m,")"]}),r.rates.length===0&&(0,Z.jsx)(Ba,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((g,x)=>(0,Z.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Z.jsx)(ce,{"aria-label":`Rate ${x+1} name`,value:g.label,placeholder:"Standard",onChange:k=>f(x,{label:k.target.value})}),(0,Z.jsx)(ce,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:g.amount,placeholder:"0",className:"af-w-32",onChange:k=>f(x,{amount:k.target.value})}),(0,Z.jsx)(y,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${x+1}`,onClick:()=>i({...r,rates:r.rates.filter((k,T)=>T!==x)}),children:(0,Z.jsx)(Fs.X,{})})]},x)),(0,Z.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[(0,Z.jsx)(Fs.Plus,{})," Add rate"]}),(0,Z.jsx)(Ba,{children:"Buyers pick one at checkout. The first is preselected."})]}),(0,Z.jsxs)("label",{className:_n,children:["Free shipping over (",m,")",(0,Z.jsx)(ce,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:g=>i({...r,threshold:g.target.value})}),(0,Z.jsx)(Ba,{children:"Orders at or above this get the cheapest rate free."})]}),d.length>0&&(0,Z.jsxs)("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",m,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),(0,Z.jsx)(or,{dirty:l,saving:o,error:u,onSave:()=>void p(),onDiscard:()=>{b(null),c()}}),s]})}var Yo="exclusive",rm=[{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 im({href:e,children:t}){return(0,Z.jsxs)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"af-inline-flex af-items-center af-gap-1 af-font-medium af-underline af-underline-offset-2 hover:af-text-foreground",children:[t,(0,Z.jsx)(Fs.ExternalLink,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function dd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=ir(e.tax_behavior??Yo),{saving:i,error:l,setError:c,run:d}=lr(),[o,u]=bn.useState(!1),b=e.stripe_tax_enabled,v=b||o,m=()=>d(async()=>{let g=a;if(g===e.tax_behavior){r();return}let x={tax_behavior:g};g!=="inclusive"&&e.tax_rate_bps!=null&&(x.tax_rate_bps=null);let k=await t(x);r(k.tax_behavior??Yo)}),p=()=>d(async()=>{let g={stripe_tax_enabled:!0,tax_behavior:a};a!=="inclusive"&&e.tax_rate_bps!=null&&(g.tax_rate_bps=null);let x=await t(g);r(x.tax_behavior??Yo),u(!1)}),f=(n||o)&&a!=="inclusive"&&e.tax_rate_bps!=null;return(0,Z.jsxs)("div",{className:"af-space-y-5",children:[(0,Z.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[(0,Z.jsx)("p",{children:"Tax at checkout is calculated by Stripe Tax, which you set up in your Stripe Dashboard (Settings \u2192 Tax): your business address, a default product tax code, and the places you're registered to collect tax."}),(0,Z.jsx)("p",{children:"Stripe only collects tax where you've added a registration; anywhere else the tax comes out as zero. Stripe Tax has its own fees, and what it covers (such as filing) depends on your Stripe Tax plan."}),(0,Z.jsx)("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:rm.map(g=>(0,Z.jsx)("li",{children:(0,Z.jsx)(im,{href:g.href,children:g.label})},g.href))})]}),(0,Z.jsx)(Ji,{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 g=>{if(o){u(!1),c(null),r();return}if(g&&!e.tax_behavior){u(!0);return}return t({stripe_tax_enabled:g})}}),v&&(0,Z.jsxs)("fieldset",{disabled:i,className:"af-space-y-4 af-pl-6",children:[(0,Z.jsxs)("label",{className:_n,children:["Do your prices already include tax?",(0,Z.jsxs)("select",{"aria-label":"Your prices",className:ad,value:a,onChange:g=>s(g.target.value),children:[(0,Z.jsx)("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),(0,Z.jsx)("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),(0,Z.jsx)(Ba,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),f&&(0,Z.jsxs)(Ba,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),o?(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Z.jsx)(y,{type:"button",size:"sm",disabled:i,onClick:()=>void p(),children:"Turn on"}),(0,Z.jsx)(y,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>{u(!1),c(null),r()},children:"Cancel"})]}),l&&(0,Z.jsx)(Wr,{children:l})]}):(0,Z.jsx)(or,{dirty:n,saving:i,error:l,onSave:()=>void m(),onDiscard:()=>{c(null),r()}})]})]})}function id(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function ud({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=ir(id(e)),{saving:i,error:l,setError:c,run:d}=lr(),o=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),u=()=>d(async()=>{let b={},v=null;if(o&&a.rate.trim()!==""){let g=Number(a.rate);if(!Number.isFinite(g)||g<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");v=Math.round(g*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 p=a.label.trim()||null;if(p!==e.tax_label&&(b.tax_label=p),Object.keys(b).length===0){r();return}let f=await t(b);r(id(f))});return(0,Z.jsxs)("fieldset",{disabled:i,className:"af-space-y-4",children:[(0,Z.jsxs)("label",{className:_n,children:["Tax rate (%)",(0,Z.jsx)(ce,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!o,value:o?a.rate:"",onChange:b=>s({...a,rate:b.target.value})}),(0,Z.jsx)(Ba,{children:o?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),(0,Z.jsxs)("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[(0,Z.jsxs)("label",{className:_n,children:["Tax ID",(0,Z.jsx)(ce,{"aria-label":"Tax ID",value:a.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...a,taxId:b.target.value})})]}),(0,Z.jsxs)("label",{className:_n,children:["Tax label",(0,Z.jsx)(ce,{"aria-label":"Tax label",value:a.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...a,label:b.target.value})})]})]}),(0,Z.jsx)(or,{dirty:n,saving:i,error:l,onSave:()=>void u(),onDiscard:()=>{c(null),r()}})]})}function fd({site:e,updateSite:t,onChangeStart:a}){let[s,n]=bn.useState(e.currency.toUpperCase()),[r,i]=bn.useState(!1),[l,c]=bn.useState(!1),[d,o]=bn.useState(null),u=e.currency.toUpperCase(),b=bn.useRef(u);bn.useEffect(()=>{b.current!==u&&(n(g=>g===b.current?u:g),b.current=u)},[u]);let v=s.trim().toUpperCase(),m=v!==u,p=/^[A-Z]{3}$/.test(v),f=async()=>{c(!0);let g=a?.(),x=!1;o(null);try{let k=await t({currency:v.toLowerCase()});x=!0;let T=k.currency_restatement;T&&!T.applied?o(T.reason?`Not changed: ${T.reason}.`:"The currency was not changed."):(n(k.currency.toUpperCase()),b.current=k.currency.toUpperCase()),i(!1)}catch(k){o(Yi(k))}finally{c(!1),g?.(x)}};return(0,Z.jsxs)("div",{className:"af-space-y-3",children:[(0,Z.jsxs)("div",{className:"af-flex af-items-end af-gap-2",children:[(0,Z.jsxs)("label",{className:_n,children:["Store currency",(0,Z.jsx)(ce,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:l||r,onChange:g=>{n(g.target.value),o(null)}})]}),m&&!r&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(y,{type:"button",size:"sm",disabled:!p,onClick:()=>i(!0),children:"Change currency"}),(0,Z.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>{n(u),o(null)},children:"Discard"})]})]}),(0,Z.jsx)(Ba,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&(0,Z.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,Z.jsxs)("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,":"," ",se(2e3,u)," becomes ",se(2e3,v),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),(0,Z.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Z.jsx)(y,{type:"button",size:"sm",disabled:l,onClick:()=>void f(),children:"Confirm change"}),(0,Z.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:l,onClick:()=>i(!1),children:"Cancel"})]})]}),d&&(0,Z.jsx)(Wr,{children:d})]})}function od(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function om(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 md({site:e,save:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=ir(od(e)),{saving:i,error:l,setError:c,run:d}=lr();if(!t)return(0,Z.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,Z.jsxs)("p",{children:["Due ",e.invoice_due_days," days after sending"]}),(0,Z.jsxs)("p",{children:["Reminders: ",om(e.invoice_reminder_schedule)]}),(0,Z.jsxs)("p",{children:["Footer: ",e.invoice_footer||"None"]}),(0,Z.jsx)(sd,{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 p=[...new Set(m)].sort((x,k)=>x-k);Jo(p,e.invoice_reminder_schedule)||(u.reminder_schedule=p);let f=a.footer.trim()||null;if(f!==e.invoice_footer&&(u.footer=f),Object.keys(u).length===0){r();return}let g=await t(u);r(g?od(g):void 0)});return(0,Z.jsxs)("fieldset",{disabled:i,className:"af-space-y-4",children:[(0,Z.jsxs)("label",{className:_n,children:["Days until due",(0,Z.jsx)(ce,{"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})})]}),(0,Z.jsxs)("label",{className:_n,children:["Reminder schedule",(0,Z.jsx)(ce,{"aria-label":"Reminder schedule",value:a.reminders,placeholder:"Off",onChange:u=>s({...a,reminders:u.target.value})}),(0,Z.jsx)(Ba,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),(0,Z.jsxs)("label",{className:_n,children:["Invoice footer",(0,Z.jsx)("textarea",{"aria-label":"Invoice footer",className:nd,maxLength:300,value:a.footer,onChange:u=>s({...a,footer:u.target.value})})]}),(0,Z.jsx)(or,{dirty:n,saving:i,error:l,onSave:()=>void o(),onDiscard:()=>{c(null),r()}})]})}function pd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=ir(e.default_email_recipients),{saving:i,error:l,setError:c,run:d}=lr(),[o,u]=bn.useState(""),[b,v]=bn.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(g=>g.toLowerCase()===f)){v("Already added.");return}s([...a,f]),u(""),v(null)}},p=()=>d(async()=>{let f=await t({default_email_recipients:a});r(f.default_email_recipients)});return(0,Z.jsxs)("fieldset",{disabled:i,className:"af-space-y-3",children:[(0,Z.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[a.map(f=>(0,Z.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[f,(0,Z.jsx)("button",{type:"button","aria-label":`Remove ${f}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(a.filter(g=>g!==f)),children:(0,Z.jsx)(Fs.X,{className:"af-h-3 af-w-3"})})]},f)),a.length===0&&(0,Z.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),(0,Z.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Z.jsx)(ce,{"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())}}),(0,Z.jsx)(y,{type:"button",variant:"outline",disabled:!o.trim(),onClick:m,children:"Add"})]}),b&&(0,Z.jsx)(Wr,{children:b}),(0,Z.jsx)(or,{dirty:n,saving:i,error:l,onSave:()=>void p(),onDiscard:()=>{c(null),r()}})]})}var pa=require("react/jsx-runtime");function Xo({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}=as({siteId:e,refreshKey:t}),b=zn.useRef(o),v=zn.useRef(e);Bs(()=>{b.current=o,v.current=e});let m=zn.useRef({}),[p,f]=zn.useState([]),g=p.some(P=>P.siteId===e),x=zn.useCallback(()=>{let P={siteId:e},_=b.current;return f(E=>[...E,P]),E=>{let w=()=>f(O=>O.filter(C=>C!==P));!(v.current===P.siteId)||E&&b.current===_?w():b.current().finally(w)}},[e]),k=P=>_=>{m.current[P]=_},T=l!==null&&l.payments_active;if(zn.useEffect(()=>{if(!T||!a)return;let P=m.current[a];P&&(P.scrollIntoView?.({behavior:"smooth",block:"start"}),P.focus({preventScroll:!0}))},[T,a]),c)return(0,pa.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,pa.jsx)(gd.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!l)return(0,pa.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d?.message??"Could not load store settings."});if(!l.payments_active)return(0,pa.jsx)(Is,{className:i,onConnectStripe:n,onUpgradePlan:r,whenActive:(0,pa.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let h={site:l,updateSite:u,refetch:o};return(0,pa.jsxs)("div",{className:`af-space-y-6 ${i??""}`,children:[d&&(0,pa.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d.message}),(0,pa.jsx)(Hn,{ref:k("checkout"),id:"checkout",title:"Checkout",children:(0,pa.jsx)(ld,{...h})}),(0,pa.jsx)(Hn,{ref:k("shipping"),id:"shipping",title:"Shipping",children:(0,pa.jsx)(cd,{...h,providerSlot:s,currencyChanging:g})}),(0,pa.jsx)(Hn,{ref:k("tax"),id:"tax",title:"Tax",children:(0,pa.jsx)(dd,{...h})}),(0,pa.jsx)(Hn,{ref:k("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:(0,pa.jsx)(fd,{...h,onChangeStart:x})})]},e)}var vd=require("lucide-react");var kn=require("react/jsx-runtime");function Gr({siteId:e,refreshKey:t,onSaveInvoiceSettings:a,className:s}){let{site:n,isLoading:r,error:i,updateSite:l,refetch:c,saveInvoiceSettings:d}=as({siteId:e,refreshKey:t,onSaveInvoiceSettings:a});return r?(0,kn.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,kn.jsx)(vd.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):n?(0,kn.jsxs)("div",{className:`af-space-y-6 ${s??""}`,children:[i&&(0,kn.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i.message}),(0,kn.jsx)(Hn,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:(0,kn.jsx)(md,{site:n,save:d})}),(0,kn.jsx)(Hn,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:(0,kn.jsx)(ud,{site:n,updateSite:l,refetch:c})})]},e):(0,kn.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i?.message??"Could not load invoice settings."})}var bd=require("lucide-react");var ns=require("react/jsx-runtime");function Qo({siteId:e,refreshKey:t,className:a}){let{site:s,isLoading:n,error:r,updateSite:i,refetch:l}=as({siteId:e,refreshKey:t});return n?(0,ns.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ns.jsx)(bd.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?(0,ns.jsxs)("div",{className:`af-space-y-3 ${a??""}`,children:[r&&(0,ns.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r.message}),(0,ns.jsx)(Hn,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:(0,ns.jsx)(pd,{site:s,updateSite:i,refetch:l})})]},e):(0,ns.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r?.message??"Could not load notification settings."})}var cr=le(require("react"),1);var St=require("react/jsx-runtime");function el({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}=Ts({refreshKey:e,initialPageSize:1,includeAggregates:!0}),v=Ds({refreshKey:e}),{api:m}=G(),p=v.filters,f=cr.useCallback(()=>m.exportRetainersCsv(p),[m,p]),[g,x]=cr.useState(!1),[k,T]=cr.useState(null),[h,P]=cr.useState(!1),_=(0,St.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:u||!o&&!d?(0,St.jsxs)("div",{role:"alert",className:"sm:af-col-span-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't load invoice totals. ",(0,St.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):o||!d?(0,St.jsxs)(St.Fragment,{children:[(0,St.jsx)(vt,{label:"Outstanding",children:(0,St.jsx)(ee,{className:"af-h-6 af-w-24"})}),(0,St.jsx)(vt,{label:"Overdue",children:(0,St.jsx)(ee,{className:"af-h-6 af-w-24"})}),(0,St.jsx)(vt,{label:"Paid this month",children:(0,St.jsx)(ee,{className:"af-h-6 af-w-24"})})]}):(0,St.jsxs)(St.Fragment,{children:[(0,St.jsx)(vt,{label:"Outstanding",detail:`${d.outstanding.count} open`,children:se(d.outstanding.amount,d.currency)}),(0,St.jsx)(vt,{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:se(d.overdue.amount,d.currency)}),(0,St.jsx)(vt,{label:"Paid this month",detail:`${d.paid_this_month.count} paid`,children:se(d.paid_this_month.amount,d.currency)})]})});return(0,St.jsxs)(Ft,{title:"Invoices",onBackToWebsite:a,hideBackButton:g,className:c,children:[_,i&&!g&&(0,St.jsxs)("div",{className:"af-mb-6",children:[(0,St.jsx)(y,{type:"button",variant:"outline",size:"sm","aria-expanded":h,"aria-controls":"af-invoice-settings",onClick:()=>P(E=>!E),children:"Invoice settings"}),h&&(0,St.jsx)("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:(0,St.jsx)(Gr,{siteId:i,refreshKey:e,onSaveInvoiceSettings:l})})]}),!g&&(0,St.jsx)(Es,{retainers:v.retainers,isLoading:v.isLoading,error:v.error,onRetry:()=>void v.refetch(),activeRetainerId:k?.id??null,onShowCycles:E=>T(w=>w?.id===E.id?null:E),total:v.total,endedTotal:v.endedTotal,isLoadingMore:v.isLoadingMore,onLoadMore:()=>void v.loadMore(),includeEnded:v.includeEnded,onIncludeEndedChange:v.setIncludeEnded,exportCsv:f}),(0,St.jsx)(ts,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:x,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,retainerFilter:k?{id:k.id,label:`${k.customer_name??k.customer_email??"Recurring invoices"} \u2014 ${k.description}`}:null,onClearRetainerFilter:()=>T(null)})]})}var Xt=le(require("react"),1);var hn=le(require("react"),1);function Mt(e,t,a){let[s,n]=hn.useState(null),[r,i]=hn.useState(!0),[l,c]=hn.useState(null),d=hn.useRef(0),o=hn.useRef(e);o.current=e;let u=hn.useRef(a);u.current=a;let b=hn.useCallback(async()=>{let m=++d.current,p=u.current;i(!0),c(null);try{let f=await o.current();m===d.current&&n({scope:p,value:f})}catch(f){m===d.current&&c(f instanceof Error?f:new Error("Request failed"))}finally{m===d.current&&i(!1)}},[]);hn.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 Xi={commitBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts"},cancelBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts/{sendId}/cancel",params:["sendId"]},createDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts"},updateDraft:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},deleteDraft:{method:"DELETE",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},testSendDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/test",params:["draftId"]},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 hd(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Xi,e)}function yd(e,t,a){let s=Xi[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 tl={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."},Kr=new Set(["sending_not_enabled","domain_not_verified","dmarc_missing","postal_address_missing"]);function ss(e){return e?tl[e]??"Sending is not available right now.":null}var jn=le(require("react"),1);var Ms=50;function Zr({siteId:e,q:t="",offset:a=0,refreshKey:s=0}){let{api:n}=G(),r=Mt(()=>n.getMarketingContacts(e,{q:t||void 0,limit:Ms,offset:a}),`${e}|${t}|${a}|${s}`,e),i=Mt(()=>n.getMarketingContactStats(e),`${e}|${s}`,e),l=Mt(()=>n.getMarketingTags(e),`${e}|${s}`,e);return{contacts:r,stats:i,tags:l,refetchAll:async()=>{await Promise.all([r.refetch(),i.refetch(),l.refetch()])}}}var Us=le(require("react"),1);var Pn=le(require("react"),1);var Cn=require("react/jsx-runtime"),Yr=e=>`af-email-settings-${e}`,al=Pn.createContext(null);function Qe(){let e=Pn.useContext(al);if(!e)throw new Error("Email panels render inside EmailView");return e}function xd(e){let{setInlineEditOpen:t}=Qe();Pn.useEffect(()=>(t(e),()=>t(!1)),[e,t])}function nl(e){return e.status==="sending"||e.status==="sent"||(e.status==="cancelled"||e.status==="failed")&&e.recipients.consumed>0}function Qi(e,t){return new Set([...e.filter(a=>a.sent).map(a=>a.id),...t.filter(nl).flatMap(a=>a.draft_id?[a.draft_id]:[])])}function da({onClick:e,children:t}){return(0,Cn.jsx)("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function dr({reason:e}){let{openSetup:t,onOpenStoreSettings:a}=Qe(),s=e&&Kr.has(e)?(0,Cn.jsx)(da,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&a?(0,Cn.jsx)(da,{onClick:a,children:"Open Store settings"}):null;return s&&(0,Cn.jsxs)(Cn.Fragment,{children:[" ",s]})}function vs(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 Fa(e,t){return vs(e)===t?!0:e instanceof Error&&e.message.includes(t)}function ur(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function pt(){let{onOrgAction:e}=Qe(),[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(c){return n(ur(c)),{ok:!1,error:c}}finally{a(!1)}},[e]);return{busy:t,error:s,setError:n,run:r}}function be({tone:e="info",children:t,className:a}){return(0,Cn.jsx)("div",{role:e==="error"?"alert":"status",className:Q("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 xa({children:e,action:t,id:a}){return(0,Cn.jsxs)("div",{id:a,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[(0,Cn.jsx)("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function Ve(e){return e.toLocaleString("en-US")}function $s(e,t){return`${e} ${t}${e===1?"":"s"}`}var Nt=require("react/jsx-runtime"),eo="I confirm that everyone in this file agreed to receive marketing email from my business.",lm={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 Jr({onImported:e}){let{canWrite:t}=Qe(),[a,s]=Us.useState(""),[n,r]=Us.useState(null),[i,l]=Us.useState(""),[c,d]=Us.useState(!1),[o,u]=Us.useState(!1),[b,v]=Us.useState(null),m=pt(),p=async()=>{if(!c||!a.trim())return;let f=i.split(",").map(x=>x.trim()).filter(Boolean),g=await m.run("importContacts",{csv:a,attested:!0,...f.length?{tags:f}:{},...o?{enroll_automations:!0}:{}});if(g.ok){let x=g.result;v(x),e?.(x)}};if(b){let f=new Map;for(let g of b.skipped_rows)f.set(g.reason,(f.get(g.reason)??0)+1);return(0,Nt.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[(0,Nt.jsx)("div",{className:"af-font-medium",children:"Import finished"}),(0,Nt.jsxs)("p",{className:"af-text-sm",children:[Ve(b.rows)," rows: ",Ve(b.created)," new, ",Ve(b.updated)," updated, ",Ve(b.skipped)," skipped."]}),f.size>0&&(0,Nt.jsx)("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...f].map(([g,x])=>(0,Nt.jsxs)("li",{children:[Ve(x)," ",lm[g]??g]},g))}),(0,Nt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),(0,Nt.jsx)(y,{type:"button",size:"sm",variant:"outline",onClick:()=>{v(null),s(""),r(null),d(!1)},children:"Import another file"})]})}return(0,Nt.jsxs)("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:f=>{f.preventDefault(),p()},children:[(0,Nt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Nt.jsx)("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),(0,Nt.jsx)("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async f=>{let g=f.target.files?.[0];g&&(r(g.name),s(await g.text()))}}),(0,Nt.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:'Needs an "email" column. Tags in a "tags" column are applied too.'}),n&&(0,Nt.jsx)("span",{className:"af-block af-text-xs",children:n})]}),(0,Nt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Nt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),(0,Nt.jsx)(ce,{"aria-label":"Tags for imported contacts",value:i,onChange:f=>l(f.target.value)})]}),(0,Nt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,Nt.jsx)("input",{"aria-label":"Send these contacts into matching automations",type:"checkbox",className:"af-mt-1",checked:o,onChange:f=>u(f.target.checked)}),(0,Nt.jsx)("span",{children:"Send these contacts into matching automations. Leave this off when they were already welcomed on another platform."})]}),(0,Nt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,Nt.jsx)("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:c,onChange:f=>d(f.target.checked)}),(0,Nt.jsxs)("span",{children:[eo," Importing people who didn't agree can get your sending paused."]})]}),m.error&&(0,Nt.jsx)(be,{tone:"error",children:m.error}),(0,Nt.jsx)(y,{type:"submit",size:"sm",disabled:!t||!c||!a.trim()||m.busy,children:m.busy?"Importing\u2026":"Import contacts"})]})}var he=require("react/jsx-runtime"),cm={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function wd(){let{siteId:e,canWrite:t,refreshKey:a}=Qe(),[s,n]=jn.useState(""),[r,i]=jn.useState(""),[l,c]=jn.useState(0),[d,o]=jn.useState(0),[u,b]=jn.useState(new Set),[v,m]=jn.useState(!1),p=Zr({siteId:e,q:r,offset:l,refreshKey:d+a}),f=pt(),g=()=>o(_=>_+1),x=p.stats.data,k=p.contacts.data,T=p.tags.data??[],h=x?x.growth.slice(-4).reduce((_,E)=>_+E.new_subscribers,0):null,P=async()=>{let _=await f.run("exportContacts",{});if(!_.ok||typeof _.result!="string"||typeof document>"u")return;let E=URL.createObjectURL(new Blob([_.result],{type:"text/csv;charset=utf-8"})),w=document.createElement("a");w.href=E,w.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(E)};return(0,he.jsxs)("div",{children:[(0,he.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[(0,he.jsx)(vt,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:x?Ve(x.total):(0,he.jsx)(ee,{className:"af-h-6 af-w-16"})}),(0,he.jsx)(vt,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:x?Ve(x.mailable):(0,he.jsx)(ee,{className:"af-h-6 af-w-16"})}),(0,he.jsx)(vt,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:h!==null?Ve(h):(0,he.jsx)(ee,{className:"af-h-6 af-w-16"})})]}),(0,he.jsxs)("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,he.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:_=>{_.preventDefault(),c(0),i(s.trim())},children:[(0,he.jsx)(ce,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:s,onChange:_=>n(_.target.value)}),(0,he.jsx)(y,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),(0,he.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>m(_=>!_),children:v?"Close import":"Import"}),(0,he.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!t||f.busy,onClick:()=>void P(),children:"Export"})]}),v&&(0,he.jsx)("div",{className:"af-mt-3",children:(0,he.jsx)(Jr,{onImported:g})}),f.error&&(0,he.jsx)(be,{tone:"error",className:"af-mt-2",children:f.error}),t&&u.size>0&&(0,he.jsx)(um,{tags:T.filter(_=>!_.system),count:u.size,busy:f.busy,onApply:async(_,E)=>{(await f.run("bulkTagContacts",{action:_,tag_id:E,contact_ids:[...u]})).ok&&(b(new Set),g())}}),(0,he.jsx)("div",{className:"af-mt-3",children:p.contacts.error?(0,he.jsx)(wt,{message:"Couldn't load contacts.",onRetry:()=>void p.contacts.refetch()}):k?k.contacts.length===0?(0,he.jsx)(la,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):(0,he.jsxs)(he.Fragment,{children:[(0,he.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:k.contacts.map(_=>(0,he.jsx)(dm,{contact:_,canWrite:t,busy:f.busy,selected:u.has(_.id),onSelect:E=>b(w=>{let I=new Set(w);return E?I.add(_.id):I.delete(_.id),I}),onUnsubscribe:async()=>{(await f.run("unsubscribeContact",{contactId:_.id})).ok&&g()}},_.id))}),(0,he.jsxs)("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[(0,he.jsxs)("span",{children:[Ve(l+1),"\u2013",Ve(l+k.contacts.length)," of ",Ve(k.total)]}),(0,he.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,he.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:l===0,onClick:()=>c(Math.max(0,l-Ms)),children:"Previous"}),(0,he.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:l+k.contacts.length>=k.total,onClick:()=>c(l+Ms),children:"Next"})]})]})]}):(0,he.jsx)(ee,{className:"af-h-24 af-w-full"})}),(0,he.jsx)(fm,{tags:T,canWrite:t,onChanged:g})]})}function dm({contact:e,canWrite:t,busy:a,selected:s,onSelect:n,onUnsubscribe:r}){return(0,he.jsxs)("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&(0,he.jsx)("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:s,onChange:i=>n(i.target.checked)}),(0,he.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,he.jsxs)("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?(0,he.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),(0,he.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[(0,he.jsx)(ie,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":cm[e.status]}),e.tags.map(i=>(0,he.jsx)(ie,{variant:"outline",children:i.label},i.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&(0,he.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:r,children:"Unsubscribe"})]})}function um({tags:e,count:t,busy:a,onApply:s}){let[n,r]=jn.useState("");return(0,he.jsxs)("div",{className:"af-mt-3 af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:[(0,he.jsxs)("span",{children:[Ve(t)," selected"]}),(0,he.jsxs)("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:n,onChange:i=>r(i.target.value),children:[(0,he.jsx)("option",{value:"",children:"Choose a tag\u2026"}),e.map(i=>(0,he.jsx)("option",{value:i.id,children:i.label},i.id))]}),(0,he.jsx)(y,{type:"button",size:"sm",variant:"outline",disabled:!n||a,onClick:()=>s("add",n),children:"Add tag"}),(0,he.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:!n||a,onClick:()=>s("remove",n),children:"Remove tag"})]})}function fm({tags:e,canWrite:t,onChanged:a}){let[s,n]=jn.useState(""),[r,i]=jn.useState(null),l=pt();return(0,he.jsxs)("div",{children:[(0,he.jsx)(xa,{children:"Tags"}),e.length===0?(0,he.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No tags yet. Contacts are tagged automatically with where they signed up and what they bought."}):(0,he.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(c=>(0,he.jsx)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:r?.id===c.id?(0,he.jsxs)("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:[(0,he.jsx)(ce,{"aria-label":`New name for ${c.label}`,value:r.label,onChange:d=>i({id:c.id,label:d.target.value})}),(0,he.jsx)(y,{type:"submit",size:"sm",disabled:!r.label.trim()||l.busy,children:"Save"})]}):(0,he.jsxs)(he.Fragment,{children:[(0,he.jsxs)("span",{children:[c.label," ",(0,he.jsxs)("span",{className:"af-text-muted-foreground",children:["\xB7 ",Ve(c.total)," contacts, ",Ve(c.mailable)," can be emailed"]})]}),t&&!c.system&&(0,he.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>i({id:c.id,label:c.label}),children:"Rename"})]})},c.id))}),t&&(0,he.jsxs)("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:[(0,he.jsx)(ce,{"aria-label":"New tag",placeholder:"New tag",value:s,maxLength:100,onChange:c=>n(c.target.value)}),(0,he.jsx)(y,{type:"submit",size:"sm",variant:"outline",disabled:!s.trim()||l.busy,children:"Add tag"})]}),l.error&&(0,he.jsx)(be,{tone:"error",className:"af-mt-2",children:l.error})]})}var Pt=le(require("react"),1),Ld=require("lucide-react");function Vs({siteId:e,refreshKey:t=0}){let{api:a}=G();return Mt(()=>a.getBroadcasts(e),`${e}|${t}`,e)}function Hs({siteId:e,kind:t,refreshKey:a=0}){let{api:s}=G();return Mt(()=>s.getEmailDrafts(e,t),`${e}|${t??""}|${a}`,`${e}|${t??""}`)}var Je=le(require("react"),1);var Xr=e=>typeof e=="number"&&Number.isFinite(e);function sl(e){if(!e||typeof e!="object")return null;let t=e;return Xr(t.x)&&Xr(t.y)&&Xr(t.width)&&Xr(t.height)?{x:t.x,y:t.y,width:t.width,height:t.height}:null}var rl=(e,t)=>Number.isInteger(e)&&e>=0&&e<t;function Sd(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=sl(s.rect);return rl(s.section,a)&&n?{type:"hover",section:s.section,rect:n}:null}case"focus":case"open":{let n=sl(s.rect);return rl(s.section,a)&&n?{type:s.type,section:s.section,rect:n}:null}case"layout":{if(!Xr(s.height)||!Array.isArray(s.sections))return null;let n=s.sections.flatMap(r=>{let i=r,l=i?sl(i.rect):null;return i&&rl(i.section,a)&&l?[{section:i.section,rect:l}]:[]});return{type:"layout",height:s.height,sections:n}}case"template":return s.region==="header"||s.region==="footer"?{type:"template",region:s.region}:null;default:return null}}var Qr=(e,t,a)=>Math.min(Math.max(e,t),Math.max(t,a));function il(e,t){let a=Qr(e.x,0,t.width),s=Qr(e.y,0,t.height);return{x:a,y:s,width:Qr(e.width,0,t.width-a),height:Qr(e.height,0,t.height-s)}}var ei={min:240,max:6e3,initial:480},Nd=e=>Qr(Math.ceil(e),ei.min,ei.max);var zs=le(require("react"),1);var dt=require("react/jsx-runtime"),ol={heading:"Heading",text:"Text",button:"Button",image:"Image",cart:"Cart"};function _d(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 ll(e){switch(e.type){case"heading":case"text":return e.text;case"button":return`${e.label}
2
+ "use strict";var Pu=Object.create;var gi=Object.defineProperty;var Cu=Object.getOwnPropertyDescriptor;var Tu=Object.getOwnPropertyNames;var Eu=Object.getPrototypeOf,Iu=Object.prototype.hasOwnProperty;var Au=(e,t)=>{for(var a in t)gi(e,a,{get:t[a],enumerable:!0})},Ul=(e,t,a,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Tu(t))!Iu.call(e,n)&&n!==a&&gi(e,n,{get:()=>t[n],enumerable:!(s=Cu(t,n))||s.enumerable});return e};var le=(e,t,a)=>(a=e!=null?Pu(Eu(e)):{},Ul(t||!e||!e.__esModule?gi(a,"default",{value:e,enumerable:!0}):a,e)),Du=e=>Ul(gi({},"__esModule",{value:!0}),e);var Vp={};Au(Vp,{AUDIENCE_PAGE_SIZE:()=>$s,AifeaturesApiError:()=>Gt,AifeaturesProvider:()=>ql,AnalyticsView:()=>gu,ContactImport:()=>Jr,CustomerDetail:()=>$r,CustomersList:()=>Ur,DOUBLE_OPT_IN_HELP:()=>ai,DashboardView:()=>_u,EMAIL_ORG_ACTIONS:()=>Xi,EMAIL_READINESS_TEXT:()=>Qo,EmailView:()=>Rl,ExportCsvButton:()=>ma,FormSettings:()=>Tr,FormSubmissions:()=>Rr,FormsDashboard:()=>ko,FormsList:()=>hr,IMPORT_ATTESTATION:()=>eo,InvoiceDetail:()=>$i,InvoiceLabelBadge:()=>ar,InvoiceSettingsPanel:()=>Gr,InvoicesList:()=>ts,InvoicesView:()=>Xo,LeadsView:()=>jr,MAX_ANALYTICS_FILTERS:()=>xs,MAX_ANALYTICS_FILTER_VALUES:()=>ws,NotificationRecipientsSettings:()=>Jo,OrderDetail:()=>Fr,OrderStatusBadge:()=>ms,OrdersList:()=>Qn,OrdersView:()=>Uo,PaymentsDashboard:()=>$o,PaymentsSetup:()=>As,ProductSettings:()=>Dr,ProductsList:()=>Ir,ProductsView:()=>Vo,PromosPanel:()=>ks,REALTIME_FAILURES_BEFORE_ERROR:()=>fo,REALTIME_POLL_MS:()=>uo,RetainerStatusBadge:()=>Vi,RetainersPanel:()=>Is,StoreSettings:()=>Yo,SubmissionDetail:()=>Sr,SubscriptionsView:()=>jo,VariantsEditor:()=>Ar,ViewShell:()=>Ft,WebhookDeliveries:()=>Pr,WebhookSettings:()=>Cr,buildEmailOrgRequest:()=>bd,chargedTotal:()=>Ln,createApiClient:()=>hi,emailReadinessText:()=>ss,formatPrice:()=>re,isEmailOrgAction:()=>vd,isZeroDecimalCurrency:()=>Xa,toMajorUnits:()=>Et,toMinorUnits:()=>oa,useAifeatures:()=>W,useAifeaturesContext:()=>W,useAnalytics:()=>Ws,useAudience:()=>Zr,useBroadcasts:()=>Hs,useBusinessSummary:()=>Ls,useCsvExport:()=>Nr,useCustomers:()=>Mr,useEmailDrafts:()=>zs,useEventDestinations:()=>_r,useForms:()=>Ns,useInvoices:()=>Es,useOrders:()=>Or,usePaymentsStatus:()=>Yn,usePeople:()=>Hr,usePerson:()=>zr,useProducts:()=>Ds,useRealtimeVisitors:()=>li,useRetainers:()=>Os,useSiteSettings:()=>as,useSubmissions:()=>xr,useSubscriptions:()=>qr});module.exports=Du(Vp);var cs=le(require("react"),1);var wo="aifeatures:analytics:timezone",So;function pr(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function Vl(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function os(){return No()??pr()}function No(){if(So!==void 0)return So;try{let e=window.localStorage.getItem(wo);return Vl(e)?e:null}catch{return null}}function Ro(e){if(!(e!==null&&!Vl(e))){So=e;try{e===null?window.localStorage.removeItem(wo):window.localStorage.setItem(wo,e)}catch{}}}function vi(e,t){let a=new URLSearchParams({period:String(e)}),s=os();return s&&a.set("timezone",s),t&&t.length>0&&a.set("filters",JSON.stringify(t)),a.toString()}var Gt=class extends Error{constructor(a,s,n){super(a);this.status=s;this.details=n;this.name="AifeaturesApiError"}};function bi(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 Hl(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 zl(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 hi(e,t="https://aifeatures.dev"){async function a(n,r={}){let i=`${t}${n}`,l=await fetch(i,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!l.ok){let u;try{u=await l.json()}catch{}throw new Gt(bi(u?.error,l.status),l.status,u)}if(l.status!==204)return l.json()}async function s(n){let r=await fetch(`${t}${n}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let i;try{i=await r.json()}catch{}throw new Gt(bi(i?.error,r.status),r.status,i)}return r.blob()}return{async getForms(){return(await a("/api/v1/forms")).forms},async getForm(n){return a(`/api/v1/forms/${n}`)},async createForm(n){return a("/api/v1/forms",{method:"POST",body:JSON.stringify(n)})},async updateForm(n,r){return a(`/api/v1/forms/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(n){await a(`/api/v1/forms/${n}`,{method:"DELETE"})},async getSubmissions(n,r={}){let i=new URLSearchParams;r.limit!==void 0&&i.set("limit",String(r.limit)),r.offset!==void 0&&i.set("offset",String(r.offset));let l=i.toString(),u=`/api/v1/forms/${n}/submissions${l?`?${l}`:""}`;return a(u)},async getSubmission(n){return a(`/api/v1/submissions/${n}`)},async exportSubmissionsCsv(n,r={}){let i=new URLSearchParams;return r.includeSpam&&i.set("include_spam","true"),s(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,u=i.id??i.name,c=`${t}/api/v1/submissions/${n}/attachments/${encodeURIComponent(u)}`,o=await fetch(c,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let m;try{m=await o.json()}catch{}throw new Gt(bi(m?.error,o.status),o.status,m)}let f=await o.blob(),b=URL.createObjectURL(f),g=document.createElement("a");g.href=b,g.download=l,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(b)},async getSite(n){return a(`/api/v1/sites/${encodeURIComponent(n)}`)},async updateSite(n,r){return a(`/api/v1/sites/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return a("/api/v1/payments/status")},getPromos(n){let r=new URLSearchParams({limit:"10"});return n&&r.set("cursor",n),a(`/api/v1/promos?${r}`)},getPromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}`)},createPromo(n){return a("/api/v1/promos",{method:"POST",body:JSON.stringify(n)})},disablePromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}/disable`,{method:"POST"})},replacePromo(n,r){return a(`/api/v1/promos/${encodeURIComponent(n)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(n={}){let r=new URLSearchParams;n.include&&r.set("include",n.include);let i=r.toString();return(await a(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(n){return a(`/api/v1/products/${n}`)},async createProduct(n){return a("/api/v1/products",{method:"POST",body:JSON.stringify(n)})},async updateProduct(n,r){return a(`/api/v1/products/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(n){await a(`/api/v1/products/${n}`,{method:"DELETE"})},async attachProductFile(n,r){let i=new FormData;i.append("file",r);let l=await fetch(`${t}/api/v1/products/${n}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!l.ok){let u;try{u=await l.json()}catch{}throw new Gt(bi(u?.error,l.status),l.status,u)}return l.json()},async attachProductFileFromUrl(n,r){return a(`/api/v1/products/${n}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(n,r){return a(`/api/v1/products/${n}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(n,r){return a(`/api/v1/options/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(n){await a(`/api/v1/options/${n}`,{method:"DELETE"})},async createVariant(n,r){return a(`/api/v1/products/${n}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(n,r){return a(`/api/v1/variants/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(n){await a(`/api/v1/variants/${n}`,{method:"DELETE"})},async setVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(n={}){let r=new URLSearchParams;n.email?r.set("email",n.email):n.q&&r.set("q",n.q),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(n){return a(`/api/v1/customers/${n}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(n={}){let r=Hl(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",Hl(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=zl(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",zl(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=os();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?${vi(n,r)}`)},async getAnalyticsTimeseries(n,r){return a(`/api/v1/analytics/timeseries?${vi(n,r)}`)},async getAnalyticsRealtime(){return a("/api/v1/analytics/realtime")},async getAnalyticsChannels(n,r){return a(`/api/v1/analytics/channels?${vi(n,r)}`)},async getAnalyticsConversions(n){return a((()=>{let r=new URLSearchParams({period:String(n)}),i=os();return i&&r.set("timezone",i),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(n,r,i){let l=new URLSearchParams({goal:n,period:String(r)}),u=os();return u&&l.set("timezone",u),i!==void 0&&l.set("limit",String(i)),a(`/api/v1/analytics/conversions/targets?${l.toString()}`)},async getAnalyticsBreakdown(n,r,i){let l=n.split("/").map(encodeURIComponent).join("/");return a(`/api/v1/analytics/${l}?${vi(r,i)}`)},async getBusinessSummary(n){let r=new URLSearchParams;r.set("tz_offset_minutes",String(n.tzOffsetMinutes));let i=os();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(`${Ca(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(`${Ca(n)}/contacts${l?`?${l}`:""}`)},async getMarketingContactStats(n){return a(`${Ca(n)}/contacts/stats`)},async getMarketingTags(n){return(await a(`${Ca(n)}/contact-tags`)).tags},async getEmailDrafts(n,r){let i=r?`?kind=${r}`:"";return(await a(`${Ca(n)}/marketing/drafts${i}`)).drafts},async getEmailDraft(n,r){return a(`${Ca(n)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(n,r,i){let l=i?.editable?"?mode=editable":"";return a(`${Ca(n)}/marketing/drafts/${encodeURIComponent(r)}/preview${l}`)},async getEmailTemplates(n){return(await a(`${Ca(n)}/marketing/templates`)).templates},async previewEmailTemplate(n,r,i){let l=i?`?draft_id=${encodeURIComponent(i)}`:"";return a(`${Ca(n)}/marketing/templates/${encodeURIComponent(r)}/preview${l}`)},async getBroadcasts(n){return(await a(`${Ca(n)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(n,r){return a(`${Ca(n)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getAutomations(n){return a(`${Ca(n)}/marketing/automations`)},async getAutomation(n,r){return a(`${Ca(n)}/marketing/automations/${encodeURIComponent(r)}`)},async getAutomationStats(n,r){return(await a(`${Ca(n)}/marketing/automations/${encodeURIComponent(r)}/stats`)).steps}}}function Ca(e){return`/api/v1/sites/${encodeURIComponent(e)}`}var ls=require("react/jsx-runtime"),jl=cs.createContext(null);function Ou(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 ql({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:n}){let r=cs.useMemo(()=>Ou(e),[e]),i=cs.useMemo(()=>hi(e,t),[e,t]),l=cs.useMemo(()=>({siteToken:e,apiUrl:t,api:i}),[e,t,i]);return r?(0,ls.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:(0,ls.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,ls.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,ls.jsx)("p",{className:"af-text-sm af-text-destructive",children:r})]})}):(0,ls.jsx)(jl.Provider,{value:l,children:(0,ls.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:n})})}function W(){let e=cs.useContext(jl);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var Zn=le(require("react"),1),Js=require("lucide-react");var yi=le(require("react"),1),wn=le(require("@radix-ui/react-tabs"),1);var Wl=require("clsx"),Gl=require("tailwind-merge"),Lu=(0,Gl.extendTailwindMerge)({prefix:"af-"});function X(...e){return Lu((0,Wl.clsx)(e))}var wi=require("react/jsx-runtime"),xi=wn.Root,vr=yi.forwardRef(({className:e,...t},a)=>(0,wi.jsx)(wn.List,{ref:a,className:X("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));vr.displayName=wn.List.displayName;var Sn=yi.forwardRef(({className:e,...t},a)=>(0,wi.jsx)(wn.Trigger,{ref:a,className:X("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));Sn.displayName=wn.Trigger.displayName;var Nn=yi.forwardRef(({className:e,...t},a)=>(0,wi.jsx)(wn.Content,{ref:a,className:X("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));Nn.displayName=wn.Content.displayName;var Kl=le(require("react"),1),Zl=require("@radix-ui/react-slot"),Yl=require("class-variance-authority");var Jl=require("react/jsx-runtime"),Bu=(0,Yl.cva)("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),y=Kl.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...n},r)=>(0,Jl.jsx)(s?Zl.Slot:"button",{className:X(Bu({variant:t,size:a,className:e})),ref:r,...n}));y.displayName="Button";var br=require("lucide-react");var Gn=le(require("react"),1);var An=require("react/jsx-runtime"),ft=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,An.jsx)("table",{ref:a,className:X("af-w-full af-caption-bottom af-text-sm",e),...t})}));ft.displayName="Table";var mt=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("thead",{ref:a,className:X("[&_tr]:af-border-b",e),...t}));mt.displayName="TableHeader";var pt=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("tbody",{ref:a,className:X("[&_tr:last-child]:af-border-0",e),...t}));pt.displayName="TableBody";var Fu=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("tfoot",{ref:a,className:X("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Fu.displayName="TableFooter";var Ue=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("tr",{ref:a,className:X("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Ue.displayName="TableRow";var te=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("th",{ref:a,className:X("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));te.displayName="TableHead";var ae=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("td",{ref:a,className:X("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));ae.displayName="TableCell";var Mu=Gn.forwardRef(({className:e,...t},a)=>(0,An.jsx)("caption",{ref:a,className:X("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Mu.displayName="TableCaption";var Rn=le(require("react"),1);function Ns(){let{api:e}=W(),[t,a]=Rn.useState([]),[s,n]=Rn.useState(!0),[r,i]=Rn.useState(null),l=Rn.useCallback(async()=>{try{n(!0),i(null);let f=await e.getForms();a(f)}catch(f){i(f instanceof Error?f:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);Rn.useEffect(()=>{l()},[l]);let u=Rn.useCallback(async f=>{let b=await e.createForm(f);return a(g=>[...g,b]),b},[e]),c=Rn.useCallback(async(f,b)=>{let g=await e.updateForm(f,b);return a(m=>m.map(v=>v.id===f?g:v)),g},[e]),o=Rn.useCallback(async f=>{await e.deleteForm(f),a(b=>b.filter(g=>g.id!==f))},[e]);return{forms:t,isLoading:s,error:r,refetch:l,createForm:u,updateForm:c,deleteForm:o}}var _t=require("react/jsx-runtime");function hr({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:n}=Ns();return s?(0,_t.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,_t.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,_t.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,_t.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):a.length===0?(0,_t.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,_t.jsx)(br.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,_t.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,_t.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,_t.jsx)("div",{className:t,children:(0,_t.jsxs)(ft,{children:[(0,_t.jsx)(mt,{children:(0,_t.jsxs)(Ue,{children:[(0,_t.jsx)(te,{children:"Name"}),(0,_t.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,_t.jsx)(pt,{children:a.map(r=>(0,_t.jsxs)(Ue,{children:[(0,_t.jsx)(ae,{className:"af-font-medium",children:r.name}),(0,_t.jsx)(ae,{className:"af-text-right",children:(0,_t.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,_t.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[(0,_t.jsx)(br.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,_t.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[(0,_t.jsx)(br.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}var ec=require("lucide-react");var Xl=require("class-variance-authority");var Ql=require("react/jsx-runtime"),$u=(0,Xl.cva)("af-inline-flex af-items-center af-rounded-md af-border af-px-2.5 af-py-0.5 af-text-xs af-font-semibold af-transition-colors focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2",{variants:{variant:{default:"af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",secondary:"af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",destructive:"af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",outline:"af-text-foreground",success:"af-border-transparent af-bg-green-100 af-text-green-800",warning:"af-border-transparent af-bg-yellow-100 af-text-yellow-800"}},defaultVariants:{variant:"default"}});function ie({className:e,variant:t,...a}){return(0,Ql.jsx)("div",{className:X($u({variant:t}),e),...a})}var Ha=require("react/jsx-runtime"),Uu={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 Si(e){switch(e.state){case"sending":return{label:"Sending",variant:"secondary",detail:null};case"sent":return{label:"Sent",variant:"secondary",detail:"Accepted for sending. Delivery has not been confirmed yet."};case"delivered":return{label:"Delivered",variant:"success",detail:"Accepted by the recipient\u2019s email server. This does not confirm it was read."};case"delivery_delayed":return{label:"Delayed",variant:"warning",detail:"Delivery is delayed. The email provider is still trying."};case"bounced":return{label:"Bounced",variant:"destructive",detail:"A receiving email server rejected this message."};case"complained":return{label:"Marked as spam",variant:"destructive",detail:"A recipient marked this email as spam. Do not resend it to that recipient."};case"suppressed":return{label:"Delivery blocked",variant:"destructive",detail:"The email provider blocked delivery to a recipient after a previous delivery problem or spam complaint."};case"failed":return{label:"Send failed",variant:"destructive",detail:"The email provider reported a sending failure."};case"unknown":return{label:"Delivery unconfirmed",variant:"warning",detail:"We could not confirm whether the email was sent. Check with the recipient before sending it again."}}}function _o(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function Vu(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 yr({deliveries:e,label:t="Email needs attention"}){return _o(e)?(0,Ha.jsxs)("span",{className:"af-mt-1 af-flex af-items-center af-gap-1 af-text-xs af-font-normal af-text-amber-800 dark:af-text-amber-300",children:[(0,Ha.jsx)(ec.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Dn({deliveries:e,problemsOnly:t=!1,className:a=""}){let s=(e??[]).filter(n=>!t||_o([n]));return s.length?(0,Ha.jsx)("div",{className:`af-space-y-3 ${a}`,"aria-label":"Email delivery",children:s.map(n=>{let r=Si(n),i=Vu(n);return(0,Ha.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Ha.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Ha.jsx)("span",{className:"af-font-medium",children:Uu[n.kind]??"Email notification"}),(0,Ha.jsx)(ie,{variant:r.variant,children:r.label})]}),(0,Ha.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&_o([n])&&(0,Ha.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This status applies to the message sent to this group. It does not mean every recipient had a delivery problem."}),r.detail&&(0,Ha.jsx)("p",{className:"af-mt-1",children:r.detail}),i&&(0,Ha.jsx)("p",{className:"af-mt-1",children:i})]},n.id)})}):null}var us=le(require("react"),1),dn=require("lucide-react");var ds=le(require("react"),1),Ke=le(require("@radix-ui/react-select"),1),Rs=require("lucide-react");var jt=require("react/jsx-runtime"),on=Ke.Root;var ln=Ke.Value,za=ds.forwardRef(({className:e,children:t,...a},s)=>(0,jt.jsxs)(Ke.Trigger,{ref:s,className:X("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...a,children:[t,(0,jt.jsx)(Ke.Icon,{asChild:!0,children:(0,jt.jsx)(Rs.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));za.displayName=Ke.Trigger.displayName;var tc=ds.forwardRef(({className:e,...t},a)=>(0,jt.jsx)(Ke.ScrollUpButton,{ref:a,className:X("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,jt.jsx)(Rs.ChevronUp,{className:"af-h-4 af-w-4"})}));tc.displayName=Ke.ScrollUpButton.displayName;var ac=ds.forwardRef(({className:e,...t},a)=>(0,jt.jsx)(Ke.ScrollDownButton,{ref:a,className:X("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,jt.jsx)(Rs.ChevronDown,{className:"af-h-4 af-w-4"})}));ac.displayName=Ke.ScrollDownButton.displayName;var ja=ds.forwardRef(({className:e,children:t,position:a="popper",...s},n)=>(0,jt.jsx)(Ke.Portal,{children:(0,jt.jsxs)(Ke.Content,{ref:n,className:X("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:a,...s,children:[(0,jt.jsx)(tc,{}),(0,jt.jsx)(Ke.Viewport,{className:X("af-p-1",a==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,jt.jsx)(ac,{})]})}));ja.displayName=Ke.Content.displayName;var Hu=ds.forwardRef(({className:e,...t},a)=>(0,jt.jsx)(Ke.Label,{ref:a,className:X("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));Hu.displayName=Ke.Label.displayName;var kt=ds.forwardRef(({className:e,children:t,...a},s)=>(0,jt.jsxs)(Ke.Item,{ref:s,className:X("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...a,children:[(0,jt.jsx)("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:(0,jt.jsx)(Ke.ItemIndicator,{children:(0,jt.jsx)(Rs.Check,{className:"af-h-4 af-w-4"})})}),(0,jt.jsx)(Ke.ItemText,{children:t})]}));kt.displayName=Ke.Item.displayName;var zu=ds.forwardRef(({className:e,...t},a)=>(0,jt.jsx)(Ke.Separator,{ref:a,className:X("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));zu.displayName=Ke.Separator.displayName;var Na=le(require("react"),1);function xr({formId:e,initialPageSize:t=25}){let{api:a}=W(),[s,n]=Na.useState([]),[r,i]=Na.useState(0),[l,u]=Na.useState(!0),[c,o]=Na.useState(null),[f,b]=Na.useState(0),[g,m]=Na.useState(t),v=Na.useRef(0),d=Na.useCallback(async()=>{if(!e)return;let T=++v.current;try{u(!0),o(null);let h={limit:g,offset:f*g},k=await a.getSubmissions(e,h);if(T!==v.current)return;if(k.submissions.length===0&&f>0){b(Math.max(0,Math.ceil(k.total/g)-1));return}n(k.submissions),i(k.total)}catch(h){if(T!==v.current)return;o(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{T===v.current&&u(!1)}},[a,e,f,g]);Na.useEffect(()=>{d()},[d]);let p=Na.useRef(d);p.current=d;let x=Na.useCallback(async T=>{await a.deleteSubmission(T),p.current()},[a]),R=Math.ceil(r/g);return{submissions:s,total:r,isLoading:l,error:c,page:f,pageSize:g,hasNextPage:f<R-1,hasPreviousPage:f>0,setPage:b,setPageSize:T=>{m(T),b(0)},refetch:d,deleteSubmission:x}}var Ni=le(require("react"),1),rc=require("lucide-react");var wr=le(require("react"),1),ea=le(require("@radix-ui/react-dialog"),1),nc=require("lucide-react");var Ta=require("react/jsx-runtime"),cn=ea.Root;var ju=ea.Portal;var sc=wr.forwardRef(({className:e,...t},a)=>(0,Ta.jsx)(ea.Overlay,{ref:a,className:X("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));sc.displayName=ea.Overlay.displayName;var qa=wr.forwardRef(({className:e,children:t,...a},s)=>(0,Ta.jsx)(ju,{children:(0,Ta.jsxs)("div",{className:"aifeatures-admin",children:[(0,Ta.jsx)(sc,{}),(0,Ta.jsxs)(ea.Content,{ref:s,className:X("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...a,children:[t,(0,Ta.jsxs)(ea.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[(0,Ta.jsx)(nc.X,{className:"af-h-4 af-w-4"}),(0,Ta.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));qa.displayName=ea.Content.displayName;var Wa=({className:e,...t})=>(0,Ta.jsx)("div",{className:X("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Wa.displayName="DialogHeader";var Ga=({className:e,...t})=>(0,Ta.jsx)("div",{className:X("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ga.displayName="DialogFooter";var Ka=wr.forwardRef(({className:e,...t},a)=>(0,Ta.jsx)(ea.Title,{ref:a,className:X("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Ka.displayName=ea.Title.displayName;var Za=wr.forwardRef(({className:e,...t},a)=>(0,Ta.jsx)(ea.Description,{ref:a,className:X("af-text-sm af-text-muted-foreground",e),...t}));Za.displayName=ea.Description.displayName;var va=require("react/jsx-runtime");function Zs({onDelete:e,iconOnly:t}){let[a,s]=Ni.useState(!1),[n,r]=Ni.useState(!1),[i,l]=Ni.useState(null);return(0,va.jsxs)(va.Fragment,{children:[(0,va.jsxs)(y,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{l(null),s(!0)},children:[(0,va.jsx)(rc.Trash2,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),(0,va.jsx)(cn,{open:a,onOpenChange:c=>{!c&&!n&&s(!1)},children:(0,va.jsxs)(qa,{children:[(0,va.jsxs)(Wa,{children:[(0,va.jsx)(Ka,{children:"Delete this submission?"}),(0,va.jsx)(Za,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),i&&(0,va.jsx)("p",{className:"af-text-sm af-text-destructive",children:i}),(0,va.jsxs)(Ga,{children:[(0,va.jsx)(y,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),(0,va.jsx)(y,{variant:"destructive",onClick:async()=>{r(!0),l(null);try{await e(),s(!1)}catch(c){l(c instanceof Error?c.message:"Failed to delete submission")}finally{r(!1)}},disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}var oc=le(require("react"),1),ba=require("lucide-react");var Le=require("react/jsx-runtime");function ic(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function qu(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 Sr({submission:e,onBack:t,onDelete:a}){let{api:s}=W(),[n,r]=oc.useState(null),i=c=>c.id??c.name,l=async c=>{r(i(c));try{await s.downloadAttachment(e.id,c)}catch(o){console.error("Download failed:",o)}finally{r(null)}},u=Object.entries(e.data).filter(([c])=>!c.startsWith("_"));return(0,Le.jsxs)("div",{children:[(0,Le.jsxs)("div",{className:"af-mb-6",children:[(0,Le.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,Le.jsx)(ba.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,Le.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Le.jsxs)("div",{children:[(0,Le.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,Le.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",ic(e.metadata.submitted_at)]})]}),a&&(0,Le.jsx)(Zs,{onDelete:a})]})]}),(0,Le.jsxs)("div",{className:"af-space-y-6",children:[(0,Le.jsx)(Dn,{deliveries:e.email_deliveries}),(0,Le.jsxs)("div",{children:[(0,Le.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,Le.jsxs)("div",{className:"af-space-y-3",children:[u.map(([c,o])=>(0,Le.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,Le.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:c.replace(/_/g," ")}),(0,Le.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof o=="string"&&o.includes(`
3
+ `)?(0,Le.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:o}):String(o)})]},c)),u.length===0&&(0,Le.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,Le.jsxs)("div",{children:[(0,Le.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,Le.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((c,o)=>(0,Le.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Le.jsx)(ba.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,Le.jsx)("span",{className:"af-text-sm",children:c.name}),(0,Le.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",qu(c.size),")"]})]}),(0,Le.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>l(c),disabled:n===i(c),children:[n===i(c)?(0,Le.jsx)(ba.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Le.jsx)(ba.Download,{className:"af-h-4 af-w-4 af-mr-1"}),n===i(c)?"Downloading...":"Download"]})]},o))})]}),(0,Le.jsxs)("div",{children:[(0,Le.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,Le.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Le.jsx)(ba.Clock,{className:"af-h-4 af-w-4"}),(0,Le.jsx)("span",{children:ic(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Le.jsx)(ba.Globe,{className:"af-h-4 af-w-4"}),(0,Le.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,Le.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,Le.jsx)(ba.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,Le.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Le.jsx)(ba.Mail,{className:"af-h-4 af-w-4"}),(0,Le.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var cc=require("lucide-react");var _s=le(require("react"),1);var Wu=/^\+[1-9]\d{1,14}$/;function lc(e){let t=e==null?"":String(e),a=!Wu.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 Ri(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function _i(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 Nr({fetchCsv:e,filename:t}){let[a,s]=_s.useState(!1),[n,r]=_s.useState(null),i=_s.useRef(!1);return{exportCsv:_s.useCallback(async()=>{if(!i.current){i.current=!0,s(!0),r(null);try{let u=await e();_i(u,Ri(t))}catch(u){r(u instanceof Error?u:new Error("Export failed"))}finally{i.current=!1,s(!1)}}},[e,t]),exporting:a,error:n}}var Ys=require("react/jsx-runtime");function ma({fetchCsv:e,filename:t,label:a="Export CSV",disabled:s,className:n}){let{exportCsv:r,exporting:i,error:l}=Nr({fetchCsv:e,filename:t});return(0,Ys.jsxs)("span",{className:n,children:[(0,Ys.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||i,"aria-busy":i,children:[(0,Ys.jsx)(cc.Download,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Exporting\u2026":a]}),l&&(0,Ys.jsx)("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}var _e=require("react/jsx-runtime");function Gu(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Ku(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 Zu=["message","comments","comment","inquiry","question","details","body","notes"];function Yu(e){let t=Object.entries(e).filter(([r,i])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof i=="string"&&i.trim()),a=new Map(t.map(([r,i])=>[r.toLowerCase(),i])),n=(Zu.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 Rr({formId:e,className:t,defaultSubmissionId:a,submissionId:s,onSelectSubmission:n}){let{api:r}=W(),{submissions:i,total:l,isLoading:u,error:c,page:o,pageSize:f,hasNextPage:b,hasPreviousPage:g,setPage:m,setPageSize:v,deleteSubmission:d}=xr({formId:e}),p=us.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[x,R]=us.useState(a??null),T=n?s??null:x,h=n??R,k=z=>!!z&&z.id===T&&z.form_id===e,P=i.find(k),[I,w]=us.useState(null),E=k(I)?I:null,[L,C]=us.useState(null);if(us.useEffect(()=>{if(C(null),!T||P||E)return;let z=!1;return r.getSubmission(T).then(ce=>{if(!z){if(ce.form_id!==e){C("This submission could not be found.");return}w(ce)}}).catch(()=>{z||C("This submission could not be found.")}),()=>{z=!0}},[r,e,T,P,E]),T){let z=P??E;return z?(0,_e.jsx)("div",{className:t,children:(0,_e.jsx)(Sr,{submission:z,onBack:()=>h(null),onDelete:async()=>{await d(z.id),h(null)}})}):L?(0,_e.jsxs)("div",{className:t,children:[(0,_e.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>h(null),className:"af-mb-2 af--ml-2",children:[(0,_e.jsx)(dn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,_e.jsx)("p",{className:"af-text-sm af-text-destructive",children:L})]}):(0,_e.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,_e.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(u)return(0,_e.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,_e.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(c)return(0,_e.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,_e.jsxs)("div",{className:"af-text-destructive",children:["Error: ",c.message]})});if(i.length===0&&o===0)return(0,_e.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,_e.jsx)(dn.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,_e.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,_e.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let Y=o*f+1,G=Math.min((o+1)*f,l);return(0,_e.jsxs)("div",{className:t,children:[(0,_e.jsx)("div",{className:"af-mb-2 af-flex af-justify-end",children:(0,_e.jsx)(ma,{fetchCsv:p,filename:"submissions"})}),(0,_e.jsxs)(ft,{children:[(0,_e.jsx)(mt,{children:(0,_e.jsxs)(Ue,{children:[(0,_e.jsx)(te,{children:"Email"}),(0,_e.jsx)(te,{children:"Preview"}),(0,_e.jsx)(te,{children:"Date"}),(0,_e.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,_e.jsx)(pt,{children:i.map(z=>{let ce=Ku(z.data),ve=Yu(z.data);return(0,_e.jsxs)(Ue,{children:[(0,_e.jsxs)(ae,{className:"af-font-medium",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[ce||(0,_e.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),z.attachments.length>0&&(0,_e.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${z.attachments.length} attachment(s)`,children:[(0,_e.jsx)(dn.Paperclip,{className:"af-h-3 af-w-3"}),(0,_e.jsx)("span",{className:"af-text-xs",children:z.attachments.length})]})]}),(0,_e.jsx)(yr,{deliveries:z.email_deliveries,label:"Notification email needs attention"})]}),(0,_e.jsx)(ae,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:ve||(0,_e.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,_e.jsx)(ae,{className:"af-text-muted-foreground",children:Gu(z.metadata.submitted_at)}),(0,_e.jsxs)(ae,{className:"af-text-right",children:[(0,_e.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>h(z.id),title:"View details",children:(0,_e.jsx)(dn.Eye,{className:"af-h-4 af-w-4"})}),(0,_e.jsx)(Zs,{iconOnly:!0,onDelete:()=>d(z.id)})]})]},z.id)})})]}),(0,_e.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,_e.jsxs)("span",{children:["Showing ",Y,"-",G," of ",l]}),(0,_e.jsxs)(on,{value:String(f),onValueChange:z=>v(Number(z)),children:[(0,_e.jsx)(za,{className:"af-w-[70px] af-h-8",children:(0,_e.jsx)(ln,{})}),(0,_e.jsxs)(ja,{children:[(0,_e.jsx)(kt,{value:"10",children:"10"}),(0,_e.jsx)(kt,{value:"25",children:"25"}),(0,_e.jsx)(kt,{value:"50",children:"50"}),(0,_e.jsx)(kt,{value:"100",children:"100"})]})]}),(0,_e.jsx)("span",{children:"per page"})]}),(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_e.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>m(o-1),disabled:!g,children:[(0,_e.jsx)(dn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,_e.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>m(o+1),disabled:!b,children:["Next",(0,_e.jsx)(dn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ja=le(require("react"),1),fs=require("lucide-react");var dc=le(require("react"),1);var uc=require("react/jsx-runtime"),de=dc.forwardRef(({className:e,type:t,...a},s)=>(0,uc.jsx)("input",{type:t,className:X("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...a}));de.displayName="Input";var fc=le(require("react"),1),mc=require("class-variance-authority");var pc=require("react/jsx-runtime"),Ju=(0,mc.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),je=fc.forwardRef(({className:e,...t},a)=>(0,pc.jsx)("label",{ref:a,className:X(Ju(),e),...t}));je.displayName="Label";var un=le(require("react"),1),ha=require("lucide-react");var Ya=le(require("react"),1);function _r(){let{api:e}=W(),[t,a]=Ya.useState([]),[s,n]=Ya.useState(!0),[r,i]=Ya.useState(null),l=Ya.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]);Ya.useEffect(()=>{l()},[l]);let u=Ya.useCallback(async g=>{let m=await e.createEventDestination(g);return a(v=>[m,...v]),m},[e]),c=Ya.useCallback(async(g,m)=>{let v=await e.updateEventDestination(g,m);return a(d=>d.map(p=>p.id===g?v:p)),v},[e]),o=Ya.useCallback(async g=>{await e.deleteEventDestination(g),a(m=>m.filter(v=>v.id!==g))},[e]),f=Ya.useCallback(async g=>{let m=await e.rotateEventDestinationSecret(g);return a(v=>v.map(d=>d.id===g?m:d)),m},[e]),b=Ya.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:s,error:r,refetch:l,createDestination:u,updateDestination:c,deleteDestination:o,rotateSecret:f,getSecret:b}}var Kn=le(require("react"),1),kr=require("lucide-react");var ta=require("react/jsx-runtime");function Pr({destinationId:e,limit:t=25,className:a}){let{api:s}=W(),[n,r]=Kn.useState([]),[i,l]=Kn.useState(!0),[u,c]=Kn.useState(null),[o,f]=Kn.useState(null),b=Kn.useCallback(async()=>{try{l(!0),c(null),r(await s.getEventDeliveries(e,t))}catch(m){c(m instanceof Error?m.message:"Failed to load deliveries")}finally{l(!1)}},[s,e,t]);Kn.useEffect(()=>{b()},[b]);let g=async m=>{try{f(m.id),c(null);let v=await s.retryEventDelivery(e,m.id);r(d=>d.map(p=>p.id===m.id?v:p))}catch(v){c(v instanceof Error?v.message:"Retry failed")}finally{f(null)}};return i?(0,ta.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,ta.jsx)(kr.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):u?(0,ta.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:u}):n.length===0?(0,ta.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):(0,ta.jsx)("div",{className:a,children:(0,ta.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(m=>{let v=m.delivered_at!==null;return(0,ta.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,ta.jsxs)("div",{className:"af-min-w-0",children:[(0,ta.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[v?(0,ta.jsx)(ie,{variant:"secondary",children:m.last_status??200}):(0,ta.jsx)(ie,{variant:"destructive",children:m.last_status??"failed"}),(0,ta.jsx)("span",{className:"af-text-sm af-truncate",children:m.type})]}),(0,ta.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[m.event_id," \xB7 ",m.created_at,m.attempts>0&&` \xB7 ${m.attempts} failed ${m.attempts===1?"attempt":"attempts"}`]}),!v&&m.last_error&&(0,ta.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:m.last_error})]}),(0,ta.jsx)(y,{variant:"ghost",size:"sm",title:"Send this event again",disabled:o===m.id,onClick:()=>g(m),children:o===m.id?(0,ta.jsx)(kr.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,ta.jsx)(kr.RotateCw,{className:"af-h-4 af-w-4"})})]},m.id)})})})}var Ee=require("react/jsx-runtime");function Cr({formId:e,topics:t,description:a,className:s}){let{destinations:n,isLoading:r,error:i,createDestination:l,updateDestination:u,deleteDestination:c,rotateSecret:o,getSecret:f}=_r(),[b,g]=un.useState(""),[m,v]=un.useState(!1),[d,p]=un.useState(null),[x,R]=un.useState(null),[T,h]=un.useState(null),[k,P]=un.useState(!1),[I,w]=un.useState(null),[E,L]=un.useState(null),[C,Y]=un.useState(null),G=un.useMemo(()=>n.filter(B=>B.form_id===e),[n,e]),z=async()=>{let B=b.trim();if(B){if(!B.startsWith("https://")){p("Webhook URLs must start with https://");return}try{v(!0),p(null),await l({url:B,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(fe){p(fe instanceof Error?fe.message:"Failed to add webhook")}finally{v(!1)}}},ce=async B=>{try{L(B.id),p(null),await o(B.id),P(!1),h(await f(B.id))}catch(fe){p(fe instanceof Error?fe.message:"Failed to rotate secret")}finally{L(null)}},ve=async B=>{try{L(B.id),p(null),await u(B.id,{status:"active"})}catch(fe){p(fe instanceof Error?fe.message:"Failed to re-enable")}finally{L(null)}},xe=async()=>{if(I)try{L(I.id),await c(I.id),w(null)}catch(B){p(B instanceof Error?B.message:"Failed to delete")}finally{L(null)}},D=async B=>{if(x===B.id){R(null),h(null);return}try{L(B.id),p(null),P(!1),R(B.id),h(await f(B.id))}catch(fe){R(null),p(fe instanceof Error?fe.message:"Failed to read secret")}finally{L(null)}},q=async()=>{if(T)try{await navigator.clipboard.writeText(T),P(!0)}catch{}};return(0,Ee.jsxs)("div",{className:s,children:[(0,Ee.jsxs)("div",{className:"af-space-y-1",children:[(0,Ee.jsx)(je,{children:"Webhooks"}),(0,Ee.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:a??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),(0,Ee.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,Ee.jsx)(de,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:B=>g(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),z())},disabled:m}),(0,Ee.jsxs)(y,{onClick:z,disabled:m||!b.trim(),children:[m?(0,Ee.jsx)(ha.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ee.jsx)(ha.Plus,{className:"af-h-4 af-w-4"}),(0,Ee.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(d||i)&&(0,Ee.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:d||i?.message}),(0,Ee.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[r&&(0,Ee.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Ee.jsx)(ha.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&G.length===0&&(0,Ee.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),G.map(B=>(0,Ee.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,Ee.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Ee.jsxs)("div",{className:"af-min-w-0",children:[(0,Ee.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Ee.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:B.url}),B.status==="disabled"?(0,Ee.jsx)(ie,{variant:"destructive",children:"Disabled"}):(0,Ee.jsx)(ie,{variant:"secondary",children:"Active"})]}),(0,Ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:B.topics.includes("*")?"All events":B.topics.join(", ")})]}),(0,Ee.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,Ee.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>Y(C===B.id?null:B.id),children:C===B.id?"Hide log":"Deliveries"}),(0,Ee.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>D(B),disabled:E===B.id,children:x===B.id?"Hide secret":"Show secret"}),(0,Ee.jsx)(y,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:E===B.id,onClick:()=>w(B),children:(0,Ee.jsx)(ha.Trash2,{className:"af-h-4 af-w-4"})})]})]}),B.status==="disabled"&&(0,Ee.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[(0,Ee.jsx)(ha.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,Ee.jsxs)("div",{className:"af-text-sm",children:[(0,Ee.jsxs)("p",{children:["We stopped sending after repeated failures."," ",B.disabled_reason]}),(0,Ee.jsx)(y,{variant:"outline",size:"sm",className:"af-mt-2",disabled:E===B.id,onClick:()=>ve(B),children:"Re-enable"})]})]}),x===B.id&&T&&(0,Ee.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,Ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Optional. Use this if you want your endpoint to check that a delivery really came from us. Rotating replaces it."}),(0,Ee.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ee.jsx)(de,{readOnly:!0,value:T,className:"af-font-mono"}),(0,Ee.jsx)(y,{variant:"outline",title:"Copy signing secret",onClick:q,children:k?(0,Ee.jsx)(ha.Check,{className:"af-h-4 af-w-4"}):(0,Ee.jsx)(ha.Copy,{className:"af-h-4 af-w-4"})}),(0,Ee.jsx)(y,{variant:"outline",title:"Rotate signing secret",disabled:E===B.id,onClick:()=>ce(B),children:E===B.id?(0,Ee.jsx)(ha.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ee.jsx)(ha.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),C===B.id&&(0,Ee.jsx)(Pr,{destinationId:B.id})]},B.id))]}),(0,Ee.jsx)(cn,{open:!!I,onOpenChange:B=>{!B&&!E&&w(null)},children:(0,Ee.jsxs)(qa,{children:[(0,Ee.jsxs)(Wa,{children:[(0,Ee.jsx)(Ka,{children:"Delete this webhook?"}),(0,Ee.jsxs)(Za,{children:["New submissions will stop being sent to ",I?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),(0,Ee.jsxs)(Ga,{children:[(0,Ee.jsx)(y,{variant:"outline",onClick:()=>w(null),disabled:!!E,children:"Cancel"}),(0,Ee.jsx)(y,{variant:"destructive",onClick:xe,disabled:!!E,children:E?"Deleting...":"Delete"})]})]})})]})}var ze=require("react/jsx-runtime");function Tr({form:e,onSaved:t,className:a}){let{updateForm:s}=Ns(),[n,r]=Ja.useState(!1),[i,l]=Ja.useState(null),[u,c]=Ja.useState(null),[o,f]=Ja.useState(e.name),[b,g]=Ja.useState(e.redirect_url||""),[m,v]=Ja.useState(e.email_recipients),[d,p]=Ja.useState("");Ja.useEffect(()=>{f(e.name),g(e.redirect_url||""),v(e.email_recipients),c(null)},[e]);let x=Ja.useCallback(async P=>{try{r(!0),c(null);let I=await s(e.id,P);l(new Date),t?.(I)}catch(I){c(I instanceof Error?I.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);Ja.useEffect(()=>{if(i){let P=setTimeout(()=>l(null),2e3);return()=>clearTimeout(P)}},[i]);let R=async()=>{let P=d.trim().toLowerCase();if(!P)return;if(!P.includes("@")){c("Please enter a valid email address");return}if(m.includes(P)){c("This email is already added");return}let I=[...m,P];v(I),p(""),c(null),await x({email_recipients:I})},T=async P=>{let I=m.filter(w=>w!==P);v(I),await x({email_recipients:I})},h=async()=>{o!==e.name&&await x({name:o})},k=async()=>{let P=b||null;P!==e.redirect_url&&await x({redirect_url:P})};return(0,ze.jsxs)("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(n||i)&&(0,ze.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,ze.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-background af-border af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,ze.jsx)(fs.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,ze.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,ze.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-green-50 af-border af-border-green-200 af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,ze.jsx)(fs.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,ze.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,ze.jsxs)("div",{className:"af-space-y-2",children:[(0,ze.jsx)(je,{htmlFor:"form-name",children:"Form Name"}),(0,ze.jsx)(de,{id:"form-name",value:o,onChange:P=>f(P.target.value),onBlur:h,placeholder:"Contact Form"}),(0,ze.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,ze.jsxs)("div",{className:"af-space-y-2",children:[(0,ze.jsx)(je,{children:"Email Recipients"}),(0,ze.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,ze.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[m.map(P=>(0,ze.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[P,(0,ze.jsx)("button",{type:"button",onClick:()=>T(P),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,ze.jsx)(fs.X,{className:"af-h-3 af-w-3"})})]},P)),m.length===0&&(0,ze.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,ze.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ze.jsx)(de,{type:"email",value:d,onChange:P=>p(P.target.value),placeholder:"Add email address",onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),R())},disabled:n}),(0,ze.jsx)(y,{type:"button",variant:"outline",onClick:R,disabled:!d.trim()||n,children:(0,ze.jsx)(fs.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,ze.jsxs)("div",{className:"af-space-y-2",children:[(0,ze.jsx)(je,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,ze.jsx)(de,{id:"redirect-url",value:b,onChange:P=>g(P.target.value),onBlur:k,placeholder:"/thank-you"}),(0,ze.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Where to send visitors after a successful submission. Use a site path (/thank-you) or a full URL (https://example.com/thank-you). Leave empty for a default success page."})]}),(0,ze.jsxs)("div",{className:"af-space-y-2",children:[(0,ze.jsx)(je,{children:"Form Endpoint"}),(0,ze.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,ze.jsx)("code",{className:"af-flex-1 af-text-xs af-bg-muted af-px-3 af-py-2 af-rounded af-border",children:e.endpoint_url})}),(0,ze.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,ze.jsxs)("div",{className:"af-space-y-2",children:[(0,ze.jsx)(je,{children:"Captcha Protection"}),(0,ze.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,ze.jsx)(ie,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,ze.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,ze.jsx)(Cr,{formId:e.id}),u&&(0,ze.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})]})}var xt=require("react/jsx-runtime");function ko({className:e,location:t,onNavigate:a,submissionId:s}){let{api:n}=W(),[r,i]=Zn.useState({submissionId:s});Zn.useEffect(()=>{s&&i({submissionId:s})},[s]);let l=a?t??{}:r,u=a??i,[c,o]=Zn.useState(null),f=`${l.formId??""}|${l.submissionId??""}`,[b,g]=Zn.useState(null),m=b?.key===f?b.message:null,v=l.formId??(c&&c.submissionId===l.submissionId?c.formId:void 0);Zn.useEffect(()=>{let P=l.submissionId;if(!P||l.formId)return;let I=!1;return n.getSubmission(P).then(w=>{I||(g(null),o({submissionId:P,formId:w.form_id}))}).catch(()=>{I||g({key:f,message:"This submission could not be found."})}),()=>{I=!0}},[n,l.submissionId,l.formId,f]);let[d,p]=Zn.useState(null);Zn.useEffect(()=>{if(!v||d?.id===v)return;let P=!1;return n.getForm(v).then(I=>{P||(g(null),p(I))}).catch(()=>{P||g({key:f,message:"This form could not be found."})}),()=>{P=!0}},[n,v,d?.id,f]);let x=(P,I)=>{p(P),u({formId:P.id,tab:I})},R=()=>u({});if(!l.formId&&!l.submissionId)return(0,xt.jsxs)("div",{className:e,children:[(0,xt.jsxs)("div",{className:"af-mb-6",children:[(0,xt.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,xt.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,xt.jsx)(hr,{onSelectForm:x})]});let h=(0,xt.jsxs)(y,{variant:"ghost",size:"sm",onClick:R,className:"af-mb-2 af--ml-2",children:[(0,xt.jsx)(Js.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(m)return(0,xt.jsxs)("div",{className:e,children:[h,(0,xt.jsx)("p",{className:"af-text-sm af-text-destructive",children:m})]});if(!v||d?.id!==v)return(0,xt.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,xt.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let k=l.submissionId?"submissions":l.tab??"submissions";return(0,xt.jsxs)("div",{className:e,children:[(0,xt.jsxs)("div",{className:"af-mb-6",children:[h,(0,xt.jsx)("h2",{className:"af-text-lg af-font-semibold",children:d.name})]}),(0,xt.jsxs)(xi,{value:k,onValueChange:P=>u({formId:v,tab:P}),children:[(0,xt.jsxs)(vr,{className:"af-mb-4",children:[(0,xt.jsxs)(Sn,{value:"submissions",className:"af-gap-2",children:[(0,xt.jsx)(Js.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,xt.jsxs)(Sn,{value:"settings",className:"af-gap-2",children:[(0,xt.jsx)(Js.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,xt.jsx)(Nn,{value:"submissions",children:(0,xt.jsx)(Rr,{formId:v,submissionId:l.submissionId,onSelectSubmission:P=>u({formId:v,tab:"submissions",submissionId:P??void 0})})}),(0,xt.jsx)(Nn,{value:"settings",children:(0,xt.jsx)(Tr,{form:d,onSaved:p})})]})]})}var dt=le(require("react"),1);var On=le(require("react"),1);function Yn(){let{api:e}=W(),[t,a]=On.useState(null),[s,n]=On.useState(!0),[r,i]=On.useState(null),l=On.useRef(0),u=On.useCallback(async()=>{let c=++l.current;try{n(!0),i(null);let o=await e.getPaymentsStatus();if(c!==l.current)return;a(o)}catch(o){if(c!==l.current)return;i(o instanceof Error?o:new Error("Failed to fetch payments status"))}finally{c===l.current&&n(!1)}},[e]);return On.useEffect(()=>{u()},[u]),{status:t,isLoading:s,error:r,refetch:u}}var Xu=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Xa(e){return Xu.has(e.toLowerCase())}function re(e,t,a){let s=Xa(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Ln(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 oa(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=Xa(t)?a:a*100;return Math.round(s)}function Et(e,t){return Xa(t)?e:e/100}function ki(e){return e.amount_paid??Math.max(0,Ln(e)-(e.credit_applied??0))}var Ne=require("react/jsx-runtime");function Er(e){return e instanceof Gt&&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 gc(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${re(e.amount_off,e.currency)} off`:"Discount unavailable"}function ks(){let{api:e,siteToken:t}=W();return(0,Ne.jsx)(Qu,{api:e},t)}function Qu({api:e}){let{status:t,error:a}=Yn(),[s,n]=dt.useState([]),[r,i]=dt.useState(null),[l,u]=dt.useState(null),[c,o]=dt.useState(!1),[f,b]=dt.useState(!1),[g,m]=dt.useState(""),[v,d]=dt.useState(null),[p,x]=dt.useState(null),[R,T]=dt.useState(!1),h=dt.useRef(0),k=dt.useCallback(async w=>{let E=++h.current;o(!0),m("");try{let L=await e.getPromos(w);if(E!==h.current)return;n(C=>w?[...C,...L.promos.filter(Y=>!C.some(G=>G.id===Y.id))]:L.promos),i(L.next_cursor),u(L.checkout_enabled)}catch(L){E===h.current&&m(Er(L))}finally{E===h.current&&o(!1)}},[e]);dt.useEffect(()=>(k(),()=>{h.current++}),[k]);async function P(w){let E=++h.current;o(!0),m(""),T(!1);try{let L=await e.getPromo(w);E===h.current&&d(L)}catch(L){E===h.current&&m(Er(L))}finally{E===h.current&&o(!1)}}async function I(){if(v){b(!0),o(!0),m("");try{let w=await e.disablePromo(v.id);if(d(w),!["inactive","expired","exhausted"].includes(w.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");T(!1),await k()}catch(w){m(Er(w))}finally{b(!1),o(!1)}}}return p?(0,Ne.jsx)(ef,{currency:t?.currency??void 0,replaces:p.replaces,onCancel:()=>x(null),onSave:async w=>{let E=p.replaces?await e.replacePromo(p.replaces.id,w):await e.createPromo(w),L=await e.getPromo(E.id);if(L.status==="pending"||L.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");d(L),x(null),await k()}}):(0,Ne.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,Ne.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,Ne.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,Ne.jsx)(y,{disabled:c||!t?.currency,onClick:()=>{m(""),x({})},children:"Create promo code"})]}),(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),l===!1&&(0,Ne.jsx)("p",{role:"status",className:"af-rounded-md af-border af-p-3 af-text-sm",children:"Checkout code entry is not enabled yet. You can prepare codes, but buyers cannot enter them in our checkout until it is enabled."}),!t?.currency&&(0,Ne.jsx)("p",{className:"af-text-sm",children:a?Er(a):"Connect Stripe and set the payment currency before creating codes."}),g&&(0,Ne.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",(0,Ne.jsx)(y,{variant:"outline",disabled:c,onClick:()=>v?void P(v.id):void k(),children:"Refresh"})]}),v?(0,Ne.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,Ne.jsx)(y,{variant:"ghost",disabled:f,onClick:()=>{d(null),T(!1),k()},children:"Back to codes"}),(0,Ne.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[v.code," \xB7 ",v.name]}),(0,Ne.jsxs)("p",{children:[gc(v)," \xB7 ",v.status]}),(0,Ne.jsxs)("p",{className:"af-text-sm",children:[v.times_redeemed==null?"Usage unavailable":`${v.times_redeemed} redemptions`,v.max_redemptions!=null?` / ${v.max_redemptions} maximum`:""]}),(0,Ne.jsxs)("p",{className:"af-text-sm",children:[v.minimum_amount!=null&&v.currency?`Minimum order: ${re(v.minimum_amount,v.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,Ne.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",v.duration==="repeating"?`${v.duration_in_months} months`:v.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,Ne.jsx)("p",{className:"af-text-sm",children:v.expires_at?`Expires ${new Date(v.expires_at).toLocaleString()}`:"No expiry"}),(0,Ne.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,Ne.jsx)(y,{variant:"outline",disabled:c,onClick:()=>void P(v.id),children:"Refresh details"}),(0,Ne.jsx)(y,{variant:"outline",disabled:c||v.status==="pending"||v.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:v}),children:"Replace with new code"}),(0,Ne.jsx)(y,{variant:"outline",disabled:c||!["active","pending","unavailable"].includes(v.status),onClick:()=>T(!0),children:v.status==="pending"?"Cancel pending offer":"Disable code"})]}),R&&(0,Ne.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,Ne.jsxs)("p",{className:"af-text-sm",children:[v.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${v.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,Ne.jsx)(y,{disabled:c,onClick:()=>void I(),children:v.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,Ne.jsx)(y,{variant:"ghost",disabled:c,onClick:()=>T(!1),children:"Cancel"})]})]}):(0,Ne.jsxs)(Ne.Fragment,{children:[s.map(w=>(0,Ne.jsxs)("button",{type:"button",disabled:c,onClick:()=>void P(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:[(0,Ne.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,Ne.jsx)("span",{className:"af-font-semibold af-break-all",children:w.code}),(0,Ne.jsx)("span",{className:"af-text-sm",children:w.status})]}),(0,Ne.jsxs)("div",{className:"af-text-sm",children:[gc(w)," \xB7"," ",w.times_redeemed==null?"Usage unavailable":`${w.times_redeemed} redemptions`]})]},w.id)),!c&&!g&&s.length===0&&(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),c&&(0,Ne.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),r&&(0,Ne.jsx)(y,{variant:"outline",disabled:c,onClick:()=>void k(r),children:"Load more"})]})]})}function ef({currency:e,replaces:t,onCancel:a,onSave:s}){let[n,r]=dt.useState(""),[i,l]=dt.useState(t?.name??""),[u,c]=dt.useState(t?.amount_off!=null?"fixed":"percent"),[o,f]=dt.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(Et(t.amount_off,e)):"")),[b,g]=dt.useState(t?.minimum_amount!=null&&e?String(Et(t.minimum_amount,e)):""),[m,v]=dt.useState(()=>{if(!t?.expires_at)return"";let ve=new Date(t.expires_at);return Number.isFinite(ve.getTime())?new Date(ve.getTime()-ve.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[d,p]=dt.useState(t?.max_redemptions?.toString()??""),[x,R]=dt.useState(t?.duration??"once"),[T,h]=dt.useState(t?.duration_in_months?.toString()??"3"),[k,P]=dt.useState(null),[I,w]=dt.useState(!1),[E,L]=dt.useState(""),C=dt.useRef(!1),Y=e&&Xa(e)?"1":"0.01";async function G(ve){if(ve.preventDefault(),C.current)return;L("");let xe=k;if(!xe){if(!e){L("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){L("Choose a different code for the replacement.");return}let D=oa(o,e),q=b?oa(b,e):null;if(u==="fixed"&&(!D||D>999999999999)||b&&(!q||q>999999999999)){L("Enter a positive amount within the supported range.");return}if(m&&new Date(m).getTime()<=Date.now()){L("Choose a future expiry.");return}xe={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:i.trim(),duration:x,...u==="percent"?{percent_off:Number(o)}:{amount_off:D,currency:e},...b?{minimum_amount:q,currency:e}:{},...m?{expires_at:new Date(m).toISOString()}:{},...d?{max_redemptions:Number(d)}:{},...x==="repeating"?{duration_in_months:Number(T)}:{}},P(xe)}C.current=!0,w(!0);try{await s(xe)}catch(D){L(Er(D)),D instanceof Gt&&D.status>=400&&D.status<500&&D.details?.retryable!==!0&&P(null)}finally{C.current=!1,w(!1)}}let z=(ve,xe,D,q={})=>(0,Ne.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[ve,(0,Ne.jsx)(de,{"aria-label":ve,value:xe,onChange:B=>D(B.target.value),...q})]}),ce="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,Ne.jsxs)("form",{onSubmit:G,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,Ne.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,Ne.jsx)("p",{className:"af-text-sm",children:"Use a different code. The old code will be disabled only after the replacement is created. Existing subscription discounts continue."}),(0,Ne.jsxs)("fieldset",{disabled:I||!!k,className:"af-grid af-gap-4",children:[z("Code",n,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),z("Name",i,l,{required:!0,maxLength:40}),(0,Ne.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,Ne.jsxs)("select",{"aria-label":"Discount type",className:ce,value:u,onChange:ve=>c(ve.target.value),children:[(0,Ne.jsx)("option",{value:"percent",children:"Percentage"}),(0,Ne.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),z("Discount",o,f,{type:"number",required:!0,min:u==="percent"?"0.01":Y,max:u==="percent"?"100":void 0,step:u==="percent"?"0.01":Y}),z("Minimum order amount",b,g,{type:"number",min:Y,step:Y,placeholder:e?.toUpperCase()}),(0,Ne.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),z("Expires at (local time)",m,v,{type:"datetime-local",step:1}),z("Maximum redemptions",d,p,{type:"number",min:1,max:1e6,step:1}),(0,Ne.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,Ne.jsxs)("select",{"aria-label":"Subscription duration",className:ce,value:x,onChange:ve=>R(ve.target.value),children:[(0,Ne.jsx)("option",{value:"once",children:"First invoice only"}),(0,Ne.jsx)("option",{value:"forever",children:"Every invoice"}),(0,Ne.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&z("Months",T,h,{type:"number",required:!0,min:1,max:36,step:1})]}),E&&(0,Ne.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:E}),k&&!I&&(0,Ne.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,Ne.jsx)("span",{className:"af-break-all",children:k.request_id})]}),(0,Ne.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,Ne.jsx)(y,{type:"submit",disabled:I,children:I?"Saving\u2026":k?"Retry same request":t?"Create replacement":"Create code"}),(0,Ne.jsx)(y,{type:"button",variant:"ghost",disabled:I||!!k,onClick:a,children:"Cancel"})]})]})}var nr=le(require("react"),1),gn=require("lucide-react");var Pi=le(require("react"),1),Jn=require("lucide-react");var Fe=require("react/jsx-runtime");function tf(e){if(e.allow_custom_amount){let t=e.min_amount!==null?re(e.min_amount,e.currency):"?",a=e.max_amount!==null?re(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":re(e.unit_amount,e.currency)}function af(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Ir({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:n,isLoading:r,error:i,deleteProduct:l}=e,[u,c]=Pi.useState(null),[o,f]=Pi.useState(!1),[b,g]=Pi.useState(null),m=async()=>{if(u)try{f(!0),g(null),await l(u.id),c(null)}catch(v){g(v instanceof Error?v.message:"Failed to delete product")}finally{f(!1)}};return r?(0,Fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Fe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):i?(0,Fe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Fe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i.message]})}):n.length===0?(0,Fe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[(0,Fe.jsx)(Jn.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Fe.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,Fe.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,Fe.jsxs)(y,{variant:"outline",onClick:()=>a?.(),children:[(0,Fe.jsx)(Jn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,Fe.jsxs)("div",{className:s,children:[(0,Fe.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,Fe.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[(0,Fe.jsx)(Jn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,Fe.jsxs)(ft,{children:[(0,Fe.jsx)(mt,{children:(0,Fe.jsxs)(Ue,{children:[(0,Fe.jsx)(te,{children:"Name"}),(0,Fe.jsx)(te,{children:"Price"}),(0,Fe.jsx)(te,{children:"Fulfillment"}),(0,Fe.jsx)(te,{children:"Status"}),(0,Fe.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,Fe.jsx)(pt,{children:n.map(v=>(0,Fe.jsxs)(Ue,{children:[(0,Fe.jsx)(ae,{className:"af-font-medium",children:v.name}),(0,Fe.jsx)(ae,{children:tf(v)}),(0,Fe.jsx)(ae,{className:"af-text-muted-foreground",children:af(v)}),(0,Fe.jsx)(ae,{children:(0,Fe.jsx)(ie,{variant:v.active?"success":"secondary",children:v.active?"Active":"Inactive"})}),(0,Fe.jsx)(ae,{className:"af-text-right",children:(0,Fe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Fe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>t?.(v),children:[(0,Fe.jsx)(Jn.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,Fe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>{g(null),c(v)},children:[(0,Fe.jsx)(Jn.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},v.id))})]}),(0,Fe.jsx)(cn,{open:!!u,onOpenChange:v=>{!v&&!o&&c(null)},children:(0,Fe.jsxs)(qa,{children:[(0,Fe.jsxs)(Wa,{children:[(0,Fe.jsx)(Ka,{children:"Delete product?"}),(0,Fe.jsxs)(Za,{children:['"',u?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&(0,Fe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),(0,Fe.jsxs)(Ga,{children:[(0,Fe.jsx)(y,{variant:"outline",onClick:()=>c(null),disabled:o,children:"Cancel"}),(0,Fe.jsx)(y,{variant:"destructive",onClick:m,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})}var It=le(require("react"),1),Qa=require("lucide-react");var Kt=le(require("react"),1),fn=require("lucide-react");var M=require("react/jsx-runtime");function Po(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Ar({productId:e,currency:t,className:a}){let{api:s}=W(),n=Xa(t)?"1":"0.01",[r,i]=Kt.useState(null),[l,u]=Kt.useState(!0),[c,o]=Kt.useState(null),[f,b]=Kt.useState(null),[g,m]=Kt.useState(!1),v=Kt.useRef(!0);Kt.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);let d=Kt.useCallback(async()=>{try{let O=await s.getProduct(e);if(!v.current)return;i(O)}catch(O){if(!v.current)return;o(O instanceof Error?O.message:"Failed to load product")}finally{v.current&&u(!1)}},[s,e]);Kt.useEffect(()=>{d()},[d]);let p=async O=>{b(null),m(!0);try{await O(),await d()}catch(V){v.current&&b(V instanceof Error?V.message:"Something went wrong")}finally{v.current&&m(!1)}},[x,R]=Kt.useState(""),[T,h]=Kt.useState(""),[k,P]=Kt.useState({}),I=()=>p(async()=>{let O=x.trim(),V=T.split(",").map($=>$.trim()).filter(Boolean);if(!O)throw new Error("Option name is required");if(V.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:O,values:V}),v.current&&(R(""),h(""))}),w=O=>p(async()=>{let V=(k[O.id]??"").trim();if(!V)throw new Error("Enter a value");await s.updateOption(O.id,{add_values:[V]}),v.current&&P($=>({...$,[O.id]:""}))}),E=(O,V)=>p(()=>s.updateOption(O.id,{remove_values:[V]})),L=O=>p(()=>s.deleteOption(O.id)),[C,Y]=Kt.useState(null),[G,z]=Kt.useState(null),[ce,ve]=Kt.useState(!1),[xe,D]=Kt.useState(null),q=r?.options??[],B=r?.variants??[],fe=()=>{z(null),Y({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(q.map(O=>[O.id,O.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},pe=O=>{z(null);let V=O.inventory?.on_hand??0,$=V<0?"":String(V);Y({variant:O,title:O.title??"",sku:O.sku??"",unitAmount:O.unit_amount!=null?String(Et(O.unit_amount,t)):"",compareAt:O.compare_at_amount!=null?String(Et(O.compare_at_amount,t)):"",active:O.active,optionValues:{},tracked:O.inventory?.tracked??!1,onHand:$,initialOnHand:$,allowBackorder:O.inventory?.allow_backorder??!1})},We=async()=>{if(!C)return;z(null);let O=C.variant?.allow_custom_amount??!1,V=null,$=null;if(!O){if(V=oa(C.unitAmount,t),V===null||V<=0){z("Enter a valid price");return}if(C.compareAt.trim()&&($=oa(C.compareAt,t),$===null||$<=V)){z("Compare-at price must be greater than the price");return}}let we=C.onHand.trim()!==C.initialOnHand.trim(),ne=parseInt(C.onHand,10);if(C.tracked&&we&&(!Number.isFinite(ne)||ne<0)){z("On-hand quantity must be zero or more");return}try{if(ve(!0),C.variant)await s.updateVariant(C.variant.id,{title:C.title.trim()||null,sku:C.sku.trim()||null,...O?{}:{unit_amount:V,compare_at_amount:$},active:C.active}),await s.setVariantInventory(C.variant.id,{tracked:C.tracked,on_hand:C.tracked&&we?ne:void 0,allow_backorder:C.allowBackorder});else{let me={};for(let qe of q){let rt=C.optionValues[qe.id];if(!rt){z(`Choose a ${qe.title}`),ve(!1);return}me[qe.title]=rt}await s.createVariant(e,{title:C.title.trim()||null,sku:C.sku.trim()||null,unit_amount:V,compare_at_amount:$,active:C.active,option_values:q.length>0?me:void 0,inventory:C.tracked?{tracked:!0,on_hand:ne,allow_backorder:C.allowBackorder}:{tracked:!1,allow_backorder:C.allowBackorder}})}await d(),v.current&&Y(null)}catch(me){if(v.current&&z(me instanceof Error?me.message:"Failed to save variant"),C.variant)try{let qe=await s.getProduct(e);v.current&&i(qe)}catch{}}finally{v.current&&ve(!1)}},Ie=()=>p(async()=>{xe&&(await s.deleteVariant(xe.id),v.current&&D(null))}),$e=C?.variant?.allow_custom_amount??!1,Qe=C?.variant!=null&&C.variant.option_values.length===0&&q.length>0&&!C.variant.active,De=C?.variant?.inventory!=null&&C.variant.inventory.on_hand<0?-C.variant.inventory.on_hand:null;function ot(O){let V=O.inventory;if(!V||!V.tracked)return(0,M.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let $=V.available??V.on_hand;return $<0?(0,M.jsxs)("span",{children:[-$," backordered"]}):(0,M.jsxs)("span",{children:[$," in stock",V.allow_backorder&&(0,M.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return l?(0,M.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:(0,M.jsx)(fn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):c?(0,M.jsx)("div",{className:a,children:(0,M.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c})}):(0,M.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,M.jsxs)("div",{className:"af-space-y-3",children:[(0,M.jsxs)("div",{children:[(0,M.jsx)(je,{children:"Options"}),(0,M.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),q.length>0&&(0,M.jsx)("div",{className:"af-space-y-3",children:q.map(O=>(0,M.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,M.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,M.jsx)("span",{className:"af-text-sm af-font-medium",children:O.title}),(0,M.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>L(O),disabled:g,children:(0,M.jsx)(fn.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,M.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:O.values.map(V=>(0,M.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[V.value,(0,M.jsx)("button",{type:"button",onClick:()=>E(O,V.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:(0,M.jsx)(fn.X,{className:"af-h-3 af-w-3"})})]},V.id))}),(0,M.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,M.jsx)(de,{value:k[O.id]??"",onChange:V=>P($=>({...$,[O.id]:V.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),w(O))},disabled:g}),(0,M.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>w(O),disabled:g||!(k[O.id]??"").trim(),children:(0,M.jsx)(fn.Plus,{className:"af-h-4 af-w-4"})})]})]},O.id))}),(0,M.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(je,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,M.jsx)(de,{id:"new-option-title",value:x,onChange:O=>R(O.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),(0,M.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,M.jsx)(je,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,M.jsx)(de,{id:"new-option-values",value:T,onChange:O=>h(O.target.value),placeholder:"S, M, L",disabled:g})]}),(0,M.jsxs)(y,{type:"button",variant:"outline",onClick:I,disabled:g||!x.trim()||!T.trim(),children:[(0,M.jsx)(fn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,M.jsxs)("div",{className:"af-space-y-3",children:[(0,M.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,M.jsx)(je,{children:"Variants"}),(0,M.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:fe,disabled:g||q.length===0,children:[(0,M.jsx)(fn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),q.length===0&&(0,M.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),B.length===0?(0,M.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,M.jsxs)(ft,{children:[(0,M.jsx)(mt,{children:(0,M.jsxs)(Ue,{children:[(0,M.jsx)(te,{children:"Variant"}),(0,M.jsx)(te,{children:"SKU"}),(0,M.jsx)(te,{children:"Price"}),(0,M.jsx)(te,{children:"Stock"}),(0,M.jsx)(te,{children:"Status"}),(0,M.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,M.jsx)(pt,{children:B.map(O=>(0,M.jsxs)(Ue,{children:[(0,M.jsx)(ae,{className:"af-font-medium",children:Po(O)}),(0,M.jsx)(ae,{className:"af-text-muted-foreground",children:O.sku||"-"}),(0,M.jsx)(ae,{children:O.unit_amount!=null?(0,M.jsxs)("span",{children:[O.compare_at_amount!=null&&(0,M.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:re(O.compare_at_amount,O.currency)}),re(O.unit_amount,O.currency)]}):O.allow_custom_amount?(0,M.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,M.jsx)(ae,{children:ot(O)}),(0,M.jsx)(ae,{children:(0,M.jsx)(ie,{variant:O.active?"success":"secondary",children:O.active?"Active":"Inactive"})}),(0,M.jsx)(ae,{className:"af-text-right",children:(0,M.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,M.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>pe(O),disabled:g,children:"Edit"}),(0,M.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>D(O),disabled:g,title:"Delete variant",children:(0,M.jsx)(fn.Trash2,{className:"af-h-4 af-w-4"})})]})})]},O.id))})]})]}),f&&(0,M.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f}),(0,M.jsx)(cn,{open:C!==null,onOpenChange:O=>{!O&&!ce&&Y(null)},children:(0,M.jsxs)(qa,{children:[(0,M.jsxs)(Wa,{children:[(0,M.jsx)(Ka,{children:C?.variant?"Edit variant":"Add variant"}),(0,M.jsx)(Za,{children:"Price, markdown, and stock live on the variant."})]}),C&&(0,M.jsxs)("div",{className:"af-space-y-3",children:[C.variant?C.variant.option_values.length>0&&(0,M.jsxs)("div",{className:"af-text-sm",children:[(0,M.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Po(C.variant)]}):q.map(O=>(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(je,{className:"af-text-xs af-text-muted-foreground",children:O.title}),(0,M.jsxs)(on,{value:C.optionValues[O.id]??"",onValueChange:V=>Y($=>$&&{...$,optionValues:{...$.optionValues,[O.id]:V}}),children:[(0,M.jsx)(za,{children:(0,M.jsx)(ln,{placeholder:`Choose ${O.title}`})}),(0,M.jsx)(ja,{children:O.values.map(V=>(0,M.jsx)(kt,{value:V.value,children:V.value},V.id))})]})]},O.id)),$e?(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(je,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,M.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,M.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsxs)(je,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,M.jsx)(de,{id:"variant-price",type:"number",min:"0",step:n,value:C.unitAmount,onChange:O=>Y(V=>V&&{...V,unitAmount:O.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(je,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,M.jsx)(de,{id:"variant-compare",type:"number",min:"0",step:n,value:C.compareAt,onChange:O=>Y(V=>V&&{...V,compareAt:O.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(je,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,M.jsx)(de,{id:"variant-sku",value:C.sku,onChange:O=>Y(V=>V&&{...V,sku:O.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,M.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,M.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,M.jsx)("input",{type:"checkbox",checked:C.tracked,onChange:O=>Y(V=>V&&{...V,tracked:O.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),C.tracked&&(0,M.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,M.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsx)(je,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,M.jsx)(de,{id:"variant-onhand",type:"number",min:"0",step:"1",value:C.onHand,onChange:O=>Y(V=>V&&{...V,onHand:O.target.value}),placeholder:De!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,M.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,M.jsx)("input",{type:"checkbox",checked:C.allowBackorder,onChange:O=>Y(V=>V&&{...V,allowBackorder:O.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),De!=null&&(0,M.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",De," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,M.jsxs)("div",{className:"af-space-y-1",children:[(0,M.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,M.jsx)("input",{type:"checkbox",checked:C.active,onChange:O=>Y(V=>V&&{...V,active:O.target.checked}),className:"af-h-4 af-w-4",disabled:Qe}),"Active (buyers can purchase this variant)"]}),Qe&&(0,M.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),G&&(0,M.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:G})]}),(0,M.jsxs)(Ga,{children:[(0,M.jsx)(y,{variant:"outline",onClick:()=>Y(null),disabled:ce,children:"Cancel"}),(0,M.jsxs)(y,{onClick:We,disabled:ce,children:[ce?(0,M.jsx)(fn.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,C?.variant?"Save":"Add variant"]})]})]})}),(0,M.jsx)(cn,{open:xe!==null,onOpenChange:O=>{!O&&!g&&D(null)},children:(0,M.jsxs)(qa,{children:[(0,M.jsxs)(Wa,{children:[(0,M.jsx)(Ka,{children:"Delete variant?"}),(0,M.jsx)(Za,{children:xe&&`"${Po(xe)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,M.jsxs)(Ga,{children:[(0,M.jsx)(y,{variant:"outline",onClick:()=>D(null),disabled:g,children:"Cancel"}),(0,M.jsx)(y,{variant:"destructive",onClick:Ie,disabled:g,children:"Delete"})]})]})})]})}var oe=require("react/jsx-runtime");function nf(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 Dr({productsState:e,product:t,currency:a,onSaved:s,className:n}){let{createProduct:r,updateProduct:i,attachProductFile:l,attachProductFileFromUrl:u}=e,c=!!t,o=t?.currency??a,f=Xa(o)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,m]=It.useState(!1),[v,d]=It.useState(null),p=It.useRef(!0);It.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);let[x,R]=It.useState(t?.name??""),[T,h]=It.useState(t?.description??""),[k,P]=It.useState(t?.allow_custom_amount?"custom":"fixed"),[I,w]=It.useState(t?.unit_amount!=null?String(Et(t.unit_amount,o)):""),[E,L]=It.useState(t?.min_amount!=null?String(Et(t.min_amount,o)):""),[C,Y]=It.useState(t?.max_amount!=null?String(Et(t.max_amount,o)):""),[G,z]=It.useState(String(t?.max_quantity??10)),ce=It.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,[ve,xe]=It.useState(t?.collect_shipping_address??!1),[D,q]=It.useState(t?.active??!0),[B,fe]=It.useState(t?.images??[]),[pe,We]=It.useState(""),[Ie,$e]=It.useState(t?.fulfillment??null),[Qe,De]=It.useState(!1),[ot,O]=It.useState(""),[V,$]=It.useState(null),we=It.useRef(null),ne=g||Qe,me=()=>{let Pe=pe.trim();if(Pe){if(B.includes(Pe)){d("This image URL is already added");return}fe(Ge=>[...Ge,Pe]),We(""),d(null)}},qe=Pe=>{fe(Ge=>Ge.filter(yt=>yt!==Pe))},rt=async()=>{if(d(null),!x.trim()){d("Product name is required");return}let Pe=null,Ge=null,yt=null,Lt=!c||k!==ce.pricingMode||(k==="fixed"?I!==ce.unitAmount:E!==ce.minAmount||C!==ce.maxAmount),Vt=!c||G!==ce.maxQuantity,it=b||k==="fixed";if(!(b||!Lt))if(k==="fixed"){if(Pe=oa(I,o),Pe===null||Pe<=0){d("Enter a valid price");return}}else{if(Ge=oa(E,o),yt=oa(C,o),Ge===null||yt===null){d("Enter valid minimum and maximum amounts");return}if(yt<Ge){d("Maximum amount must be at least the minimum amount");return}}let Qt=parseInt(G,10);if(it&&Vt&&(!Number.isFinite(Qt)||Qt<1)){d("Max quantity must be at least 1");return}try{m(!0);let et;if(c&&t){let Rt={name:x.trim(),description:T.trim()||null,images:B,collect_shipping_address:ve,active:D};!b&&Lt&&(Rt.allow_custom_amount=k==="custom",k==="fixed"?Rt.unit_amount=Pe:(Rt.min_amount=Ge,Rt.max_amount=yt)),it&&Vt&&(Rt.max_quantity=Qt),et=await i(t.id,Rt),ce.pricingMode=et.allow_custom_amount?"custom":"fixed",ce.unitAmount=et.unit_amount!=null?String(Et(et.unit_amount,o)):"",ce.minAmount=et.min_amount!=null?String(Et(et.min_amount,o)):"",ce.maxAmount=et.max_amount!=null?String(Et(et.max_amount,o)):"",ce.maxQuantity=String(et.max_quantity)}else{let Rt={name:x.trim(),allow_custom_amount:k==="custom",collect_shipping_address:ve,active:D};T.trim()&&(Rt.description=T.trim()),B.length>0&&(Rt.images=B),k==="fixed"?(Rt.unit_amount=Pe,Rt.max_quantity=Qt):(Rt.min_amount=Ge,Rt.max_amount=yt),et=await r(Rt)}if(!p.current)return;$e(et.fulfillment),s?.(et)}catch(et){if(!p.current)return;d(et instanceof Error?et.message:"Failed to save product")}finally{p.current&&m(!1)}},nt=async Pe=>{let Ge=Pe.target.files?.[0];if(!(!Ge||!t))try{De(!0),$(null);let yt=await l(t.id,Ge);if(!p.current)return;$e(yt.fulfillment),s?.(yt)}catch(yt){if(!p.current)return;$(yt instanceof Error?yt.message:"Failed to upload file")}finally{p.current&&(De(!1),we.current&&(we.current.value=""))}},Ot=async()=>{let Pe=ot.trim();if(!(!Pe||!t))try{De(!0),$(null);let Ge=await u(t.id,Pe);if(!p.current)return;$e(Ge.fulfillment),O(""),s?.(Ge)}catch(Ge){if(!p.current)return;$(Ge instanceof Error?Ge.message:"Failed to fetch file")}finally{p.current&&De(!1)}};return(0,oe.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(je,{htmlFor:"product-name",children:"Name"}),(0,oe.jsx)(de,{id:"product-name",value:x,onChange:Pe=>R(Pe.target.value),placeholder:"My product"})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(je,{htmlFor:"product-description",children:"Description"}),(0,oe.jsx)("textarea",{id:"product-description",value:T,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"})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(je,{children:"Pricing"}),b?(0,oe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):(0,oe.jsxs)(oe.Fragment,{children:[(0,oe.jsxs)(on,{value:k,onValueChange:Pe=>P(Pe),children:[(0,oe.jsx)(za,{className:"af-w-[260px]",children:(0,oe.jsx)(ln,{})}),(0,oe.jsxs)(ja,{children:[(0,oe.jsx)(kt,{value:"fixed",children:"Fixed price"}),(0,oe.jsx)(kt,{value:"custom",children:"Buyer chooses the amount"})]})]}),k==="fixed"?(0,oe.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsxs)(je,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",o.toUpperCase(),")"]}),(0,oe.jsx)(de,{id:"product-price",type:"number",min:"0",step:f,value:I,onChange:Pe=>w(Pe.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsxs)(je,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",o.toUpperCase(),")"]}),(0,oe.jsx)(de,{id:"product-min-amount",type:"number",min:"0",step:f,value:E,onChange:Pe=>L(Pe.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsxs)(je,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",o.toUpperCase(),")"]}),(0,oe.jsx)(de,{id:"product-max-amount",type:"number",min:"0",step:f,value:C,onChange:Pe=>Y(Pe.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,oe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Buyers pick their own amount within these bounds (tip jar, pay-what-you-want). Quantity is always 1."})]}),(0,oe.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",o.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||k==="fixed")&&(0,oe.jsxs)("div",{className:"af-space-y-1",children:[(0,oe.jsx)(je,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,oe.jsx)(de,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:G,onChange:Pe=>z(Pe.target.value),className:"af-w-[140px]"})]})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(je,{children:"Images"}),(0,oe.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,oe.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[B.map(Pe=>(0,oe.jsxs)(ie,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,oe.jsx)("span",{className:"af-truncate",children:Pe}),(0,oe.jsx)("button",{type:"button",onClick:()=>qe(Pe),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:(0,oe.jsx)(Qa.X,{className:"af-h-3 af-w-3"})})]},Pe)),B.length===0&&(0,oe.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,oe.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,oe.jsx)(de,{type:"url",value:pe,onChange:Pe=>We(Pe.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:Pe=>{Pe.key==="Enter"&&(Pe.preventDefault(),me())},disabled:g}),(0,oe.jsx)(y,{type:"button",variant:"outline",onClick:me,disabled:!pe.trim()||g,children:(0,oe.jsx)(Qa.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(je,{children:"Digital File"}),(0,oe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, Word, Excel, PowerPoint, CSV, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),c?(0,oe.jsxs)("div",{className:"af-space-y-3",children:[Ie?.type==="download"&&(0,oe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,oe.jsx)(Qa.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,oe.jsx)("span",{className:"af-text-sm",children:Ie.filename}),Ie.size!=null&&(0,oe.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",nf(Ie.size),")"]})]}),Ie?.type==="redirect"&&Ie.url&&(0,oe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,oe.jsx)(Qa.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,oe.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Ie.url]})]}),(0,oe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,oe.jsx)("input",{ref:we,type:"file",onChange:nt,className:"af-hidden",disabled:ne}),(0,oe.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>we.current?.click(),disabled:ne,children:[Qe?(0,oe.jsx)(Qa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,oe.jsx)(Qa.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Ie?.type==="download"?"Replace file":"Upload file"]}),(0,oe.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,oe.jsx)(de,{type:"url",value:ot,onChange:Pe=>O(Pe.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Qe}),(0,oe.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:Ot,disabled:!ot.trim()||ne,children:"Fetch from URL"})]}),V&&(0,oe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:V})]}):(0,oe.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsx)(je,{children:"Settings"}),(0,oe.jsxs)("div",{className:"af-space-y-2",children:[(0,oe.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,oe.jsx)("input",{type:"checkbox",checked:ve,onChange:Pe=>xe(Pe.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,oe.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,oe.jsx)("input",{type:"checkbox",checked:D,onChange:Pe=>q(Pe.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),c&&t&&(0,oe.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,oe.jsx)(je,{children:"Options & Variants"}),(0,oe.jsx)(Ar,{productId:t.id,currency:o})]}),v&&(0,oe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),(0,oe.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,oe.jsxs)(y,{type:"button",onClick:rt,disabled:ne,children:[g?(0,oe.jsx)(Qa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,c?"Save changes":"Create product"]})})]})}var aa=le(require("react"),1),en=require("lucide-react");var Bt=le(require("react"),1);var sf=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Or({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=W(),[s,n]=Bt.useState([]),[r,i]=Bt.useState(0),[l,u]=Bt.useState(!0),[c,o]=Bt.useState(null),[f,b]=Bt.useState(0),[g,m]=Bt.useState(e),[v,d]=Bt.useState(void 0),[p,x]=Bt.useState(""),[R,T]=Bt.useState(""),[h,k]=Bt.useState(""),[P,I]=Bt.useState(!1),[w,E]=Bt.useState(!1),[L,C]=Bt.useState(void 0),Y=L?L.join(","):"",G=Bt.useMemo(()=>{if(!Y)return;let D=new Set(Y.split(","));return sf.filter(q=>!D.has(q))},[Y]),z=Bt.useMemo(()=>{let D={};return v?D.status=v:G?D.excludeStatus=G:P||(D.excludeStatus=["pending","expired"]),p.trim()&&(D.customerEmail=p.trim()),R.trim()&&(D.from=R.trim()),h.trim()&&(D.to=h.trim()),w&&(D.unfulfilledOnly=!0),D},[v,G,P,p,R,h,w]),ce=Bt.useRef(0),ve=Bt.useCallback(async()=>{let D=++ce.current;try{u(!0),o(null);let q={...z,limit:g,offset:f*g},B=await a.getOrders(q);if(D!==ce.current)return;n(B.orders),i(B.total)}catch(q){if(D!==ce.current)return;o(q instanceof Error?q:new Error("Failed to fetch orders"))}finally{D===ce.current&&u(!1)}},[a,f,g,z,t]);Bt.useEffect(()=>{ve()},[ve]);let xe=Math.ceil(r/g);return{orders:s,total:r,isLoading:l,error:c,page:f,pageSize:g,hasNextPage:f<xe-1,hasPreviousPage:f>0,setPage:b,setPageSize:D=>{m(D),b(0)},status:v,setStatus:D=>{d(D),b(0)},statusIn:L,setStatusIn:D=>{C(D&&D.length>0?D:void 0),b(0)},customerEmail:p,setCustomerEmail:D=>{x(D),b(0)},from:R,setFrom:D=>{T(D),b(0)},to:h,setTo:D=>{k(D),b(0)},showAbandoned:P,setShowAbandoned:D=>{I(D),b(0)},unfulfilledOnly:w,setUnfulfilledOnly:D=>{E(D),b(0)},clearFilters:()=>{d(void 0),C(void 0),I(!1),E(!1),x(""),T(""),k(""),b(0)},filters:z,refetch:ve}}var qt=le(require("react"),1),tt=require("lucide-react");var vc=le(require("react"),1),Bn=le(require("@radix-ui/react-popover"),1);var Ci=require("react/jsx-runtime"),Ti=Bn.Root,Ei=Bn.Trigger;var Lr=vc.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},n)=>(0,Ci.jsx)(Bn.Portal,{children:(0,Ci.jsx)("div",{className:"aifeatures-admin",children:(0,Ci.jsx)(Bn.Content,{ref:n,align:t,sideOffset:a,className:X("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...s})})}));Lr.displayName=Bn.Content.displayName;var Br=require("react/jsx-runtime"),rf={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function of(e){return rf[e]??e}function bc(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 Ps({status:e,className:t}){return(0,Br.jsx)(ie,{variant:bc(e),className:t,children:of(e)})}function ms({status:e}){return(0,Br.jsx)(Ps,{status:e})}function Xs({order:e,className:t}){return e.line_items.some(a=>a.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,Br.jsx)(ie,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Br.jsx)(ie,{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)}`}var S=require("react/jsx-runtime"),wc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Cs="af-text-xs af-text-muted-foreground";function Co(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 lf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sc(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 Ii=24,cf=["paid","partially_refunded"],df=["paid","partially_refunded","disputed"],uf=/^[A-Za-z0-9 _-]*$/,hc=100;function Io(e,t,a,s,n){let r=cf.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 ${Ii} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${Ii} 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<Ii&&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<Ii&&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 yc({title:e,recipient:t,status:a,attempts:s,side:n,orderStatus:r,action:i,delivery:l}){if(l)return(0,S.jsxs)("div",{children:[(0,S.jsx)(Dn,{deliveries:[l]}),i&&(0,S.jsx)("div",{className:"af-mt-2",children:i})]});let u=Io(n,a,s,r,t);return(0,S.jsxs)("div",{children:[(0,S.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,S.jsxs)("div",{className:"af-min-w-0",children:[(0,S.jsx)("div",{className:"af-text-sm",children:e}),t&&(0,S.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,S.jsx)(ie,{variant:u.variant,className:"af-shrink-0",children:u.label})]}),u.detail&&(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:u.detail}),i&&(0,S.jsx)("div",{className:"af-mt-2",children:i})]})}function xc(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=lf(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}: ${Sc(n)}`)}function ff(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Ao({value:e,label:t,children:a,className:s,size:n="icon"}){let[r,i]=qt.useState(!1);if(!ff())return null;let l=async()=>{try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},u=r?(0,S.jsx)(tt.Check,{className:"af-h-3 af-w-3"}):(0,S.jsx)(tt.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,S.jsx)(y,{variant:"ghost",size:"icon",className:X("af-h-6 af-w-6 af-shrink-0",s),onClick:l,title:t,"aria-label":t,children:u}):(0,S.jsxs)(y,{variant:"outline",size:"sm",className:s,onClick:l,"aria-label":t,children:[r?(0,S.jsx)(tt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,S.jsx)(tt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":a]})}function To({label:e,value:t}){return(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Cs,children:e}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,S.jsx)(Ao,{value:t,label:`Copy ${e}`})]})]})}function mf({src:e}){let[t,a]=qt.useState(!1);return!e||t?(0,S.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-10 af-w-10 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-muted",children:(0,S.jsx)(tt.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,S.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>a(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Fn({title:e,action:t,children:a,className:s}){return(0,S.jsxs)("section",{className:X("af-rounded-lg af-border af-p-4",s),children:[(0,S.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,S.jsx)("h4",{className:wc,children:e}),t]}),(0,S.jsx)("div",{className:"af-mt-3",children:a})]})}function Ea({label:e,emphasis:t,divider:a,children:s}){return(0,S.jsxs)("div",{className:X("af-flex af-items-baseline af-justify-between af-gap-6",a&&"af-mt-2 af-border-t af-pt-2"),children:[(0,S.jsx)("span",{className:t?"af-text-base af-font-semibold":Cs,children:e}),(0,S.jsx)("span",{className:X("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function Eo({onSelect:e,disabled:t,icon:a,children:s}){return(0,S.jsxs)(y,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,S.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function pf(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 ${re(ki(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?Si(a):Io("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?Si(a):Io("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 ${re(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 Fr({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:n=!1,onPrevOrder:r,onNextOrder:i,hasPrevOrder:l=!1,hasNextOrder:u=!1}){let{api:c}=W(),[o,f]=qt.useState(e),[b,g]=qt.useState(null),[m,v]=qt.useState(null),[d,p]=qt.useState(!1),[x,R]=qt.useState(!1),[T,h]=qt.useState(!1),[k,P]=qt.useState(!1),[I,w]=qt.useState(""),[E,L]=qt.useState(!1),[C,Y]=qt.useState(null),[G,z]=qt.useState(!1),[ce,ve]=qt.useState(""),[xe,D]=qt.useState([]),[q,B]=qt.useState(!1),[fe,pe]=qt.useState(!1),[We,Ie]=qt.useState(null);qt.useEffect(()=>{f(e)},[e]);let $e=U=>{let lt=U.id===o.id&&U.email_deliveries===void 0?{...U,email_deliveries:o.email_deliveries}:U;f(lt),s?.(lt)},Qe=Object.entries(o.metadata??{}),De=Math.max(0,ki(o)-o.amount_refunded),ot=(o.status==="paid"||o.status==="partially_refunded")&&De>0,O=o.exclusive_tax_total!=null,V=U=>typeof U.amountNet=="number"?U.amountNet+(U.exclusiveTax??0):(typeof U.unitAmount=="number"?U.unitAmount:0)*(typeof U.quantity=="number"&&U.quantity>0?U.quantity:1),$=Math.max(0,(o.shipping_total??0)-(o.shipping_refunded??0)),we=xe.reduce((U,lt)=>U+V(o.line_items[lt]??{}),0)+(q?$:0),ne=o.tax_total??0,me=Math.max(0,(o.exclusive_tax_total??0)-o.line_items.reduce((U,lt)=>U+(lt.exclusiveTax??0),0)),qe=O?q&&$>0?me:0:o.automatic_tax&&o.tax_behavior==="exclusive"&&ne>0&&o.amount_total+(o.shipping_total??0)>0?Math.min(Math.max(0,ne-(o.tax_refunded??0)),Math.round(ne*we/(o.amount_total+(o.shipping_total??0)))):0,rt=o.source==="subscription"&&(o.credit_applied??0)>0&&o.line_items.length===1?Math.min(we+qe,De):we+qe,nt=xe.length>0||q,Ot=nt?rt:oa(ce,o.currency),Pe=Xa(o.currency)?"1":"0.01",Ge=async()=>{try{p(!0),g(null),v(null),await c.resendOrderReceipt(o.id);let U=await c.getOrder(o.id);$e(U),v("Receipt email queued.")}catch(U){g(U instanceof Error?U.message:"Failed to resend receipt")}finally{p(!1)}},yt=async()=>{try{R(!0),g(null),v(null);let U=await c.resetOrderDownloads(o.id);$e(U),h(!1),v("Download count reset.")}catch(U){g(U instanceof Error?U.message:"Failed to reset downloads")}finally{R(!1)}},Lt=o.line_items.some(U=>U.collectShippingAddress===!0&&!U.refunded&&!U.unavailableReason),Vt=typeof o.merchant_fulfilled_at=="string",it=df.includes(o.status)||o.status==="refunded"&&o.line_items.some(U=>U.collectShippingAddress===!0&&U.amountNet===0&&!U.refunded&&!U.unavailableReason),Qt=I.trim(),et=uf.test(Qt)&&Qt.length<=hc,Rt=async U=>{try{L(!0),Y(null),v(null);let lt=await c.setOrderFulfillment(o.id,{fulfilled:U,...U&&Qt?{trackingNumber:Qt}:{}});$e(lt),w(""),v(U?"Marked as shipped.":"Marked as not shipped.")}catch(lt){lt instanceof Gt&&lt.status===409?Y(`This order is ${o.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Y(lt instanceof Error?lt.message:"Failed to update the order")}finally{L(!1)}},Va=()=>{Ie(null),ve(String(Et(De,o.currency))),D([]),B(!1),z(!0)},In=U=>D(lt=>lt.includes(U)?lt.filter(Pa=>Pa!==U):[...lt,U]),Te=async(U,lt)=>{if(a)try{pe(!0),Ie(null),await a(o,U,lt);let Pa=await c.getOrder(o.id);$e(Pa),z(!1),v("Refund issued.")}catch(Pa){Ie(Pa instanceof Error?Pa.message:"Refund failed")}finally{pe(!1)}},Tt=async()=>{if(nt){if(rt<=0){Ie("The lines you picked were charged nothing");return}if(rt>De){Ie(`That selection exceeds the refundable remainder (${re(De,o.currency)})`);return}await Te(rt,{...xe.length>0?{line_items:[...xe].sort((lt,Pa)=>lt-Pa)}:{},...q?{shipping:!0}:{}});return}let U=oa(ce,o.currency);if(U===null||U<=0){Ie("Enter a valid refund amount");return}if(U>De){Ie(`Amount exceeds the refundable remainder (${re(De,o.currency)})`);return}await Te(U,{amount:U})},H=()=>Te(De,{full:!0}),Oe=!o.subscription_history_only&&o.fulfillment_type==="download",zt=!o.subscription_history_only&&n&&Lt,xn=pf(o),se=o.shipping_address?xc(o.shipping_address).join(`
4
+ `):"",ia=o.shipping_total!=null,xo=o.exclusive_tax_total??(o.automatic_tax&&o.tax_behavior==="exclusive"?o.tax_total??0:0),Ll=o.exclusive_tax_total!=null?Math.max(0,(o.tax_total??0)-xo):o.automatic_tax&&o.tax_behavior==="exclusive"?0:o.tax_total??0,Bl=xo>0,ku=Ll>0,Fl=o.amount_subtotal!=null||ia||Bl||(o.discount_total??0)>0,mr=[];return o.subscription_history_only||mr.push((0,S.jsx)(Eo,{icon:d?(0,S.jsx)(tt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,S.jsx)(tt.Mail,{className:"af-h-4 af-w-4"}),disabled:d||o.fulfillment_status!=="fulfilled",onSelect:()=>{P(!1),Ge()},children:"Resend receipt"},"resend")),Oe&&mr.push((0,S.jsx)(Eo,{icon:(0,S.jsx)(tt.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{P(!1),h(!0)},children:"Reset download count"},"reset")),ot&&mr.push((0,S.jsxs)("div",{children:[(0,S.jsx)(Eo,{icon:(0,S.jsx)(tt.Undo2,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{P(!1),Va()},children:"Refund\u2026"}),!a&&(0,S.jsx)("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),(0,S.jsxs)("div",{children:[(0,S.jsxs)("div",{className:"af-mb-6",children:[(0,S.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,S.jsx)(tt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,S.jsxs)("div",{className:"af-min-w-0",children:[(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.jsx)("h3",{className:"af-text-xl af-font-semibold",children:Xn(o)}),(0,S.jsx)(Ps,{status:o.status}),n&&!o.subscription_history_only&&(0,S.jsx)(Xs,{order:o}),o.is_test&&(0,S.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,S.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Co(o.created_at)]}),o.is_test&&(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||i)&&(0,S.jsxs)("div",{className:"af-flex af-items-center",children:[(0,S.jsx)(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!l,"aria-label":"Previous order",children:(0,S.jsx)(tt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,S.jsx)(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:i,disabled:!u,"aria-label":"Next order",children:(0,S.jsx)(tt.ChevronRight,{className:"af-h-4 af-w-4"})})]}),zt&&(Vt?(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",o.merchant_fulfilled_at?` \xB7 ${Co(o.merchant_fulfilled_at)}`:""]}),it&&(0,S.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>Rt(!1),disabled:E,children:[E?(0,S.jsx)(tt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(tt.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):it?(0,S.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,S.jsx)(de,{value:I,onChange:U=>w(U.target.value),placeholder:"Tracking number (optional)",maxLength:hc,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:E}),(0,S.jsxs)(y,{variant:"default",className:"af-shrink-0",onClick:()=>Rt(!0),disabled:E||!et,children:[E?(0,S.jsx)(tt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(tt.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),mr.length>0&&(0,S.jsxs)(Ti,{open:k,onOpenChange:P,children:[(0,S.jsx)(Ei,{asChild:!0,children:(0,S.jsx)(y,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,S.jsx)(tt.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,S.jsx)(Lr,{children:(0,S.jsx)("div",{className:"af-space-y-0.5",children:mr})})]})]})]}),zt&&!Vt&&!et&&(0,S.jsx)("p",{className:"af-mt-2 af-text-xs af-text-destructive",children:"Tracking numbers can use letters, numbers, spaces, dashes and underscores \u2014 up to 100 characters."}),C&&(0,S.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:C}),m&&(0,S.jsx)("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:m}),b&&(0,S.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:b})]}),(0,S.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,S.jsxs)("div",{className:"af-space-y-6",children:[o.line_items.length>0&&(0,S.jsx)(Fn,{title:"Items",children:(0,S.jsx)("ul",{className:"af-space-y-3",children:o.line_items.map((U,lt)=>{let Pa=typeof U.name=="string"&&U.name?U.name:"Item",Ml=typeof U.quantity=="number"&&U.quantity>0?U.quantity:1,$l=typeof U.unitAmount=="number";return(0,S.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,S.jsx)(mf,{src:typeof U.imageUrl=="string"&&U.imageUrl?U.imageUrl:void 0}),(0,S.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,S.jsxs)("div",{className:"af-text-sm af-font-medium",children:[Pa,typeof U.variantTitle=="string"&&U.variantTitle&&(0,S.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",U.variantTitle]})]}),(0,S.jsxs)("div",{className:Cs,children:[Ml," \xD7"," ",$l?re(U.unitAmount,o.currency):"\u2014"]}),U.unavailableReason==="oversold"&&!U.refunded&&(0,S.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:U.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),U.refunded===!0&&(0,S.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:U.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,S.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof U.amountNet=="number"||$l?re(U.amountNet??U.unitAmount*Ml,o.currency):"\u2014"})]},lt)})})}),Qe.length>0&&(0,S.jsx)(Fn,{title:"Order details",children:(0,S.jsx)("dl",{className:"af-space-y-2",children:Qe.map(([U,lt])=>(0,S.jsxs)("div",{children:[(0,S.jsx)("dt",{className:X(Cs,"af-capitalize"),children:U.replace(/_/g," ")}),(0,S.jsx)("dd",{className:"af-text-sm af-break-words",children:Sc(lt)})]},U))})}),(0,S.jsx)(Fn,{title:"Totals",children:(0,S.jsxs)("div",{className:"af-w-full",children:[Fl&&(0,S.jsx)(Ea,{label:"Subtotal",children:re(o.amount_subtotal??o.amount_total+(o.discount_total??0),o.currency)}),(o.discount_total??0)>0&&(0,S.jsxs)(Ea,{label:"Discount",children:["\u2212",re(o.discount_total,o.currency)]}),ia&&(0,S.jsx)(Ea,{label:"Shipping",children:o.shipping_total===0?"Free":re(o.shipping_total??0,o.currency)}),Bl&&(0,S.jsx)(Ea,{label:"Tax",children:re(xo,o.currency)}),(0,S.jsx)(Ea,{label:"Total",emphasis:!0,divider:Fl,children:re(Ln(o),o.currency)}),(o.credit_applied??0)>0&&(0,S.jsxs)(Ea,{label:"Credit applied",children:["\u2212",re(o.credit_applied,o.currency)]}),o.amount_paid!=null&&(0,S.jsx)(Ea,{label:"Amount paid",children:re(o.amount_paid,o.currency)}),ku&&(0,S.jsx)(Ea,{label:"incl. tax",children:re(Ll,o.currency)}),o.base_currency!=null&&o.base_amount_total!=null&&(0,S.jsxs)(Ea,{label:"Your price",children:[re(o.base_amount_total,o.base_currency),(0,S.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",o.currency.toUpperCase()]})]}),o.amount_refunded>0&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(Ea,{label:"Refunded",children:["\u2212",re(o.amount_refunded,o.currency),(o.shipping_refunded??0)>0&&(0,S.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",re(o.shipping_refunded??0,o.currency)," ","shipping"]})]}),(0,S.jsx)(Ea,{label:"Net",children:(0,S.jsx)("span",{className:"af-font-medium",children:re(Math.max(0,ki(o)-o.amount_refunded),o.currency)})})]})]})}),o.application_fee_state&&(0,S.jsxs)(Fn,{title:"Platform fee",children:[o.application_fee_original!=null&&(0,S.jsx)(Ea,{label:"Collected",children:re(o.application_fee_original,o.application_fee_currency??o.currency)}),o.application_fee_returned!=null&&(0,S.jsx)(Ea,{label:"Returned",children:re(o.application_fee_returned,o.application_fee_currency??o.currency)}),o.application_fee_retained!=null&&(0,S.jsx)(Ea,{label:"Retained",children:re(o.application_fee_retained,o.application_fee_currency??o.currency)}),o.application_fee_state!=="complete"&&(0,S.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:o.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,S.jsx)(Fn,{title:"Timeline",children:(0,S.jsx)("ol",{className:"af-space-y-3",children:xn.map(U=>(0,S.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,S.jsx)("span",{"aria-hidden":"true",className:X("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",U.tone==="destructive"?"af-bg-destructive":U.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,S.jsxs)("div",{className:"af-min-w-0",children:[(0,S.jsx)("div",{className:"af-text-sm af-break-words",children:U.text}),U.at&&(0,S.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:Co(U.at)})]})]},U.key))})})]}),(0,S.jsxs)("div",{className:"af-space-y-6",children:[(0,S.jsx)(Fn,{title:"Customer",children:(0,S.jsxs)("div",{className:"af-space-y-2",children:[(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Cs,children:"Email"}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:o.customer_email||(0,S.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),o.customer_email&&(0,S.jsx)(Ao,{value:o.customer_email,label:"Copy email"})]})]}),o.customer_name&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Cs,children:"Name"}),(0,S.jsx)("div",{className:"af-text-sm",children:o.customer_name})]}),o.customer&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Cs,children:"Customer record"}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.jsx)("span",{className:"af-break-all af-text-sm",children:o.customer.name||o.customer.email}),(0,S.jsx)(ie,{variant:"secondary",children:"Linked"})]})]})]})}),o.shipping_address&&(0,S.jsx)(Fn,{title:"Ship to",action:(0,S.jsx)(Ao,{value:se,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,S.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:xc(o.shipping_address).map((U,lt)=>(0,S.jsx)("div",{children:U},lt))})}),o.subscription_history_only?(0,S.jsx)(Fn,{title:"Subscription history",children:(0,S.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This renewal had no payment due. No items were fulfilled and no purchase receipt was sent."})}):(0,S.jsxs)(Fn,{title:"Emails",children:[(0,S.jsx)(Dn,{deliveries:o.email_deliveries?.filter(U=>!["purchase_receipt","merchant_sale"].includes(U.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,S.jsxs)("div",{className:"af-space-y-4",children:[(0,S.jsx)(yc,{side:"buyer",title:"Receipt to buyer",delivery:o.email_deliveries?.find(U=>U.kind==="purchase_receipt"),recipient:o.customer_email,status:o.buyer_email_status,attempts:o.buyer_email_attempts,orderStatus:o.status,action:(0,S.jsxs)(y,{variant:"outline",size:"sm",onClick:Ge,disabled:d||o.fulfillment_status!=="fulfilled",children:[d?(0,S.jsx)(tt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(tt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,S.jsx)(yc,{side:"merchant",title:"Sale alert to you",delivery:o.email_deliveries?.find(U=>U.kind==="merchant_sale"),recipient:null,status:o.merchant_email_status,attempts:o.merchant_email_attempts,orderStatus:o.status})]})]}),Oe&&(0,S.jsx)(Fn,{title:"Download",children:(0,S.jsxs)("div",{className:"af-space-y-2",children:[(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,S.jsx)(tt.Download,{className:"af-h-4 af-w-4"}),(0,S.jsxs)("span",{children:["Downloaded ",o.download_count," time",o.download_count===1?"":"s"]})]}),o.download_url&&(0,S.jsx)("a",{href:o.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,S.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,S.jsx)("summary",{className:X(wc,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,S.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,S.jsx)(To,{label:"Order ID",value:o.id}),o.stripe_checkout_session_id&&(0,S.jsx)(To,{label:"Checkout session",value:o.stripe_checkout_session_id}),o.stripe_payment_intent_id&&(0,S.jsx)(To,{label:"Payment",value:o.stripe_payment_intent_id})]})]})]})]}),(0,S.jsx)(cn,{open:T,onOpenChange:U=>{!U&&!x&&h(!1)},children:(0,S.jsxs)(qa,{children:[(0,S.jsxs)(Wa,{children:[(0,S.jsx)(Ka,{children:"Reset download count?"}),(0,S.jsx)(Za,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,S.jsxs)(Ga,{children:[(0,S.jsx)(y,{variant:"outline",onClick:()=>h(!1),disabled:x,children:"Cancel"}),(0,S.jsx)(y,{onClick:yt,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),(0,S.jsx)(cn,{open:G,onOpenChange:U=>{!U&&!fe&&z(!1)},children:(0,S.jsxs)(qa,{children:[(0,S.jsxs)(Wa,{children:[(0,S.jsx)(Ka,{children:"Refund order"}),(0,S.jsxs)(Za,{children:["Refund up to ",re(De,o.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,S.jsxs)("div",{className:"af-space-y-4",children:[(o.line_items.length>0||$>0)&&(0,S.jsxs)("div",{className:"af-space-y-2",children:[(0,S.jsx)(je,{children:"Items"}),(0,S.jsxs)("div",{className:"af-space-y-2",children:[o.line_items.map((U,lt)=>{let Pa=U.refunded===!0;return(0,S.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,S.jsx)("input",{type:"checkbox",checked:xe.includes(lt),onChange:()=>In(lt),disabled:fe||Pa||!!U.unavailableReason||V(U)<=0,className:"af-h-4 af-w-4"}),(0,S.jsxs)("span",{className:Pa?"af-text-muted-foreground af-line-through":void 0,children:[typeof U.name=="string"&&U.name?U.name:"Item",typeof U.variantTitle=="string"&&U.variantTitle?` \u2014 ${U.variantTitle}`:"",typeof U.quantity=="number"&&U.quantity>1?` \xD7 ${U.quantity}`:""]}),(0,S.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Pa?"Refunded":re(V(U),o.currency)})]},lt)}),$>0&&(0,S.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,S.jsx)("input",{type:"checkbox",checked:q,onChange:U=>B(U.target.checked),disabled:fe,className:"af-h-4 af-w-4"}),(0,S.jsx)("span",{children:"Shipping"}),(0,S.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:re($,o.currency)})]})]})]}),(0,S.jsxs)("div",{className:"af-space-y-2",children:[(0,S.jsxs)(je,{htmlFor:"refund-amount",children:["Amount (",o.currency.toUpperCase(),")"]}),(0,S.jsx)(de,{id:"refund-amount",type:"number",min:"0",step:Pe,value:nt?String(Et(rt,o.currency)):ce,onChange:U=>ve(U.target.value),disabled:fe||nt}),nt&&(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),We&&(0,S.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:We}),(0,S.jsxs)(Ga,{children:[(0,S.jsx)(y,{variant:"outline",onClick:()=>z(!1),disabled:fe,children:"Cancel"}),(0,S.jsx)(y,{variant:"outline",onClick:H,disabled:fe,children:"Refund everything"}),(0,S.jsx)(y,{variant:"destructive",onClick:Tt,disabled:fe,children:fe?"Refunding...":Ot!==null&&Ot>0?`Refund ${re(Ot,o.currency)}`:"Refund"})]})]})})]})}var Ai=le(require("react"),1),Di=require("lucide-react");var At=require("react/jsx-runtime");function Ft({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:n}){let r=Ai.useRef(null);return Ai.useEffect(()=>{r.current?.focus()},[]),(0,At.jsxs)("div",{className:X("af-bg-background",n),children:[(0,At.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,At.jsx)("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!a&&(0,At.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,At.jsx)(Di.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,At.jsx)("div",{className:"af-p-4",children:s})]})}function Q({className:e}){return(0,At.jsx)("div",{"aria-hidden":"true",className:X("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function gt({label:e,children:t,detail:a,valueClassName:s}){return(0,At.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,At.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,At.jsx)("div",{className:X("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&(0,At.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function wt({message:e,onRetry:t}){return(0,At.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,At.jsx)("span",{children:e}),(0,At.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,At.jsx)(Di.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function la({icon:e,children:t}){return(0,At.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,At.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function Qs({icon:e,heading:t,body:a,action:s,className:n,children:r}){return(0,At.jsxs)("div",{className:X("af-px-6 af-py-10 af-text-center",n),children:[(0,At.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,At.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,At.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&(0,At.jsx)(y,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}var F=require("react/jsx-runtime"),gf={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Nc={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Rc(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 _c(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 Oi(e){return e.customer?.name||e.customer_name||null}function vf({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:n=!1,emptyMessage:r,onDetailOpenChange:i,maxRows:l,onViewAll:u}){let c=typeof l=="number",{api:o}=W(),f=Or({refreshKey:a}),{orders:b,total:g,isLoading:m,error:v,page:d,pageSize:p,hasNextPage:x,hasPreviousPage:R,setPage:T,setPageSize:h,customerEmail:k,setCustomerEmail:P,setStatusIn:I,from:w,setFrom:E,to:L,setTo:C,showAbandoned:Y,setShowAbandoned:G,setUnfulfilledOnly:z,filters:ce,refetch:ve}=f,xe=aa.useCallback(()=>o.exportOrdersCsv(ce),[o,ce]),[D,q]=aa.useState("list"),[B,fe]=aa.useState(null),[pe,We]=aa.useState(""),[Ie,$e]=aa.useState(""),[Qe,De]=aa.useState(!c&&n?"needs_shipping":"all"),[ot,O]=aa.useState(!1),[V,$]=aa.useState(!!s&&!c),[we,ne]=aa.useState(null);aa.useEffect(()=>{if(!s||c)return;let se=!1;return $(!0),ne(null),o.getOrder(s).then(ia=>{se||(fe(ia),q("detail"))}).catch(()=>{se||ne("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{se||$(!1)}),()=>{se=!0}},[o,s,c]);let me=aa.useCallback(se=>{De(se);let ia=Nc[se];I(ia.statusIn),z(ia.unfulfilledOnly)},[I,z]);aa.useEffect(()=>{n&&!c&&z(!0)},[]);let qe=aa.useRef(!n);aa.useEffect(()=>{qe.current||m||(qe.current=!0,b.length===0&&me("all"))},[m,b.length,me]);let rt=D==="detail"&&!!B;aa.useEffect(()=>{i?.(rt)},[rt,i]);let nt=(w?1:0)+(L?1:0)+(Y?1:0),Ot=nt>0||!!k||!!Ie,Pe=!!w&&!!L&&w>L,Ge=!c||!!u,yt=se=>{if(c){u?.();return}fe(se),q("detail")},Lt=()=>{q("list"),fe(null),ve()},Vt=se=>{let ia=se.trim();if(!ia){$e(""),k&&P("");return}if(ia.startsWith("#")||/^\d+$/.test(ia)){$e(ia),k&&P("");return}$e(""),P(ia)},it=()=>{We(""),$e(""),P(""),E(""),C(""),G(!1),O(!1)},Qt=Ie.replace(/^#/,"").toLowerCase(),et=Qt?b.filter(se=>String(se.order_number??"")===Qt||se.id.toLowerCase().startsWith(Qt)):b,Rt=c?et.slice(0,l):et,Va=B?b.findIndex(se=>se.id===B.id):-1,In=Va>0,Te=Va>=0&&Va<b.length-1;if(V)return(0,F.jsx)("div",{className:t,children:(0,F.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,F.jsx)(en.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(D==="detail"&&B)return(0,F.jsx)("div",{className:t,children:(0,F.jsx)(Fr,{order:B,onBack:Lt,onRefund:e,onOrderUpdated:se=>fe(se),allowFulfillment:n,onPrevOrder:In?()=>fe(b[Va-1]):void 0,onNextOrder:Te?()=>fe(b[Va+1]):void 0,hasPrevOrder:In,hasNextOrder:Te},B.id)});let H=(0,F.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[we&&(0,F.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:we}),(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,F.jsx)("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(se=>(0,F.jsx)("button",{type:"button","aria-pressed":Qe===se,onClick:()=>me(se),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Qe===se?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:gf[se]},se))}),(0,F.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,F.jsx)(en.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,F.jsx)(de,{type:"text",value:pe,onChange:se=>We(se.target.value),onBlur:()=>Vt(pe),onKeyDown:se=>{se.key==="Enter"&&(se.preventDefault(),Vt(pe))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,F.jsxs)(y,{type:"button",variant:nt>0?"secondary":"ghost",size:"sm",onClick:()=>O(se=>!se),"aria-expanded":ot,children:[(0,F.jsx)(en.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",nt>0&&(0,F.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:nt})]}),Ot&&(0,F.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:it,children:"Clear filters"}),(0,F.jsx)(ma,{fetchCsv:xe,filename:"orders",disabled:!!Ie,className:"af-ml-auto"})]}),(ot||!!w||!!L)&&(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2",children:[(0,F.jsx)(je,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,F.jsx)(de,{id:"orders-from",type:"date",value:w,max:L||void 0,onChange:se=>E(se.target.value),className:"af-w-[170px]"}),(0,F.jsx)(je,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,F.jsx)(de,{id:"orders-to",type:"date",value:L,min:w||void 0,onChange:se=>C(se.target.value),className:"af-w-[170px]"}),!Nc[Qe].statusIn&&(0,F.jsx)(y,{type:"button",variant:Y?"secondary":"ghost",size:"sm",onClick:()=>G(!Y),"aria-pressed":Y,children:Y?"Hide abandoned":"Show abandoned"})]}),Pe&&(0,F.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(m)return(0,F.jsxs)("div",{className:t,children:[c?null:H,(0,F.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(se=>(0,F.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,F.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,F.jsx)(Q,{className:"af-h-4 af-w-16"}),(0,F.jsx)(Q,{className:"af-h-4 af-w-14"})]}),(0,F.jsx)(Q,{className:"af-mt-2 af-h-3 af-w-40"}),(0,F.jsx)(Q,{className:"af-mt-2 af-h-3 af-w-24"})]},se))}),(0,F.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,F.jsxs)(ft,{children:[(0,F.jsx)(mt,{children:(0,F.jsxs)(Ue,{children:[(0,F.jsx)(te,{children:"Order"}),(0,F.jsx)(te,{children:"Date"}),(0,F.jsx)(te,{children:"Customer"}),(0,F.jsx)(te,{children:"Items"}),(0,F.jsx)(te,{className:"af-text-right",children:"Total"}),(0,F.jsx)(te,{children:"Status"}),(0,F.jsx)(te,{className:"af-w-8"})]})}),(0,F.jsx)(pt,{"aria-hidden":"true",children:[0,1,2,3,4].map(se=>(0,F.jsxs)(Ue,{children:[(0,F.jsx)(ae,{children:(0,F.jsx)(Q,{className:"af-h-4 af-w-14"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(Q,{className:"af-h-4 af-w-24"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(Q,{className:"af-h-4 af-w-40"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(Q,{className:"af-h-4 af-w-32"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(Q,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,F.jsx)(ae,{children:(0,F.jsx)(Q,{className:"af-h-5 af-w-16"})}),(0,F.jsx)(ae,{})]},se))})]})}),(0,F.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(v)return(0,F.jsxs)("div",{className:t,children:[c?null:H,(0,F.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,F.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,F.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>ve(),children:"Try again"})]})]});let Oe=Qe!=="all";if(et.length===0&&d===0)return Ot||Oe?(0,F.jsxs)("div",{className:t,children:[!c&&H,(0,F.jsx)(la,{children:"No orders match these filters."})]}):(0,F.jsx)("div",{className:t,children:(0,F.jsx)(Qs,{icon:en.Receipt,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!c&&(0,F.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>G(!0),children:"Show abandoned checkouts"})})});let zt=d*p+1,xn=Math.min((d+1)*p,g);return(0,F.jsxs)("div",{className:t,children:[c?null:H,(0,F.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Rt.map(se=>(0,F.jsxs)("button",{type:"button",onClick:()=>yt(se),disabled:!Ge,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ge?" hover:af-bg-muted/50":""}`,children:[(0,F.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,F.jsx)("span",{className:"af-font-medium",children:Xn(se)}),(0,F.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:re(Ln(se),se.currency)})]}),(0,F.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,F.jsxs)("div",{className:"af-truncate af-text-sm",children:[se.customer_email||(0,F.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Oi(se)&&(0,F.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Oi(se)]})]}),(0,F.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:_c(se)}),se.amount_refunded>0&&(0,F.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",re(se.amount_refunded,se.currency)," refunded"]})]}),(0,F.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,F.jsx)(Ps,{status:se.status}),(0,F.jsx)(yr,{deliveries:se.email_deliveries}),se.is_test&&(0,F.jsx)(ie,{variant:"outline",children:"Test"}),n&&(0,F.jsx)(Xs,{order:se}),(0,F.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Rc(se.created_at)})]})]},se.id))}),(0,F.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,F.jsxs)(ft,{children:[(0,F.jsx)(mt,{children:(0,F.jsxs)(Ue,{children:[(0,F.jsx)(te,{children:"Order"}),(0,F.jsx)(te,{children:"Date"}),(0,F.jsx)(te,{children:"Customer"}),(0,F.jsx)(te,{children:"Items"}),(0,F.jsx)(te,{className:"af-text-right",children:"Total"}),(0,F.jsx)(te,{children:"Status"}),(0,F.jsx)(te,{className:"af-w-8"})]})}),(0,F.jsx)(pt,{children:Rt.map(se=>(0,F.jsxs)(Ue,{onClick:Ge?()=>yt(se):void 0,className:Ge?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,F.jsxs)(ae,{className:"af-whitespace-nowrap af-font-medium",children:[(0,F.jsx)("button",{type:"button",onClick:ia=>{ia.stopPropagation(),yt(se)},disabled:!Ge,"aria-label":`Open order ${Xn(se)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ge?" hover:af-underline":""}`,children:Xn(se)}),se.is_test&&(0,F.jsx)(ie,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,F.jsx)(ae,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Rc(se.created_at)}),(0,F.jsxs)(ae,{className:"af-max-w-[220px]",children:[(0,F.jsx)("div",{className:"af-truncate",children:se.customer_email||(0,F.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Oi(se)&&(0,F.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Oi(se)})]}),(0,F.jsx)(ae,{className:"af-max-w-[220px]",children:(0,F.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:_c(se)})}),(0,F.jsxs)(ae,{className:"af-whitespace-nowrap af-text-right",children:[(0,F.jsx)("div",{className:"af-font-medium af-tabular-nums",children:re(Ln(se),se.currency)}),se.amount_refunded>0&&(0,F.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",re(se.amount_refunded,se.currency)," ","refunded"]})]}),(0,F.jsx)(ae,{children:(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,F.jsx)(Ps,{status:se.status}),(0,F.jsx)(yr,{deliveries:se.email_deliveries}),n&&(0,F.jsx)(Xs,{order:se})]})}),(0,F.jsx)(ae,{className:"af-w-8 af-text-right",children:(0,F.jsx)(en.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},se.id))})]})}),c?null:(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,F.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,F.jsx)("span",{children:Qt?`${et.length} matching this page`:`Showing ${zt}-${xn} of ${g}`}),(0,F.jsxs)(on,{value:String(p),onValueChange:se=>h(Number(se)),children:[(0,F.jsx)(za,{className:"af-w-[70px] af-h-8",children:(0,F.jsx)(ln,{})}),(0,F.jsxs)(ja,{children:[(0,F.jsx)(kt,{value:"10",children:"10"}),(0,F.jsx)(kt,{value:"25",children:"25"}),(0,F.jsx)(kt,{value:"50",children:"50"}),(0,F.jsx)(kt,{value:"100",children:"100"})]})]}),(0,F.jsx)("span",{children:"per page"})]}),(0,F.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,F.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>T(d-1),disabled:!R,children:[(0,F.jsx)(en.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,F.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>T(d+1),disabled:!x,children:["Next",(0,F.jsx)(en.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function Qn(e){return(0,F.jsx)(vf,{...e},e.maxRows==null?"full":"compact")}var er=le(require("react"),1),Mn=require("lucide-react");var Ia=le(require("react"),1);function Mr({initialPageSize:e=25}={}){let{api:t}=W(),[a,s]=Ia.useState([]),[n,r]=Ia.useState(0),[i,l]=Ia.useState(!0),[u,c]=Ia.useState(null),[o,f]=Ia.useState(0),[b,g]=Ia.useState(e),[m,v]=Ia.useState(""),d=Ia.useRef(0),p=Ia.useCallback(async()=>{let R=++d.current;try{l(!0),c(null);let T={limit:b,offset:o*b};m.trim()&&(T.email=m.trim());let h=await t.getCustomers(T);if(R!==d.current)return;s(h.customers),r(h.total)}catch(T){if(R!==d.current)return;c(T instanceof Error?T:new Error("Failed to fetch customers"))}finally{R===d.current&&l(!1)}},[t,o,b,m]);Ia.useEffect(()=>{p()},[p]);let x=Math.ceil(n/b);return{customers:a,total:n,isLoading:i,error:u,page:o,pageSize:b,hasNextPage:o<x-1,hasPreviousPage:o>0,setPage:f,setPageSize:R=>{g(R),f(0)},email:m,setEmail:R=>{v(R),f(0)},refetch:p}}var Ts=le(require("react"),1),Li=require("lucide-react");var Ae=require("react/jsx-runtime");function kc(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 bf(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 $r({customer:e,onBack:t,className:a}){let{api:s}=W(),[n,r]=Ts.useState(null),[i,l]=Ts.useState([]),[u,c]=Ts.useState(!0),[o,f]=Ts.useState(null);Ts.useEffect(()=>{let m=!1;return c(!0),f(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([v,d])=>{m||(r(v),l(d.orders))}).catch(v=>{m||f(v instanceof Error?v.message:"Failed to load customer")}).finally(()=>{m||c(!1)}),()=>{m=!0}},[s,e.id,e.email]);let b=n?.addresses??[],g=n?.order_count??i.length;return(0,Ae.jsxs)("div",{className:a,children:[(0,Ae.jsxs)("div",{className:"af-mb-6",children:[(0,Ae.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,Ae.jsx)(Li.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,Ae.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,Ae.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",kc(e.created_at)]})]}),u?(0,Ae.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,Ae.jsx)(Li.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):o?(0,Ae.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o}):(0,Ae.jsxs)("div",{className:"af-space-y-6",children:[(0,Ae.jsx)(Dn,{deliveries:n?.email_deliveries}),(0,Ae.jsxs)("div",{children:[(0,Ae.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,Ae.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,Ae.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,Ae.jsx)("span",{children:e.email})]}),e.name&&(0,Ae.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,Ae.jsx)("span",{children:e.name})]}),e.phone&&(0,Ae.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,Ae.jsx)("span",{children:e.phone})]}),(0,Ae.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,Ae.jsx)("span",{children:g})]})]})]}),b.length>0&&(0,Ae.jsxs)("div",{children:[(0,Ae.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,Ae.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(m=>(0,Ae.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[m.is_default&&(0,Ae.jsx)(ie,{variant:"secondary",className:"af-mb-1",children:"Default"}),bf(m).map((v,d)=>(0,Ae.jsx)("div",{children:v},d))]},m.id))})]}),(0,Ae.jsxs)("div",{children:[(0,Ae.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),i.length===0?(0,Ae.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,Ae.jsxs)(ft,{children:[(0,Ae.jsx)(mt,{children:(0,Ae.jsxs)(Ue,{children:[(0,Ae.jsx)(te,{children:"Date"}),(0,Ae.jsx)(te,{children:"Amount"}),(0,Ae.jsx)(te,{children:"Status"})]})}),(0,Ae.jsx)(pt,{children:i.map(m=>(0,Ae.jsxs)(Ue,{children:[(0,Ae.jsx)(ae,{className:"af-text-muted-foreground",children:kc(m.created_at)}),(0,Ae.jsx)(ae,{children:re(Ln(m),m.currency)}),(0,Ae.jsx)(ae,{children:(0,Ae.jsx)(ms,{status:m.status})})]},m.id))})]})]})]})]})}var ke=require("react/jsx-runtime");function hf(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 Ur({className:e}){let{customers:t,total:a,isLoading:s,error:n,page:r,pageSize:i,hasNextPage:l,hasPreviousPage:u,setPage:c,setPageSize:o,email:f,setEmail:b,refetch:g}=Mr(),{api:m}=W(),v=er.useCallback(()=>m.exportCustomersCsv(),[m]),[d,p]=er.useState("list"),[x,R]=er.useState(null),[T,h]=er.useState(""),k=L=>{R(L),p("detail")},P=()=>{p("list"),R(null),g()};if(d==="detail"&&x)return(0,ke.jsx)("div",{className:e,children:(0,ke.jsx)($r,{customer:x,onBack:P})});let I=(0,ke.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,ke.jsx)(de,{type:"email",value:T,onChange:L=>h(L.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),b(T.trim()))}}),(0,ke.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>b(T.trim()),children:[(0,ke.jsx)(Mn.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),f&&(0,ke.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),b("")},children:"Clear"}),(0,ke.jsx)(ma,{fetchCsv:v,filename:"customers",className:"af-ml-auto"})]});if(s)return(0,ke.jsxs)("div",{className:e,children:[I,(0,ke.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ke.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,ke.jsxs)("div",{className:e,children:[I,(0,ke.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ke.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&r===0)return(0,ke.jsxs)("div",{className:e,children:[f&&I,(0,ke.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,ke.jsx)(Mn.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ke.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:f?"No customers match that email.":(0,ke.jsxs)(ke.Fragment,{children:["No customers yet.",(0,ke.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let w=r*i+1,E=Math.min((r+1)*i,a);return(0,ke.jsxs)("div",{className:e,children:[I,(0,ke.jsxs)(ft,{children:[(0,ke.jsx)(mt,{children:(0,ke.jsxs)(Ue,{children:[(0,ke.jsx)(te,{children:"Email"}),(0,ke.jsx)(te,{children:"Name"}),(0,ke.jsx)(te,{children:"Phone"}),(0,ke.jsx)(te,{children:"Customer since"}),(0,ke.jsx)(te,{className:"af-text-right",children:"Actions"})]})}),(0,ke.jsx)(pt,{children:t.map(L=>(0,ke.jsxs)(Ue,{children:[(0,ke.jsx)(ae,{className:"af-font-medium",children:L.email}),(0,ke.jsx)(ae,{children:L.name||(0,ke.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ke.jsx)(ae,{children:L.phone||(0,ke.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ke.jsx)(ae,{className:"af-text-muted-foreground",children:hf(L.created_at)}),(0,ke.jsx)(ae,{className:"af-text-right",children:(0,ke.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>k(L),title:"View customer",children:(0,ke.jsx)(Mn.Eye,{className:"af-h-4 af-w-4"})})})]},L.id))})]}),(0,ke.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ke.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ke.jsxs)("span",{children:["Showing ",w,"-",E," of ",a]}),(0,ke.jsxs)(on,{value:String(i),onValueChange:L=>o(Number(L)),children:[(0,ke.jsx)(za,{className:"af-w-[70px] af-h-8",children:(0,ke.jsx)(ln,{})}),(0,ke.jsxs)(ja,{children:[(0,ke.jsx)(kt,{value:"10",children:"10"}),(0,ke.jsx)(kt,{value:"25",children:"25"}),(0,ke.jsx)(kt,{value:"50",children:"50"}),(0,ke.jsx)(kt,{value:"100",children:"100"})]})]}),(0,ke.jsx)("span",{children:"per page"})]}),(0,ke.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ke.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>c(r-1),disabled:!u,children:[(0,ke.jsx)(Mn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ke.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>c(r+1),disabled:!l,children:["Next",(0,ke.jsx)(Mn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ze=le(require("react"),1),Yt=require("lucide-react");var Zt=le(require("react"),1);function Es({initialPageSize:e=25,refreshKey:t,includeAggregates:a=!1}={}){let{api:s}=W(),[n,r]=Zt.useState([]),[i,l]=Zt.useState(0),[u,c]=Zt.useState(null),[o,f]=Zt.useState(!0),[b,g]=Zt.useState(null),[m,v]=Zt.useState(0),[d,p]=Zt.useState(e),[x,R]=Zt.useState(void 0),[T,h]=Zt.useState(""),[k,P]=Zt.useState(""),[I,w]=Zt.useState(""),[E,L]=Zt.useState(""),[C,Y]=Zt.useState(""),G=x?x.join(","):"",z=Zt.useRef(0),ce=Zt.useCallback(async()=>{let xe=++z.current;f(!0),g(null);try{let D={labels:G?G.split(","):void 0,customerEmail:T||void 0,q:k||void 0,from:I||void 0,to:E||void 0,retainerId:C||void 0,includeAggregates:a,limit:d,offset:m*d},q=await s.getInvoices(D);if(xe!==z.current)return;if(m>0&&m*d>=q.total){v(Math.max(0,Math.ceil(q.total/d)-1));return}r(q.invoices),l(q.total),a&&c(q.aggregates??null)}catch(D){if(xe!==z.current)return;g(D instanceof Error?D:new Error("Failed to fetch invoices"))}finally{xe===z.current&&f(!1)}},[s,G,T,k,I,E,C,m,d,a]);Zt.useEffect(()=>{ce()},[ce,t]);let ve=xe=>D=>{v(0),xe(D)};return{invoices:n,total:i,aggregates:u,isLoading:o,error:b,page:m,pageSize:d,hasNextPage:(m+1)*d<i,hasPreviousPage:m>0,setPage:v,setPageSize:ve(p),labels:x,setLabels:ve(R),customerEmail:T,setCustomerEmail:ve(h),q:k,setQ:ve(P),from:I,setFrom:ve(w),to:E,setTo:ve(L),retainerId:C,setRetainerId:ve(Y),clearFilters:()=>{v(0),R(void 0),h(""),P(""),w(""),L(""),Y("")},refetch:ce}}var N=require("react/jsx-runtime"),yf={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 Bo(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:yf[e.label]??e.label}function xf(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 Lo={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},wf={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function ar({invoice:e,className:t}){return(0,N.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,N.jsx)(ie,{variant:xf(e.label),className:t,children:Bo(e)}),e.collection_method==="charge_automatically"&&(0,N.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"})]})}function Mi({delivery:e,className:t}){if(!e)return null;let a=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,N.jsx)(ie,{variant:a,className:t,children:Lo[e.state]??e.state})}function tr(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function pn(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 Pc={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Bi={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},Do=100,Oo=5e3;async function Sf(e,t){let a=[],s=0;for(let n=0;n<Oo;n+=Do){let r=await e.getInvoices({...t,limit:Do,offset:n});if(s=r.total,a.push(...r.invoices),r.invoices.length<Do||a.length>=s)break}return{invoices:a.slice(0,Oo),total:s,truncated:s>a.length||s>Oo}}function Tc(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,tr(s),Bo(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),re(s.amount_subtotal,s.currency),re(s.tax_total,s.currency),re(s.amount_total,s.currency),s.amount_due===null?"":re(s.amount_due,s.currency),s.amount_paid===null?"":re(s.amount_paid,s.currency),re(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?"":re(s.discount_total,s.currency),s.collection_method??""]);return[t,...a].map(s=>s.map(lc).join(",")).join(`
5
+ `)}function Nf(e){_i(new Blob([Tc(e)],{type:"text/csv;charset=utf-8"}),Ri("invoices"))}function Rf({className:e,refreshKey:t,initialInvoiceId:a,onDetailOpenChange:s,onConnectStripe:n,onUpgradePlan:r,needsPaidPlan:i=!1,retainerFilter:l=null,onClearRetainerFilter:u,maxRows:c,onViewAll:o}){let f=typeof c=="number",{api:b}=W(),{invoices:g,total:m,isLoading:v,error:d,page:p,pageSize:x,hasNextPage:R,hasPreviousPage:T,setPage:h,labels:k,setLabels:P,customerEmail:I,setCustomerEmail:w,q:E,setQ:L,from:C,setFrom:Y,to:G,setTo:z,retainerId:ce,setRetainerId:ve,refetch:xe}=Es({refreshKey:t}),[D,q]=Ze.useState(typeof c=="number"?"all":"open"),[B,fe]=Ze.useState(""),[pe,We]=Ze.useState(null),Ie=Ze.useRef(0),$e=!f||!!o,Qe=Ze.useCallback(H=>{if(f){o?.();return}Ie.current++,ot(!1),We(H)},[f,o]),[De,ot]=Ze.useState(!1),[O,V]=Ze.useState(0),[$,we]=Ze.useState(null),[ne,me]=Ze.useState(!1),[qe,rt]=Ze.useState(0);Ze.useEffect(()=>{We(H=>{if(!H)return H;let Oe=g.find(zt=>zt.id===H.id);return Oe&&Oe!==H?Oe:H})},[g]);let[nt,Ot]=Ze.useState(!1),[Pe,Ge]=Ze.useState(null),yt=async()=>{if(!nt){Ot(!0),Ge(null);try{let{invoices:H,total:Oe,truncated:zt}=await Sf(b,{labels:k,customerEmail:I,q:E,from:C,to:G,retainerId:ce});Nf(H),Ge(zt?`Exported the first ${H.length.toLocaleString()} of ${Oe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ge("Couldn't export \u2014 try again.")}finally{Ot(!1)}}},Lt=!I&&!E&&!C&&!G&&!ce,[Vt,it]=Ze.useState(null);Ze.useEffect(()=>{if(v||m>0||!Lt||D!=="open")return;let H=!1;return b.getInvoices({limit:1}).then(Oe=>{H||it(Oe.total>0)}).catch(()=>{H||it(!0)}),()=>{H=!0}},[b,v,m,Lt,D,t]),Ze.useEffect(()=>{P(f?Bi.all:Bi.open)},[]),Ze.useEffect(()=>{let H=l?.id??"";H!==ce&&(ve(H),H&&(q("all"),P(Bi.all),w(""),L(""),fe(""),Y(""),z("")))},[l?.id]),Ze.useEffect(()=>{let H=!1;return me(!1),b.getInvoiceSettings().then(Oe=>{H||we({payments_active:Oe.payments_active,blocked:Oe.blocked})}).catch(()=>{H||me(!0)}),()=>{H=!0}},[b,t,qe]),Ze.useEffect(()=>{if(!a||f)return;let H=!1,Oe=Ie.current;return ot(!1),b.getInvoice(a).then(zt=>{!H&&Oe===Ie.current&&We(zt)}).catch(()=>{!H&&Oe===Ie.current&&ot(!0)}),()=>{H=!0}},[b,a,O,f]),Ze.useEffect(()=>{s?.(pe!==null)},[pe,s]);let Qt=H=>{q(H),P(Bi[H])},et=H=>{let Oe=H.trim();if(!Oe){E&&L(""),I&&w("");return}if(Oe.includes("@")){E&&L(""),w(Oe);return}I&&w(""),L(Oe.replace(/^#/,""))},Rt=g,Va=f?Rt.slice(0,c):Rt,In=De&&(0,N.jsxs)("div",{role:"alert",className:"af-mb-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't open the requested invoice. ",(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>V(H=>H+1),children:"Retry opening invoice"})]});if(pe)return(0,N.jsxs)("div",{className:e,children:[In,(0,N.jsx)($i,{invoice:pe,refreshKey:t,onBack:()=>{Qe(null),xe()}},pe.id)]});let Te=(0,N.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[ne&&(0,N.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>rt(H=>H+1),children:"Retry setup check"})]}),In,$?.blocked&&(0,N.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",$.blocked.reason?`: ${$.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),l&&(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,N.jsxs)(ie,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",l.label]}),u&&(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:u,children:"Clear schedule filter"})]}),(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,N.jsx)("div",{role:"group","aria-label":"Invoice views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Object.keys(Pc).map(H=>(0,N.jsx)("button",{type:"button","aria-pressed":D===H,onClick:()=>Qt(H),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",D===H?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Pc[H]},H))}),(0,N.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,N.jsx)(Yt.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,N.jsx)(de,{type:"text",value:B,onChange:H=>fe(H.target.value),onBlur:()=>et(B),onKeyDown:H=>{H.key==="Enter"&&(H.preventDefault(),et(B))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,N.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,N.jsx)(je,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,N.jsx)(de,{id:"invoices-from",type:"date",value:C,max:G||void 0,onChange:H=>Y(H.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,N.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,N.jsx)(je,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,N.jsx)(de,{id:"invoices-to",type:"date",value:G,min:C||void 0,onChange:H=>z(H.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,N.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void yt(),disabled:nt||v||!!d||m===0,"aria-busy":nt,children:[(0,N.jsx)(Yt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),nt?"Exporting\u2026":"Export CSV (all matching)"]})]}),Pe&&(0,N.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:Pe})]});return v?(0,N.jsxs)("div",{className:e,children:[f?null:Te,(0,N.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(H=>(0,N.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,N.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,N.jsx)(Q,{className:"af-h-4 af-w-20"}),(0,N.jsx)(Q,{className:"af-h-4 af-w-16"})]}),(0,N.jsx)(Q,{className:"af-mt-2 af-h-3 af-w-40"})]},H))})]}):d?(0,N.jsxs)("div",{className:e,children:[f?null:Te,(0,N.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>void xe(),children:"Retry"})]})]}):m===0&&Lt&&(D==="all"||Vt===!1)&&(D==="open"||D==="all")?$?.blocked?(0,N.jsxs)("div",{className:e,children:[f?null:Te,(0,N.jsx)(Fi,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):i?(0,N.jsxs)("div",{className:e,children:[f?null:Te,(0,N.jsx)(Fi,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):$&&!$.payments_active?(0,N.jsxs)("div",{className:e,children:[f?null:Te,(0,N.jsx)(Fi,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):(0,N.jsxs)("div",{className:e,children:[f?null:Te,(0,N.jsx)(Fi,{heading:"No invoices yet",body:!$||ne?"Once invoice setup is ready, you can send invoices from the chat.":"Ask in the chat to send an invoice to a client for your services."})]}):(0,N.jsxs)("div",{className:e,children:[f?null:Te,Va.length===0?(0,N.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:"No invoices match."}):(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Va.map(H=>(0,N.jsxs)("button",{type:"button",onClick:()=>Qe(H),disabled:!$e,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${$e?" hover:af-bg-muted/50":""}`,children:[(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,N.jsx)("span",{className:"af-font-medium",children:tr(H)}),(0,N.jsx)(ar,{invoice:H})]}),(0,N.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:H.customer_name??H.customer_email??"\u2014"}),H.delivery&&(0,N.jsx)("div",{className:"af-mt-1",children:(0,N.jsx)(Mi,{delivery:H.delivery})}),(0,N.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[(0,N.jsx)("span",{children:H.collection_method==="charge_automatically"?"Automatic collection":H.due_at?`Due ${pn(H.due_at)}`:"Due on receipt"}),(0,N.jsx)("span",{className:"af-font-medium af-tabular-nums",children:re(H.amount_due??H.amount_total,H.currency)})]})]},H.id))}),(0,N.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,N.jsxs)(ft,{children:[(0,N.jsx)(mt,{children:(0,N.jsxs)(Ue,{children:[(0,N.jsx)(te,{children:"Invoice"}),(0,N.jsx)(te,{children:"Created"}),(0,N.jsx)(te,{children:"Customer"}),(0,N.jsx)(te,{children:"Due"}),(0,N.jsx)(te,{className:"af-text-right",children:"Amount"}),(0,N.jsx)(te,{children:"Status"}),(0,N.jsx)(te,{children:"Delivery"}),(0,N.jsx)(te,{className:"af-w-8"})]})}),(0,N.jsx)(pt,{children:Va.map(H=>(0,N.jsxs)(Ue,{className:$e?"af-cursor-pointer":void 0,onClick:$e?()=>Qe(H):void 0,children:[(0,N.jsx)(ae,{className:"af-font-medium",children:(0,N.jsx)("button",{type:"button",disabled:!$e,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${$e?" hover:af-underline":""}`,onClick:Oe=>{Oe.stopPropagation(),Qe(H)},"aria-label":`Open invoice ${tr(H)}`,children:tr(H)})}),(0,N.jsx)(ae,{children:pn(H.created_at)}),(0,N.jsxs)(ae,{children:[(0,N.jsx)("div",{children:H.customer_name??"\u2014"}),(0,N.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:H.customer_email})]}),(0,N.jsx)(ae,{children:H.collection_method==="charge_automatically"?"Automatic":H.due_at?pn(H.due_at):"On receipt"}),(0,N.jsx)(ae,{className:"af-text-right af-tabular-nums",children:re(H.amount_due??H.amount_total,H.currency)}),(0,N.jsx)(ae,{children:(0,N.jsx)(ar,{invoice:H})}),(0,N.jsx)(ae,{children:(0,N.jsx)(Mi,{delivery:H.delivery})}),(0,N.jsx)(ae,{children:(0,N.jsx)(Yt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},H.id))})]})}),f?null:(0,N.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,N.jsxs)("span",{children:[m," invoice",m===1?"":"s"]}),(0,N.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,N.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(p-1),disabled:!T,"aria-label":"Previous page",children:(0,N.jsx)(Yt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,N.jsxs)("span",{className:"af-tabular-nums",children:[p*x+1,"\u2013",Math.min((p+1)*x,m)]}),(0,N.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(p+1),disabled:!R,"aria-label":"Next page",children:(0,N.jsx)(Yt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Fi({heading:e,body:t,action:a}){return(0,N.jsx)(Qs,{icon:Yt.FileText,heading:e,body:t,action:a})}function ts(e){return(0,N.jsx)(Rf,{...e},e.maxRows==null?"full":"compact")}var es="af-text-xs af-text-muted-foreground";function Cc(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function $i({invoice:e,onBack:t,refreshKey:a,className:s}){let{api:n}=W(),r=Ze.useRef(null);Ze.useEffect(()=>{r.current?.focus()},[e.id]);let[i,l]=Ze.useState(!1),[u,c]=Ze.useState(null),[o,f]=Ze.useState(!1),[b,g]=Ze.useState(!1),m=Ze.useRef(0),[v,d]=Ze.useState(null),[p,x]=Ze.useState(!1),[R,T]=Ze.useState(0);Ze.useEffect(()=>{let C=!1;return x(!1),n.getInvoice(e.id).then(Y=>{C||d({source:e,value:Y})}).catch(()=>{C||x(!0)}),()=>{C=!0}},[n,e,a,R]);let h=v?.source===e?v.value:e,k=h.collection_method==="charge_automatically";Ze.useEffect(()=>(m.current++,c(null),f(!1),g(!1),l(!1),()=>{m.current++}),[n,h,a]);let P=C=>C==null?"\u2014":re(C,h.currency),I=async()=>{if(!(!h.pay_url||!Cc()))try{await navigator.clipboard.writeText(h.pay_url),l(!0),setTimeout(()=>l(!1),1500)}catch{}},w=async()=>{if(u){c(null);return}let C=++m.current;g(!1),f(!0);try{let Y=await n.getInvoicePreview(h.id);C===m.current&&c(Y)}catch{C===m.current&&g(!0)}finally{C===m.current&&f(!1)}},E=h.bill_to,L=E?[E.company,E.name,E.address?.line1,E.address?.line2,[E.address?.city,E.address?.state,E.address?.postal_code].filter(Boolean).join(", "),E.address?.country,E.tax_id?`${E.tax_id.value}`:null,E.po_number?`PO ${E.po_number}`:null,E.service_period?`Service period: ${E.service_period}`:null].filter(C=>!!C&&C.length>0):[];return(0,N.jsxs)("div",{className:s,children:[(0,N.jsxs)("div",{className:"af-mb-4",children:[(0,N.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,N.jsx)(Yt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,N.jsxs)("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",tr(h)]}),(0,N.jsx)(ar,{invoice:h}),(0,N.jsx)(Mi,{delivery:h.delivery})]}),(0,N.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[h.customer_name??h.customer_email,h.customer_name&&h.customer_email?` \xB7 ${h.customer_email}`:""]})]}),p&&(0,N.jsxs)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't refresh this invoice. These details may be out of date. ",(0,N.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>T(C=>C+1),children:"Retry details"})]}),h.label==="failed"&&(0,N.jsx)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),h.label==="creating"&&(0,N.jsx)("p",{role:"status",className:"af-mb-4 af-text-sm af-text-muted-foreground",children:"This invoice is still being created. Its final details will appear when it is ready."}),(0,N.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,N.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,N.jsxs)(ft,{children:[(0,N.jsx)(mt,{children:(0,N.jsxs)(Ue,{children:[(0,N.jsx)(te,{children:"Description"}),(0,N.jsx)(te,{className:"af-text-right",children:"Qty"}),(0,N.jsx)(te,{className:"af-text-right",children:"Amount"})]})}),(0,N.jsx)(pt,{children:h.line_items.map((C,Y)=>(0,N.jsxs)(Ue,{children:[(0,N.jsx)(ae,{style:{overflowWrap:"anywhere"},children:C.description}),(0,N.jsx)(ae,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:C.quantity}),(0,N.jsx)(ae,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:P(C.amount)})]},Y))})]}),(0,N.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,N.jsx)(ps,{label:"Subtotal",value:P(h.amount_subtotal)}),(h.discount_total??0)>0&&(0,N.jsx)(ps,{label:"Discount",value:`-${P(h.discount_total)}`}),h.tax_total>0&&(0,N.jsx)(ps,{label:h.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:P(h.tax_total)}),(0,N.jsx)(ps,{label:"Total",value:P(h.amount_total),strong:!0}),h.credit_applied>0&&(0,N.jsx)(ps,{label:"Credit applied",value:`-${P(h.credit_applied)}`}),h.amount_due!==null&&h.amount_due!==h.amount_total&&(0,N.jsx)(ps,{label:"Amount due",value:P(h.amount_due),strong:!0}),h.amount_paid!==null&&h.amount_paid>0&&(0,N.jsx)(ps,{label:"Amount paid",value:P(h.amount_paid)}),h.amount_refunded>0&&(0,N.jsx)(ps,{label:"Refunded",value:P(h.amount_refunded)})]}),h.credit_notes?.length>0&&(0,N.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,N.jsx)("div",{className:es,children:"Credit notes"}),h.credit_notes.map(C=>(0,N.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,N.jsxs)("span",{className:"af-text-muted-foreground",children:[pn(C.created_at)," \xB7 ",C.origin==="dashboard"?"issued in Stripe":"refund",C.stripe_credit_note_id?"":" \xB7 being created"]}),(0,N.jsxs)("span",{className:"af-tabular-nums",children:["-",re(C.amount,C.currency)]})]},C.id))]})]}),(h.note||h.footer)&&(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[h.note&&(0,N.jsxs)("div",{children:[(0,N.jsx)("div",{className:es,children:"Note"}),(0,N.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:h.note})]}),h.footer&&(0,N.jsxs)("div",{children:[(0,N.jsx)("div",{className:es,children:"Footer"}),(0,N.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:h.footer})]})]}),u&&!k&&(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,N.jsxs)("div",{className:X(es,"af-break-words"),children:["Email preview \u2014 ",u.subject]}),(0,N.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,N.jsx)("iframe",{title:"Invoice email preview",srcDoc:u.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,N.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,N.jsx)(mn,{label:"Created",value:pn(h.created_at)}),(0,N.jsx)(mn,{label:"Due",value:h.collection_method==="charge_automatically"?"Managed in Stripe":h.due_at?pn(h.due_at):"On receipt"}),h.paid_at&&(0,N.jsx)(mn,{label:"Paid",value:pn(h.paid_at)}),h.payment_method&&(0,N.jsx)(mn,{label:"Paid by",value:h.paid_out_of_band?`${h.payment_method} (recorded outside Stripe)`:h.payment_method}),h.payment_state!=="none"&&(0,N.jsx)(mn,{label:"Payment",value:h.payment_state==="processing"?"Processing":h.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),h.delivery&&(0,N.jsx)(mn,{label:"Delivery",value:`${Lo[h.delivery.state]} \xB7 ${h.delivery.recipient}`}),h.marked_uncollectible_at&&(0,N.jsx)(mn,{label:"Written off",value:pn(h.marked_uncollectible_at)}),h.correction_reason&&(0,N.jsx)(mn,{label:"Correction",value:h.correction_reason}),h.replaced_by_order_id&&(0,N.jsx)(mn,{label:"Replaced by",value:h.replaced_by_order_id}),h.collection_method==="charge_automatically"?(0,N.jsx)(mn,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):h.retainer_id&&(0,N.jsx)(mn,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),h.replaces_order_id&&(0,N.jsx)(mn,{label:"Replaces",value:h.replaces_order_id})]}),(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,N.jsx)("div",{className:es,children:"Reminders"}),k?(0,N.jsx)("div",{children:"View automatic payment reminders in Stripe."}):h.reminders.disabled?(0,N.jsx)("div",{children:"Off for this invoice."}):h.reminders.paused_until?(0,N.jsxs)("div",{children:["Paused until ",pn(h.reminders.paused_until),"."]}):h.reminders.next_at?(0,N.jsxs)("div",{children:["Next on ",pn(h.reminders.next_at),"."]}):h.reminders.final_sent_at?(0,N.jsxs)("div",{children:["Final reminder sent ",pn(h.reminders.final_sent_at),"."]}):(0,N.jsx)("div",{children:"None scheduled."}),!k&&(0,N.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",h.reminders.schedule.length===0?"none":h.reminders.schedule.map(C=>C<0?`${-C}d before`:C===0?"due day":`${C}d after`).join(", ")]})]}),h.communications&&h.communications.length>0&&(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,N.jsx)("div",{className:es,children:"Email delivery history"}),h.communications.map(C=>(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,N.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[wf[C.kind]??C.kind,C.kind==="reminder"&&C.slot!==null?` #${C.slot}`:"",(0,N.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",C.recipient]})]}),(0,N.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Lo[C.state]??C.state," \xB7 ",pn(C.state_at??C.created_at)]})]},C.id))]}),L.length>0&&(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,N.jsx)("div",{className:es,children:"Bill to"}),L.map((C,Y)=>(0,N.jsx)("div",{className:"af-break-words",children:C},Y))]}),(0,N.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[h.pay_url&&(0,N.jsxs)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void I(),disabled:!Cc(),children:[(0,N.jsx)(Yt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Copied":k?"Copy invoice link":"Copy pay link"]}),h.pdf_url&&(0,N.jsx)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,N.jsxs)("a",{href:h.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,N.jsx)(Yt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!k&&(0,N.jsxs)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void w(),disabled:o,children:[o?(0,N.jsx)(Yt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,N.jsx)(Yt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),u?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!k&&(0,N.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),h.pay_url&&(0,N.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:h.pay_url}),(0,N.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:k?"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 mn({label:e,value:t}){return(0,N.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,N.jsx)("span",{className:X(es,"af-shrink-0"),children:e}),(0,N.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function ps({label:e,value:t,strong:a}){return(0,N.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,N.jsx)("dt",{className:X(es,a&&"af-font-medium af-text-foreground"),children:e}),(0,N.jsx)("dd",{className:X("af-tabular-nums",a&&"af-font-semibold"),children:t})]})}var Ic=require("lucide-react");var at=require("react/jsx-runtime"),_f={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Ec={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function kf(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 Ac(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>Ec[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>Ec[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":_f[e.status]}function Dc(e){let t=e.interval==="year"?"every year":"every month";return`${re(e.amount,e.currency)} ${t}`}function Pf(e){return e.status==="canceled"?`Ended ${Ui(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Ui(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 ${Ui(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Ui(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Ui(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 Vi({retainer:e,className:t}){return(0,at.jsx)(ie,{variant:kf(e.status),className:X("af-max-w-full af-whitespace-normal af-break-words",t),children:Ac(e)})}function Is({retainers:e,isLoading:t,error:a,onRetry:s,onShowCycles:n,activeRetainerId:r,total:i,endedTotal:l=0,isLoadingMore:u=!1,onLoadMore:c,includeEnded:o=!1,onIncludeEndedChange:f,exportCsv:b,className:g}){let m=!!f;if(!t&&!a&&e.length===0&&!(m&&(o||l>0)))return null;let v=i!==void 0?Math.max(0,i-e.length):0;return(0,at.jsxs)("section",{className:X("af-mb-6",g),"aria-label":"Recurring invoices",children:[(0,at.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,at.jsx)(Ic.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,at.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,at.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),m&&(0,at.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":o,onClick:()=>f?.(!o),children:o?"Hide ended recurring invoices":l>0&&e.length===0?`Show ended recurring invoices (${l})`:"Show ended recurring invoices"}),b&&(0,at.jsx)(ma,{fetchCsv:b,filename:"retainers",className:m?void 0:"af-ml-auto"})]}),a?(0,at.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",(0,at.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?(0,at.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(d=>(0,at.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,at.jsx)(Q,{className:"af-h-4 af-w-48"}),(0,at.jsx)(Q,{className:"af-mt-2 af-h-3 af-w-32"})]},d))}):e.length===0?(0,at.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:o?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,at.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(d=>{let p=r===d.id;return(0,at.jsxs)("li",{className:X("af-rounded-md af-border af-p-3",p&&"af-border-primary af-bg-muted/40"),children:[(0,at.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,at.jsxs)("div",{className:"af-min-w-0",children:[(0,at.jsx)("div",{className:"af-truncate af-font-medium",children:d.customer_name??d.customer_email??"\u2014"}),(0,at.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:d.description})]}),(0,at.jsx)(Vi,{retainer:d})]}),d.collection_method==="charge_automatically"?(0,at.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,at.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"}),(0,at.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Automatic charging is enabled in Stripe. View or change the billing terms there. To edit this schedule from the chat, switch it back to sending invoices in Stripe."})]}):(0,at.jsx)("div",{className:"af-mt-2 af-text-sm",children:Dc(d)}),(0,at.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-text-xs af-text-muted-foreground",children:[(0,at.jsxs)("span",{children:[Pf(d)," \xB7 ",d.cycles.count===0?"no invoices yet":`${d.cycles.paid} paid${d.cycles.open>0?`, ${d.cycles.open} open`:""}`]}),d.cycles.count>0&&(0,at.jsx)(y,{type:"button",variant:p?"secondary":"ghost",size:"sm",onClick:()=>n(d),"aria-pressed":p,children:p?"Showing invoices":"View invoices"})]}),d.status==="failed"&&d.operation?.last_error&&(0,at.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",d.operation.last_error,". Ask in the chat to try again."]})]},d.id)})}),!t&&!a&&v>0&&c&&(0,at.jsx)("div",{className:"af-mt-2",children:(0,at.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:c,disabled:u,children:u?"Loading\u2026":`Load more (${v} more)`})})]})}var Oc=le(require("react"),1),tn=require("lucide-react");var Ve=require("react/jsx-runtime");function As({onConnectStripe:e,onUpgradePlan:t,whenActive:a,className:s}){let{status:n,isLoading:r,error:i,refetch:l}=Yn(),[u,c]=Oc.useState(!1),o=async()=>{c(!0);try{await l()}finally{c(!1)}};return r&&!n?(0,Ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ve.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!n?(0,Ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ve.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):n.status==="active"?a!==void 0?(0,Ve.jsx)("div",{className:s,children:a}):(0,Ve.jsx)("div",{className:s,children:(0,Ve.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-green-50 af-border af-border-green-200 af-rounded-lg af-p-4",children:[(0,Ve.jsx)(tn.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Ve.jsxs)("div",{children:[(0,Ve.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Ve.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",n.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,Ve.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[n.reason==="needs_stripe"&&(0,Ve.jsxs)("div",{className:"af-space-y-3",children:[(0,Ve.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ve.jsx)(tn.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ve.jsxs)("div",{children:[(0,Ve.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"It only takes a few minutes. You'll enter your details with Stripe, who handle the payments, and money from sales goes straight to your own bank."})]})]}),e?(0,Ve.jsxs)(y,{onClick:e,children:[(0,Ve.jsx)(tn.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),n.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),n.reason==="needs_paid_plan"&&(0,Ve.jsxs)("div",{className:"af-space-y-3",children:[(0,Ve.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ve.jsx)(tn.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ve.jsxs)("div",{children:[(0,Ve.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your products are saved as drafts. Upgrade to a paid plan to start accepting payments on your site."})]})]}),t?(0,Ve.jsx)(y,{onClick:t,children:"Upgrade plan"}):(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),n.reason==="account_disabled"&&(0,Ve.jsxs)("div",{className:"af-space-y-3",children:[(0,Ve.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-yellow-50 af-border af-border-yellow-200 af-rounded-lg af-p-4",children:[(0,Ve.jsx)(tn.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Ve.jsxs)("div",{children:[(0,Ve.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),n.stripe_account_connected?(0,Ve.jsx)("p",{className:"af-text-sm af-text-yellow-800",children:"Your Stripe account can't currently accept charges. Check your Stripe account for outstanding requirements or notifications \u2014 once Stripe re-enables charges, payments resume here automatically."}):(0,Ve.jsx)("p",{className:"af-text-sm af-text-yellow-800",children:"Payments are currently paused for this site. If you think this is a mistake, get in touch with support and we'll look into it with you."})]})]}),(0,Ve.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&n.stripe_account_connected&&(0,Ve.jsxs)(y,{onClick:e,children:[(0,Ve.jsx)(tn.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Ve.jsxs)(y,{variant:"outline",onClick:o,disabled:u,children:[u?(0,Ve.jsx)(tn.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Ve.jsx)(tn.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var Ra=le(require("react"),1);function Fo(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function Ds({includeStats:e=!1,refreshKey:t}={}){let{api:a}=W(),[s,n]=Ra.useState([]),[r,i]=Ra.useState(!0),[l,u]=Ra.useState(null),c=Ra.useRef(0),o=Ra.useCallback(async()=>{let d=++c.current;try{i(!0),u(null);let p=await a.getProducts(e?{include:"stats"}:{});if(d!==c.current)return;n(p)}catch(p){if(d!==c.current)return;u(p instanceof Error?p:new Error("Failed to fetch products"))}finally{d===c.current&&i(!1)}},[a,e,t]);Ra.useEffect(()=>{o()},[o]);let f=Ra.useCallback(async d=>{let p=await a.createProduct(d);return n(x=>[p,...x]),p},[a]),b=Ra.useCallback(async(d,p)=>{let x=await a.updateProduct(d,p);return n(R=>Fo(R,d,x)),x},[a]),g=Ra.useCallback(async d=>{await a.deleteProduct(d),n(p=>p.filter(x=>x.id!==d))},[a]),m=Ra.useCallback(async(d,p)=>{let x=await a.attachProductFile(d,p);return n(R=>Fo(R,d,x)),x},[a]),v=Ra.useCallback(async(d,p)=>{let x=await a.attachProductFileFromUrl(d,p);return n(R=>Fo(R,d,x)),x},[a]);return{products:s,isLoading:r,error:l,refetch:o,createProduct:f,updateProduct:b,deleteProduct:g,attachProductFile:m,attachProductFileFromUrl:v}}var _a=le(require("react"),1);var Mo=["creating","active","paused","canceling"],Cf=["canceled","failed"],Tf={statuses:Mo},Ef={};function Os({refreshKey:e,includeEnded:t=!1,limit:a=50}={}){let{api:s}=W(),[n,r]=_a.useState([]),[i,l]=_a.useState(0),[u,c]=_a.useState(0),[o,f]=_a.useState(!0),[b,g]=_a.useState(!1),[m,v]=_a.useState(null),[d,p]=_a.useState(t),x=_a.useRef(0),R=_a.useCallback(async()=>{let h=++x.current;f(!0),g(!1),v(null);try{let k=await s.getRetainers({statuses:d?void 0:Mo,limit:a,offset:0});if(h!==x.current)return;if(r(k.retainers),l(k.total),!d&&k.total===0){let P=await s.getRetainers({statuses:Cf,limit:1,offset:0});if(h!==x.current)return;c(P.total)}else c(0)}catch(k){if(h!==x.current)return;v(k instanceof Error?k:new Error("Failed to fetch retainers"))}finally{h===x.current&&f(!1)}},[s,d,a]);_a.useEffect(()=>{R()},[R,e]);let T=_a.useCallback(async()=>{if(o||b||n.length>=i)return;let h=x.current;g(!0);try{let k=await s.getRetainers({statuses:d?void 0:Mo,limit:a,offset:n.length});if(h!==x.current)return;r(P=>{let I=new Set(P.map(w=>w.id));return[...P,...k.retainers.filter(w=>!I.has(w.id))]}),l(k.total)}catch(k){if(h!==x.current)return;v(k instanceof Error?k:new Error("Failed to fetch retainers"))}finally{h===x.current&&g(!1)}},[s,d,a,o,b,n.length,i]);return{retainers:n,total:i,endedTotal:u,hasMore:n.length<i,isLoading:o,isLoadingMore:b,error:m,includeEnded:d,setIncludeEnded:p,loadMore:T,refetch:R,filters:d?Ef:Tf}}var Me=require("react/jsx-runtime");function $o({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:n}){let[r,i]=nr.useState(t),[l,u]=nr.useState("list"),[c,o]=nr.useState(null),f=Ds(),{status:b,error:g}=Yn(),m=b?.currency,v=R=>{o(R),u("edit")},d=()=>{o(null),u("create")},p=()=>{u("list"),o(null)},x=R=>{o(R),u("edit")};return(0,Me.jsxs)("div",{className:e,children:[(0,Me.jsxs)("div",{className:"af-mb-6",children:[(0,Me.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Me.jsxs)(xi,{value:r,onValueChange:R=>i(R),children:[(0,Me.jsxs)(vr,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Me.jsxs)(Sn,{value:"products",className:"af-gap-2",children:[(0,Me.jsx)(gn.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Me.jsxs)(Sn,{value:"orders",className:"af-gap-2",children:[(0,Me.jsx)(gn.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Me.jsxs)(Sn,{value:"invoices",className:"af-gap-2",children:[(0,Me.jsx)(gn.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Me.jsxs)(Sn,{value:"customers",className:"af-gap-2",children:[(0,Me.jsx)(gn.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Me.jsx)(Sn,{value:"promos",children:"Promo codes"}),(0,Me.jsxs)(Sn,{value:"setup",className:"af-gap-2",children:[(0,Me.jsx)(gn.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Me.jsx)(Nn,{value:"products",children:l==="list"?(0,Me.jsx)(Ir,{productsState:f,onSelectProduct:v,onCreateProduct:d}):(0,Me.jsxs)("div",{children:[(0,Me.jsxs)("div",{className:"af-mb-6",children:[(0,Me.jsxs)(y,{variant:"ghost",size:"sm",onClick:p,className:"af-mb-2 af--ml-2",children:[(0,Me.jsx)(gn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Me.jsx)("h3",{className:"af-text-lg af-font-semibold",children:l==="create"?"New Product":c?.name})]}),l==="create"&&!m?(0,Me.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?(0,Me.jsxs)("div",{className:"af-text-destructive",children:["Error: ",g.message]}):(0,Me.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Me.jsx)(Dr,{productsState:f,product:l==="edit"?c:null,currency:m??"usd",onSaved:x},l==="edit"?c?.id??"edit":"new")]})}),(0,Me.jsx)(Nn,{value:"orders",children:(0,Me.jsx)(Qn,{onRefund:s})}),(0,Me.jsx)(Nn,{value:"invoices",children:(0,Me.jsx)(If,{onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),(0,Me.jsx)(Nn,{value:"customers",children:(0,Me.jsx)(Ur,{})}),(0,Me.jsx)(Nn,{value:"promos",children:(0,Me.jsx)(ks,{})}),(0,Me.jsx)(Nn,{value:"setup",children:(0,Me.jsx)(As,{onConnectStripe:a,onUpgradePlan:n})})]})]})}function If({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a}){let s=Os(),[n,r]=nr.useState(null),[i,l]=nr.useState(!1);return(0,Me.jsxs)(Me.Fragment,{children:[!i&&(0,Me.jsx)(Is,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:n?.id??null,onShowCycles:u=>r(c=>c?.id===u.id?null:u),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),(0,Me.jsx)(ts,{onDetailOpenChange:l,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}var Bc=le(require("react"),1);var $n=le(require("react"),1);function Ls({refreshKey:e}={}){let{api:t}=W(),[a,s]=$n.useState(null),[n,r]=$n.useState(!0),[i,l]=$n.useState(null),u=$n.useRef(0),c=$n.useCallback(async()=>{let o=++u.current;try{r(!0),l(null);let f=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(o!==u.current)return;s(f)}catch(f){if(o!==u.current)return;l(f instanceof Error?f:new Error("Failed to fetch summary"))}finally{o===u.current&&r(!1)}},[t,e]);return $n.useEffect(()=>{c()},[c]),{summary:a,isLoading:n,error:i,refetch:c}}var vt=require("react/jsx-runtime");function Lc(e,t){if(e.settled.complete)return{headline:re(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:re(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${re(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:re(0,t),extra:[]}}function Uo({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:n,className:r}){let{summary:i,isLoading:l,error:u,refetch:c}=Ls({refreshKey:e}),[o,f]=Bc.useState(!1),b=(0,vt.jsx)("div",{className:"af-mb-6",children:u&&!i?(0,vt.jsx)(wt,{message:"Couldn't load your revenue summary.",onRetry:()=>c()}):(0,vt.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:l||!i?(0,vt.jsxs)(vt.Fragment,{children:[(0,vt.jsx)(gt,{label:"This week",children:(0,vt.jsx)(Q,{className:"af-h-6 af-w-24"})}),(0,vt.jsx)(gt,{label:"Today",children:(0,vt.jsx)(Q,{className:"af-h-6 af-w-24"})}),(0,vt.jsx)(gt,{label:"Needs attention",children:(0,vt.jsx)(Q,{className:"af-h-6 af-w-10"})})]}):(0,vt.jsx)(vt.Fragment,{children:(()=>{let g=Lc(i.revenue.d7,i.currency),m=Lc(i.revenue.today,i.currency);return(0,vt.jsxs)(vt.Fragment,{children:[(0,vt.jsx)(gt,{label:"This week",detail:g.extra.length>0?(0,vt.jsx)("div",{children:g.extra.map(v=>(0,vt.jsx)("div",{children:v},v))}):void 0,children:g.headline}),(0,vt.jsx)(gt,{label:"Today",detail:m.extra.length>0?(0,vt.jsx)("div",{children:m.extra.map(v=>(0,vt.jsx)("div",{children:v},v))}):void 0,children:m.headline}),(0,vt.jsx)(gt,{label:"Needs attention",valueClassName:i.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:i.needs_attention.count===0?"All clear":i.needs_attention.items[0]?.title??void 0,children:i.needs_attention.count})]})})()})})});return(0,vt.jsxs)(Ft,{title:"Orders",onBackToWebsite:n,hideBackButton:o,className:r,children:[b,(0,vt.jsx)(Qn,{refreshKey:e,initialOrderId:t,onDetailOpenChange:f,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var vn=le(require("react"),1),sr=require("lucide-react");var Un=le(require("react"),1),Gi=require("lucide-react");var ca=require("react/jsx-runtime"),Fc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",gs="af-text-xs af-text-muted-foreground",Hi="af-text-sm af-font-medium af-tabular-nums",Af=3;function Df(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let u=e.min_amount??t?.min_amount??null,c=e.max_amount??t?.max_amount??null;return u!==null&&c!==null?{text:`Buyer chooses (${re(u,a)} \u2013 ${re(c,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(n===null||r===null)return{text:"Varies by variant",compareAt:null};let i=n===r?re(n,a):`${re(n,a)} \u2013 ${re(r,a)}`,l=t?.compare_at_amount??null;return{text:i,compareAt:l!==null&&l>r?re(l,a):null}}function zi({product:e,className:t}){let a=Df(e);return(0,ca.jsxs)("div",{className:t,children:[(0,ca.jsx)("span",{className:Hi,children:a.text}),a.compareAt&&(0,ca.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function ji({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,ca.jsx)(ie,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,ca.jsxs)(ie,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,ca.jsx)(ie,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,ca.jsxs)(ie,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,ca.jsx)(ie,{variant:"warning",children:"Low stock"}):null}function qi(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Wi(e){return e.map(t=>re(t.amount,t.currency)).join(" + ")}function Mc(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${re(e.min_amount,e.currency)} \u2013 ${re(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":re(e.unit_amount,e.currency)}function $c({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,ca.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?(0,ca.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ca.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,a)}),(0,ca.jsx)(ie,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?(0,ca.jsx)(ie,{variant:"destructive",children:"Out of stock"}):(0,ca.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ca.jsx)("span",{className:"af-tabular-nums",children:a}),a<=Af&&(0,ca.jsx)(ie,{variant:"warning",children:"Low"})]})}var ue=require("react/jsx-runtime");function Vr({title:e,children:t,className:a}){return(0,ue.jsxs)("section",{className:X("af-rounded-lg af-border af-p-4",a),children:[(0,ue.jsx)("h4",{className:Fc,children:e}),(0,ue.jsx)("div",{className:"af-mt-3",children:t})]})}function Uc({src:e,className:t}){let[a,s]=Un.useState(!1);return Un.useEffect(()=>s(!1),[e]),!e||a?(0,ue.jsx)("div",{"aria-hidden":"true",className:X("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,ue.jsx)(Gi.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,ue.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:X("af-object-cover",t)})}function Vc({product:e,showStats:t=!1,onBack:a}){let{api:s}=W(),[n,r]=Un.useState(null),[i,l]=Un.useState(!0),[u,c]=Un.useState(null),[o,f]=Un.useState(0),[b,g]=Un.useState(0);Un.useEffect(()=>{let h=!1;return l(!0),c(null),s.getProduct(e.id).then(k=>{h||r(k)}).catch(k=>{h||c(k instanceof Error?k:new Error("Failed to load product"))}).finally(()=>{h||l(!1)}),()=>{h=!0}},[s,e.id,o]);let m=n?{...e,...n}:e,v=m.images.length>0?m.images:e.images,d=v[b]??v[0],p=qi(m),x=t?m.stats:void 0,R=n?.variants??[],T=R.length>1;return(0,ue.jsxs)("div",{children:[(0,ue.jsxs)("div",{className:"af-mb-6",children:[(0,ue.jsxs)(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,ue.jsx)(Gi.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,ue.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,ue.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:m.name}),(0,ue.jsx)(ie,{variant:m.active?"success":"secondary",children:m.active?"Active":"Draft"}),(0,ue.jsx)(ji,{product:m})]}),(0,ue.jsx)(zi,{product:m,className:"af-mt-1"}),!m.active&&(0,ue.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),(0,ue.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,ue.jsxs)("div",{className:"af-space-y-2",children:[(0,ue.jsx)(Uc,{src:d,className:"af-h-48 af-w-full af-rounded-md af-border"}),v.length>1&&(0,ue.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:v.map((h,k)=>(0,ue.jsx)("button",{type:"button",onClick:()=>g(k),"aria-label":`Show photo ${k+1} of ${v.length}`,"aria-pressed":k===b,className:X("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",k===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,ue.jsx)(Uc,{src:h,className:"af-h-12 af-w-12 af-rounded-md"})},`${h}-${k}`))})]}),(0,ue.jsxs)("div",{className:"af-space-y-6",children:[m.description&&(0,ue.jsx)(Vr,{title:"Description",children:(0,ue.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:m.description})}),i?(0,ue.jsxs)(Vr,{title:"Variants",children:[(0,ue.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(h=>(0,ue.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,ue.jsx)(Q,{className:"af-h-4 af-w-28"}),(0,ue.jsx)(Q,{className:"af-h-4 af-w-20"}),(0,ue.jsx)(Q,{className:"af-h-4 af-w-16"})]},h))}),(0,ue.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):u?(0,ue.jsx)(wt,{message:"Couldn't load this product's variants.",onRetry:()=>f(h=>h+1)}):T?(0,ue.jsx)(Vr,{title:`Variants \xB7 ${R.length}`,children:(0,ue.jsx)("div",{className:"af-overflow-x-auto",children:(0,ue.jsxs)(ft,{children:[(0,ue.jsx)(mt,{children:(0,ue.jsxs)(Ue,{children:[(0,ue.jsx)(te,{children:"Variant"}),(0,ue.jsx)(te,{children:"SKU"}),(0,ue.jsx)(te,{className:"af-text-right",children:"Price"}),(0,ue.jsx)(te,{children:"Stock"})]})}),(0,ue.jsx)(pt,{children:R.map(h=>(0,ue.jsxs)(Ue,{children:[(0,ue.jsxs)(ae,{className:"af-font-medium",children:[h.title||h.option_values.map(k=>k.value).join(" / ")||"\u2014",!h.active&&(0,ue.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,ue.jsx)(ae,{className:"af-text-muted-foreground",children:h.sku?(0,ue.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:h.sku}):"\u2014"}),(0,ue.jsxs)(ae,{className:"af-whitespace-nowrap af-text-right",children:[(0,ue.jsx)("div",{className:Hi,children:Mc(h)}),h.compare_at_amount!==null&&h.unit_amount!==null&&h.compare_at_amount>h.unit_amount&&(0,ue.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:re(h.compare_at_amount,h.currency)})]}),(0,ue.jsx)(ae,{className:"af-text-sm",children:(0,ue.jsx)($c,{variant:h})})]},h.id))})]})})}):null,(0,ue.jsx)(Vr,{title:"Details",children:(0,ue.jsxs)("dl",{className:"af-space-y-2",children:[(0,ue.jsxs)("div",{children:[(0,ue.jsx)("dt",{className:gs,children:"Delivery"}),(0,ue.jsx)("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&&(0,ue.jsxs)("div",{children:[(0,ue.jsx)("dt",{className:gs,children:"Sends buyers to"}),(0,ue.jsx)("dd",{className:"af-break-all af-text-sm",children:m.fulfillment.url})]}),(0,ue.jsxs)("div",{children:[(0,ue.jsx)("dt",{className:gs,children:"Shipping address"}),(0,ue.jsx)("dd",{className:"af-text-sm",children:m.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,ue.jsxs)("div",{children:[(0,ue.jsx)("dt",{className:gs,children:"Most one buyer can order"}),(0,ue.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:m.max_quantity})]})]})}),x&&(0,ue.jsx)(Vr,{title:"Last 30 days",children:(0,ue.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,ue.jsxs)("div",{children:[(0,ue.jsx)("dt",{className:gs,children:"Units sold"}),(0,ue.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),(0,ue.jsxs)("div",{children:[(0,ue.jsx)("dt",{className:gs,children:"Orders"}),(0,ue.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),(0,ue.jsxs)("div",{children:[(0,ue.jsx)("dt",{className:gs,children:"Gross"}),(0,ue.jsx)("dd",{className:Hi,children:x.gross.length>0?Wi(x.gross):"\u2014"})]})]})}),(0,ue.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var J=require("react/jsx-runtime"),Of={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Lf=["all","active","draft","low_stock","out_of_stock"];function Hc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function zc(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Bf(e){return e.inventory?.out_of_stock??!1}function Ff(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return zc(e);case"out_of_stock":return Bf(e);default:return!0}}function Mf({product:e,showStats:t,onOpen:a}){let s=e.images[0],n=t?e.stats:void 0,r=qi(e),i=e.variant_count??0;return(0,J.jsxs)("button",{type:"button",onClick:a,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?(0,J.jsx)("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,J.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:(0,J.jsx)(sr.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,J.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,J.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,J.jsxs)("div",{className:"af-min-w-0",children:[(0,J.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,J.jsx)(zi,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,J.jsx)(ie,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,J.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,J.jsx)(ji,{product:e}),i>1&&(0,J.jsxs)(ie,{variant:"outline",children:[i," variants"]}),r&&(0,J.jsx)(ie,{variant:"outline",children:r})]}),n&&(0,J.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Wi(n.gross)}`:""," ",(0,J.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function $f(){return(0,J.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:[0,1,2,3,4,5].map(e=>(0,J.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,J.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,J.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,J.jsx)(Q,{className:"af-w-32"}),(0,J.jsx)(Q,{className:"af-w-16"}),(0,J.jsx)(Q,{className:"af-h-5 af-w-24"})]})]},e))})}function Vo({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:n,isLoading:r,error:i,refetch:l}=Ds({includeStats:t,refreshKey:e}),[u,c]=vn.useState(!1),[o,f]=vn.useState(null),[b,g]=vn.useState("all"),{api:m}=W(),v=vn.useCallback(()=>m.exportProductsCsv(),[m]),[d,p]=vn.useState(""),[x,R]=vn.useState("newest"),T=vn.useMemo(()=>{if(!t)return null;let G=null;for(let z of n)!z.stats||z.stats.units_sold===0||(!G||z.stats.units_sold>(G.stats?.units_sold??0))&&(G=z);return G},[n,t]),h=vn.useMemo(()=>n.filter(zc).length,[n]),k=d.trim().toLowerCase(),P=vn.useMemo(()=>{let z=[...n.filter(ce=>Ff(ce,b)&&(!k||ce.name.toLowerCase().includes(k)))];return x==="name"?z.sort((ce,ve)=>ce.name.localeCompare(ve.name)):x==="best_selling"?z.sort((ce,ve)=>(ve.stats?.units_sold??0)-(ce.stats?.units_sold??0)):z.sort((ce,ve)=>Hc(ve.created_at)-Hc(ce.created_at)),z},[n,b,k,x]),I=b!=="all"||!!k,w=()=>{g("all"),p("")},E=r||i!==null&&n.length===0,L=(0,J.jsx)("div",{className:"af-mb-6",children:(0,J.jsx)("div",{className:X("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:E?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(gt,{label:"Products",children:(0,J.jsx)(Q,{className:"af-h-6 af-w-10"})}),t?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(gt,{label:"Best seller",children:(0,J.jsx)(Q,{className:"af-h-6 af-w-28"})}),(0,J.jsx)(gt,{label:"Low stock",children:(0,J.jsx)(Q,{className:"af-h-6 af-w-10"})})]}):(0,J.jsx)(gt,{label:"Active",children:(0,J.jsx)(Q,{className:"af-h-6 af-w-10"})})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(gt,{label:"Products",children:n.length}),t?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(gt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:T?`${T.stats?.units_sold??0} sold, last 30 days`:void 0,children:T?(0,J.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:T.name}):(0,J.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,J.jsx)(gt,{label:"Low stock",children:h})]}):(0,J.jsx)(gt,{label:"Active",children:n.filter(G=>G.active).length})]})})}),C=(0,J.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,J.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,J.jsx)("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Lf.map(G=>(0,J.jsx)("button",{type:"button","aria-pressed":b===G,onClick:()=>g(G),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",b===G?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Of[G]},G))}),(0,J.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,J.jsx)(sr.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,J.jsx)(de,{type:"text",value:d,onChange:G=>p(G.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,J.jsxs)(on,{value:x,onValueChange:G=>R(G),children:[(0,J.jsx)(za,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,J.jsx)(ln,{})}),(0,J.jsxs)(ja,{children:[(0,J.jsx)(kt,{value:"newest",children:"Newest"}),(0,J.jsx)(kt,{value:"name",children:"Name A\u2013Z"}),t&&(0,J.jsx)(kt,{value:"best_selling",children:"Best selling"})]})]}),I&&(0,J.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:w,children:"Clear filters"}),(0,J.jsx)(ma,{fetchCsv:v,filename:"products",label:I?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&n.length===0?(0,J.jsx)(Q,{className:"af-h-4 af-w-28"}):(0,J.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:I?`${P.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),Y;return o?Y=(0,J.jsx)(Vc,{product:o,showStats:t,onBack:()=>{f(null),l()}},o.id):r&&n.length===0?Y=(0,J.jsxs)(J.Fragment,{children:[C,(0,J.jsx)($f,{}),(0,J.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):i&&n.length===0?Y=(0,J.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,J.jsx)(wt,{message:"Couldn't load your products.",onRetry:()=>l()})}):n.length===0?Y=(0,J.jsxs)(la,{icon:(0,J.jsx)(sr.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,J.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):Y=(0,J.jsxs)(J.Fragment,{children:[C,i&&(0,J.jsx)("div",{className:"af-mb-4",children:(0,J.jsx)(wt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>l()})}),P.length===0?(0,J.jsxs)(la,{children:["No products match these filters.",(0,J.jsx)("br",{}),(0,J.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:w,children:"Show all products"})]}):(0,J.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:P.map(G=>(0,J.jsx)(Mf,{product:G,showStats:t,onOpen:()=>f(G)},G.id))})]}),(0,J.jsx)(Ft,{title:"Products",onBackToWebsite:a,hideBackButton:!!o,className:s,children:u?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(y,{variant:"ghost",onClick:()=>c(!1),children:"Back to products"}),(0,J.jsx)(ks,{})]}):(0,J.jsxs)(J.Fragment,{children:[!o&&(0,J.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,J.jsx)(y,{variant:"outline",onClick:()=>c(!0),children:"Promo codes"})}),!o&&L,Y]})})}var Da=le(require("react"),1),Wt=require("lucide-react");var Aa=le(require("react"),1);function Hr({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=W(),[s,n]=Aa.useState([]),[r,i]=Aa.useState(!0),[l,u]=Aa.useState(null),[c,o]=Aa.useState(0),[f]=Aa.useState(e),[b,g]=Aa.useState(""),[m,v]=Aa.useState(void 0),d=Aa.useRef(0),p=Aa.useCallback(async({afterRemoval:x=!1}={})=>{let R=++d.current;try{i(!0),u(null);let T={limit:f,offset:c*f};b.trim()&&(T.q=b.trim()),m&&(T.source=m);let h=await a.getPeople(T);if(R!==d.current)return;if(x&&h.people.length===0&&c>0){o(c-1);return}n(h.people)}catch(T){if(R!==d.current)return;u(T instanceof Error?T:new Error("Failed to fetch people"))}finally{R===d.current&&i(!1)}},[a,c,f,b,m,t]);return Aa.useEffect(()=>{p()},[p]),{people:s,isLoading:r,error:l,page:c,pageSize:f,hasNextPage:s.length===f,hasPreviousPage:c>0,setPage:o,q:b,setQ:x=>{g(x),o(0)},source:m,setSource:x=>{v(x),o(0)},refetch:()=>p(),refetchAfterRemoval:()=>p({afterRemoval:!0})}}var Vn=le(require("react"),1);function zr(e,{refreshKey:t}={}){let{api:a}=W(),[s,n]=Vn.useState(null),[r,i]=Vn.useState(e!==null),[l,u]=Vn.useState(null),c=Vn.useRef(0),o=Vn.useCallback(async()=>{if(e===null){n(null),i(!1),u(null);return}let f=++c.current;try{i(!0),u(null);let b=await a.getPerson(e);if(f!==c.current)return;n(b)}catch(b){if(f!==c.current)return;u(b instanceof Error?b:new Error("Failed to fetch person"))}finally{f===c.current&&i(!1)}},[a,e,t]);return Vn.useEffect(()=>{o()},[o]),{person:s,isLoading:r,error:l,refetch:o}}var _=require("react/jsx-runtime"),Ho="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Uf="af-text-xs af-text-muted-foreground";function rr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function zo(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function Vf(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Hf({value:e,label:t}){let[a,s]=Da.useState(!1);return Vf()?(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[a?(0,_.jsx)(Wt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,_.jsx)(Wt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function jc(e){return(0,_.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,_.jsxs)(ie,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,_.jsx)(ie,{variant:"secondary",children:"Contact form"})]})}function qc(e){return e.name?e.name:e.email?e.email:(0,_.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var zf=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,jf=40;function qf(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),s=t.find(([n,r])=>zf.test(n)&&typeof r=="string"&&r.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=jf).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 Wf(e){return e.replace(/_/g," ")}function Gf(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Kf({data:e}){let{message:t,rest:a}=qf(e);return t===null&&a.length===0?(0,_.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,_.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,_.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),a.length>0&&(0,_.jsx)("dl",{className:"af-space-y-1",children:a.map(([s,n])=>(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,_.jsx)("dt",{className:X(Uf,"af-w-28 af-shrink-0 af-capitalize"),children:Wf(s)}),(0,_.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Gf(n)})]},s))})]})}function Gc({formName:e,createdAt:t,data:a,onDelete:s}){return(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)(ie,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,_.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,_.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:rr(t)}),(0,_.jsx)(Zs,{iconOnly:!0,onDelete:s})]}),(0,_.jsx)(Kf,{data:a})]})}function Zf(e){return e.charged_total??e.amount_total}function Yf({email:e,refreshKey:t,onBack:a,onRemoved:s}){let{api:n}=W(),{person:r,isLoading:i,error:l,refetch:u}=zr(e,{refreshKey:t}),c=async f=>{await n.deleteSubmission(f),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?u():a()},o=zo(e,r?.submissions[0]?.form_name);return(0,_.jsxs)("div",{children:[(0,_.jsxs)("div",{className:"af-mb-6",children:[(0,_.jsxs)(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,_.jsx)(Wt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,_.jsxs)("div",{className:"af-min-w-0",children:[i?(0,_.jsx)(Q,{className:"af-h-7 af-w-48"}):(0,_.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),(0,_.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,_.jsx)(Hf,{value:e,label:"Copy email address"})]})]}),(0,_.jsx)(y,{asChild:!0,children:(0,_.jsxs)("a",{href:o,children:[(0,_.jsx)(Wt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),i?(0,_.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(f=>(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsx)(Q,{className:"af-w-40"}),(0,_.jsx)(Q,{className:"af-mt-2 af-w-64"})]},f)),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):l||!r?(0,_.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,_.jsx)(wt,{message:"Couldn't load this person.",onRetry:()=>u()})}):(0,_.jsxs)("div",{className:"af-space-y-6",children:[r.customer&&(0,_.jsxs)("div",{children:[(0,_.jsx)("h4",{className:X(Ho,"af-mb-3"),children:"Customer"}),(0,_.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&(0,_.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,_.jsx)("dd",{children:r.customer.name})]}),r.customer.phone&&(0,_.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,_.jsx)("dd",{children:r.customer.phone})]}),(0,_.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,_.jsx)("dd",{children:rr(r.customer.created_at)})]})]})]}),r.orders.length>0&&(0,_.jsxs)("div",{children:[(0,_.jsx)("h4",{className:X(Ho,"af-mb-3"),children:"Purchases"}),(0,_.jsx)("div",{className:"af-overflow-x-auto",children:(0,_.jsxs)(ft,{children:[(0,_.jsx)(mt,{children:(0,_.jsxs)(Ue,{children:[(0,_.jsx)(te,{children:"Order"}),(0,_.jsx)(te,{children:"Date"}),(0,_.jsx)(te,{className:"af-text-right",children:"Total"}),(0,_.jsx)(te,{children:"Status"})]})}),(0,_.jsx)(pt,{children:r.orders.map(f=>(0,_.jsxs)(Ue,{children:[(0,_.jsx)(ae,{className:"af-whitespace-nowrap af-font-medium",children:Xn(f)}),(0,_.jsx)(ae,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rr(f.created_at)}),(0,_.jsx)(ae,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:re(Zf(f),f.currency)}),(0,_.jsx)(ae,{children:(0,_.jsx)(ms,{status:f.status})})]},f.id))})]})}),(0,_.jsx)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),r.submissions.length>0&&(0,_.jsxs)("div",{children:[(0,_.jsx)("h4",{className:X(Ho,"af-mb-3"),children:"Messages"}),(0,_.jsx)("div",{className:"af-space-y-3",children:r.submissions.map(f=>(0,_.jsx)(Gc,{formName:f.form_name,createdAt:f.created_at,data:f.data,onDelete:()=>c(f.id)},f.id))})]})]})]})}function Jf({submissionId:e,onBack:t,onRemoved:a}){let{api:s}=W(),[n,r]=Da.useState(null),[i,l]=Da.useState(!0),[u,c]=Da.useState(null),[o,f]=Da.useState(0);return Da.useEffect(()=>{let b=!1;return l(!0),c(null),s.getSubmission(e).then(g=>{b||r(g)}).catch(g=>{b||c(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{b||l(!1)}),()=>{b=!0}},[s,e,o]),(0,_.jsxs)("div",{children:[(0,_.jsxs)("div",{className:"af-mb-6",children:[(0,_.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,_.jsx)(Wt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,_.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,_.jsx)(Q,{className:"af-mt-1 af-h-4 af-w-32"}):n&&(0,_.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:rr(n.metadata.submitted_at)})]}),i?(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,_.jsx)(Q,{className:"af-w-40"}),(0,_.jsx)(Q,{className:"af-mt-2 af-w-64"}),(0,_.jsx)(Q,{className:"af-mt-2 af-w-52"}),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):u||!n?(0,_.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,_.jsx)(wt,{message:"Couldn't load this submission.",onRetry:()=>f(b=>b+1)})}):(0,_.jsxs)("div",{className:"af-space-y-3",children:[(0,_.jsx)(Gc,{formName:null,createdAt:n.metadata.submitted_at,data:n.data,onDelete:async()=>{await s.deleteSubmission(e),a(),t()}}),(0,_.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"No email address came with this submission, so there is nobody to reply to."})]})]})}var Xf={all:"All",customers:"Customers",leads:"Leads"},Qf=["all","customers","leads"],Wc={all:void 0,customers:"customer",leads:"lead"};function em({refreshKey:e,onBackToWebsite:t,className:a,maxRows:s,onViewAll:n}){let r=typeof s=="number",{people:i,isLoading:l,error:u,page:c,pageSize:o,hasNextPage:f,hasPreviousPage:b,setPage:g,q:m,setQ:v,source:d,setSource:p,refetch:x,refetchAfterRemoval:R}=Hr({refreshKey:e}),[T,h]=Da.useState({kind:"list"}),[k,P]=Da.useState(""),I=d==="customer"?"customers":d==="lead"?"leads":"all",w=q=>{Wc[q]!==d&&p(Wc[q])},{api:E}=W(),L=Da.useCallback(()=>E.exportPeopleCsv({...m?{q:m}:{},...d?{source:d}:{}}),[E,m,d]),C=!r||!!n,Y=q=>{if(r){n?.();return}q.email?h({kind:"person",email:q.email}):q.submission_id&&h({kind:"submission",submissionId:q.submission_id})},G=Da.useRef(!1),z=()=>{G.current=!0},ce=()=>{h({kind:"list"}),G.current?(G.current=!1,R()):x()},ve=q=>{let B=q.trim();B!==m&&v(B)},xe=r?i.slice(0,s):i,D;if(T.kind==="person")D=(0,_.jsx)(Yf,{email:T.email,refreshKey:e,onBack:ce,onRemoved:z});else if(T.kind==="submission")D=(0,_.jsx)(Jf,{submissionId:T.submissionId,onBack:ce,onRemoved:z});else{let q=(0,_.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Qf.map(B=>(0,_.jsx)("button",{type:"button","aria-pressed":I===B,onClick:()=>w(B),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",I===B?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Xf[B]},B))}),(0,_.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,_.jsx)(Wt.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,_.jsx)(de,{type:"text",value:k,onChange:B=>P(B.target.value),onBlur:()=>ve(k),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),ve(k))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),m&&(0,_.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{P(""),v("")},children:"Clear search"}),(0,_.jsx)(ma,{fetchCsv:L,filename:"people",className:"af-ml-auto"})]});if(l)D=(0,_.jsxs)("div",{children:[r?null:q,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(B=>(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,_.jsx)(Q,{className:"af-h-4 af-w-32"}),(0,_.jsx)(Q,{className:"af-h-4 af-w-16"})]}),(0,_.jsx)(Q,{className:"af-mt-2 af-h-5 af-w-28"}),(0,_.jsx)(Q,{className:"af-mt-2 af-h-3 af-w-56"})]},B))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(ft,{children:[(0,_.jsx)(mt,{children:(0,_.jsxs)(Ue,{children:[(0,_.jsx)(te,{children:"Person"}),(0,_.jsx)(te,{children:"Came from"}),(0,_.jsx)(te,{children:"Latest message"}),(0,_.jsx)(te,{children:"Last activity"}),(0,_.jsx)(te,{className:"af-w-8"}),(0,_.jsx)(te,{className:"af-w-8"})]})}),(0,_.jsx)(pt,{"aria-hidden":"true",children:[0,1,2,3,4].map(B=>(0,_.jsxs)(Ue,{children:[(0,_.jsx)(ae,{children:(0,_.jsx)(Q,{className:"af-h-4 af-w-40"})}),(0,_.jsx)(ae,{children:(0,_.jsx)(Q,{className:"af-h-5 af-w-24"})}),(0,_.jsx)(ae,{children:(0,_.jsx)(Q,{className:"af-h-4 af-w-56"})}),(0,_.jsx)(ae,{children:(0,_.jsx)(Q,{className:"af-h-4 af-w-24"})}),(0,_.jsx)(ae,{}),(0,_.jsx)(ae,{})]},B))})]})}),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(u)D=(0,_.jsxs)("div",{children:[r?null:q,(0,_.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,_.jsx)(wt,{message:"Couldn't load your leads.",onRetry:()=>x()})})]});else if(xe.length===0&&c===0){let B=!!m||I!=="all";D=(0,_.jsxs)("div",{children:[B&&q,B?(0,_.jsx)(la,{children:m?"Nobody matches that search.":I==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,_.jsx)(Qs,{icon:Wt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(i.length===0)D=(0,_.jsxs)("div",{children:[r?null:q,(0,_.jsx)(la,{children:"No more results."}),(0,_.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>g(c-1),children:[(0,_.jsx)(Wt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let B=c*o+1,fe=c*o+i.length;D=(0,_.jsxs)("div",{children:[r?null:q,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:xe.map((pe,We)=>(0,_.jsxs)("div",{onClick:C?()=>Y(pe):void 0,className:`af-rounded-md af-border af-p-3${C?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,_.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,_.jsxs)("div",{className:"af-min-w-0",children:[(0,_.jsx)("button",{type:"button",onClick:Ie=>{Ie.stopPropagation(),Y(pe)},disabled:!C,"aria-label":`Open ${pe.name||pe.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${C?" hover:af-underline":""}`,children:qc(pe)}),pe.name&&pe.email&&(0,_.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:pe.email})]}),(0,_.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,_.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:rr(pe.last_activity_at)}),pe.email&&(0,_.jsx)(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,_.jsx)("a",{href:zo(pe.email),onClick:Ie=>Ie.stopPropagation(),"aria-label":`Email ${pe.email}`,children:(0,_.jsx)(Wt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,_.jsx)("div",{className:"af-mt-2",children:jc(pe)}),pe.latest_message_excerpt&&(0,_.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:pe.latest_message_excerpt})]},pe.email??pe.submission_id??We))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(ft,{children:[(0,_.jsx)(mt,{children:(0,_.jsxs)(Ue,{children:[(0,_.jsx)(te,{children:"Person"}),(0,_.jsx)(te,{children:"Came from"}),(0,_.jsx)(te,{children:"Latest message"}),(0,_.jsx)(te,{children:"Last activity"}),(0,_.jsx)(te,{className:"af-w-8",children:(0,_.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,_.jsx)(te,{className:"af-w-8"})]})}),(0,_.jsx)(pt,{children:xe.map((pe,We)=>(0,_.jsxs)(Ue,{onClick:C?()=>Y(pe):void 0,className:C?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,_.jsxs)(ae,{className:"af-max-w-[260px] af-font-medium",children:[(0,_.jsx)("button",{type:"button",onClick:Ie=>{Ie.stopPropagation(),Y(pe)},disabled:!C,"aria-label":`Open ${pe.name||pe.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${C?" hover:af-underline":""}`,children:qc(pe)}),pe.name&&pe.email&&(0,_.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:pe.email})]}),(0,_.jsx)(ae,{children:jc(pe)}),(0,_.jsx)(ae,{className:"af-max-w-[320px]",children:pe.latest_message_excerpt?(0,_.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:pe.latest_message_excerpt}):(0,_.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,_.jsx)(ae,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rr(pe.last_activity_at)}),(0,_.jsx)(ae,{className:"af-w-8",children:pe.email&&(0,_.jsx)(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,_.jsx)("a",{href:zo(pe.email),onClick:Ie=>Ie.stopPropagation(),"aria-label":`Email ${pe.email}`,children:(0,_.jsx)(Wt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,_.jsx)(ae,{className:"af-w-8 af-text-right",children:(0,_.jsx)(Wt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},pe.email??pe.submission_id??We))})]})}),!r&&(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,_.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${B}-${fe}`}),(0,_.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>g(c-1),disabled:!b,children:[(0,_.jsx)(Wt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>g(c+1),disabled:!f,children:["Next",(0,_.jsx)(Wt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?(0,_.jsx)("div",{className:a,children:D}):(0,_.jsx)(Ft,{title:"Leads",onBackToWebsite:t,hideBackButton:T.kind!=="list",className:a,children:D})}function jr(e){return(0,_.jsx)(em,{...e},e.maxRows==null?"full":"compact")}var Xc=le(require("react"),1),Bs=require("lucide-react");var Oa=le(require("react"),1);function qr({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=W(),[s,n]=Oa.useState([]),[r,i]=Oa.useState(0),[l,u]=Oa.useState(!0),[c,o]=Oa.useState(null),[f,b]=Oa.useState(0),[g,m]=Oa.useState(e),[v,d]=Oa.useState(void 0),p=Oa.useRef(0),x=Oa.useCallback(async()=>{let T=++p.current;try{u(!0),o(null);let h={limit:g,offset:f*g};v&&(h.status=v);let k=await a.getSubscriptions(h);if(T!==p.current)return;n(k.subscriptions),i(k.total)}catch(h){if(T!==p.current)return;o(h instanceof Error?h:new Error("Failed to fetch subscriptions"))}finally{T===p.current&&u(!1)}},[a,f,g,v,t]);Oa.useEffect(()=>{x()},[x]);let R=Math.ceil(r/g);return{subscriptions:s,total:r,isLoading:l,error:c,page:f,pageSize:g,hasNextPage:f<R-1,hasPreviousPage:f>0,setPage:b,setPageSize:T=>{m(T),b(0)},status:v,setStatus:T=>{d(T),b(0)},refetch:x}}var K=require("react/jsx-runtime");function Kc(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 Zc({sub:e}){return e.status==="canceled"?(0,K.jsx)(ie,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,K.jsx)(ie,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,K.jsx)(ie,{variant:"warning",children:"Scheduled to cancel"}):(0,K.jsx)(ie,{variant:"success",children:"Active"}):(0,K.jsx)(ie,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function tm(e,t){let a=re(t,e.currency);return e.plan_interval_count===1?`${a} / ${e.plan_interval}`:`${a} every ${e.plan_interval_count} ${e.plan_interval}s`}function Yc({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,K.jsxs)("div",{children:[(0,K.jsx)("div",{className:"af-font-medium af-tabular-nums",children:tm(e,e.current_amount)}),t&&(0,K.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",re(e.plan_amount,e.currency)]})]})}function Jc(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Kc(e.current_period_end)}`:"Ends at period end":e.current_period_end?Kc(e.current_period_end):"\u2014"}function jo({refreshKey:e,onBackToWebsite:t,className:a}){let{subscriptions:s,total:n,isLoading:r,error:i,page:l,pageSize:u,hasNextPage:c,hasPreviousPage:o,setPage:f,status:b,refetch:g}=qr({refreshKey:e}),{api:m}=W(),v=Xc.useCallback(()=>m.exportSubscriptionsCsv(b?{status:b}:{}),[m,b]),d;if(r)d=(0,K.jsxs)("div",{children:[(0,K.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(p=>(0,K.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,K.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,K.jsx)(Q,{className:"af-h-4 af-w-40"}),(0,K.jsx)(Q,{className:"af-h-4 af-w-20"})]}),(0,K.jsx)(Q,{className:"af-mt-2 af-h-3 af-w-32"}),(0,K.jsx)(Q,{className:"af-mt-2 af-h-5 af-w-24"})]},p))}),(0,K.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,K.jsxs)(ft,{children:[(0,K.jsx)(mt,{children:(0,K.jsxs)(Ue,{children:[(0,K.jsx)(te,{children:"Subscriber"}),(0,K.jsx)(te,{children:"Plan"}),(0,K.jsx)(te,{className:"af-text-right",children:"Amount"}),(0,K.jsx)(te,{children:"Renews"}),(0,K.jsx)(te,{children:"Status"})]})}),(0,K.jsx)(pt,{"aria-hidden":"true",children:[0,1,2,3,4].map(p=>(0,K.jsxs)(Ue,{children:[(0,K.jsx)(ae,{children:(0,K.jsx)(Q,{className:"af-h-4 af-w-44"})}),(0,K.jsx)(ae,{children:(0,K.jsx)(Q,{className:"af-h-4 af-w-32"})}),(0,K.jsx)(ae,{className:"af-text-right",children:(0,K.jsx)(Q,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,K.jsx)(ae,{children:(0,K.jsx)(Q,{className:"af-h-4 af-w-24"})}),(0,K.jsx)(ae,{children:(0,K.jsx)(Q,{className:"af-h-5 af-w-20"})})]},p))})]})}),(0,K.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(i)d=(0,K.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,K.jsx)(wt,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(s.length===0&&l===0)d=(0,K.jsx)(la,{icon:(0,K.jsx)(Bs.Repeat,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(s.length===0)d=(0,K.jsxs)("div",{children:[(0,K.jsx)(la,{children:"No more results."}),(0,K.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,K.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>f(l-1),children:[(0,K.jsx)(Bs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let p=l*u+1,x=l*u+s.length;d=(0,K.jsxs)("div",{children:[(0,K.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,K.jsx)(ma,{fetchCsv:v,filename:"subscriptions"})}),(0,K.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(R=>(0,K.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,K.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,K.jsxs)("div",{className:"af-min-w-0",children:[(0,K.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:R.customer_email||(0,K.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,K.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:R.plan_title||"Untitled plan"})]}),(0,K.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,K.jsx)(Yc,{sub:R})})]}),(0,K.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,K.jsx)(Zc,{sub:R}),R.is_test&&(0,K.jsx)(ie,{variant:"outline",children:"Test"}),(0,K.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Jc(R)})]}),(0,K.jsx)(Dn,{deliveries:R.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},R.id))}),(0,K.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,K.jsxs)(ft,{children:[(0,K.jsx)(mt,{children:(0,K.jsxs)(Ue,{children:[(0,K.jsx)(te,{children:"Subscriber"}),(0,K.jsx)(te,{children:"Plan"}),(0,K.jsx)(te,{className:"af-text-right",children:"Amount"}),(0,K.jsx)(te,{children:"Renews"}),(0,K.jsx)(te,{children:"Status"})]})}),(0,K.jsx)(pt,{children:s.map(R=>(0,K.jsxs)(Ue,{children:[(0,K.jsx)(ae,{className:"af-max-w-[240px]",children:(0,K.jsx)("div",{className:"af-truncate af-font-medium",children:R.customer_email||(0,K.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,K.jsx)(ae,{className:"af-max-w-[220px]",children:(0,K.jsx)("div",{className:"af-truncate",children:R.plan_title||(0,K.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,K.jsx)(ae,{className:"af-whitespace-nowrap af-text-right",children:(0,K.jsx)(Yc,{sub:R})}),(0,K.jsx)(ae,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Jc(R)}),(0,K.jsxs)(ae,{children:[(0,K.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,K.jsx)(Zc,{sub:R}),R.is_test&&(0,K.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,K.jsx)(Dn,{deliveries:R.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},R.id))})]})}),(0,K.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,K.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${p}-${x} of ${n}`}),(0,K.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,K.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>f(l-1),disabled:!o,children:[(0,K.jsx)(Bs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,K.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>f(l+1),disabled:!c,children:["Next",(0,K.jsx)(Bs.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,K.jsx)(Ft,{title:"Subscriptions",onBackToWebsite:t,className:a,children:d})}var zn=le(require("react"),1),md=require("lucide-react");var ya=le(require("react"),1);var Ki=le(require("react"),1),Fs=typeof window>"u"?Ki.useEffect:Ki.useLayoutEffect;var Zi=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},am=(e,t)=>e instanceof Error?e:new Error(t);function nm(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 Qc(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function as({siteId:e,refreshKey:t,onSaveInvoiceSettings:a}){let{api:s}=W(),[n,r]=ya.useState(null),[i,l]=ya.useState(!0),[u,c]=ya.useState(null),o=ya.useRef(null),[f,b]=ya.useState(()=>Qc(s,e)),g=f.api!==s||f.siteId!==e,m=f;g&&(m=Qc(s,e),b(m),r(null),l(!0),c(null));let v=ya.useRef(m);Fs(()=>{v.current!==m&&(v.current=m,o.current=null)},[m]);let d=(w,E)=>v.current===w&&E>w.applied,p=(w,E,L)=>d(w,E)?(w.applied=E,o.current=L,r(L),l(!1),!0):!1,x=async w=>{for(;w.writing;)await w.idle;let E=++w.seq;try{let L=await w.api.getSite(w.siteId);return p(w,E,L)&&c(null),{seq:E,error:null}}catch(L){return{seq:E,error:am(L,"Failed to load store settings")}}},R=(w,E)=>{let L=async()=>{if(v.current!==w)throw new Error("Not saved: the store switched to another site first.");w.writing=!0,w.idle=new Promise(Y=>{w.markIdle=Y});try{return await E(++w.seq)}finally{w.writing=!1,w.markIdle()}},C=w.queue.then(L,L);return w.queue=C.catch(()=>{}),C},T=ya.useCallback(async()=>{let w=await x(m);w.error&&d(m,w.seq)&&(c(w.error),l(!1))},[m]);ya.useEffect(()=>{T()},[T,t]);let h=ya.useCallback(w=>R(m,async E=>{let L=await m.api.updateSite(m.siteId,w),{currency_restatement:C,...Y}=L;return p(m,E,Y)&&c(G=>G instanceof Zi?G:null),L}),[m]),k=ya.useRef(a);Fs(()=>{k.current=a});let P=ya.useCallback(async(w,E)=>{await R(m,()=>w());let L=await x(m);return L.error&&d(m,L.seq)&&o.current&&(p(m,L.seq,{...o.current,...E}),c(new Zi(`Saved, but couldn't refresh settings: ${L.error.message}`))),v.current===m?o.current:null},[m]),I=ya.useCallback(w=>{let E=k.current;return P(()=>E(w),nm(w))},[P]);return{site:g?null:n,isLoading:g||i,error:g?null:u,refetch:T,updateSite:h,saveInvoiceSettings:a?I:null}}var na=le(require("react"),1),Go=require("lucide-react");var Dt=require("react/jsx-runtime");function Yi(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",ed="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",td="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 La({children:e}){return(0,Dt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Wr({children:e}){return(0,Dt.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var Hn=na.forwardRef(function({id:t,title:a,description:s,children:n},r){let i=`af-store-${t}-title`;return(0,Dt.jsxs)("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":i,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[(0,Dt.jsxs)("div",{className:"af-space-y-1",children:[(0,Dt.jsx)("h3",{id:i,className:"af-text-sm af-font-semibold",children:a}),s&&(0,Dt.jsx)(La,{children:s})]}),n]})});function Ji({label:e,description:t,checked:a,onSave:s,disabled:n=!1,disabledReason:r}){let[i,l]=na.useState(null),[u,c]=na.useState(null),o=i??a,f=async b=>{l(b),c(null);try{await s(b)}catch(g){c(Yi(g))}finally{l(null)}};return(0,Dt.jsxs)("div",{className:"af-space-y-1",children:[(0,Dt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,Dt.jsx)("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":o,checked:o,disabled:n||i!==null,onChange:b=>void f(b.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),(0,Dt.jsxs)("span",{className:"af-space-y-0.5",children:[(0,Dt.jsxs)("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,i!==null&&(0,Dt.jsx)(Go.Loader2,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&(0,Dt.jsx)(La,{children:t})]})]}),(n&&r||u)&&(0,Dt.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[n&&r&&(0,Dt.jsx)(La,{children:r}),u&&(0,Dt.jsx)(Wr,{children:u})]})]})}var Wo=(e,t)=>JSON.stringify(e)===JSON.stringify(t),qo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function sm(e,t,a,s=[]){if(!qo(e)||!qo(t)||!qo(a))return{draft:Wo(e,t)?a:e,dropped:[]};let n=[],r={...a};for(let i of Object.keys(a))Wo(e[i],t[i])||(s.includes(i)?n.push(i):r[i]=e[i]);return{draft:r,dropped:n}}function ir(e,t){let a=JSON.stringify(e),[s,n]=na.useState(e),[r,i]=na.useState([]),l=na.useRef(e),u=na.useRef(e),c=na.useRef(s);Fs(()=>{u.current=e,c.current=s});let o=na.useRef(t?.when);na.useEffect(()=>{let b=Object.is(o.current,t?.when)?[]:t?.fields??[];if(o.current=t?.when,Wo(l.current,u.current)&&b.length===0)return;let g=sm(c.current,l.current,u.current,b);l.current=u.current,n(g.draft),g.dropped.length&&i(g.dropped)},[a,t?.when]);let f=na.useCallback(b=>{n(b??u.current),i([])},[]);return{draft:s,setDraft:n,dirty:JSON.stringify(s)!==a,reset:f,dropped:r}}function or({dirty:e,saving:t,error:a,onSave:s,onDiscard:n}){return e?(0,Dt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Dt.jsxs)(y,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&(0,Dt.jsx)(Go.Loader2,{className:"af-animate-spin"}),"Save"]}),(0,Dt.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:n,children:"Discard"}),a&&(0,Dt.jsx)("p",{role:"alert",className:X("af-text-sm af-text-destructive"),children:a})]}):null}function lr(){let[e,t]=na.useState(!1),[a,s]=na.useState(null),n=na.useCallback(async r=>{t(!0),s(null);try{await r()}catch(i){s(Yi(i))}finally{t(!1)}},[]);return{saving:e,error:a,setError:s,run:n}}function ad({what:e}){return(0,Dt.jsxs)(La,{children:["Only the site owner can change ",e,"."]})}var bn=le(require("react"),1),Ms=require("lucide-react");var Z=require("react/jsx-runtime"),Zo=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function id({site:e,updateSite:t}){return(0,Z.jsxs)("div",{className:"af-space-y-4",children:[(0,Z.jsx)(Ji,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:a=>t({collect_phone_at_checkout:a})}),e.checkout_marketing_consent!==void 0&&(0,Z.jsx)(Ji,{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 nd(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 od({site:e,updateSite:t,refetch:a,providerSlot:s,currencyChanging:n=!1}){let{draft:r,setDraft:i,dirty:l,reset:u,dropped:c}=ir(nd(e),{when:e.currency,fields:["rates","threshold"]}),{saving:o,error:f,setError:b,run:g}=lr(),m=e.currency.toUpperCase(),v=()=>g(async()=>{let p={},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 T=x.length?x:null;Zo(T,e.shipping_countries)||(p.shipping_countries=T);let h=[];for(let w of r.rates){let E=w.label.trim(),L=oa(w.amount,e.currency);if(!E)throw new Error("Every rate needs a name.");if(w.amount.trim()===""||L===null)throw new Error(`Enter a price for "${E}" (0 for free).`);h.push({label:E,amount:L})}let k=h.length?h:null;Zo(k,e.shipping_rates)||(p.shipping_rates=k);let P=null;if(r.threshold.trim()!==""&&(P=oa(r.threshold,e.currency),P===null||P===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(P!==e.free_shipping_over&&(p.free_shipping_over=P),Object.keys(p).length===0){u();return}("shipping_rates"in p||"free_shipping_over"in p)&&(p.expected_currency=e.currency);let I;try{I=await t(p)}catch(w){throw w instanceof Gt&&w.details?.code==="currency_changed"&&await a?.(),w}u(nd(I))}),d=(p,x)=>i({...r,rates:r.rates.map((R,T)=>T===p?{...R,...x}:R)});return(0,Z.jsxs)("fieldset",{disabled:o||n,className:"af-space-y-4",children:[(0,Z.jsxs)("label",{className:_n,children:["Countries you ship to",(0,Z.jsx)(de,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:p=>i({...r,countries:p.target.value})}),(0,Z.jsx)(La,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsxs)("p",{className:"af-text-sm",children:["Flat shipping rates (",m,")"]}),r.rates.length===0&&(0,Z.jsx)(La,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((p,x)=>(0,Z.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Z.jsx)(de,{"aria-label":`Rate ${x+1} name`,value:p.label,placeholder:"Standard",onChange:R=>d(x,{label:R.target.value})}),(0,Z.jsx)(de,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:p.amount,placeholder:"0",className:"af-w-32",onChange:R=>d(x,{amount:R.target.value})}),(0,Z.jsx)(y,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${x+1}`,onClick:()=>i({...r,rates:r.rates.filter((R,T)=>T!==x)}),children:(0,Z.jsx)(Ms.X,{})})]},x)),(0,Z.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[(0,Z.jsx)(Ms.Plus,{})," Add rate"]}),(0,Z.jsx)(La,{children:"Buyers pick one at checkout. The first is preselected."})]}),(0,Z.jsxs)("label",{className:_n,children:["Free shipping over (",m,")",(0,Z.jsx)(de,{"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})}),(0,Z.jsx)(La,{children:"Orders at or above this get the cheapest rate free."})]}),c.length>0&&(0,Z.jsxs)("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",m,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),(0,Z.jsx)(or,{dirty:l,saving:o,error:f,onSave:()=>void v(),onDiscard:()=>{b(null),u()}}),s]})}var Ko="exclusive",rm=[{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 im({href:e,children:t}){return(0,Z.jsxs)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"af-inline-flex af-items-center af-gap-1 af-font-medium af-underline af-underline-offset-2 hover:af-text-foreground",children:[t,(0,Z.jsx)(Ms.ExternalLink,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function ld({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=ir(e.tax_behavior??Ko),{saving:i,error:l,setError:u,run:c}=lr(),[o,f]=bn.useState(!1),b=e.stripe_tax_enabled,g=b||o,m=()=>c(async()=>{let p=a;if(p===e.tax_behavior){r();return}let x={tax_behavior:p};p!=="inclusive"&&e.tax_rate_bps!=null&&(x.tax_rate_bps=null);let R=await t(x);r(R.tax_behavior??Ko)}),v=()=>c(async()=>{let p={stripe_tax_enabled:!0,tax_behavior:a};a!=="inclusive"&&e.tax_rate_bps!=null&&(p.tax_rate_bps=null);let x=await t(p);r(x.tax_behavior??Ko),f(!1)}),d=(n||o)&&a!=="inclusive"&&e.tax_rate_bps!=null;return(0,Z.jsxs)("div",{className:"af-space-y-5",children:[(0,Z.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[(0,Z.jsx)("p",{children:"Tax at checkout is calculated by Stripe Tax, which you set up in your Stripe Dashboard (Settings \u2192 Tax): your business address, a default product tax code, and the places you're registered to collect tax."}),(0,Z.jsx)("p",{children:"Stripe only collects tax where you've added a registration; anywhere else the tax comes out as zero. Stripe Tax has its own fees, and what it covers (such as filing) depends on your Stripe Tax plan."}),(0,Z.jsx)("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:rm.map(p=>(0,Z.jsx)("li",{children:(0,Z.jsx)(im,{href:p.href,children:p.label})},p.href))})]}),(0,Z.jsx)(Ji,{label:"Stripe automatic tax",description:b?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:g,onSave:async p=>{if(o){f(!1),u(null),r();return}if(p&&!e.tax_behavior){f(!0);return}return t({stripe_tax_enabled:p})}}),g&&(0,Z.jsxs)("fieldset",{disabled:i,className:"af-space-y-4 af-pl-6",children:[(0,Z.jsxs)("label",{className:_n,children:["Do your prices already include tax?",(0,Z.jsxs)("select",{"aria-label":"Your prices",className:ed,value:a,onChange:p=>s(p.target.value),children:[(0,Z.jsx)("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),(0,Z.jsx)("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),(0,Z.jsx)(La,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),d&&(0,Z.jsxs)(La,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),o?(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Z.jsx)(y,{type:"button",size:"sm",disabled:i,onClick:()=>void v(),children:"Turn on"}),(0,Z.jsx)(y,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>{f(!1),u(null),r()},children:"Cancel"})]}),l&&(0,Z.jsx)(Wr,{children:l})]}):(0,Z.jsx)(or,{dirty:n,saving:i,error:l,onSave:()=>void m(),onDiscard:()=>{u(null),r()}})]})]})}function sd(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function cd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=ir(sd(e)),{saving:i,error:l,setError:u,run:c}=lr(),o=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),f=()=>c(async()=>{let b={},g=null;if(o&&a.rate.trim()!==""){let p=Number(a.rate);if(!Number.isFinite(p)||p<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(p*100)}o&&g!==e.tax_rate_bps&&(b.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let m=a.taxId.trim()||null;m!==e.tax_id&&(b.tax_id=m);let v=a.label.trim()||null;if(v!==e.tax_label&&(b.tax_label=v),Object.keys(b).length===0){r();return}let d=await t(b);r(sd(d))});return(0,Z.jsxs)("fieldset",{disabled:i,className:"af-space-y-4",children:[(0,Z.jsxs)("label",{className:_n,children:["Tax rate (%)",(0,Z.jsx)(de,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!o,value:o?a.rate:"",onChange:b=>s({...a,rate:b.target.value})}),(0,Z.jsx)(La,{children:o?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),(0,Z.jsxs)("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[(0,Z.jsxs)("label",{className:_n,children:["Tax ID",(0,Z.jsx)(de,{"aria-label":"Tax ID",value:a.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...a,taxId:b.target.value})})]}),(0,Z.jsxs)("label",{className:_n,children:["Tax label",(0,Z.jsx)(de,{"aria-label":"Tax label",value:a.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...a,label:b.target.value})})]})]}),(0,Z.jsx)(or,{dirty:n,saving:i,error:l,onSave:()=>void f(),onDiscard:()=>{u(null),r()}})]})}function dd({site:e,updateSite:t,onChangeStart:a}){let[s,n]=bn.useState(e.currency.toUpperCase()),[r,i]=bn.useState(!1),[l,u]=bn.useState(!1),[c,o]=bn.useState(null),f=e.currency.toUpperCase(),b=bn.useRef(f);bn.useEffect(()=>{b.current!==f&&(n(p=>p===b.current?f:p),b.current=f)},[f]);let g=s.trim().toUpperCase(),m=g!==f,v=/^[A-Z]{3}$/.test(g),d=async()=>{u(!0);let p=a?.(),x=!1;o(null);try{let R=await t({currency:g.toLowerCase()});x=!0;let T=R.currency_restatement;T&&!T.applied?o(T.reason?`Not changed: ${T.reason}.`:"The currency was not changed."):(n(R.currency.toUpperCase()),b.current=R.currency.toUpperCase()),i(!1)}catch(R){o(Yi(R))}finally{u(!1),p?.(x)}};return(0,Z.jsxs)("div",{className:"af-space-y-3",children:[(0,Z.jsxs)("div",{className:"af-flex af-items-end af-gap-2",children:[(0,Z.jsxs)("label",{className:_n,children:["Store currency",(0,Z.jsx)(de,{"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&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(y,{type:"button",size:"sm",disabled:!v,onClick:()=>i(!0),children:"Change currency"}),(0,Z.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>{n(f),o(null)},children:"Discard"})]})]}),(0,Z.jsx)(La,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&(0,Z.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,Z.jsxs)("p",{className:"af-text-sm",children:["Change the store currency from ",f," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",re(2e3,f)," becomes ",re(2e3,g),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),(0,Z.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Z.jsx)(y,{type:"button",size:"sm",disabled:l,onClick:()=>void d(),children:"Confirm change"}),(0,Z.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:l,onClick:()=>i(!1),children:"Cancel"})]})]}),c&&(0,Z.jsx)(Wr,{children:c})]})}function rd(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function om(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 ud({site:e,save:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=ir(rd(e)),{saving:i,error:l,setError:u,run:c}=lr();if(!t)return(0,Z.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,Z.jsxs)("p",{children:["Due ",e.invoice_due_days," days after sending"]}),(0,Z.jsxs)("p",{children:["Reminders: ",om(e.invoice_reminder_schedule)]}),(0,Z.jsxs)("p",{children:["Footer: ",e.invoice_footer||"None"]}),(0,Z.jsx)(ad,{what:"invoice defaults"})]});let o=()=>c(async()=>{let f={},b=Number(a.dueDays);if(a.dueDays.trim()===""||!Number.isInteger(b)||b<0||b>90)throw new Error("Due days must be a whole number from 0 to 90.");b!==e.invoice_due_days&&(f.due_days=b);let m=a.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(m.some(x=>!Number.isInteger(x)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let v=[...new Set(m)].sort((x,R)=>x-R);Zo(v,e.invoice_reminder_schedule)||(f.reminder_schedule=v);let d=a.footer.trim()||null;if(d!==e.invoice_footer&&(f.footer=d),Object.keys(f).length===0){r();return}let p=await t(f);r(p?rd(p):void 0)});return(0,Z.jsxs)("fieldset",{disabled:i,className:"af-space-y-4",children:[(0,Z.jsxs)("label",{className:_n,children:["Days until due",(0,Z.jsx)(de,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:a.dueDays,onChange:f=>s({...a,dueDays:f.target.value})})]}),(0,Z.jsxs)("label",{className:_n,children:["Reminder schedule",(0,Z.jsx)(de,{"aria-label":"Reminder schedule",value:a.reminders,placeholder:"Off",onChange:f=>s({...a,reminders:f.target.value})}),(0,Z.jsx)(La,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),(0,Z.jsxs)("label",{className:_n,children:["Invoice footer",(0,Z.jsx)("textarea",{"aria-label":"Invoice footer",className:td,maxLength:300,value:a.footer,onChange:f=>s({...a,footer:f.target.value})})]}),(0,Z.jsx)(or,{dirty:n,saving:i,error:l,onSave:()=>void o(),onDiscard:()=>{u(null),r()}})]})}function fd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=ir(e.default_email_recipients),{saving:i,error:l,setError:u,run:c}=lr(),[o,f]=bn.useState(""),[b,g]=bn.useState(null),m=()=>{let d=o.trim().toLowerCase();if(d){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d)){g("Enter a valid email address.");return}if(a.some(p=>p.toLowerCase()===d)){g("Already added.");return}s([...a,d]),f(""),g(null)}},v=()=>c(async()=>{let d=await t({default_email_recipients:a});r(d.default_email_recipients)});return(0,Z.jsxs)("fieldset",{disabled:i,className:"af-space-y-3",children:[(0,Z.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[a.map(d=>(0,Z.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[d,(0,Z.jsx)("button",{type:"button","aria-label":`Remove ${d}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(a.filter(p=>p!==d)),children:(0,Z.jsx)(Ms.X,{className:"af-h-3 af-w-3"})})]},d)),a.length===0&&(0,Z.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),(0,Z.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Z.jsx)(de,{"aria-label":"Add notification email",type:"email",value:o,placeholder:"Add email address",onChange:d=>{f(d.target.value),g(null)},onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),m())}}),(0,Z.jsx)(y,{type:"button",variant:"outline",disabled:!o.trim(),onClick:m,children:"Add"})]}),b&&(0,Z.jsx)(Wr,{children:b}),(0,Z.jsx)(or,{dirty:n,saving:i,error:l,onSave:()=>void v(),onDiscard:()=>{u(null),r()}})]})}var pa=require("react/jsx-runtime");function Yo({siteId:e,refreshKey:t,section:a,shippingProviderSlot:s,onConnectStripe:n,onUpgradePlan:r,className:i}){let{site:l,isLoading:u,error:c,refetch:o,updateSite:f}=as({siteId:e,refreshKey:t}),b=zn.useRef(o),g=zn.useRef(e);Fs(()=>{b.current=o,g.current=e});let m=zn.useRef({}),[v,d]=zn.useState([]),p=v.some(k=>k.siteId===e),x=zn.useCallback(()=>{let k={siteId:e},P=b.current;return d(I=>[...I,k]),I=>{let w=()=>d(L=>L.filter(C=>C!==k));!(g.current===k.siteId)||I&&b.current===P?w():b.current().finally(w)}},[e]),R=k=>P=>{m.current[k]=P},T=l!==null&&l.payments_active;if(zn.useEffect(()=>{if(!T||!a)return;let k=m.current[a];k&&(k.scrollIntoView?.({behavior:"smooth",block:"start"}),k.focus({preventScroll:!0}))},[T,a]),u)return(0,pa.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,pa.jsx)(md.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!l)return(0,pa.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c?.message??"Could not load store settings."});if(!l.payments_active)return(0,pa.jsx)(As,{className:i,onConnectStripe:n,onUpgradePlan:r,whenActive:(0,pa.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let h={site:l,updateSite:f,refetch:o};return(0,pa.jsxs)("div",{className:`af-space-y-6 ${i??""}`,children:[c&&(0,pa.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c.message}),(0,pa.jsx)(Hn,{ref:R("checkout"),id:"checkout",title:"Checkout",children:(0,pa.jsx)(id,{...h})}),(0,pa.jsx)(Hn,{ref:R("shipping"),id:"shipping",title:"Shipping",children:(0,pa.jsx)(od,{...h,providerSlot:s,currencyChanging:p})}),(0,pa.jsx)(Hn,{ref:R("tax"),id:"tax",title:"Tax",children:(0,pa.jsx)(ld,{...h})}),(0,pa.jsx)(Hn,{ref:R("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:(0,pa.jsx)(dd,{...h,onChangeStart:x})})]},e)}var pd=require("lucide-react");var kn=require("react/jsx-runtime");function Gr({siteId:e,refreshKey:t,onSaveInvoiceSettings:a,className:s}){let{site:n,isLoading:r,error:i,updateSite:l,refetch:u,saveInvoiceSettings:c}=as({siteId:e,refreshKey:t,onSaveInvoiceSettings:a});return r?(0,kn.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,kn.jsx)(pd.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):n?(0,kn.jsxs)("div",{className:`af-space-y-6 ${s??""}`,children:[i&&(0,kn.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i.message}),(0,kn.jsx)(Hn,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:(0,kn.jsx)(ud,{site:n,save:c})}),(0,kn.jsx)(Hn,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:(0,kn.jsx)(cd,{site:n,updateSite:l,refetch:u})})]},e):(0,kn.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i?.message??"Could not load invoice settings."})}var gd=require("lucide-react");var ns=require("react/jsx-runtime");function Jo({siteId:e,refreshKey:t,className:a}){let{site:s,isLoading:n,error:r,updateSite:i,refetch:l}=as({siteId:e,refreshKey:t});return n?(0,ns.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ns.jsx)(gd.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?(0,ns.jsxs)("div",{className:`af-space-y-3 ${a??""}`,children:[r&&(0,ns.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r.message}),(0,ns.jsx)(Hn,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:(0,ns.jsx)(fd,{site:s,updateSite:i,refetch:l})})]},e):(0,ns.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r?.message??"Could not load notification settings."})}var cr=le(require("react"),1);var St=require("react/jsx-runtime");function Xo({refreshKey:e,initialInvoiceId:t,onBackToWebsite:a,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,siteId:i,onSaveInvoiceSettings:l,className:u}){let{aggregates:c,isLoading:o,error:f,refetch:b}=Es({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=Os({refreshKey:e}),{api:m}=W(),v=g.filters,d=cr.useCallback(()=>m.exportRetainersCsv(v),[m,v]),[p,x]=cr.useState(!1),[R,T]=cr.useState(null),[h,k]=cr.useState(!1),P=(0,St.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:f||!o&&!c?(0,St.jsxs)("div",{role:"alert",className:"sm:af-col-span-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't load invoice totals. ",(0,St.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):o||!c?(0,St.jsxs)(St.Fragment,{children:[(0,St.jsx)(gt,{label:"Outstanding",children:(0,St.jsx)(Q,{className:"af-h-6 af-w-24"})}),(0,St.jsx)(gt,{label:"Overdue",children:(0,St.jsx)(Q,{className:"af-h-6 af-w-24"})}),(0,St.jsx)(gt,{label:"Paid this month",children:(0,St.jsx)(Q,{className:"af-h-6 af-w-24"})})]}):(0,St.jsxs)(St.Fragment,{children:[(0,St.jsx)(gt,{label:"Outstanding",detail:`${c.outstanding.count} open`,children:re(c.outstanding.amount,c.currency)}),(0,St.jsx)(gt,{label:"Overdue",detail:c.overdue.count===0?"Nothing overdue":`${c.overdue.count} overdue`,valueClassName:c.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:re(c.overdue.amount,c.currency)}),(0,St.jsx)(gt,{label:"Paid this month",detail:`${c.paid_this_month.count} paid`,children:re(c.paid_this_month.amount,c.currency)})]})});return(0,St.jsxs)(Ft,{title:"Invoices",onBackToWebsite:a,hideBackButton:p,className:u,children:[P,i&&!p&&(0,St.jsxs)("div",{className:"af-mb-6",children:[(0,St.jsx)(y,{type:"button",variant:"outline",size:"sm","aria-expanded":h,"aria-controls":"af-invoice-settings",onClick:()=>k(I=>!I),children:"Invoice settings"}),h&&(0,St.jsx)("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:(0,St.jsx)(Gr,{siteId:i,refreshKey:e,onSaveInvoiceSettings:l})})]}),!p&&(0,St.jsx)(Is,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:R?.id??null,onShowCycles:I=>T(w=>w?.id===I.id?null:I),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded,exportCsv:d}),(0,St.jsx)(ts,{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:()=>T(null)})]})}var Xt=le(require("react"),1);var hn=le(require("react"),1);function Mt(e,t,a){let[s,n]=hn.useState(null),[r,i]=hn.useState(!0),[l,u]=hn.useState(null),c=hn.useRef(0),o=hn.useRef(e);o.current=e;let f=hn.useRef(a);f.current=a;let b=hn.useCallback(async()=>{let m=++c.current,v=f.current;i(!0),u(null);try{let d=await o.current();m===c.current&&n({scope:v,value:d})}catch(d){m===c.current&&u(d instanceof Error?d:new Error("Request failed"))}finally{m===c.current&&i(!1)}},[]);hn.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 Xi={commitBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts"},cancelBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts/{sendId}/cancel",params:["sendId"]},createDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts"},updateDraft:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},deleteDraft:{method:"DELETE",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},testSendDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/test",params:["draftId"]},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 vd(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Xi,e)}function bd(e,t,a){let s=Xi[e],n="params"in s?s.params:[],r={...a};delete r.siteId;let i=s.path.replace("{siteId}",encodeURIComponent(t));for(let u of n){let c=r[u];if(typeof c!="string"&&typeof c!="number")throw new Error(`${e} needs ${u}`);i=i.replace(`{${u}}`,encodeURIComponent(String(c))),delete r[u]}let l=s.method==="GET"||s.method==="DELETE"?void 0:r;return{method:s.method,path:i,body:l}}var Qo={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."},Kr=new Set(["sending_not_enabled","domain_not_verified","dmarc_missing","postal_address_missing"]);function ss(e){return e?Qo[e]??"Sending is not available right now.":null}var jn=le(require("react"),1);var $s=50;function Zr({siteId:e,q:t="",offset:a=0,refreshKey:s=0}){let{api:n}=W(),r=Mt(()=>n.getMarketingContacts(e,{q:t||void 0,limit:$s,offset:a}),`${e}|${t}|${a}|${s}`,e),i=Mt(()=>n.getMarketingContactStats(e),`${e}|${s}`,e),l=Mt(()=>n.getMarketingTags(e),`${e}|${s}`,e);return{contacts:r,stats:i,tags:l,refetchAll:async()=>{await Promise.all([r.refetch(),i.refetch(),l.refetch()])}}}var Vs=le(require("react"),1);var Pn=le(require("react"),1);var Cn=require("react/jsx-runtime"),Yr=e=>`af-email-settings-${e}`,el=Pn.createContext(null);function Xe(){let e=Pn.useContext(el);if(!e)throw new Error("Email panels render inside EmailView");return e}function hd(e){let{setInlineEditOpen:t}=Xe();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 Qi(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 da({onClick:e,children:t}){return(0,Cn.jsx)("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function dr({reason:e}){let{openSetup:t,onOpenStoreSettings:a}=Xe(),s=e&&Kr.has(e)?(0,Cn.jsx)(da,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&a?(0,Cn.jsx)(da,{onClick:a,children:"Open Store settings"}):null;return s&&(0,Cn.jsxs)(Cn.Fragment,{children:[" ",s]})}function vs(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 Ba(e,t){return vs(e)===t?!0:e instanceof Error&&e.message.includes(t)}function ur(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function bt(){let{onOrgAction:e}=Xe(),[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(u){return n(ur(u)),{ok:!1,error:u}}finally{a(!1)}},[e]);return{busy:t,error:s,setError:n,run:r}}function he({tone:e="info",children:t,className:a}){return(0,Cn.jsx)("div",{role:e==="error"?"alert":"status",className:X("af-rounded-md af-border af-px-3 af-py-2 af-text-sm",e==="warning"&&"af-border-yellow-300 af-bg-yellow-50 af-text-yellow-900",e==="error"&&"af-border-destructive af-bg-destructive/10 af-text-destructive",e==="success"&&"af-border-green-300 af-bg-green-50 af-text-green-900",a),children:t})}function xa({children:e,action:t,id:a}){return(0,Cn.jsxs)("div",{id:a,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[(0,Cn.jsx)("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function He(e){return e.toLocaleString("en-US")}function Us(e,t){return`${e} ${t}${e===1?"":"s"}`}var Nt=require("react/jsx-runtime"),eo="I confirm that everyone in this file agreed to receive marketing email from my business.",lm={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 Jr({onImported:e}){let{canWrite:t}=Xe(),[a,s]=Vs.useState(""),[n,r]=Vs.useState(null),[i,l]=Vs.useState(""),[u,c]=Vs.useState(!1),[o,f]=Vs.useState(!1),[b,g]=Vs.useState(null),m=bt(),v=async()=>{if(!u||!a.trim())return;let d=i.split(",").map(x=>x.trim()).filter(Boolean),p=await m.run("importContacts",{csv:a,attested:!0,...d.length?{tags:d}:{},...o?{enroll_automations:!0}:{}});if(p.ok){let x=p.result;g(x),e?.(x)}};if(b){let d=new Map;for(let p of b.skipped_rows)d.set(p.reason,(d.get(p.reason)??0)+1);return(0,Nt.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[(0,Nt.jsx)("div",{className:"af-font-medium",children:"Import finished"}),(0,Nt.jsxs)("p",{className:"af-text-sm",children:[He(b.rows)," rows: ",He(b.created)," new, ",He(b.updated)," updated, ",He(b.skipped)," skipped."]}),d.size>0&&(0,Nt.jsx)("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...d].map(([p,x])=>(0,Nt.jsxs)("li",{children:[He(x)," ",lm[p]??p]},p))}),(0,Nt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),(0,Nt.jsx)(y,{type:"button",size:"sm",variant:"outline",onClick:()=>{g(null),s(""),r(null),c(!1)},children:"Import another file"})]})}return(0,Nt.jsxs)("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:d=>{d.preventDefault(),v()},children:[(0,Nt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Nt.jsx)("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),(0,Nt.jsx)("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async d=>{let p=d.target.files?.[0];p&&(r(p.name),s(await p.text()))}}),(0,Nt.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:'Needs an "email" column. Tags in a "tags" column are applied too.'}),n&&(0,Nt.jsx)("span",{className:"af-block af-text-xs",children:n})]}),(0,Nt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Nt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),(0,Nt.jsx)(de,{"aria-label":"Tags for imported contacts",value:i,onChange:d=>l(d.target.value)})]}),(0,Nt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,Nt.jsx)("input",{"aria-label":"Send these contacts into matching automations",type:"checkbox",className:"af-mt-1",checked:o,onChange:d=>f(d.target.checked)}),(0,Nt.jsx)("span",{children:"Send these contacts into matching automations. Leave this off when they were already welcomed on another platform."})]}),(0,Nt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,Nt.jsx)("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:u,onChange:d=>c(d.target.checked)}),(0,Nt.jsxs)("span",{children:[eo," Importing people who didn't agree can get your sending paused."]})]}),m.error&&(0,Nt.jsx)(he,{tone:"error",children:m.error}),(0,Nt.jsx)(y,{type:"submit",size:"sm",disabled:!t||!u||!a.trim()||m.busy,children:m.busy?"Importing\u2026":"Import contacts"})]})}var ye=require("react/jsx-runtime"),cm={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function yd(){let{siteId:e,canWrite:t,refreshKey:a}=Xe(),[s,n]=jn.useState(""),[r,i]=jn.useState(""),[l,u]=jn.useState(0),[c,o]=jn.useState(0),[f,b]=jn.useState(new Set),[g,m]=jn.useState(!1),v=Zr({siteId:e,q:r,offset:l,refreshKey:c+a}),d=bt(),p=()=>o(P=>P+1),x=v.stats.data,R=v.contacts.data,T=v.tags.data??[],h=x?x.growth.slice(-4).reduce((P,I)=>P+I.new_subscribers,0):null,k=async()=>{let P=await d.run("exportContacts",{});if(!P.ok||typeof P.result!="string"||typeof document>"u")return;let I=URL.createObjectURL(new Blob([P.result],{type:"text/csv;charset=utf-8"})),w=document.createElement("a");w.href=I,w.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(I)};return(0,ye.jsxs)("div",{children:[(0,ye.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[(0,ye.jsx)(gt,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:x?He(x.total):(0,ye.jsx)(Q,{className:"af-h-6 af-w-16"})}),(0,ye.jsx)(gt,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:x?He(x.mailable):(0,ye.jsx)(Q,{className:"af-h-6 af-w-16"})}),(0,ye.jsx)(gt,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:h!==null?He(h):(0,ye.jsx)(Q,{className:"af-h-6 af-w-16"})})]}),(0,ye.jsxs)("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,ye.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:P=>{P.preventDefault(),u(0),i(s.trim())},children:[(0,ye.jsx)(de,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:s,onChange:P=>n(P.target.value)}),(0,ye.jsx)(y,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),(0,ye.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>m(P=>!P),children:g?"Close import":"Import"}),(0,ye.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!t||d.busy,onClick:()=>void k(),children:"Export"})]}),g&&(0,ye.jsx)("div",{className:"af-mt-3",children:(0,ye.jsx)(Jr,{onImported:p})}),d.error&&(0,ye.jsx)(he,{tone:"error",className:"af-mt-2",children:d.error}),t&&f.size>0&&(0,ye.jsx)(um,{tags:T.filter(P=>!P.system),count:f.size,busy:d.busy,onApply:async(P,I)=>{(await d.run("bulkTagContacts",{action:P,tag_id:I,contact_ids:[...f]})).ok&&(b(new Set),p())}}),(0,ye.jsx)("div",{className:"af-mt-3",children:v.contacts.error?(0,ye.jsx)(wt,{message:"Couldn't load contacts.",onRetry:()=>void v.contacts.refetch()}):R?R.contacts.length===0?(0,ye.jsx)(la,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):(0,ye.jsxs)(ye.Fragment,{children:[(0,ye.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:R.contacts.map(P=>(0,ye.jsx)(dm,{contact:P,canWrite:t,busy:d.busy,selected:f.has(P.id),onSelect:I=>b(w=>{let E=new Set(w);return I?E.add(P.id):E.delete(P.id),E}),onUnsubscribe:async()=>{(await d.run("unsubscribeContact",{contactId:P.id})).ok&&p()}},P.id))}),(0,ye.jsxs)("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[(0,ye.jsxs)("span",{children:[He(l+1),"\u2013",He(l+R.contacts.length)," of ",He(R.total)]}),(0,ye.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ye.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:l===0,onClick:()=>u(Math.max(0,l-$s)),children:"Previous"}),(0,ye.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:l+R.contacts.length>=R.total,onClick:()=>u(l+$s),children:"Next"})]})]})]}):(0,ye.jsx)(Q,{className:"af-h-24 af-w-full"})}),(0,ye.jsx)(fm,{tags:T,canWrite:t,onChanged:p})]})}function dm({contact:e,canWrite:t,busy:a,selected:s,onSelect:n,onUnsubscribe:r}){return(0,ye.jsxs)("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&(0,ye.jsx)("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:s,onChange:i=>n(i.target.checked)}),(0,ye.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,ye.jsxs)("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?(0,ye.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),(0,ye.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[(0,ye.jsx)(ie,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":cm[e.status]}),e.tags.map(i=>(0,ye.jsx)(ie,{variant:"outline",children:i.label},i.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&(0,ye.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:r,children:"Unsubscribe"})]})}function um({tags:e,count:t,busy:a,onApply:s}){let[n,r]=jn.useState("");return(0,ye.jsxs)("div",{className:"af-mt-3 af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:[(0,ye.jsxs)("span",{children:[He(t)," selected"]}),(0,ye.jsxs)("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:n,onChange:i=>r(i.target.value),children:[(0,ye.jsx)("option",{value:"",children:"Choose a tag\u2026"}),e.map(i=>(0,ye.jsx)("option",{value:i.id,children:i.label},i.id))]}),(0,ye.jsx)(y,{type:"button",size:"sm",variant:"outline",disabled:!n||a,onClick:()=>s("add",n),children:"Add tag"}),(0,ye.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:!n||a,onClick:()=>s("remove",n),children:"Remove tag"})]})}function fm({tags:e,canWrite:t,onChanged:a}){let[s,n]=jn.useState(""),[r,i]=jn.useState(null),l=bt();return(0,ye.jsxs)("div",{children:[(0,ye.jsx)(xa,{children:"Tags"}),e.length===0?(0,ye.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No tags yet. Contacts are tagged automatically with where they signed up and what they bought."}):(0,ye.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(u=>(0,ye.jsx)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:r?.id===u.id?(0,ye.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async c=>{c.preventDefault(),(await l.run("updateTag",{tagId:u.id,label:r.label.trim()})).ok&&(i(null),a())},children:[(0,ye.jsx)(de,{"aria-label":`New name for ${u.label}`,value:r.label,onChange:c=>i({id:u.id,label:c.target.value})}),(0,ye.jsx)(y,{type:"submit",size:"sm",disabled:!r.label.trim()||l.busy,children:"Save"})]}):(0,ye.jsxs)(ye.Fragment,{children:[(0,ye.jsxs)("span",{children:[u.label," ",(0,ye.jsxs)("span",{className:"af-text-muted-foreground",children:["\xB7 ",He(u.total)," contacts, ",He(u.mailable)," can be emailed"]})]}),t&&!u.system&&(0,ye.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>i({id:u.id,label:u.label}),children:"Rename"})]})},u.id))}),t&&(0,ye.jsxs)("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async u=>{u.preventDefault(),(await l.run("createTag",{label:s.trim()})).ok&&(n(""),a())},children:[(0,ye.jsx)(de,{"aria-label":"New tag",placeholder:"New tag",value:s,maxLength:100,onChange:u=>n(u.target.value)}),(0,ye.jsx)(y,{type:"submit",size:"sm",variant:"outline",disabled:!s.trim()||l.busy,children:"Add tag"})]}),l.error&&(0,ye.jsx)(he,{tone:"error",className:"af-mt-2",children:l.error})]})}var Pt=le(require("react"),1),Dd=require("lucide-react");function Hs({siteId:e,refreshKey:t=0}){let{api:a}=W();return Mt(()=>a.getBroadcasts(e),`${e}|${t}`,e)}function zs({siteId:e,kind:t,refreshKey:a=0}){let{api:s}=W();return Mt(()=>s.getEmailDrafts(e,t),`${e}|${t??""}|${a}`,`${e}|${t??""}`)}var Ye=le(require("react"),1);var Xr=e=>typeof e=="number"&&Number.isFinite(e);function al(e){if(!e||typeof e!="object")return null;let t=e;return Xr(t.x)&&Xr(t.y)&&Xr(t.width)&&Xr(t.height)?{x:t.x,y:t.y,width:t.width,height:t.height}:null}var nl=(e,t)=>Number.isInteger(e)&&e>=0&&e<t;function xd(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=al(s.rect);return nl(s.section,a)&&n?{type:"hover",section:s.section,rect:n}:null}case"focus":case"open":{let n=al(s.rect);return nl(s.section,a)&&n?{type:s.type,section:s.section,rect:n}:null}case"layout":{if(!Xr(s.height)||!Array.isArray(s.sections))return null;let n=s.sections.flatMap(r=>{let i=r,l=i?al(i.rect):null;return i&&nl(i.section,a)&&l?[{section:i.section,rect:l}]:[]});return{type:"layout",height:s.height,sections:n}}case"template":return s.region==="header"||s.region==="footer"?{type:"template",region:s.region}:null;default:return null}}var Qr=(e,t,a)=>Math.min(Math.max(e,t),Math.max(t,a));function sl(e,t){let a=Qr(e.x,0,t.width),s=Qr(e.y,0,t.height);return{x:a,y:s,width:Qr(e.width,0,t.width-a),height:Qr(e.height,0,t.height-s)}}var ei={min:240,max:6e3,initial:480},wd=e=>Qr(Math.ceil(e),ei.min,ei.max);var js=le(require("react"),1);var ut=require("react/jsx-runtime"),rl={heading:"Heading",text:"Text",button:"Button",image:"Image",cart:"Cart"};function Nd(e){switch(e){case"heading":case"text":return{type:e,text:""};case"button":return{type:e,label:"",url:"https://"};case"image":return{type:e,url:"",alt:""};case"cart":return{type:e,label:"Return to your cart"}}}function il(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 Rd(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 mm={...ol,text:"Markdown: **bold**, *italic*, [link](https://\u2026), blank line = new paragraph"};function kd({block:e,isNew:t,busy:a,error:s,onPickImage:n,onDone:r,onRemove:i,onCancel:l,style:c,className:d}){let[o,u]=zs.useState(e),[b,v]=zs.useState(!1),m=g=>u(x=>({...x,...g})),p=zs.useRef(null);zs.useEffect(()=>p.current?.focus(),[]);let f=g=>{g&&!p.current&&(p.current=g)};return(0,dt.jsx)("form",{"data-testid":"section-editor",style:c,className:d,onSubmit:g=>{g.preventDefault(),Rd(o)&&r(o)},onKeyDown:g=>{g.key==="Escape"&&!a&&l()},children:(0,dt.jsxs)("div",{className:"af-space-y-2",children:[o.type==="heading"&&(0,dt.jsx)(ce,{ref:f,"aria-label":"Heading",value:o.text,maxLength:200,onChange:g=>m({text:g.target.value})}),o.type==="text"&&(0,dt.jsx)("textarea",{ref:f,"aria-label":"Text",className:"af-min-h-[120px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-font-mono af-text-sm",value:o.text,maxLength:5e3,onChange:g=>m({text:g.target.value})}),o.type==="button"&&(0,dt.jsxs)("div",{className:"af-grid af-gap-2 sm:af-grid-cols-2",children:[(0,dt.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",(0,dt.jsx)(ce,{ref:f,"aria-label":"Button label",value:o.label,maxLength:80,onChange:g=>m({label:g.target.value})})]}),(0,dt.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Opens",(0,dt.jsx)(ce,{"aria-label":"Button link",type:"url",value:o.url,onChange:g=>m({url:g.target.value})})]})]}),o.type==="image"&&(0,dt.jsxs)("div",{className:"af-space-y-2",children:[n?(0,dt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[o.url&&(0,dt.jsx)("img",{src:o.url,alt:"",className:"af-h-12 af-w-12 af-rounded af-object-cover"}),(0,dt.jsx)(y,{ref:f,type:"button",variant:"outline",size:"sm",disabled:b,onClick:async()=>{v(!0);try{let g=await n();g&&u(x=>({...x,url:g.url,alt:g.alt??(x.type==="image"?x.alt:"")}))}finally{v(!1)}},children:"Choose from your site's images\u2026"})]}):(0,dt.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Image address (https://\u2026)",(0,dt.jsx)(ce,{ref:f,"aria-label":"Image URL",type:"url",value:o.url,onChange:g=>m({url:g.target.value})})]}),(0,dt.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Describe the image (for people who can't see it)",(0,dt.jsx)(ce,{"aria-label":"Image description",value:o.alt??"",maxLength:200,onChange:g=>m({alt:g.target.value})})]})]}),o.type==="cart"&&(0,dt.jsxs)("div",{className:"af-space-y-2",children:[(0,dt.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Each shopper sees their own cart here. There's nothing to write but the button."}),(0,dt.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",(0,dt.jsx)(ce,{ref:f,"aria-label":"Cart button label",value:o.label,maxLength:80,onChange:g=>m({label:g.target.value})})]})]}),s&&(0,dt.jsx)(be,{tone:"error",children:s}),(0,dt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,dt.jsx)("span",{className:"af-grow af-text-xs af-text-muted-foreground",children:mm[o.type]}),!t&&(0,dt.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:i,children:"Remove"}),(0,dt.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:l,children:"Cancel"}),(0,dt.jsx)(y,{type:"submit",size:"sm",disabled:a||!Rd(o),children:"Done"})]})]})})}var Pd=le(require("react"),1),Cd=require("lucide-react");var Ce=require("react/jsx-runtime"),qn="standard",to={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"?(0,Ce.jsx)(ie,{variant:"secondary",children:"Archived"}):e.locked?(0,Ce.jsx)(ie,{variant:"secondary",children:"In use"}):null:(0,Ce.jsx)(ie,{variant:"secondary",children:"Built in"})}function dl(e){return e>0?`Used by ${e} draft${e===1?"":"s"}`:null}function Td(e,t){let{api:a}=G(),{siteId:s,refreshKey:n,settings:r}=Qe(),i=JSON.stringify([r?.business_name,r?.postal_address,r?.brand]);return Mt(()=>a.previewEmailTemplate(s,e),`${s}|${e}|${t}|${n}|${i}`,`${s}|${e}|${t}`)}function ao({templateId:e,version:t,className:a,frame:s}){let n=Td(e,t);return(0,Ce.jsx)("div",{"aria-hidden":!0,className:`af-pointer-events-none af-overflow-hidden af-bg-white ${a}`,children:n.data&&(0,Ce.jsx)("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:(0,Ce.jsx)("iframe",{title:"",tabIndex:-1,sandbox:"",srcDoc:n.data.html,style:{width:s.width,height:s.height,border:0,transform:`scale(${s.scale})`,transformOrigin:"top left"}})})})}function Ed({template:e,onBack:t,onOpenTemplate:a,onOpenDraft:s,onAskAssistant:n,reload:r,refreshKey:i}){let l=Td(e?.id??qn,e?.updated_at??"builtin");return(0,Ce.jsxs)("div",{className:"af-space-y-4",children:[(0,Ce.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,Ce.jsx)(Cd.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All templates"]}),(0,Ce.jsxs)("div",{className:"af-grid af-gap-4 md:af-grid-cols-[minmax(0,1fr)_280px]",children:[(0,Ce.jsxs)("div",{children:[l.data?(0,Ce.jsx)("iframe",{title:"Template preview",sandbox:"",srcDoc:l.data.html,className:"af-h-[520px] af-w-full af-rounded-md af-border af-bg-white"}):l.error?(0,Ce.jsxs)(be,{tone:"warning",children:[vs(l.error)==="postal_address_missing"?"Add your business postal address to preview your emails.":"Couldn't load this preview.",(0,Ce.jsx)(dr,{reason:vs(l.error)})]}):(0,Ce.jsx)(ee,{className:"af-h-[520px] af-w-full"}),(0,Ce.jsx)("p",{className:"af-mt-2 af-text-center af-text-xs af-text-muted-foreground",children:"Shown with a sample email"})]}),(0,Ce.jsxs)("div",{className:"af-space-y-3",children:[(0,Ce.jsx)(pm,{template:e,onOpenTemplate:a,onAskAssistant:n,reload:r}),(0,Ce.jsx)(gm,{templateId:e?.id??null,onOpenDraft:s,refreshKey:i})]})]})]})}function pm({template:e,onOpenTemplate:t,onAskAssistant:a,reload:s}){let{canWrite:n}=Qe(),r=pt(),[i,l]=Pd.useState(null),c=e?.name??"Standard",d=async(f,g)=>{let x=await r.run(f,g);l(null),x.ok&&f==="deleteEmailTemplate"&&t(null),!x.ok&&Fa(x.error,"template_in_use")&&r.setError("Emails use this template now."),s()},o=async f=>{let g=await r.run("copyEmailTemplate",{templateId:f.id});g.ok&&(t(g.result.id),s())},u=f=>(0,Ce.jsx)(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:r.busy,onClick:()=>void o(f),children:"Make a copy"}),b=(0,Ce.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:r.busy,onClick:()=>l("delete"),children:"Delete"}),v=(0,Ce.jsx)(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,g,x]=i==="delete"?["Delete this template?","Delete",()=>d("deleteEmailTemplate",{templateId:e.id})]:["Archive this template?","Archive",()=>d("archiveEmailTemplate",{templateId:e.id})];m=(0,Ce.jsxs)(Ce.Fragment,{children:[(0,Ce.jsx)("p",{className:"af-text-sm",children:f}),(0,Ce.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ce.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),(0,Ce.jsx)(y,{type:"button",size:"sm",variant:i==="delete"?"destructive":"default",className:"af-ml-auto",disabled:r.busy,onClick:()=>void x(),children:g})]})]})}else e?e.status==="archived"?m=(0,Ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,Ce.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:r.busy,onClick:()=>void d("unarchiveEmailTemplate",{templateId:e.id}),children:"Unarchive"}),u(e)]}):e.locked?m=(0,Ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_archive&&v,u(e)]}):m=(0,Ce.jsxs)(Ce.Fragment,{children:[a&&(0,Ce.jsx)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>a(to.update(e.name)),children:"\u2728 Change this template with the editor"}),(e.can_delete||e.can_archive)&&(0,Ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_delete&&b,e.can_archive&&v]})]}):m=a&&(0,Ce.jsx)(y,{type:"button",size:"sm",onClick:()=>a(to.copyStandard),children:"Make a copy"});let p=e&&e.status==="active"&&!e.locked?dl(e.usage.drafts):null;return(0,Ce.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Ce.jsx)("h3",{"data-testid":"template-title",className:"af-grow af-truncate af-text-sm af-font-semibold",children:c}),(0,Ce.jsx)(cl,{template:e})]}),p&&(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:p}),r.error&&(0,Ce.jsx)(be,{tone:"error",children:r.error}),m]})}function gm({templateId:e,onOpenDraft:t,refreshKey:a}){let{siteId:s}=Qe(),n=Hs({siteId:s,kind:"broadcast",refreshKey:a}),r=Vs({siteId:s,refreshKey:a}),i=n.data?.filter(u=>(u.template?.id??null)===e)??null,l=r.data??[],c=Qi(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(0,Ce.jsxs)("div",{"data-testid":"template-usage",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,Ce.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Emails using it"}),n.error||r.error?(0,Ce.jsx)(wt,{message:"Couldn't load the emails.",onRetry:()=>{n.refetch(),r.refetch()}}):!i||!r.data?(0,Ce.jsx)(ee,{className:"af-h-10 af-w-full"}):i.length===0?(0,Ce.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No emails use it."}):(0,Ce.jsx)("ul",{className:"af-space-y-1",children:i.map(u=>{let b=o(u.id),v=(0,Ce.jsxs)(Ce.Fragment,{children:[(0,Ce.jsx)("span",{className:"af-block af-truncate af-text-sm",children:u.subject||"(no subject)"}),(0,Ce.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["Broadcast \xB7 ",b]})]});return(0,Ce.jsx)("li",{children:b==="Sent"?(0,Ce.jsx)("div",{className:"af-rounded-md af-px-2 af-py-1",children:v}):(0,Ce.jsx)("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)})})]})}var an=require("react/jsx-runtime");function Id({draft:e,disabled:t,onChanged:a}){let{api:s}=G(),{siteId:n,refreshKey:r}=Qe(),i=Mt(()=>s.getEmailTemplates(n),`${n}|${r}`,n),l=pt(),c=e.template?.id??qn,d=c===qn,o=(i.data??[]).filter(p=>p.status==="active"),u=o.find(p=>p.id===c),b=d?"Standard":e.template?.name??u?.name??"",v=d?"builtin":u?.updated_at??"current",m=async p=>{if(p===c)return;let f=await l.run("setDraftTemplate",{draftId:e.id,template_id:p===qn?null:p,expected_version:e.version});f.ok?await a():Fa(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."):Fa(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()):Fa(f.error,"template_archived")&&(l.setError("That template is archived."),await i.refetch())};return(0,an.jsxs)("div",{"data-testid":"template-card",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,an.jsx)("div",{className:"af-text-sm af-font-semibold",children:"Template"}),(0,an.jsxs)("div",{className:"af-flex af-items-center af-gap-3",children:[(0,an.jsx)(ao,{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}}),(0,an.jsx)("div",{className:"af-min-w-0 af-grow af-truncate af-text-sm af-font-medium",children:b})]}),(0,an.jsxs)("label",{className:"af-grid af-gap-1 af-text-xs af-text-muted-foreground",children:["Switch to",(0,an.jsxs)("select",{"aria-label":"Switch to",value:c,disabled:t||l.busy,onChange:p=>void m(p.target.value),className:"af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-text-sm af-text-foreground",children:[(0,an.jsx)("option",{value:qn,children:"Standard"}),o.map(p=>(0,an.jsx)("option",{value:p.id,children:p.name},p.id)),!d&&!u&&(0,an.jsx)("option",{value:c,disabled:!0,children:b})]})]}),l.error&&(0,an.jsx)(be,{tone:"error",children:l.error})]})}var bs=require("react/jsx-runtime");function Ad({live:e,joinsOnSave:t,notice:a,onBackToCanvas:s}){return(0,bs.jsxs)("div",{"data-testid":"automation-step-panel",className:"af-space-y-2",children:[e?(0,bs.jsxs)(be,{tone:"success",children:[(0,bs.jsx)("span",{className:"af-font-medium",children:"Live."})," Saved changes send to the next people who reach this step."]}):t?(0,bs.jsx)(be,{children:"This email joins the automation when you save it with a subject and some content."}):null,a,(0,bs.jsx)("p",{className:"af-text-sm",children:(0,bs.jsx)(da,{onClick:s,children:"Back to the automation"})})]})}var Ne=require("react/jsx-runtime"),vm={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"},bm=320,hm=600,ym=e=>({top:Math.max(0,e.y-24),left:e.x});function xm(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 no({draftId:e,renderCommit:t,automationStep:a,allowCart:s,onSaved:n,scheduled:r,onAskAssistant:i,onPickImage:l}){let{api:c}=G(),{siteId:d,canWrite:o,refreshKey:u,openSettings:b}=Qe(),v=o&&!r,m=Je.useRef(v);m.current=v;let[p,f]=Je.useState(null),[g,x]=Je.useState(null),[k,T]=Je.useState(null),[h,P]=Je.useState(null),[_,E]=Je.useState(null),[w,I]=Je.useState(null),[O,C]=Je.useState(null),[Y,X]=Je.useState(null),[q,de]=Je.useState(null),[ge,ye]=Je.useState({}),[D,W]=Je.useState(ei.initial),[B,ue]=Je.useState(!1),me=pt(),We=pt(),Ie=Je.useRef(null),He=Je.useRef(null),et=Je.useRef(0),De=Je.useRef(!1),Ke=Je.useRef(!1),L=Je.useCallback(Te=>{De.current=Te!==null,I(Te)},[]);xd(w!==null);let V=Je.useRef(p);V.current=p;let $=Je.useRef(0),xe=Je.useCallback(async(Te={})=>{let Tt=++$.current,z=m.current,Oe=()=>z?c.previewEmailDraft(d,e,{editable:!0}):c.previewEmailDraft(d,e),[zt,xn]=await Promise.allSettled([c.getEmailDraft(d,e),Oe()]),ne=xn,ia=()=>zt.status==="fulfilled"&&ne.status==="fulfilled"&&ne.value.version!==zt.value.version;if(ia()&&Tt===$.current&&([ne]=await Promise.allSettled([Oe()])),Tt===$.current){if(Te.background&&De.current){Ke.current=!0;return}if(P(null),T(null),zt.status==="rejected"){P(ur(zt.reason));return}f(zt.value),ne.status==="fulfilled"?x({...ne.value,editable:z&&!ia()}):(x(null),T(Fa(ne.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:ur(ne.reason),code:null}))}},[c,d,e]);Je.useEffect(()=>{f(null),x(null),xe()},[xe]);let H=Je.useRef(v);Je.useEffect(()=>{H.current!==v&&(H.current=v,v||L(null),xe())},[v,xe,L]);let ke=Je.useRef(u);Je.useEffect(()=>{if(u!==ke.current){if(ke.current=u,De.current){Ke.current=!0;return}xe({background:!0})}},[u,xe]);let ze=()=>{L(null),me.setError(null),Ke.current&&(Ke.current=!1,xe())},gt=async(Te,Tt,z)=>{let Oe=await me.run("updateDraft",{draftId:e,expected_version:Te.version,...Tt});Oe.ok?(C(null),He.current=null,Ke.current=!1,L(null),await xe(),n?.()):Fa(Oe.error,"version_conflict")&&(me.setError(null),C(z),Ke.current=!1,L(null),await xe())},st=Je.useRef({frame:null,html:null,count:0}),[Ot,Pe]=Je.useState(null),Ge=(Te,Tt)=>{let z=st.current;z.frame!==Te.currentTarget||z.html!==Tt?st.current={frame:Te.currentTarget,html:Tt,count:1}:++z.count>1&&Pe(Tt)},yt=g!==null&&Ot===g.html,Lt=v&&g?.editable===!0&&!yt;if(Je.useEffect(()=>{if(!Lt)return;let Te=Tt=>{let z=V.current;if(!z)return;let Oe=Sd(Tt,Ie.current?.contentWindow,z.blocks.length);if(Oe)switch(Oe.type){case"hover":de(Oe.section===null?null:{section:Oe.section,rect:Oe.rect});return;case"focus":He.current=Oe.section;return;case"open":if(He.current=Oe.section,De.current)return;X(null),ue(!1),L({kind:"section",base:z,index:Oe.section,block:z.blocks[Oe.section],isNew:!1,anchor:Oe.rect,key:++et.current});return;case"layout":W(Nd(Oe.height));{let zt=Object.fromEntries(Oe.sections.map(xn=>[xn.section,xn.rect]));ye(xn=>xm(xn,zt)?xn:zt)}return;case"template":De.current||X(Oe.region);return}};return window.addEventListener("message",Te),()=>window.removeEventListener("message",Te)},[Lt,L]),h)return(0,Ne.jsxs)(be,{tone:"error",children:["Couldn't load this email. ",h]});if(!p)return(0,Ne.jsx)(ee,{className:"af-h-40 af-w-full"});let Vt={width:Ie.current?.clientWidth||hm,height:Lt?D:ei.initial},it=w?.kind==="section"?w:null,Qt=(()=>{if(!it)return null;if(!it.isNew)return ge[it.index]??it.anchor;let Te=ge[it.index-1];return Te?{x:Te.x,y:Te.y+Te.height,width:Te.width,height:0}:null})(),tt=Qt?il(Qt,Vt):null,Rt=s??p.kind==="recovery",Va=p.template?.name??"Standard",In=it&&(0,Ne.jsx)(kd,{block:it.block,isNew:it.isNew,busy:me.busy,error:me.error,onPickImage:l,onCancel:ze,onRemove:()=>{let{base:Te}=it;gt(Te,{subject:Te.subject,preheader:Te.preheader,blocks:Te.blocks.filter((Tt,z)=>z!==it.index)},ll(it.block))},onDone:Te=>{let{base:Tt}=it,z=it.isNew?[...Tt.blocks.slice(0,it.index),Te,...Tt.blocks.slice(it.index)]:Tt.blocks.map((Oe,zt)=>zt===it.index?Te:Oe);gt(Tt,{subject:Tt.subject,preheader:Tt.preheader,blocks:z},ll(Te))},className:tt?"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:tt?{top:tt.y,left:tt.x,width:Math.min(Math.max(tt.width,bm),Vt.width)}:void 0},it.key);return(0,Ne.jsxs)("div",{className:"af-grid af-gap-4 lg:af-grid-cols-[minmax(0,1fr)_300px]",children:[(0,Ne.jsxs)("div",{className:"af-min-w-0 af-space-y-3",children:[w?.kind==="subject"?(0,Ne.jsx)(wm,{draft:w.base,busy:me.busy,error:me.error,onCancel:ze,onDone:Te=>void gt(w.base,{...Te,blocks:w.base.blocks},[Te.subject,Te.preheader??""].join(`
8
- `))}):Lt?(0,Ne.jsx)("button",{type:"button","data-testid":"subject-line",onClick:()=>{De.current||(X(null),L({kind:"subject",base:p}))},className:"af-block af-w-full af-rounded-md af-border af-border-dashed af-px-3 af-py-2 af-text-left hover:af-border-primary",children:(0,Ne.jsx)(Dd,{draft:p})}):(0,Ne.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:(0,Ne.jsx)(Dd,{draft:p})}),r&&(0,Ne.jsxs)(be,{tone:"info",children:[(0,Ne.jsxs)("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."]}),(0,Ne.jsx)(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&&(0,Ne.jsx)("p",{className:"af-mt-1 af-text-destructive",children:r.error})]}),O!==null&&(0,Ne.jsxs)(be,{tone:"warning",children:[(0,Ne.jsx)("p",{children:"This email changed while you were editing, so your change wasn't saved. Here is the latest version; your text is below to apply again."}),(0,Ne.jsx)("textarea",{readOnly:!0,"aria-label":"Your unsaved text",value:O,className:"af-mt-2 af-min-h-[72px] af-w-full af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-font-mono af-text-xs af-text-foreground"}),(0,Ne.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>C(null),children:"Dismiss"})]}),Y&&(0,Ne.jsx)("div",{"data-testid":"template-hint",children:(0,Ne.jsx)(be,{children:Y==="header"?(0,Ne.jsxs)(Ne.Fragment,{children:['The header is part of the "',Va,'" template. Switch templates on the right.']}):(0,Ne.jsxs)(Ne.Fragment,{children:["Every email ends with this footer. Your business name and address come from"," ",(0,Ne.jsx)(da,{onClick:()=>b("sender"),children:"Settings"}),"."]})})}),yt&&v&&(0,Ne.jsx)(be,{tone:"warning",children:"This template tried to open another page in the preview, so the preview can't be edited here."}),g?(0,Ne.jsxs)("div",{className:"af-relative",children:[(0,Ne.jsx)("iframe",{ref:Ie,title:"Email preview",sandbox:Lt?"allow-scripts":"",srcDoc:g.html,onLoad:Lt?Te=>Ge(Te,g.html):void 0,style:{height:Vt.height},className:"af-block af-w-full af-rounded-md af-border af-bg-white"},Lt?"editable":"read-only"),Lt&&q&&!w&&(0,Ne.jsx)("div",{"aria-hidden":!0,className:"af-pointer-events-none af-absolute af-rounded af-bg-primary af-px-2 af-py-0.5 af-text-xs af-text-primary-foreground",style:ym(il(q.rect,Vt)),children:vm[p.blocks[q.section]?.type??"text"]}),tt&&In]}):k?(0,Ne.jsxs)(be,{tone:"warning",children:[k.text,(0,Ne.jsx)(dr,{reason:k.code})]}):(0,Ne.jsx)(ee,{className:"af-h-40 af-w-full"}),!tt&&In,Lt&&!w&&(0,Ne.jsxs)("div",{className:"af-space-y-2",children:[(0,Ne.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>ue(Te=>!Te),"aria-expanded":B,children:"+ Add a section"}),B&&(0,Ne.jsx)("div",{"data-testid":"add-section-menu",className:"af-flex af-flex-wrap af-gap-2",children:["text","heading","button","image",...Rt?["cart"]:[]].map(Te=>(0,Ne.jsx)(y,{type:"button",size:"sm",variant:"secondary",onClick:()=>{let Tt=He.current!==null?He.current+1:p.blocks.length;ue(!1),X(null),L({kind:"section",base:p,index:Tt,block:_d(Te),isNew:!0,anchor:null,key:++et.current})},children:ol[Te]},Te))})]}),(0,Ne.jsx)("p",{className:"af-text-center af-text-xs af-text-muted-foreground",children:"Header and footer come from your template."})]}),(0,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[(0,Ne.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!o||We.busy,onClick:async()=>{E(null);let Te=await We.run("testSendDraft",{draftId:e});Te.ok&&E(Te.result?.sent_to??"your email")},children:"Send a test to me"}),_&&(0,Ne.jsxs)(be,{tone:"success",children:["Test sent to ",_,"."]}),We.error&&(0,Ne.jsx)(be,{tone:"error",children:We.error}),g&&!r&&t?.({draft:p,preview:g,reload:()=>xe()}),a&&(0,Ne.jsx)(Ad,{...a})]}),(0,Ne.jsx)(Id,{draft:p,disabled:!v||w!==null,onChanged:async()=>{await xe(),n?.()}}),i&&o&&(0,Ne.jsx)(y,{type:"button",variant:"outline",className:"af-w-full",onClick:()=>i(`Update the "${p.subject}" email to `),children:"\u2728 Change this email with the editor"})]})]})}function Dd({draft:e}){return(0,Ne.jsxs)(Ne.Fragment,{children:[(0,Ne.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Subject "}),(0,Ne.jsx)("span",{className:"af-font-medium",children:e.subject||"(no subject)"}),e.preheader&&(0,Ne.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:[" \u2014 ",e.preheader]})]})}function wm({draft:e,busy:t,error:a,onDone:s,onCancel:n}){let[r,i]=Je.useState(e.subject),[l,c]=Je.useState(e.preheader??"");return(0,Ne.jsxs)("form",{className:"af-space-y-2 af-rounded-md af-border af-p-3",onSubmit:d=>{d.preventDefault(),s({subject:r,preheader:l.trim()||null})},children:[(0,Ne.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Subject",(0,Ne.jsx)(ce,{"aria-label":"Subject",value:r,maxLength:200,autoFocus:!0,onChange:d=>i(d.target.value)})]}),(0,Ne.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Preview text (the grey line after the subject in the inbox)",(0,Ne.jsx)(ce,{"aria-label":"Preview text",value:l,maxLength:200,onChange:d=>c(d.target.value)})]}),a&&(0,Ne.jsx)(be,{tone:"error",children:a}),(0,Ne.jsxs)("div",{className:"af-flex af-justify-end af-gap-2",children:[(0,Ne.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:t,onClick:n,children:"Cancel"}),(0,Ne.jsx)(y,{type:"submit",size:"sm",disabled:t,children:"Done"})]})]})}var ve=require("react/jsx-runtime"),Sm={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function Bd({openDraftId:e,onOpenDraft:t,onAskAssistant:a,onPickImage:s}){let{siteId:n,canWrite:r,refreshKey:i}=Qe(),[l,c]=Pt.useState(0),d=l+i,o=Hs({siteId:n,kind:"broadcast",refreshKey:d}),u=Vs({siteId:n,refreshKey:d}),b=pt(),v=pt(),m=Qi(o.data??[],u.data??[]),p=o.data?.filter(f=>!m.has(f.id))??null;if(e){let f=u.data?.find(g=>g.draft_id===e&&g.status==="scheduled");return(0,ve.jsxs)("div",{className:"af-space-y-4",children:[(0,ve.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>t(null),children:[(0,ve.jsx)(Ld.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),!u.data&&!u.error||!o.data&&!o.error?(0,ve.jsx)(ee,{className:"af-h-40 af-w-full"}):m.has(e)?(0,ve.jsx)(be,{children:"This email has been sent, so it can't change. Duplicate it from the list to send it again."}):(0,ve.jsx)(no,{draftId:e,onSaved:()=>c(g=>g+1),renderCommit:g=>(0,ve.jsx)(km,{...g,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(0,ve.jsxs)("div",{children:[(0,ve.jsx)(xa,{children:"Drafts"}),o.error?(0,ve.jsx)(wt,{message:"Couldn't load drafts.",onRetry:()=>void o.refetch()}):p?p.length===0?(0,ve.jsx)(la,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):(0,ve.jsx)("ul",{"data-testid":"drafts",className:"af-divide-y af-rounded-md af-border",children:p.map(f=>(0,ve.jsxs)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[(0,ve.jsx)("span",{className:"af-truncate af-text-sm",children:f.subject||"(no subject)"}),(0,ve.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(f.id),children:"Review"})]},f.id))}):(0,ve.jsx)(ee,{className:"af-h-10 af-w-full"}),(0,ve.jsx)(xa,{children:"Sent and scheduled"}),b.error&&(0,ve.jsx)(be,{tone:"error",children:b.error}),v.error&&(0,ve.jsx)(be,{tone:"error",children:v.error}),u.error?(0,ve.jsx)(wt,{message:"Couldn't load broadcasts.",onRetry:()=>void u.refetch()}):u.data?u.data.length===0?(0,ve.jsx)(la,{children:"Nothing sent yet."}):(0,ve.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:u.data.map(f=>(0,ve.jsx)(Nm,{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&&nl(f)?async()=>{let g=await v.run("duplicateDraft",{draftId:f.draft_id});g.ok&&(c(x=>x+1),t(g.result.id))}:void 0},f.id))}):(0,ve.jsx)(ee,{className:"af-h-10 af-w-full"})]})}function Nm({broadcast:e,canCancel:t,busy:a,onCancel:s,onDuplicate:n}){return(0,ve.jsxs)("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[(0,ve.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,ve.jsx)("span",{className:"af-truncate af-text-sm af-font-medium",children:e.subject}),(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ve.jsx)(ie,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Sm[e.status]}),t&&(0,ve.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:s,children:"Cancel"}),n&&(0,ve.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:n,children:"Duplicate"})]})]}),(0,ve.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",Ve(e.recipients.planned)," recipients \xB7 ",Ve(e.stats.delivered)," delivered \xB7 ",Ve(e.stats.opened)," opened \xB7"," ",Ve(e.stats.clicked)," clicked \xB7 ",Ve(e.stats.bounced)," bounced \xB7 ",Ve(e.stats.complained)," complaints \xB7"," ",Ve(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&(0,ve.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:ss(e.status_reason)})]})}var Fd=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function Od(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:Fd(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:s?Rm(a):"",suggested:t!==null||a!==null,timePassed:a!==null&&!s}}function Rm(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 _m=(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 km({draft:e,preview:t,reload:a,onCommitted:s}){let{api:n}=G(),{siteId:r,canWrite:i,settings:l,refreshKey:c}=Qe(),[d,o]=Pt.useState(null),[u,b]=Pt.useState(!1),[v,m]=Pt.useState(null),[p,f]=Pt.useState(()=>Od(e)),[g,x]=Pt.useState(p.tagIds),[k,T]=Pt.useState(p.match),[h,P]=Pt.useState(p.scheduleAt),[_,E]=Pt.useState(0),w=!_m({tagIds:g,match:k,scheduleAt:h},p),I=Fd(e);Pt.useEffect(()=>{if(I===p.key||e.id===p.draftId&&w)return;let H=Od(e);f(H),x(H.tagIds),T(H.match),P(H.scheduleAt),E(0)},[I,e,p,w]);let O=Pt.useMemo(()=>d?new Set(d.map(H=>H.id)):null,[d]),C=O!==null&&g.every(H=>O.has(H));Pt.useEffect(()=>{if(!O||g.every(ke=>O.has(ke)))return;let H=ke=>ke.filter(ze=>O.has(ze));E(ke=>ke+g.length-H(g).length),x(H(g)),f(ke=>({...ke,tagIds:H(ke.tagIds)}))},[O,g]);let[Y,X]=Pt.useState(null),[q,de]=Pt.useState(null),[ge,ye]=Pt.useState(null),D=pt();Pt.useEffect(()=>{n.getMarketingTags(r).then(H=>{o(H),b(!1)},()=>{o(null),b(!0)}),n.getMarketingContactStats(r).then(m,()=>m(null))},[n,r,c]);let W=h?new Date(h).toISOString():null,B=JSON.stringify([g,k,W]),ue=Y?.plan??null,me=Y!==null&&Y.key===B,We=Pt.useRef(0),Ie=Pt.useCallback(async()=>{let H=++We.current;de(null);try{let ke=await n.estimateBroadcast(r,{targeting:{tag_ids:g,match:k},scheduled_at:W});H===We.current&&X({key:B,plan:ke})}catch(ke){if(H!==We.current)return;X(null),de(ur(ke))}},[n,r,g,k,W,B,c]),He=Pt.useRef(!1);Pt.useEffect(()=>{if(!C&&g.length>0)return;if(!He.current){He.current=!0,Ie();return}let H=setTimeout(()=>void Ie(),300);return()=>clearTimeout(H)},[Ie,C,g.length]);let et=l&&!l.readiness.can_send?ss(l.readiness.reason):null,De=ue!==null&&!ue.fits,Ke=v?Math.max(0,v.by_status.subscribed-v.mailable):null,L=v&&ue&&Ke!==null?Math.max(0,v.total-ue.recipients-Ke):null,V=!i||D.busy||!ue||!me||De||ue.recipients===0||et!==null||u&&g.length>0,$=async()=>{ye(null);let H=await D.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:g,match:k},scheduled_at:W});if(H.ok){ye({tone:"success",text:W?"Scheduled.":"Sending now."}),s();return}Fa(H.error,"version_conflict")?(D.setError(null),await a(),ye({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):Fa(H.error,"over_allowance")&&await Ie()},xe=H=>x(ke=>ke.includes(H)?ke.filter(ze=>ze!==H):[...ke,H]);return(0,ve.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[p.suggested&&!w&&(0,ve.jsx)(be,{children:"Suggested by your assistant \u2014 review before sending."}),(0,ve.jsx)(xa,{children:"Who gets it"}),u&&(0,ve.jsx)(be,{tone:"warning",children:g.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."}),_>0&&(0,ve.jsx)(be,{tone:"warning",children:_===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),d&&d.length>0?(0,ve.jsxs)("div",{className:"af-space-y-2",children:[(0,ve.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:d.map(H=>(0,ve.jsxs)("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[(0,ve.jsx)("input",{type:"checkbox",checked:g.includes(H.id),onChange:()=>xe(H.id)}),H.label]},H.id))}),g.length>1&&(0,ve.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",(0,ve.jsxs)("select",{"aria-label":"Tag match",value:k,onChange:H=>T(H.target.value),className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,ve.jsx)("option",{value:"any",children:"any of these tags"}),(0,ve.jsx)("option",{value:"all",children:"all of these tags"})]})]}),g.length===0&&(0,ve.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):(0,ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Everyone who can be emailed."}),(0,ve.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,ve.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),(0,ve.jsx)(ce,{"aria-label":"Schedule time",type:"datetime-local",value:h,onChange:H=>P(H.target.value)})]}),p.timePassed&&!h&&(0,ve.jsx)(be,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),q?(0,ve.jsxs)(be,{tone:"error",children:["Couldn't work out the audience. ",q]}):ue?(0,ve.jsxs)("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[(0,ve.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,ve.jsx)(ul,{label:"Will receive it",value:ue.recipients}),(0,ve.jsx)(ul,{label:"Suppressed (bounced or complained)",value:Ke}),(0,ve.jsx)(ul,{label:"Not included",value:L})]}),(0,ve.jsxs)("p",{className:"af-text-muted-foreground",children:[Ve(ue.allowance.remaining)," of ",Ve(ue.allowance.monthly)," emails left this month."]}),ue.sample_size!==null&&(0,ve.jsxs)(be,{children:["We'll send to ",Ve(ue.sample_size)," people first and check for bounces before sending the rest."]}),ue.ramp_days.length>1&&(0,ve.jsxs)(be,{children:["Your domain is new, so this goes out over ",ue.ramp_days.length," days:"," ",ue.ramp_days.map(H=>`${Ve(H.recipients)} on ${H.date}`).join(", "),"."]})]}):(0,ve.jsx)(ee,{className:"af-h-12 af-w-full"}),De&&ue&&(0,ve.jsxs)(be,{tone:"warning",children:["This send needs ",Ve(ue.recipients)," emails, but only ",Ve(ue.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),et&&(0,ve.jsxs)(be,{tone:"warning",children:[et,(0,ve.jsx)(dr,{reason:l?.readiness.reason})]}),ge&&(0,ve.jsx)(be,{tone:ge.tone,children:ge.text}),D.error&&(0,ve.jsx)(be,{tone:"error",children:D.error}),(0,ve.jsx)(y,{type:"button",disabled:V,onClick:()=>void $(),children:W?"Schedule":"Send now"})]})}function ul({label:e,value:t}){return(0,ve.jsxs)("div",{className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,ve.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,ve.jsx)("div",{className:"af-font-semibold",children:t===null?"\u2014":Ve(t)})]})}var ka=le(require("react"),1);var qs=require("lucide-react");var js=le(require("react"),1),Jt=require("lucide-react");var A=require("react/jsx-runtime"),Pm=[{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."}],Cm="hello";function ml(e){return`${Cm}@${e}`}function Md({onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,onTurnOn:s,siteDomain:n,businessName:r}){let{api:i}=G(),{siteId:l,settings:c,canWrite:d,refreshKey:o,refetchSettings:u}=Qe(),b=Mt(()=>i.getMarketingContactStats(l),`${l}|${o}`,l),[v,m]=js.useState(!1),[p,f]=js.useState(null);if(!c)return null;let g=b.data?.by_status.subscribed??0,x={siteDomain:n,businessName:r};return Tm(c)?(0,A.jsx)(pl,{settings:c,site:x,waiting:g,children:d?s&&(0,A.jsxs)("div",{className:"af-space-y-2",children:[(0,A.jsxs)(y,{disabled:v,onClick:async()=>{m(!0),f(null);try{await s(),await u()}catch(k){f(k instanceof Error?k.message:"Couldn't turn on email. Try again.")}finally{m(!1)}},children:["Get started ",(0,A.jsx)(Jt.ArrowRight,{className:"af-ml-2 af-h-4 af-w-4","aria-hidden":!0})]}),p&&(0,A.jsx)(be,{tone:"error",children:p})]}):(0,A.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Only the site owner can set up email."})}):(0,A.jsx)(Em,{settings:c,site:x,waiting:g,onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a})}function Tm(e){return e.readiness.reason==="sending_not_enabled"}function pl({settings:e,site:t,waiting:a=0,children:s}){return(0,A.jsx)("div",{className:"af-mx-auto af-max-w-3xl af-px-2 af-py-8",children:(0,A.jsxs)("div",{className:"af-grid af-items-center af-gap-10 md:af-grid-cols-[1fr_18rem]",children:[(0,A.jsxs)("div",{children:[(0,A.jsxs)("div",{className:"af-mb-3 af-inline-flex af-items-center af-gap-1.5 af-rounded-full af-bg-muted af-px-2.5 af-py-1 af-text-xs af-font-medium",children:[(0,A.jsx)(Jt.Mail,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0})," Email marketing"]}),(0,A.jsx)("h3",{className:"af-text-2xl af-font-semibold af-tracking-tight",children:"Turn visitors into regulars"}),(0,A.jsx)("p",{className:"af-mt-2 af-text-muted-foreground",children:"Build an email list from your website and reach those people directly, whenever you have something worth telling them."}),(0,A.jsx)("ol",{className:"af-mt-6 af-space-y-3",children:Pm.map((n,r)=>(0,A.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,A.jsx)("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-border af-text-xs af-font-semibold",children:r+1}),(0,A.jsxs)("p",{className:"af-text-sm",children:[(0,A.jsxs)("span",{className:"af-font-medium",children:[n.title,"."]})," ",(0,A.jsx)("span",{className:"af-text-muted-foreground",children:n.body})]})]},n.title))}),a>0&&(0,A.jsxs)("p",{className:"af-mt-5 af-rounded-md af-bg-amber-50 af-px-3 af-py-2 af-text-sm af-text-amber-900",children:[(0,A.jsxs)("span",{className:"af-font-semibold",children:[Ve(a)," ",a===1?"person has":"people have"]})," ","already signed up and ",a===1?"is":"are"," waiting for your first email."]}),(0,A.jsx)("div",{className:"af-mt-6",children:s})]}),(0,A.jsx)(so,{settings:e,site:t,className:"af-rotate-1"})]})})}function $d({onUpgradePlan:e}){return(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-border-violet-200 af-bg-gradient-to-r af-from-violet-50 af-to-white af-p-4",children:[(0,A.jsx)(Jt.Lock,{className:"af-h-5 af-w-5 af-shrink-0 af-text-violet-700","aria-hidden":!0}),(0,A.jsxs)("div",{className:"af-flex-1",children:[(0,A.jsx)("div",{className:"af-text-sm af-font-semibold af-text-violet-900",children:"Email marketing is part of Pro"}),(0,A.jsx)("div",{className:"af-text-sm af-text-violet-900/80",children:"Collect subscribers and send newsletters from your own domain."})]}),e&&(0,A.jsx)(y,{size:"sm",onClick:e,children:"Upgrade to Pro"})]})}function Em({settings:e,site:t,waiting:a,onStartDomainSetup:s,onConnectDomain:n,onAskAssistant:r}){let{refetchSettings:i,canWrite:l}=Qe(),[c,d]=js.useState(null),o=p=>d(f=>f===p?null:p),{siteDomain:u}=t,b=ti(e),v=u===null&&!e.domain.sending_domain,m=!!e.postal_address;return(0,A.jsxs)("div",{className:"af-mx-auto af-max-w-4xl af-py-4",children:[(0,A.jsxs)("div",{className:"af-mb-6 af-flex af-items-start af-justify-between af-gap-6",children:[(0,A.jsxs)("div",{children:[(0,A.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Set up email"}),(0,A.jsxs)("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&&(0,A.jsxs)("div",{className:"af-text-right",children:[(0,A.jsx)("div",{className:"af-text-2xl af-font-semibold",children:Ve(a)}),(0,A.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[a===1?"subscriber":"subscribers"," waiting"]})]})]}),!l&&(0,A.jsx)(be,{className:"af-mb-4",children:"Only the site owner can finish setup."}),(0,A.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_16rem]",children:[(0,A.jsxs)("div",{className:"af-space-y-4",children:[(0,A.jsxs)(fl,{title:u??"Your domain",sub:"One domain for your website and your email.",children:[u&&(0,A.jsx)(En,{icon:Jt.Globe,label:"Website",value:u,status:(0,A.jsx)(Tn,{tone:"green",children:"Live"})}),v?(0,A.jsx)(En,{icon:Jt.Mail,label:"Email sending",value:"Needs a custom domain",status:(0,A.jsx)(Tn,{tone:"gray",children:"Not available"}),action:n&&l?{label:"Connect domain",onClick:n}:void 0}):(0,A.jsxs)(En,{icon:Jt.Mail,label:"Email sending",value:e.domain.sending_domain??(u?`news.${u}`:"news.yourdomain.com"),status:gl(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&&(0,A.jsx)("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:"Emails go out from a subdomain of your site's domain, so they reach inboxes and are clearly from you. If we manage your domain's DNS we add the records; otherwise you'll get a few to copy into your DNS provider."}),(0,A.jsx)(vl,{settings:e,canWrite:l,onStartDomainSetup:s,onChanged:i})]})]}),(0,A.jsx)(fl,{title:"Sender",sub:"Who your emails are from. The mailing address is legally required in every email.",children:(0,A.jsx)(En,{icon:Jt.PenLine,label:m?e.business_name??"Sender":"Not set",value:e.postal_address??"Name, mailing address and reply-to",status:m?(0,A.jsx)(Tn,{tone:"green",children:"Done"}):(0,A.jsx)(Tn,{tone:"gray",children:"Needed"}),action:l?{label:m?"Edit":"Add",onClick:()=>o("sender")}:void 0,expanded:c==="sender",children:(0,A.jsx)(Im,{settings:e,businessName:t.businessName,onSaved:async()=>{await i(),d(null)}})})}),(0,A.jsx)(fl,{title:"How people join your list",sub:"Only people who asked to hear from you get your emails.",children:(0,A.jsx)(Lm,{onAskAssistant:l?r:void 0})})]}),(0,A.jsxs)("aside",{className:"af-space-y-3",children:[(0,A.jsx)("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails will look like"}),(0,A.jsx)(so,{settings:e,site:t})]})]})]})}function fl({title:e,sub:t,children:a}){return(0,A.jsxs)("section",{className:"af-rounded-xl af-border af-bg-background",children:[(0,A.jsxs)("div",{className:"af-px-5 af-pb-3 af-pt-4",children:[(0,A.jsx)("h4",{className:"af-text-sm af-font-semibold",children:e}),(0,A.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:t})]}),(0,A.jsx)("div",{className:"af-space-y-2 af-px-3 af-pb-3",children:a})]})}function En({icon:e,marker:t,label:a,value:s,mono:n=!0,hint:r,status:i,action:l,expanded:c=!1,children:d}){return(0,A.jsxs)("div",{className:"af-rounded-lg af-border af-bg-muted/30",children:[(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-p-3",children:[t?(0,A.jsxs)("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-xs af-font-semibold af-text-background",children:[(0,A.jsx)("span",{"aria-hidden":!0,children:t}),(0,A.jsxs)("span",{className:"af-sr-only",children:["Shown at ",t," in the preview"]})]}):e&&(0,A.jsx)("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-background",children:(0,A.jsx)(e,{className:"af-h-4 af-w-4","aria-hidden":!0})}),(0,A.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,A.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:a}),(0,A.jsx)("div",{className:Q("af-truncate af-text-sm",n&&"af-font-mono"),children:s}),r&&(0,A.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:r})]}),i,l&&(0,A.jsxs)(y,{size:"sm",variant:c?"secondary":"outline","aria-expanded":d?c:void 0,onClick:l.onClick,children:[l.label,d&&(0,A.jsx)(Jt.ChevronDown,{className:Q("af-ml-1 af-h-3.5 af-w-3.5 af-transition-transform",c&&"af-rotate-180"),"aria-hidden":!0})]})]}),c&&d&&(0,A.jsx)("div",{className:"af-border-t af-bg-background af-p-4",children:d})]})}function Tn({tone:e,children:t}){return(0,A.jsx)("span",{className:Q("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 ti(e){return e.domain.status==="verified"&&e.domain.dmarc_status==="ok"}function gl(e){let{sending_domain:t,status:a}=e.domain;return!t||a==="none"?(0,A.jsx)(Tn,{tone:"gray",children:"Not set up"}):a==="verified"?ti(e)?(0,A.jsx)(Tn,{tone:"green",children:"Live"}):(0,A.jsx)(Tn,{tone:"amber",children:"DMARC record missing"}):a==="failed"?(0,A.jsx)(Tn,{tone:"red",children:"Records not found"}):(0,A.jsx)(Tn,{tone:"amber",children:"Waiting for DNS"})}function Im({settings:e,businessName:t,onSaved:a}){let{canWrite:s}=Qe(),[n,r]=js.useState(e.business_name??t??""),[i,l]=js.useState(e.postal_address??""),[c,d]=js.useState(e.reply_to??""),o=pt();return(0,A.jsxs)("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:[(0,A.jsx)(Am,{name:n,address:i}),(0,A.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,A.jsx)("span",{className:"af-text-sm af-font-medium",children:"Sender name"}),(0,A.jsx)(ce,{"aria-label":"Business name",value:n,disabled:!s,onChange:u=>r(u.target.value)})]}),(0,A.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,A.jsx)("span",{className:"af-text-sm af-font-medium",children:"Mailing address"}),(0,A.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:i,disabled:!s,onChange:u=>l(u.target.value)}),(0,A.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Anti-spam law requires it at the bottom of every email. A PO box works."})]}),(0,A.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,A.jsx)("span",{className:"af-text-sm af-font-medium",children:"Replies go to (optional)"}),(0,A.jsx)(ce,{"aria-label":"Reply-to email",type:"email",value:c,disabled:!s,onChange:u=>d(u.target.value)}),(0,A.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Your account email or an address on your domain."})]}),o.error&&(0,A.jsx)(be,{tone:"error",children:o.error}),s&&(0,A.jsx)(y,{type:"submit",size:"sm",disabled:o.busy||!i.trim(),children:"Save sender details"})]})}function Am({name:e,address:t}){return(0,A.jsxs)("div",{className:"af-rounded-lg af-bg-muted/50 af-px-4 af-py-4 af-text-center af-text-xs af-leading-relaxed af-text-muted-foreground",children:[(0,A.jsx)("div",{className:"af-mb-1 af-text-[10px] af-uppercase af-tracking-wide",children:"Footer of every email"}),(0,A.jsxs)("div",{children:["\xA9 ",new Date().getFullYear()," ",(0,A.jsx)("span",{className:"af-font-medium af-text-foreground",children:e.trim()||"Your business"})]}),(0,A.jsx)("div",{className:Q(!t.trim()&&"af-italic af-text-amber-700"),children:t.trim()||"No mailing address yet"}),(0,A.jsxs)("div",{children:[(0,A.jsx)("span",{className:"af-underline",children:"Manage preferences"})," | ",(0,A.jsx)("span",{className:"af-underline",children:"Unsubscribe"})]})]})}var Dm={1:"From",2:"Subject and body",3:"Footer"};function so({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?(0,A.jsxs)("div",{"data-preview-region":u,"data-highlighted":n===u,className:Q("af-relative af-rounded-md af-transition-shadow",n===u&&"af-ring-2 af-ring-primary af-ring-offset-2",b),children:[(0,A.jsxs)("span",{className:"af-absolute -af-left-3 -af-top-2 af-flex af-h-5 af-w-5 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-[10px] af-font-semibold af-text-background",children:[(0,A.jsx)("span",{"aria-hidden":!0,children:u}),(0,A.jsxs)("span",{className:"af-sr-only",children:[u,". ",Dm[u],":"]})]}),v]}):(0,A.jsx)("div",{className:b,children:v});return(0,A.jsxs)("div",{className:Q("af-rounded-lg af-border af-bg-background af-p-4 af-shadow-sm",a),"aria-hidden":s?void 0:!0,"aria-label":s?"Email preview":void 0,role:s?"group":void 0,children:[o(1,"af-flex af-items-start af-gap-3",(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-sm af-font-semibold af-text-white",style:c,children:i.slice(0,1).toUpperCase()}),(0,A.jsxs)("div",{className:"af-min-w-0",children:[(0,A.jsx)("div",{className:"af-truncate af-text-sm af-font-semibold",children:i}),(0,A.jsxs)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:["<",ml(l),">"]}),(0,A.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:"to me"})]})]})),o(2,"af-mt-4 af-space-y-2",(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)("div",{className:"af-text-sm af-font-medium",children:"What's new this month"}),(0,A.jsx)("div",{className:"af-h-2 af-w-full af-rounded af-bg-muted"}),(0,A.jsx)("div",{className:"af-h-2 af-w-5/6 af-rounded af-bg-muted"}),(0,A.jsx)("div",{className:"af-h-2 af-w-2/3 af-rounded af-bg-muted"})]})),o(3,"af-mt-4 af-border-t af-pt-2 af-text-center af-text-[10px] af-leading-snug af-text-muted-foreground",(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)("div",{children:d??(0,A.jsx)("span",{className:"af-italic af-text-amber-700",children:"Mailing address goes here"})}),(0,A.jsx)("div",{className:"af-underline",children:"Unsubscribe"})]}))]})}var Om="Add a newsletter signup to my footer";function Lm({onAskAssistant:e}){let t=bl();if(!t.data)return null;let{signups:a,optIns:s,others:n}=hl(t.data);return(0,A.jsxs)("div",{className:"af-space-y-3",children:[a.length===0?(0,A.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-gap-2 af-rounded-lg af-border af-border-dashed af-px-6 af-py-6 af-text-center",children:[(0,A.jsx)("div",{className:"af-flex af-h-10 af-w-10 af-items-center af-justify-center af-rounded-full af-bg-muted",children:(0,A.jsx)(Jt.Mail,{className:"af-h-5 af-w-5","aria-hidden":!0})}),(0,A.jsx)("div",{className:"af-text-sm af-font-medium",children:"Add a signup form to your site"}),(0,A.jsx)("p",{className:"af-max-w-sm af-text-xs af-text-muted-foreground",children:`A short "Get our news" form, usually in the footer. It's how most of your list will find you.`}),e&&(0,A.jsxs)(y,{type:"button",size:"sm",className:"af-mt-1",onClick:()=>e(Om),children:[(0,A.jsx)(Jt.Sparkles,{className:"af-mr-1.5 af-h-3.5 af-w-3.5","aria-hidden":!0}),"Add signup form"]})]}):(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[(0,A.jsx)(Jt.Check,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),(0,A.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,A.jsx)("span",{className:"af-font-medium",children:"Signup form is live"}),(0,A.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",a.map(r=>r.name).join(", ")]})]})]}),s.length>0&&(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[(0,A.jsx)(Jt.Check,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),(0,A.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,A.jsx)("span",{className:"af-font-medium",children:"Opt-in checkbox"}),(0,A.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",s.map(r=>r.name).join(", ")]})]})]}),a.length===0&&n.length>0&&(0,A.jsxs)("p",{className:"af-px-2 af-text-xs af-text-muted-foreground",children:["Your ",n.length===1?"form":"forms"," ",n.map(r=>`"${r.name}"`).join(", "),' can also add people, with a "Send me news" checkbox.',e&&(0,A.jsxs)(A.Fragment,{children:[" ",(0,A.jsx)("button",{type:"button",className:"af-font-medium af-text-foreground af-underline af-underline-offset-2",onClick:()=>e(yl(n)),children:"Add the checkbox"})]})]})]})}var re=require("react/jsx-runtime"),ai="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 Bm(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 xl({onStartDomainSetup:e,onAskAssistant:t}){let{settings:a,refetchSettings:s,canWrite:n,settingsSection:r}=Qe(),[i,l]=ka.useState(null),[c,d]=ka.useState(null),[o,u]=ka.useState(""),b=a!==null;if(ka.useEffect(()=>{b&&r&&document.getElementById(Yr(r))?.scrollIntoView?.({block:"start"})},[b,r]),!a)return(0,re.jsx)(ee,{className:"af-h-40 af-w-full"});let v=h=>d(P=>P===h?null:h),m=()=>d(null),p=async()=>{await s(),m()},f=(h,P,_)=>({id:_,"data-settings-row":h,onMouseEnter:()=>l(P),onMouseLeave:()=>l(null),onFocus:()=>l(P),onBlur:()=>l(null)}),g=ti(a),{sending_domain:x,status:k}=a.domain,T=h=>n?{expanded:c===h}:{};return(0,re.jsx)("div",{className:"af-@container",children:(0,re.jsxs)("div",{className:"af-grid af-items-start af-gap-6 @2xl:af-grid-cols-[minmax(0,17rem)_minmax(0,1fr)]",children:[(0,re.jsxs)("aside",{className:"af-space-y-3 af-pl-3",children:[(0,re.jsx)("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails look like this"}),(0,re.jsx)(so,{settings:a,site:{},numbered:!0,highlight:i,postalAddress:c==="address"?o:void 0}),(0,re.jsx)(Hm,{settings:a})]}),(0,re.jsxs)("div",{children:[(0,re.jsx)(xa,{children:"From"}),(0,re.jsxs)("div",{className:"af-space-y-2",children:[(0,re.jsx)("div",{...f("Sending domain",1,Yr("domain")),children:(0,re.jsx)(En,{marker:1,label:"Sending from",value:x?ml(x):"No sending domain yet",status:gl(a),action:!g&&n?{label:x?k==="verified"||k==="failed"?"Fix":"Details":"Set up",onClick:()=>v("domain")}:void 0,...T("domain"),children:(0,re.jsx)(vl,{settings:a,canWrite:n,onStartDomainSetup:e,onChanged:s})})}),(0,re.jsx)("div",{...f("Sender name and replies",1),children:(0,re.jsx)(En,{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:()=>v("sender")}:void 0,...T("sender"),children:(0,re.jsx)(Fm,{settings:a,onSaved:p,onCancel:m})})})]}),(0,re.jsx)(xa,{children:"Brand"}),(0,re.jsx)("div",{...f("Brand color and logo",2),children:(0,re.jsx)(En,{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:()=>v("brand")}:void 0,...T("brand"),children:(0,re.jsx)(Mm,{settings:a,onSaved:p,onCancel:m})})}),(0,re.jsx)(xa,{children:"Footer"}),(0,re.jsx)("div",{...f("Mailing address",3,Yr("sender")),children:(0,re.jsx)(En,{marker:3,label:"Mailing address",mono:!1,value:a.postal_address??"Not set",hint:"Anti-spam law requires it at the bottom of every email. A PO box works.",status:a.postal_address?void 0:(0,re.jsx)(Tn,{tone:"amber",children:"Needed"}),action:n?{label:a.postal_address?"Edit":"Add",onClick:()=>{u(a.postal_address??""),v("address")}}:void 0,...T("address"),children:(0,re.jsx)($m,{settings:a,draft:o,onDraft:u,onSaved:p,onCancel:m})})}),(0,re.jsxs)("div",{id:Yr("signups"),children:[(0,re.jsx)(xa,{children:"Who gets it"}),(0,re.jsxs)("div",{className:"af-space-y-2",children:[(0,re.jsx)("div",{...f("Double opt-in",null),children:(0,re.jsx)(Um,{settings:a,canWrite:n,onSaved:s})}),(0,re.jsx)(zm,{onAskAssistant:n?t:void 0})]})]})]})]})})}function io(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 wl({busy:e,error:t,canSave:a=!0,onSave:s,onCancel:n,children:r}){return(0,re.jsxs)("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),await s()},children:[r,t&&(0,re.jsx)(be,{tone:"error",children:t}),(0,re.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,re.jsx)(y,{type:"submit",size:"sm",disabled:e||!a,children:"Save"}),(0,re.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Cancel"})]})]})}function Fm({settings:e,onSaved:t,onCancel:a}){let[s,n]=ka.useState(e.business_name??""),[r,i]=ka.useState(e.reply_to??""),l=pt();return(0,re.jsxs)(wl,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",io(e,{business_name:s.trim()||null,reply_to:r.trim()||null}))).ok&&await t()},children:[(0,re.jsx)(ro,{label:"Sender name",children:(0,re.jsx)(ce,{"aria-label":"Business name",value:s,onChange:c=>n(c.target.value)})}),(0,re.jsx)(ro,{label:"Replies go to (your account email or an address on your domain)",children:(0,re.jsx)(ce,{"aria-label":"Reply-to email",type:"email",value:r,onChange:c=>i(c.target.value)})})]})}function Mm({settings:e,onSaved:t,onCancel:a}){let[s,n]=ka.useState(e.brand.color),[r,i]=ka.useState(e.brand.logo_url??""),l=pt();return(0,re.jsx)(wl,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",io(e,{brand:{color:s,logo_url:r.trim()||null}}))).ok&&await t()},children:(0,re.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-3",children:[(0,re.jsx)(ro,{label:"Brand color",children:(0,re.jsx)(ce,{"aria-label":"Brand color",type:"color",className:"af-h-9 af-w-16 af-p-1",value:s,onChange:c=>n(c.target.value)})}),(0,re.jsx)(ro,{label:"Logo URL (https)",children:(0,re.jsx)(ce,{"aria-label":"Logo URL",value:r,onChange:c=>i(c.target.value)})})]})})}function $m({settings:e,draft:t,onDraft:a,onSaved:s,onCancel:n}){let r=pt();return(0,re.jsx)(wl,{busy:r.busy,error:r.error,canSave:!!t.trim(),onCancel:n,onSave:async()=>{(await r.run("updateSettings",io(e,{postal_address:t.trim()}))).ok&&await s()},children:(0,re.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:t,onChange:i=>a(i.target.value)})})}function Um({settings:e,canWrite:t,onSaved:a}){let[s,n]=ka.useState(null),[r,i]=ka.useState(!1),l=pt(),c=s??e.double_opt_in;return(0,re.jsxs)("div",{className:"af-space-y-2",children:[(0,re.jsx)(En,{icon:qs.ShieldCheck,label:"Double opt-in",mono:!1,value:c?"New subscribers confirm by email first":"New subscribers join straight away",status:(0,re.jsxs)("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[(0,re.jsx)("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:ai,className:"af-inline-flex af-h-4 af-w-4 af-cursor-help af-items-center af-justify-center af-rounded-full af-border af-text-[10px]",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:"?"}),(0,re.jsx)("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!r,className:"af-absolute af-right-0 af-top-6 af-z-10 af-w-72 af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:ai}),(0,re.jsx)("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",io(e,{double_opt_in:o}))).ok&&await a(),n(null)}})]})}),l.error&&(0,re.jsx)(be,{tone:"error",children:l.error})]})}function vl({settings:e,canWrite:t,onStartDomainSetup:a,onChanged:s}){let[n,r]=ka.useState(null),[i,l]=ka.useState(!1),[c,d]=ka.useState(null),o=ti(e);return(0,re.jsxs)("div",{children:[(0,re.jsx)("p",{className:"af-text-sm",children:Bm(e)}),!o&&a&&(0,re.jsx)(y,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||i,onClick:async()=>{l(!0),d(null);try{r(await a()),await s()}catch(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&&(0,re.jsx)(be,{tone:"error",className:"af-mt-2",children:c}),n?.records&&n.records.length>0&&(0,re.jsxs)("div",{className:"af-mt-3 af-space-y-1",children:[(0,re.jsx)("p",{className:"af-text-sm",children:"Add these records at your domain provider:"}),(0,re.jsxs)("table",{className:"af-w-full af-text-left af-text-xs",children:[(0,re.jsx)("thead",{children:(0,re.jsxs)("tr",{children:[(0,re.jsx)("th",{className:"af-py-1 af-pr-2",children:"Type"}),(0,re.jsx)("th",{className:"af-py-1 af-pr-2",children:"Name"}),(0,re.jsx)("th",{className:"af-py-1 af-pr-2",children:"Value"}),(0,re.jsx)("th",{className:"af-py-1",children:"Priority"})]})}),(0,re.jsx)("tbody",{children:n.records.map((u,b)=>(0,re.jsxs)("tr",{className:"af-border-t af-align-top",children:[(0,re.jsx)("td",{className:"af-py-1 af-pr-2",children:u.type}),(0,re.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:u.name}),(0,re.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:u.value}),(0,re.jsx)("td",{className:"af-py-1",children:u.priority??""})]},b))})]})]}),n&&(0,re.jsx)(Vm,{result:n})]})}function Vm({result:e}){return e.status==="no_domain"?(0,re.jsx)(be,{tone:"warning",className:"af-mt-2",children:"Emails send from your own domain, so this site needs a custom domain first. Connect one, then come back to finish here."}):e.status==="not_available"?(0,re.jsx)(be,{tone:"warning",className:"af-mt-2",children:"Email sending isn't available for this site. It needs the Pro plan."}):e.records&&e.records.length>0?null:(0,re.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",children:"We added the DNS records for you. Verification usually finishes within a few hours."})}function Hm({settings:e}){let{monthly:t,sent:a,reserved:s}=e.allowance,n=a+s;return(0,re.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[Ve(n)," of ",Ve(t)," emails used this month (",Ve(Math.max(0,t-n))," left). Receipts and form notifications don't count."]})}function bl(){let{api:e}=G(),{siteId:t,refreshKey:a}=Qe();return Mt(async()=>Promise.all((await e.getForms()).map(s=>e.getForm(s.id))),`${t}|${a}`,t)}function hl(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 yl(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 zm({onAskAssistant:e}){let t=bl();if(!t.data||t.data.length===0)return null;let{signups:a,optIns:s,others:n}=hl(t.data),r=[{id:"signup",label:"Signup forms",note:"Submitting one subscribes the visitor.",forms:a,icon:qs.Check},{id:"opt_in",label:'Forms with a "Send me news" checkbox',note:"Visitors who tick the box join your list.",forms:s,icon:qs.Check},{id:"other",label:"Other forms",note:"These don't add anyone to your list.",forms:n,icon:qs.FileText,action:a.length===0&&e?{label:"Add the checkbox",onClick:()=>e(yl(n))}:void 0}];return(0,re.jsx)(re.Fragment,{children:r.filter(i=>i.forms.length>0).map(i=>(0,re.jsx)("div",{"data-form-group":i.id,children:(0,re.jsx)(En,{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 ro({label:e,children:t}){return(0,re.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,re.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}var oo=le(require("react"),1);var ht=require("react/jsx-runtime");function Vd({templateId:e,onOpenTemplate:t,onOpenDraft:a,onAskAssistant:s}){let{api:n}=G(),{siteId:r,canWrite:i,refreshKey:l}=Qe(),[c,d]=oo.useState(0),o=c+l,u=Mt(()=>n.getEmailTemplates(r),`${r}|${o}`,r),b=oo.useCallback(()=>d(f=>f+1),[]),v=i?s:void 0;if(e){let f=e===qn?null:u.data?.find(g=>g.id===e);if(f!==void 0)return(0,ht.jsx)(Ed,{template:f,onBack:()=>t(null),onOpenTemplate:t,onOpenDraft:a,onAskAssistant:v,reload:b,refreshKey:o},e);if(u.isLoading)return(0,ht.jsx)(ee,{className:"af-h-96 af-w-full"})}let m=u.data?.filter(f=>f.status!=="archived")??[],p=u.data?.filter(f=>f.status==="archived")??[];return(0,ht.jsxs)("div",{children:[(0,ht.jsxs)("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[(0,ht.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Templates"}),v&&(0,ht.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>v(to.create),children:"\u2728 New template with the editor"})]}),(0,ht.jsxs)(Ud,{children:[(0,ht.jsx)(Sl,{template:null,onOpen:()=>t(qn)}),m.map(f=>(0,ht.jsx)(Sl,{template:f,onOpen:()=>t(f.id)},f.id))]}),u.error&&!u.data?(0,ht.jsx)("div",{className:"af-mt-3",children:(0,ht.jsx)(wt,{message:"Couldn't load your templates.",onRetry:()=>void u.refetch()})}):!u.data&&(0,ht.jsx)(ee,{className:"af-mt-3 af-h-10 af-w-full"}),p.length>0&&(0,ht.jsxs)("div",{"data-testid":"archived-templates",children:[(0,ht.jsx)(xa,{children:"Archived"}),(0,ht.jsx)(Ud,{children:p.map(f=>(0,ht.jsx)(Sl,{template:f,onOpen:()=>t(f.id)},f.id))})]})]})}function Ud({children:e}){return(0,ht.jsx)("ul",{className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:e})}function jm(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 Sl({template:e,onOpen:t}){let a=e?.name??"Standard",s=e&&jm(e);return(0,ht.jsxs)("li",{"data-testid":"template-card",className:"af-relative af-overflow-hidden af-rounded-md af-border hover:af-border-primary",children:[(0,ht.jsx)(ao,{templateId:e?.id??qn,version:e?.updated_at??"builtin",className:"af-h-40 af-border-b",frame:{width:600,height:400,scale:.4}}),(0,ht.jsxs)("div",{className:"af-space-y-1 af-p-2",children:[(0,ht.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ht.jsx)("span",{"data-testid":"template-name",className:"af-grow af-truncate af-text-sm af-font-medium",children:a}),(0,ht.jsx)(cl,{template:e})]}),s&&(0,ht.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:s})]}),(0,ht.jsx)("button",{type:"button","aria-label":`Open ${a}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}var nn=le(require("react"),1),fo=require("lucide-react");var Ma=le(require("react"),1),wa=require("lucide-react");var pe=require("react/jsx-runtime"),qm=365*24,Wm=[1,24,48,72,168];function co(e){return e.map(t=>t.type==="send"?{type:"send",draft_id:t.draft_id}:{type:"wait",wait_hours:t.wait_hours})}function hs(e){return e%168===0?$s(e/168,"week"):e%24===0?$s(e/24,"day"):$s(e,"hour")}var si={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 ri(e,t){return e.slice(0,t+1).filter(a=>a.type==="send").length}var lo=300,Hd=64,Gm=24,ni={trigger:72,send:104,wait:64,waitEditing:196,exit:44};function Km(e,t){let a=[],s=0,n=r=>{a.push({...r,y:s}),s+=r.height+Hd};return n({id:"trigger",kind:"trigger",height:ni.trigger}),e.forEach((r,i)=>n({id:r.step_key,kind:r.type,index:i,height:r.type==="send"?ni.send:r.step_key===t?ni.waitEditing:ni.wait})),n({id:"exit",kind:"exit",height:ni.exit}),{nodes:a,height:s-Hd}}var jd=Ma.createContext(null);function ii(){let e=Ma.useContext(jd);if(!e)throw new Error("Canvas nodes render inside AutomationCanvas");return e}function Nl(e,t){let a=e[t];return a.type==="send"?`email ${ri(e,t)}`:`the ${hs(a.wait_hours)} wait`}function qd(e){let{automation:t,onChangeSteps:a}=e,s=t.steps,[n,r]=Ma.useState(null),[i,l]=Ma.useState(null),[c,d]=Ma.useState(null),o=(m,p)=>{d(null),r(null),l(null),a(m,p)},u=co(s),b={...e,insertAt:n,setInsertAt:m=>{d(null),r(m)},editingWait:i,setEditingWait:l,insertWait:m=>{if(!u.slice(m).some(p=>p.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,p)=>o(u.map((f,g)=>g===m?{type:"wait",wait_hours:p}:f),`Change ${Nl(s,m)} to ${hs(p)}`),move:(m,p)=>{let f=[...u];[f[m],f[m+p]]=[f[m+p],f[m]],o(f,`Move ${Nl(s,m)} ${p<0?"up":"down"}`)},remove:m=>o(u.filter((p,f)=>f!==m),`Remove ${Nl(s,m)}`)},v=Km(s,i);return(0,pe.jsxs)(jd.Provider,{value:b,children:[c&&(0,pe.jsx)(be,{className:"af-mb-2",children:c}),(0,pe.jsx)("div",{"data-testid":"automation-canvas",className:"af-rounded-md af-border af-bg-muted/40",style:{height:v.height+2*Gm},children:(0,pe.jsx)(Ma.Suspense,{fallback:(0,pe.jsx)(ee,{className:"af-h-full af-w-full"}),children:(0,pe.jsx)(Zm,{layout:v,steps:s})})})]})}var Zm=Ma.lazy(async()=>({default:Ym(await import("@xyflow/react"))}));function Ym(e){let t=l=>[{type:"target",position:e.Position.Top,x:lo/2,y:0,width:1,height:1},{type:"source",position:e.Position.Bottom,x:lo/2,y:l,width:1,height:1}],a=()=>(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)(e.Handle,{type:"target",position:e.Position.Top,isConnectable:!1,className:"!af-opacity-0"}),(0,pe.jsx)(e.Handle,{type:"source",position:e.Position.Bottom,isConnectable:!1,className:"!af-opacity-0"})]}),s=l=>(0,pe.jsxs)(pe.Fragment,{children:[l,(0,pe.jsx)(a,{})]}),n={trigger:()=>s((0,pe.jsx)(zd,{kind:"trigger"})),send:({data:l})=>s((0,pe.jsx)(Jm,{index:l.index,step:l.step})),wait:({data:l})=>s((0,pe.jsx)(Xm,{index:l.index,step:l.step})),exit:()=>s((0,pe.jsx)(zd,{kind:"exit"}))};function r({id:l,sourceX:c,sourceY:d,targetX:o,targetY:u,data:b}){let[v,m,p]=e.getStraightPath({sourceX:c,sourceY:d,targetX:o,targetY:u});return(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)(e.BaseEdge,{id:l,path:v}),(0,pe.jsx)(e.EdgeLabelRenderer,{children:(0,pe.jsx)("div",{className:"nodrag nopan af-pointer-events-auto af-absolute",style:{transform:`translate(-50%, -50%) translate(${m}px, ${p}px)`},children:(0,pe.jsx)(ep,{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:lo,height:b.height,style:{width:lo,height:b.height},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(0,pe.jsx)(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 zd({kind:e}){let{automation:t}=ii();return e==="exit"?(0,pe.jsx)("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"}):(0,pe.jsxs)("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:[(0,pe.jsx)(wa.Zap,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,pe.jsxs)("div",{className:"af-min-w-0",children:[(0,pe.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:"Trigger"}),(0,pe.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:si[t.trigger_type].title})]})]})}function Wd({index:e,label:t}){let{automation:a,editable:s,move:n,remove:r}=ii();if(!s)return null;let i=a.steps.length-1;return(0,pe.jsxs)("div",{className:"af-flex af-shrink-0 af-gap-0.5",children:[(0,pe.jsx)(Rl,{label:`Move ${t} up`,disabled:e===0,onClick:()=>n(e,-1),children:(0,pe.jsx)(wa.ArrowUp,{})}),(0,pe.jsx)(Rl,{label:`Move ${t} down`,disabled:e===i,onClick:()=>n(e,1),children:(0,pe.jsx)(wa.ArrowDown,{})}),(0,pe.jsx)(Rl,{label:`Remove ${t}`,onClick:()=>r(e),children:(0,pe.jsx)(wa.Trash2,{})})]})}function Rl({label:e,disabled:t,onClick:a,children:s}){return(0,pe.jsx)(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 Jm({index:e,step:t}){let{automation:a,statsByStep:s,onOpenEmail:n}=ii(),r=ri(a.steps,e),i=s[t.step_key];return(0,pe.jsxs)("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:[(0,pe.jsxs)("div",{className:"af-flex af-items-start af-gap-2",children:[(0,pe.jsx)(wa.Mail,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0"}),(0,pe.jsxs)("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:[(0,pe.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Email ",r]}),(0,pe.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:t.subject||"(no subject)"})]}),a.status==="on"&&t.live&&(0,pe.jsx)(ie,{variant:"success",children:"Live"}),(0,pe.jsx)(Wd,{index:e,label:`email ${r}`})]}),(0,pe.jsx)("p",{"data-testid":"canvas-email-stats",className:"af-text-xs af-text-muted-foreground",children:i?`Sent ${Ve(i.sent)} \xB7 Opened ${Ve(i.opened)} \xB7 Clicked ${Ve(i.clicked)}`:"Not sent yet"})]})}function Xm({index:e,step:t}){let{editable:a,editingWait:s,setEditingWait:n,setWait:r}=ii(),i=`the ${hs(t.wait_hours)} wait`,l=a&&s===t.step_key;return(0,pe.jsxs)("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:[(0,pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,pe.jsx)(wa.Clock,{className:"af-h-4 af-w-4 af-shrink-0"}),a?(0,pe.jsxs)("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 ",hs(t.wait_hours)]}):(0,pe.jsxs)("span",{className:"af-grow af-text-sm",children:["Wait ",hs(t.wait_hours)]}),(0,pe.jsx)(Wd,{index:e,label:i})]}),l&&(0,pe.jsx)(Qm,{hours:t.wait_hours,onSave:c=>r(e,c),onCancel:()=>n(null)})]})}function Qm({hours:e,onSave:t,onCancel:a}){let s=e%24===0,[n,r]=Ma.useState(String(s?e/24:e)),[i,l]=Ma.useState(s?"days":"hours"),c=Number(n)*(i==="days"?24:1),d=Number.isInteger(c)&&c>=1&&c<=qm;return(0,pe.jsxs)("div",{"data-testid":"wait-editor",className:"nodrag af-space-y-2",children:[(0,pe.jsx)("div",{className:"af-flex af-flex-wrap af-gap-1",children:Wm.map(o=>(0,pe.jsx)(y,{type:"button",size:"sm",variant:o===e?"default":"outline",className:"af-h-7 af-px-2",onClick:()=>t(o),children:hs(o)},o))}),(0,pe.jsxs)("form",{className:"af-flex af-items-center af-gap-1",onSubmit:o=>{o.preventDefault(),d&&t(c)},children:[(0,pe.jsx)(ce,{"aria-label":"Custom wait",type:"number",min:1,value:n,onChange:o=>r(o.target.value),className:"af-h-7 af-w-20"}),(0,pe.jsxs)("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:[(0,pe.jsx)("option",{value:"hours",children:"hours"}),(0,pe.jsx)("option",{value:"days",children:"days"})]}),(0,pe.jsx)(y,{type:"submit",size:"sm",className:"af-h-7 af-px-2",disabled:!d,children:"Save"}),(0,pe.jsx)(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:a,children:"Cancel"})]}),!d&&(0,pe.jsx)("p",{className:"af-text-xs af-text-destructive",children:"A wait is 1 hour to 365 days."})]})}function ep({index:e}){let{editable:t,insertAt:a,setInsertAt:s,insertWait:n,onInsertEmail:r}=ii();if(!t)return null;let i=a===e;return(0,pe.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,pe.jsx)("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:Q("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:(0,pe.jsx)(wa.Plus,{className:"af-h-3.5 af-w-3.5"})}),i&&(0,pe.jsxs)("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:[(0,pe.jsxs)(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:()=>n(e),children:[(0,pe.jsx)(wa.Clock,{})," Wait"]}),(0,pe.jsxs)(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:()=>{s(null),r(e)},children:[(0,pe.jsx)(wa.Mail,{})," Email"]})]})]})}var j=require("react/jsx-runtime"),tp="Create an automation that ",ap={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 Gd({automation:e}){let[t,a]=e.status==="on"?e.available?["success","On"]:["warning","Unavailable"]:["secondary",e.status==="draft"?"Draft":"Off"];return(0,j.jsx)(ie,{"data-testid":"automation-state",variant:t,children:a})}function np(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 ${ri(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 ss(e)??"Something went wrong. Try again."}}function _l(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 oi({code:e,automation:t,stepKey:a,onOpenEmail:s}){let{openSettings:n,openSetup:r,onOpenStoreSettings:i}=Qe(),l=t&&a?t.steps.find(d=>d.step_key===a):void 0,c=null;return e==="postal_address_missing"?c=(0,j.jsx)(da,{onClick:()=>n("sender"),children:"Add it in Settings"}):e==="checkout_consent_off"&&i?c=(0,j.jsx)(da,{onClick:i,children:"Open Store settings"}):e==="email_empty"&&l?.type==="send"&&s?c=(0,j.jsx)(da,{onClick:()=>s(l.draft_id),children:"Open the email"}):e==="domain_not_verified"||e==="dmarc_missing"?c=(0,j.jsx)(da,{onClick:()=>n("domain"),children:"Fix in Settings"}):e==="sending_not_enabled"&&(c=(0,j.jsx)(da,{onClick:r,children:"Finish setup"})),(0,j.jsxs)(j.Fragment,{children:[np(e,t,a),c&&(0,j.jsxs)(j.Fragment,{children:[" ",c]})]})}function Kd({automationId:e,onOpenAutomation:t,list:a,onAskAssistant:s,onPickImage:n}){let{canWrite:r}=Qe(),i=r?s:void 0;if(e){let l=a.data?.automations.find(c=>c.id===e);if(l)return(0,j.jsx)(ip,{automation:l,reload:a.refetch,onBack:()=>t(null),onAskAssistant:i,onPickImage:n},l.id);if(!a.data&&!a.error)return(0,j.jsx)(ee,{className:"af-h-96 af-w-full"})}return(0,j.jsxs)("div",{children:[(0,j.jsxs)("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[(0,j.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Automations"}),i&&(0,j.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i(tp),children:"\u2728 New automation with the editor"})]}),a.error&&!a.data?(0,j.jsx)(wt,{message:"Couldn't load your automations.",onRetry:()=>void a.refetch()}):a.data?(0,j.jsxs)(j.Fragment,{children:[a.data.capabilities.suggestions.length>0&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(xa,{children:"Suggested"}),(0,j.jsx)("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=>(0,j.jsx)(rp,{suggestion:l,list:a.data,reload:a.refetch,onOpenAutomation:t},l))})]}),(0,j.jsx)(xa,{children:"Your automations"}),a.data.automations.length===0?(0,j.jsx)(la,{children:"No automations yet. Turn on a suggestion above, or ask the editor to build one."}):(0,j.jsx)("ul",{"data-testid":"automations",className:"af-divide-y af-rounded-md af-border",children:a.data.automations.map(l=>(0,j.jsx)(sp,{automation:l,onOpen:()=>t(l.id)},l.id))})]}):(0,j.jsx)(ee,{className:"af-h-24 af-w-full"})]})}function Zd(e){return[si[e.trigger_type].title,...e.steps.map(t=>t.type==="send"?"Email":`Wait ${hs(t.wait_hours)}`)].join(" \u2192 ")}function Yd(e){let{api:t}=G(),{siteId:a,refreshKey:s}=Qe(),n=e.status==="draft",r=Mt(()=>n?Promise.resolve([]):t.getAutomationStats(a,e.id),`${a}|${e.id}|${e.version}|${e.status}|${s}`,`${a}|${e.id}`);return nn.useMemo(()=>Object.fromEntries((r.data??[]).map(i=>[i.step_key,i])),[r.data])}function sp({automation:e,onOpen:t}){let a=Object.values(Yd(e)),s=n=>Ve(a.reduce((r,i)=>r+i[n],0));return(0,j.jsxs)("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:[(0,j.jsxs)("div",{className:"af-min-w-0 af-grow af-space-y-0.5",children:[(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,j.jsx)("span",{className:"af-truncate af-text-sm af-font-medium",children:e.name}),(0,j.jsx)(Gd,{automation:e})]}),(0,j.jsx)("p",{"data-testid":"automation-chain",className:"af-truncate af-text-xs af-text-muted-foreground",children:Zd(e)}),a.length>0&&(0,j.jsxs)("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")]})]}),(0,j.jsx)(fo.ChevronRight,{className:"af-h-4 af-w-4 af-shrink-0 af-text-muted-foreground"}),(0,j.jsx)("button",{type:"button","aria-label":`Open ${e.name}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}function rp({suggestion:e,list:t,reload:a,onOpenAutomation:s}){let{api:n}=G(),{siteId:r,canWrite:i,onOpenStoreSettings:l}=Qe(),c=pt(),[d,o]=nn.useState(!1),[u,b]=nn.useState(null),v=ap[e],m=t.automations.find(x=>x.trigger_type===v.trigger&&x.list_tag_id===null),p=e==="recovery"&&t.capabilities.checkout_consent==="off_available",f=async()=>{o(!1),b(null);let x=await c.run("addSuggestedAutomation",{key:e}),k=x.ok?x.result:null;if(!x.ok){let h=Fa(x.error,"automation_exists")?x.error:null,P=h?.automation_id??h?.details?.automation_id;if(!P)return;if(c.setError(null),k=await n.getAutomation(r,P).catch(()=>null),!k)return void a()}let T=await c.run("turnOnAutomation",{automationId:k.id,expected_version:k.version});T.ok||(c.setError(null),b({code:vs(T.error),stepKey:_l(T.error)})),await a()},g=()=>m?(0,j.jsx)("p",{className:"af-text-sm",children:(0,j.jsx)(da,{onClick:()=>s(m.id),children:"Open the automation"})}):i?d?(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsxs)("p",{className:"af-text-sm",children:['Turn on "',v.title,'"? It sends ',$s(v.emails,"email")," to each person who ",si[v.trigger].phrase,"."]}),(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>o(!1),children:"Cancel"}),(0,j.jsx)(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:c.busy,onClick:()=>void f(),children:"Turn on"})]})]}):p?(0,j.jsxs)("div",{className:"af-space-y-1",children:[(0,j.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Needs the marketing consent box at checkout, in Store settings."}),(0,j.jsx)(y,{type:"button",size:"sm",disabled:!l,onClick:()=>l?.(),children:"Turn on"})]}):(0,j.jsx)("div",{children:(0,j.jsx)(y,{type:"button",size:"sm",disabled:c.busy,onClick:()=>o(!0),children:"Turn on"})}):null;return(0,j.jsxs)("li",{"data-testid":"suggestion-card",className:"af-flex af-flex-col af-gap-2 af-rounded-md af-border af-p-3",children:[(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,j.jsx)("span",{"data-testid":"suggestion-title",className:"af-grow af-text-sm af-font-medium",children:v.title}),m&&(0,j.jsx)(ie,{variant:"secondary",children:"Added"})]}),(0,j.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:v.description}),u&&(0,j.jsxs)(be,{tone:"warning",children:["Not turned on. ",(0,j.jsx)(oi,{code:u.code,automation:m,stepKey:u.stepKey})]}),c.error&&(0,j.jsx)(be,{tone:"error",children:c.error}),g()]})}var uo={on:{message:(e,t)=>`Turn on "${e.name}"? It sends ${$s(t,"email")} to each person who ${si[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 ip({automation:e,reload:t,onBack:a,onAskAssistant:s,onPickImage:n}){let{api:r}=G(),{siteId:i,canWrite:l}=Qe(),c=Yd(e),d=pt(),o=pt(),u=pt(),[b,v]=nn.useState(null),[m,p]=nn.useState(null),[f,g]=nn.useState(null),[x,k]=nn.useState(null),[T,h]=nn.useState(null),[P,_]=nn.useState(!1),E=e.status==="on",w=e.steps.filter(D=>D.type==="send").length,I=async D=>{_(!0);try{await D()}finally{_(!1)}},O=(D,W)=>I(async()=>{g(null),k(null);let B=await d.run("updateAutomation",{automationId:e.id,expected_version:e.version,steps:D});if(!B.ok){let ue=vs(B.error);ue==="version_conflict"?(d.setError(null),g(W)):(ue==="email_empty"||ue==="postal_address_missing")&&(d.setError(null),k({code:ue,stepKey:_l(B.error)}))}await t()}),C=D=>I(async()=>{let W=await d.run("createDraft",{kind:"automation",automation_id:e.id,subject:"",blocks:[]});if(!W.ok)return;let B=W.result.id;if(E)return h({draftId:B,joinAt:D});let ue=co(e.steps);await O([...ue.slice(0,D),{type:"send",draft_id:B},...ue.slice(D)],"Add an email")}),Y=nn.useRef(Promise.resolve()),X=D=>{let W=Y.current.then(async()=>{let B=await r.getEmailDraft(i,D.draftId).catch(()=>null);if(!B||!B.subject.trim()||B.blocks.length===0)return;let ue=await r.getAutomation(i,e.id).catch(()=>null);if(!ue)return;if(ue.steps.some(He=>He.type==="send"&&He.draft_id===D.draftId))return h({draftId:D.draftId});let me=co(ue.steps),We=Math.min(D.joinAt,me.length);(await u.run("updateAutomation",{automationId:e.id,expected_version:ue.version,steps:[...me.slice(0,We),{type:"send",draft_id:D.draftId},...me.slice(We)]})).ok&&h({draftId:D.draftId}),await t()});return Y.current=W.catch(()=>{}),W},q=async D=>{v(null),p(null);let W=D==="turnOnAutomation"?{automationId:e.id,expected_version:e.version}:{automationId:e.id},B=await o.run(D,W);!B.ok&&D==="turnOnAutomation"&&(o.setError(null),p({code:vs(B.error),stepKey:_l(B.error)})),B.ok&&D==="deleteAutomation"&&a(),await t()},de=D=>(0,j.jsxs)("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:[(0,j.jsx)(da,{onClick:a,children:"Automations"}),(0,j.jsx)(fo.ChevronRight,{className:"af-h-3.5 af-w-3.5"}),D===void 0?(0,j.jsx)("span",{className:"af-font-medium af-text-foreground",children:e.name}):(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(da,{onClick:()=>h(null),children:e.name}),(0,j.jsx)(fo.ChevronRight,{className:"af-h-3.5 af-w-3.5"}),(0,j.jsx)("span",{className:"af-font-medium af-text-foreground",children:D})]})]});if(T){let D=e.steps.findIndex(B=>B.type==="send"&&B.draft_id===T.draftId),W=T.joinAt!==void 0;return(0,j.jsxs)("div",{children:[de(D>=0?`Email ${ri(e.steps,D)}`:"New email"),(0,j.jsx)(no,{draftId:T.draftId,allowCart:e.trigger_type==="abandoned_checkout",automationStep:{live:E&&!W,joinsOnSave:E&&W,notice:u.error&&(0,j.jsxs)(be,{tone:"error",children:["Couldn't add this email to the automation. ",u.error]}),onBackToCanvas:()=>h(null)},onSaved:()=>{T.joinAt!==void 0?X({draftId:T.draftId,joinAt:T.joinAt}):t()},onAskAssistant:s,onPickImage:n},T.draftId)]})}let ge=e.blocked_by[0]??null,ye=E&&!e.available;return(0,j.jsxs)("div",{className:"af-space-y-3",children:[de(),(0,j.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,j.jsx)("h3",{"data-testid":"automation-title",className:"af-grow af-truncate af-text-base af-font-semibold",children:e.name}),(0,j.jsx)(Gd,{automation:e}),l&&!b&&(0,j.jsx)(j.Fragment,{children:E?(0,j.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:o.busy,onClick:()=>v("off"),children:"Turn off"}):(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:o.busy,onClick:()=>v("delete"),children:"Delete"}),(0,j.jsx)(y,{type:"button",size:"sm",disabled:o.busy,onClick:()=>v("on"),children:"Turn on"})]})})]}),(0,j.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:Zd(e)}),b&&(0,j.jsxs)("div",{"data-testid":"automation-confirm",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,j.jsx)("p",{className:"af-text-sm",children:uo[b].message(e,w)}),(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>v(null),children:"Cancel"}),(0,j.jsx)(y,{type:"button",size:"sm",variant:uo[b].variant,className:"af-ml-auto",disabled:o.busy,onClick:()=>void q(uo[b].action),children:uo[b].label})]})]}),m&&(0,j.jsxs)(be,{tone:"warning",children:[(0,j.jsx)("span",{className:"af-font-medium",children:"Not turned on."})," ",(0,j.jsx)(oi,{code:m.code,automation:e,stepKey:m.stepKey,onOpenEmail:D=>h({draftId:D})})]}),o.error&&(0,j.jsx)(be,{tone:"error",children:o.error}),ye?(0,j.jsxs)(be,{tone:"warning",children:[(0,j.jsx)("span",{className:"af-font-medium",children:"Unavailable."})," ",(0,j.jsx)(oi,{code:ge??"trigger_unavailable",automation:e})," Nobody new enters it; people already in it still get their remaining emails."]}):ge&&!m&&(0,j.jsxs)(be,{tone:"warning",children:[E?"Not sending right now.":"Won't send yet."," ",(0,j.jsx)(oi,{code:ge,automation:e})]}),E&&!ye&&(0,j.jsxs)(be,{tone:"success",children:[(0,j.jsx)("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&&(0,j.jsxs)(be,{tone:"warning",children:["This automation changed while you were editing, so your change wasn't saved: ",(0,j.jsx)("span",{className:"af-font-medium",children:f}),". Here is the latest version; make the change again if you still want it."]}),x&&(0,j.jsxs)(be,{tone:"warning",children:["Not saved. ",(0,j.jsx)(oi,{code:x.code,automation:e,stepKey:x.stepKey,onOpenEmail:D=>h({draftId:D})})]}),d.error&&(0,j.jsx)(be,{tone:"error",children:d.error}),(0,j.jsx)(qd,{automation:e,statsByStep:c,editable:l&&!d.busy&&!P,onChangeSteps:(D,W)=>void O(D,W),onInsertEmail:D=>void C(D),onOpenEmail:D=>h({draftId:D})})]})}var Xe=require("react/jsx-runtime"),op=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"automations",label:"Automations"},{id:"templates",label:"Templates"},{id:"settings",label:"Settings"}];function Wn(e,t={}){return{tab:e,draftId:null,templateId:null,automationId:null,...t}}var Jd=e=>!!(e.tab||e.draftId||e.templateId||e.automationId);function Xd(e){return e.draftId?Wn("broadcasts"):e.templateId?Wn("templates",{templateId:e.templateId}):e.automationId?Wn("automations",{automationId:e.automationId}):Wn(e.tab==="template"?"templates":e.tab??"audience")}var lp={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function kl(e){return(0,Xe.jsx)(cp,{...e},e.siteId)}function cp({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:p,onTurnOn:f,siteDomain:g,businessName:x,onOpenStoreSettings:k,refreshKey:T=0,className:h}){let{api:P}=G(),_=Mt(()=>P.getMarketingSettings(e),`${e}|${T}`,e),E=Mt(()=>P.getAutomations(e),`${e}|${T}`,e),w=E.data?.capabilities.automations_enabled===!0,I={tab:n,draftId:s,templateId:i,automationId:r},[O,C]=Xt.useState(()=>Xd(I)),[Y,X]=Xt.useState(s??null),[q,de]=Xt.useState(Jd(I)),[ge,ye]=Xt.useState(null),[D,W]=Xt.useState(!1),B=Xt.useCallback(()=>de(!1),[]),ue=Xt.useCallback(H=>{C(Wn("settings")),ye(H??null)},[]),me=H=>{C(Wn(H)),ye(null)},We=Xt.useCallback(H=>C(Wn("broadcasts",{draftId:H})),[]),Ie=Xt.useCallback(H=>C(Wn("templates",{templateId:H})),[]),He=Xt.useCallback(H=>C(Wn("automations",{automationId:H})),[]),et=!q&&_.data!==null&&dp(_.data),De=O.tab==="automations"&&!w&&!E.data&&!E.error,Ke=O.tab==="automations"&&!w&&!De?"audience":O.tab,L=_.data&&!_.error?up(_.data):null,V=JSON.stringify([l??null,n??null,s??null,i??null,r??null]),$=Xt.useRef(V);Xt.useEffect(()=>{if(V===$.current||D)return;$.current=V;let H={tab:n,draftId:s,templateId:i,automationId:r};Jd(H)&&(C(Xd(H)),X(H.draftId??null),ye(null),de(!0))},[V,D,n,s,i,r]),Xt.useEffect(()=>{if(!Y||a)return;let H=!0,ke=ze=>{H&&(C(Wn("broadcasts",{draftId:ze})),X(null))};return P.getEmailDraft(e,Y).then(ze=>ke(ze.kind==="broadcast"?ze.id:null),()=>ke(null)),()=>{H=!1}},[P,e,Y,a]);let xe=Xt.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:c,settings:_.data,refetchSettings:_.refetch,refreshKey:T,openSetup:B,openSettings:ue,settingsSection:ge,onOpenStoreSettings:k,setInlineEditOpen:W}),[e,t,c,_.data,_.refetch,T,B,ue,ge,k]);return a?(0,Xe.jsx)(Ft,{title:"Email Marketing",onBackToWebsite:u,className:h,children:(0,Xe.jsx)(pl,{settings:_.data,site:{siteDomain:g,businessName:x},children:(0,Xe.jsx)($d,{onUpgradePlan:b})})}):(0,Xe.jsx)(Ft,{title:"Email Marketing",onBackToWebsite:u,className:h,children:(0,Xe.jsx)(al.Provider,{value:xe,children:et?(0,Xe.jsx)(Md,{onStartDomainSetup:o,onConnectDomain:v,onAskAssistant:m,onTurnOn:f,siteDomain:g,businessName:x}):(0,Xe.jsxs)(Xe.Fragment,{children:[_.error&&!_.data&&(0,Xe.jsx)(wt,{message:"Couldn't load email settings.",onRetry:()=>void _.refetch()}),L&&(0,Xe.jsx)(mp,{reason:L,pauseReason:_.data?.paused.reason??null,onRequestReview:d}),!t&&(0,Xe.jsx)(be,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),(0,Xe.jsx)("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:op.filter(H=>H.id!=="automations"||w).map(H=>(0,Xe.jsxs)("button",{type:"button",role:"tab","aria-selected":Ke===H.id,onClick:()=>me(H.id),className:Q("af-border-b-2 af-px-3 af-py-2 af-text-sm",Ke===H.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:[H.label,H.id==="settings"&&L&&(0,Xe.jsx)("span",{"data-testid":"settings-dot",role:"img","aria-label":"Sending is on hold",className:"af-ml-1.5 af-inline-block af-h-1.5 af-w-1.5 af-rounded-full af-bg-amber-600 af-align-middle"})]},H.id))}),(0,Xe.jsx)("div",{role:"tabpanel",children:Y||De?(0,Xe.jsx)(ee,{className:"af-h-24 af-w-full"}):Ke==="audience"?(0,Xe.jsx)(wd,{}):Ke==="broadcasts"?(0,Xe.jsx)(Bd,{openDraftId:O.draftId,onOpenDraft:We,onAskAssistant:m,onPickImage:p}):Ke==="automations"?(0,Xe.jsx)(Kd,{automationId:O.automationId,onOpenAutomation:He,list:E,onAskAssistant:m,onPickImage:p}):Ke==="templates"?(0,Xe.jsx)(Vd,{templateId:O.templateId,onOpenTemplate:Ie,onOpenDraft:We,onAskAssistant:m}):(0,Xe.jsx)(xl,{onStartDomainSetup:o,onAskAssistant:m})})]})})})}function dp(e){return!e.paused.paused_at&&!e.readiness.can_send&&Kr.has(e.readiness.reason??"")}function up(e){if(e.paused.paused_at)return"paused";let t=e.readiness.reason;return!e.readiness.can_send&&t&&Kr.has(t)?t:null}var fp={domain_not_verified:"domain",dmarc_missing:"domain",postal_address_missing:"sender"};function mp({reason:e,pauseReason:t,onRequestReview:a}){let{openSetup:s,openSettings:n}=Qe(),[r,i]=Xt.useState("idle");if(e==="paused")return(0,Xe.jsx)("div",{"data-testid":"email-hold",className:"af-mb-3",children:(0,Xe.jsxs)(be,{tone:"warning",children:[(0,Xe.jsx)("div",{className:"af-font-medium",children:"Sending is paused."}),(0,Xe.jsxs)("p",{children:[lp[t??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),a&&(r==="sent"?(0,Xe.jsx)("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):(0,Xe.jsx)(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{i("sending");try{await a(),i("sent")}catch{i("failed")}},children:"Request review"})),r==="failed"&&(0,Xe.jsx)("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]})});let l=fp[e];return(0,Xe.jsx)("div",{"data-testid":"email-hold",className:"af-mb-3",children:(0,Xe.jsxs)(be,{tone:"warning",children:["Sending is on hold. ",ss(e)," ",l?(0,Xe.jsx)(da,{onClick:()=>n(l),children:"Fix in Settings"}):(0,Xe.jsx)(da,{onClick:s,children:"Finish setup"})]})})}var sa=le(require("react"),1);var pp=2e3,ga=()=>({data:null,error:null,isLoading:!0});function Ws(e,{refreshKey:t,breakdowns:a=[],filters:s=[]}={}){let{api:n}=G(),[r,i]=sa.useState(ga),[l,c]=sa.useState(ga),[d,o]=sa.useState(ga),[u,b]=sa.useState(ga),[v,m]=sa.useState(ga),p=D=>Object.fromEntries(D.map(W=>[W,ga()])),[f,g]=sa.useState(()=>p(a)),x=sa.useRef(0),k=sa.useRef(0),T=sa.useRef("idle"),h=a.join(","),P=os()??"",_=JSON.stringify(s),E=`${e}:${h}:${_}:${P}`,[w,I]=sa.useState({api:n,fetchIdentity:E});(w.api!==n||w.fetchIdentity!==E)&&(I({api:n,fetchIdentity:E}),x.current+=1,i(ga),c(ga),o(ga),b(ga),g(p(h?h.split(","):[])));let O=`${e}:${String(t??"")}:${P}`,[C,Y]=sa.useState({api:n,conversionsIdentity:O});(C.api!==n||C.conversionsIdentity!==O)&&(Y({api:n,conversionsIdentity:O}),k.current+=1,T.current="idle",m(ga));let X=sa.useCallback(async D=>{let W=++x.current,B=h?h.split(","):[];i(ga),c(ga),o(ga),b(ga),g(Object.fromEntries(B.map(L=>[L,ga()])));let ue=T.current!=="pending"&&(D?.force===!0||T.current==="idle"),me=(L,V)=>V.then($=>{W===x.current&&L({data:$,error:null,isLoading:!1})},$=>{W===x.current&&L({data:null,error:$ instanceof Error?$:new Error("Failed to fetch report"),isLoading:!1})}),We=n.getAnalyticsStatus(),Ie=me(i,We),He=Symbol("status-timeout"),et,De=await Promise.race([We.then(L=>L,()=>null),new Promise(L=>{et=setTimeout(()=>L(He),pp)})]);if(clearTimeout(et),W!==x.current)return;if(De===He&&i({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),De!==null&&De!==He&&(De.collecting!==!0||De.first_seen===null&&!De.first_seen_unavailable||De.first_seen!==null&&De.first_seen_in_reports===!1)){let L={data:null,error:null,isLoading:!1};c(L),o(L),b(L),g(Object.fromEntries(B.map(V=>[V,{...L}]))),ue&&(m(L),T.current="done"),await Ie;return}await Promise.all([De===He?Promise.resolve():Ie,me(c,n.getAnalyticsSummary(e,s)),me(o,n.getAnalyticsTimeseries(e,s)),me(b,n.getAnalyticsChannels(e,s)),ue?(()=>{T.current="pending";let L=++k.current;return m(ga),n.getAnalyticsConversions(e).then(V=>{L===k.current&&(m({data:V,error:null,isLoading:!1}),T.current="done")},V=>{L===k.current&&(m({data:null,error:V instanceof Error?V:new Error("Failed to fetch report"),isLoading:!1}),T.current="done")})})():Promise.resolve(),...B.map(L=>n.getAnalyticsBreakdown(L,e,s).then(V=>{W===x.current&&g($=>({...$,[L]:{data:V,error:null,isLoading:!1}}))},V=>{W===x.current&&g($=>({...$,[L]:{data:null,error:V instanceof Error?V:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,_,O,P]),q=sa.useCallback(async()=>{let D=x.current;try{let W=await n.getAnalyticsStatus();if(D!==x.current)return;i({data:W,error:null,isLoading:!1})}catch(W){if(D!==x.current)return;i(B=>({data:B.data,error:W instanceof Error?W:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),de=sa.useCallback(()=>X({force:!0}),[X]);sa.useEffect(()=>{X()},[X,t]);let ge=r.isLoading||l.isLoading||d.isLoading||u.isLoading||v.isLoading||Object.values(f).some(D=>D.isLoading),ye=[d,l,u,v,...Object.values(f)].map(D=>D.data?.status==="ok"?D.data.timezone:void 0).find(D=>D!==void 0);return{status:r,summary:l,timeseries:d,channels:u,conversions:v,breakdowns:f,reportedZone:ye,isLoading:ge,refetch:de,refetchStatus:q}}var ra=le(require("react"),1);var mo=3e4,po=3;function li(e={}){let t="collecting"in e,{collecting:a,statusFailed:s=!1,identity:n}=e,{api:r}=G(),[i,l]=ra.useState(null),[c,d]=ra.useState(null),[o,u]=ra.useState(!1),[b,v]=ra.useState(null),[m,p]=ra.useState(!1),[f,g]=ra.useState(!0),[x,k]=ra.useState(0),T=ra.useRef(0),h=ra.useRef(0),P=ra.useRef(void 0);a!==void 0&&(P.current=a);let _=t?P.current===!0||P.current===void 0&&s:!0,[E,w]=ra.useState({api:r,identity:n}),I=n!==void 0&&n!==E.identity;(E.api!==r||I)&&(P.current=void 0,w({api:r,identity:n}),h.current+=1,T.current=0,l(null),d(null),u(!1),v(null),p(!1),g(!0),k(0));let O=ra.useRef(()=>{}),C=ra.useRef(null),Y=ra.useCallback(async()=>{if(C.current!==null&&C.current===h.current)return;let X=++h.current;C.current=X;try{let q=await r.getAnalyticsRealtime();if(X!==h.current)return;if(q.status==="unreachable"){p(!0),u(!0),g(!1),k(de=>de+1);return}T.current=0,p(!1),l(q.data.current_visitors),d(q.as_of),u(!1),v(null),g(!1),k(de=>de+1)}catch(q){if(X!==h.current)return;T.current+=1,g(!1),k(de=>de+1),u(!0),T.current>=po&&v(q instanceof Error?q:new Error("Realtime unavailable"))}finally{C.current===X&&(C.current=null)}},[r]);return O.current=()=>void Y(),ra.useEffect(()=>{let X,q=()=>{X===void 0&&(X=setInterval(()=>O.current(),mo))},de=()=>{X!==void 0&&(clearInterval(X),X=void 0)},ge=()=>{typeof document<"u"&&document.hidden?de():(O.current(),q())};return _?((typeof document>"u"||!document.hidden)&&(O.current(),q()),document?.addEventListener("visibilitychange",ge),()=>{de(),document?.removeEventListener("visibilitychange",ge),h.current+=1}):()=>{document?.removeEventListener("visibilitychange",ge)}},[E.api,E.identity,_]),{currentVisitors:i,asOf:c,isStale:o,error:b,isUnreachable:m,isInitialLoad:f,polls:x}}var Ut=le(require("react"),1);var Qd=le(require("react"),1);var Gs=require("react/jsx-runtime");function gp(){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 Pl({value:e,chosen:t,onChange:a}){let s=pr(),n=t===null&&s!==null&&e===s,r=Qd.useMemo(()=>{let i=gp();return i.includes(e)?i:[e,...i]},[e]);return(0,Gs.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,Gs.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,Gs.jsxs)("select",{value:n?"":e,onChange:i=>a(i.target.value===""?null:i.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[(0,Gs.jsx)("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(i=>(0,Gs.jsx)("option",{value:i,children:i.replace(/_/g," ")},i))]})]})}var go=(e,{published:t}={})=>{let a=t===!1,s=e!=null&&(!e.collecting||a&&e.first_seen===null&&!e.first_seen_unavailable),n=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,i=n||r;return{notCollecting:s,awaitingFirstVisit:n,firstVisitTooRecent:r,holdingForFirstData:i,nothingToReport:s||i}};var ci=le(require("react"),1),vp=3e4;function vo({status:e,holdingForFirstData:t,refetchStatus:a,refetch:s}){ci.useEffect(()=>{if(!t)return;let r,i=()=>{r===void 0&&(r=setInterval(()=>void a(),vp))},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=ci.useRef(void 0);ci.useEffect(()=>{if(!e){n.current=void 0;return}let r=n.current;n.current=t,r===!0&&!t&&s()},[e,t,s])}var Ks=le(require("react"),1);var bp=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Pa(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?Pa(i*s):`${i}${n}`}return String(e)}function fr(e){return`${(e*100).toFixed(1)}%`}function di(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 tu(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`:di(t)}function au(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function nu(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 ui(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function su(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`${bp[t-1]} ${a}`}function eu(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function hp(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function ru(e,t,a="UTC"){let s=new Map(t.map(i=>[i.date,i])),n=[],r=eu(e.to,a);for(let i=eu(e.from,a);i<r;i=hp(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 iu(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=new Date(`${e}T00:00:00Z`);if(Number.isNaN(s.getTime()))return e;let n=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${n} ${a[s.getUTCMonth()]}`}var sn=require("react/jsx-runtime");function ou({what:e="This report",onRetry:t,collecting:a}){return(0,sn.jsxs)("div",{role:"status",className:"af-flex af-flex-col af-items-center af-gap-1 af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-8 af-text-center",children:[(0,sn.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,sn.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:a===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),t?(0,sn.jsx)("button",{type:"button",onClick:t,className:"af-mt-2 af-rounded-md af-border af-border-border af-px-3 af-py-1 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Try again"}):null]})}function bo({what:e="No data"}){return(0,sn.jsx)("div",{className:"af-flex af-items-center af-justify-center af-rounded-md af-px-4 af-py-8 af-text-center af-text-xs af-text-muted-foreground",children:e})}function rs({sourced:e,error:t,isLoading:a,what:s,onRetry:n,collecting:r,children:i}){return a?(0,sn.jsx)("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,sn.jsx)(ou,{what:s,onRetry:n,collecting:r}):!e||e.status==="unreachable"?(0,sn.jsx)(ou,{what:s,onRetry:n,collecting:r}):(0,sn.jsx)(sn.Fragment,{children:i(e.data)})}var Ct=require("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:c=9}){let[d,o]=Ks.useState(!1);if(e.length===0)return(0,Ct.jsx)(bo,{what:r});let u=e.reduce((m,p)=>Math.max(m,Number(p[a]??0)),0)||1,b=Math.max(0,e.length-c),v=d?e:e.slice(0,c);return(0,Ct.jsxs)(Ct.Fragment,{children:[(0,Ct.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Ct.jsx)("thead",{children:(0,Ct.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Ct.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,Ct.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),(0,Ct.jsx)("tbody",{children:v.map((m,p)=>{let f=Number(m[a]??0),g=m[t]??null,x=ui(g),k=n?m[n]:null,T=g!==null&&(l?l(g,k):!0);return(0,Ct.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,Ct.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,Ct.jsx)("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,f/u*100)}%`}}),g!==null&&i&&T?(0,Ct.jsx)("button",{type:"button",onClick:()=>i(g,k),title:`Filter by ${x}`,"aria-label":`Filter by ${x}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:x}):(0,Ct.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:x}),k?(0,Ct.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:k}):null]}),(0,Ct.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Pa(f)})]},`${x}-${k??""}-${p}`)})})]}),b>0?(0,Ct.jsx)("button",{type:"button",onClick:()=>o(m=>!m),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:d?"Show fewer":`Show all ${e.length}`}):null]})}function fi({title:e,tabs:t,defaultTabId:a,headerRight:s}){let[n,r]=Ks.useState(a),i=t.find(v=>v.id===n)??t[0],l=Ks.useId(),c=v=>`${l}-tab-${v}`,d=v=>`${l}-panel-${v}`,o=Ks.useRef(null),u=(v,m)=>{v.preventDefault();let p=(m+t.length)%t.length;r(t[p].id),o.current?.querySelectorAll('[role="tab"]')?.[p]?.focus()};return(0,Ct.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,Ct.jsxs)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:[(0,Ct.jsx)("div",{ref:o,role:"tablist","aria-label":e,onKeyDown:v=>{let m=t.findIndex(p=>p.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=>(0,Ct.jsx)("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?(0,Ct.jsx)("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]})}var $a=le(require("react"),1),ws=le(require("@radix-ui/react-popover"),1);var ys=3,xs=100;var rt=require("react/jsx-runtime"),mi={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"},yp=Object.keys(mi);function lu(e){let t=mi[e.dimension],a=e.operator==="is_not"?"is not":"is",s=e.values.map(n=>ui(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>xs||s.length===e[a].values.length?e:e.map((n,r)=>r===a?{...n,values:s}:n)}return t.values.length>xs||e.length>=ys?e:[...e,t]}function xp(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 cu(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>xs||e.length>=ys?e:[...e,t]}function wp(e){return{dimension:e,operator:"is",search:"",picked:[]}}function du(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=xp(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 uu(e){let{filters:t,onChange:a}=e,s=t.length>=ys;return $a.useEffect(()=>{if(t.length===0)return;let n=r=>{let i=r.target;i&&(i.tagName==="INPUT"||i.closest('[role="dialog"]'))||r.key==="Escape"&&a([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[t.length,a]),(0,rt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,r)=>(0,rt.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-1 af-rounded-full af-border af-border-border af-bg-muted af-py-1 af-pl-3 af-pr-1 af-text-xs",children:[(0,rt.jsx)("span",{className:"af-text-foreground",children:lu(n)}),(0,rt.jsx)("button",{type:"button","aria-label":`Remove filter ${lu(n)}`,onClick:()=>a(t.filter((i,l)=>l!==r)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),(0,rt.jsx)(Sp,{...e,disabled:s}),t.length>0?(0,rt.jsx)("button",{type:"button",onClick:()=>a([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Sp({filters:e,onChange:t,suggestions:a,resetKey:s,disabled:n,expandValues:r}){let[i,l]=$a.useState(!1),c=$a.useRef(null),[d,o]=$a.useState(null);$a.useEffect(()=>{o(c.current?.closest(".aifeatures-admin")??null)},[]);let[u,b]=$a.useState(null),[v,m]=$a.useState("is"),[p,f]=$a.useState(""),[g,x]=$a.useState([]);$a.useEffect(()=>{i||(b(null),m("is"),f(""),x([]))},[i]);let k=$a.useRef(s);k.current!==s&&(k.current=s,i&&l(!1),u!==null&&b(null),g.length>0&&x([]),p!==""&&f(""),v!=="is"&&m("is"));let T=I=>{let O=wp(I);b(O.dimension),x(O.picked),f(O.search),m(O.operator)},P=(u?a[u]??[]:[]).filter(I=>I.toLowerCase().includes(p.trim().toLowerCase())),_=u===null||g.length===0?null:El(e,{dimension:u,operator:v,values:r?r(u,g):g}),E=_!==null&&_!==e,w=()=>{let I=_;!I||I===e||(t(I),l(!1))};return(0,rt.jsxs)(ws.Root,{open:i,onOpenChange:l,children:[(0,rt.jsx)(ws.Trigger,{asChild:!0,children:(0,rt.jsx)("button",{ref:c,type:"button",disabled:!1,title:n?`At most ${ys} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),(0,rt.jsx)(ws.Portal,{container:d,children:(0,rt.jsx)(ws.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?(0,rt.jsxs)("div",{children:[(0,rt.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,rt.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:yp.filter(I=>a[I]!==void 0).map(I=>{let O=a[I]?.length??0,C=!e.some(Y=>Y.dimension===I)&&e.length>=ys;return(0,rt.jsxs)("button",{type:"button",onClick:()=>T(I),disabled:O===0||C,className:"af-flex af-w-full af-items-center af-justify-between af-rounded-md af-px-2 af-py-1.5 af-text-left af-text-xs af-text-foreground hover:af-bg-muted disabled:af-text-muted-foreground disabled:hover:af-bg-transparent",children:[(0,rt.jsx)("span",{children:mi[I]}),(0,rt.jsx)("span",{className:"af-text-muted-foreground",children:O===0?"no data":C?"no room":O})]},I)})})]}):(0,rt.jsxs)("div",{children:[(0,rt.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,rt.jsx)("button",{type:"button",onClick:()=>T(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,rt.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:mi[u]}),(0,rt.jsxs)("select",{"aria-label":"Operator",value:v,onChange:I=>m(I.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,rt.jsx)("option",{value:"is",children:"is"}),(0,rt.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,rt.jsx)("input",{type:"text",value:p,onChange:I=>f(I.target.value),placeholder:"Search\u2026","aria-label":`Search ${mi[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"}),(0,rt.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:P.length===0?(0,rt.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",p,"\u201D."]}):P.map(I=>(0,rt.jsxs)("label",{className:"af-flex af-cursor-pointer af-items-center af-gap-2 af-rounded-md af-px-2 af-py-1.5 af-text-xs af-text-foreground hover:af-bg-muted",children:[(0,rt.jsx)("input",{type:"checkbox",checked:g.includes(I),disabled:!g.includes(I)&&g.length>=xs,onChange:O=>x(C=>O.target.checked?[...C,I]:C.filter(Y=>Y!==I))}),(0,rt.jsx)("span",{className:"af-break-all",children:ui(I)})]},I))}),(0,rt.jsx)("button",{type:"button",onClick:w,disabled:!E,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:g.length<=1?"Apply filter":g.length>=xs?`Apply filter (${g.length} values \u2014 the maximum)`:`Apply filter (${g.length} values)`})]})})})]})}var $t=require("react/jsx-runtime"),Np=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Pa,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Pa,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Pa,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:di,chart:"visit_duration_seconds"}];function Rp({current:e,previous:t,downIsGood:a}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let n=s>0,r=a?!n:n,i=`${n?"+":""}${(s*100).toFixed(1)}%`;return(0,$t.jsx)("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:i})}function fu({summary:e,selected:t,onSelect:a}){return(0,$t.jsx)("div",{className:"af-@container",children:(0,$t.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Np.map(s=>{let n=s.chart===t,r=a!==void 0,i=(0,$t.jsxs)($t.Fragment,{children:[(0,$t.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),(0,$t.jsxs)("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[(0,$t.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?(0,$t.jsx)(Rp,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?(0,$t.jsx)("button",{type:"button","aria-pressed":n,onClick:()=>a(s.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:i},s.key):(0,$t.jsx)("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(0,$t.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1","aria-hidden":"true",children:[(0,$t.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,$t.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return(0,$t.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let i=t?su(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(0,$t.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:c,children:[(0,$t.jsx)("span",{"aria-hidden":"true",className:a?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),(0,$t.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,$t.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),(0,$t.jsx)("span",{className:"af-sr-only",children:c})]})}var mu=le(require("react"),1),pu=require("lucide-react");var lt=require("react/jsx-runtime");function ho(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function yo({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]=mu.useState(!1),d=e.filter(f=>!f.implicit||f.visitors>0||f.events>0||ho(f,i)),o=a?(0,lt.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This period starts before we began collecting for this site, so these counts cover less time than the dates suggest."}):s?(0,lt.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null;if(d.length===0)return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsx)(bo,{what:n}),o]});let u=d.slice(0,r),b=i?d.find(f=>ho(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,p=Math.max(0,e.length-v.length);return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,lt.jsx)("thead",{children:(0,lt.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,lt.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,lt.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,lt.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,lt.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,lt.jsx)("tbody",{children:m.map((f,g)=>(0,lt.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":ho(f,i)?"true":void 0,children:[(0,lt.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:ho(f,i)?(0,lt.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,lt.jsx)(pu.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,lt.jsx)("span",{className:"af-font-medium af-text-foreground",children:f.goal}),(0,lt.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):f.goal}),(0,lt.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Pa(f.visitors)}),(0,lt.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Pa(f.events)}),(0,lt.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:f.conversion_rate===null?(0,lt.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):fr(f.conversion_rate)})]},`${f.goal}-${g}`))})]}),p>0?(0,lt.jsx)("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,(0,lt.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Pa(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),o]})}var Ua=require("recharts");var Ht=require("react/jsx-runtime"),xo={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Dl={visitors:Pa,visits:Pa,pageviews:Pa,views_per_visit:e=>e.toFixed(2),bounce_rate:fr,visit_duration_seconds:di},_p=31,kp=new Set(["visitors","visits","pageviews"]),Pp={...Dl,bounce_rate:au,visit_duration_seconds:tu},Al=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Cp=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Tp=[.01,.02,.05,.1,.2,.25,.5,1],Ep=[.25,.5,1,2,5,10,25,50],Ip={visitors:Al,visits:Al,pageviews:Al,views_per_visit:Ep,bounce_rate:Tp,visit_duration_seconds:Cp};function Ap({active:e,payload:t,label:a,metric:s}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return(0,Ht.jsxs)("div",{className:"af-rounded-lg af-border af-border-border af-bg-popover af-px-3 af-py-2 af-text-popover-foreground af-shadow-md",children:[(0,Ht.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:xo[s]}),(0,Ht.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,Ht.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,Ht.jsx)("span",{className:"af-text-muted-foreground",children:iu(String(a))}),(0,Ht.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Dl[s](Number(n[s]??0))})]})]})}function wo({rows:e,window:t,metric:a,timeZone:s="UTC",height:n=260}){let r=ru(t,e,s),i=Dl[a],l=Pp[a],c=nu(r.reduce((o,u)=>Math.max(o,Number(u[a]??0)),0),Ip[a]),d=`${xo[a]} by day: ${r.map(o=>`${Cl(o.date)}: ${i(Number(o[a]??0))}`).join("; ")}.`;return(0,Ht.jsxs)("figure",{"aria-label":`${xo[a]} over time`,className:"af-m-0",children:[(0,Ht.jsx)(Ua.ResponsiveContainer,{width:"100%",height:n,children:(0,Ht.jsxs)(Ua.AreaChart,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,Ht.jsx)("defs",{children:(0,Ht.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,Ht.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,Ht.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,Ht.jsx)(Ua.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,Ht.jsx)(Ua.XAxis,{dataKey:"date",tickFormatter:Cl,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,Ht.jsx)(Ua.YAxis,{allowDecimals:!kp.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}}),(0,Ht.jsx)(Ua.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,Ht.jsx)(Ap,{metric:a})}),(0,Ht.jsx)(Ua.Area,{type:"linear",dataKey:a,name:xo[a],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=_p?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,Ht.jsx)("figcaption",{className:"af-sr-only",children:d})]})}var we=require("react/jsx-runtime"),Dp="2026-08-13",Op=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Lp=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function gu({filters:e,onFiltersChange:t,refreshKey:a,onBackToWebsite:s,primaryConversion:n,className:r,published:i,lastPublishedAt:l}){let[c,d]=Ut.useState(30),[o,u]=Ut.useState(()=>_o()),b=e!==void 0&&t!==void 0,[v,m]=Ut.useState(e??[]),{api:p}=G(),[f,g]=Ut.useState(p);f!==p&&(g(p),!b&&v.length>0&&m([]));let x=b?e:v,k=Ut.useCallback($=>{t&&t($),b||m($)},[t,b]),T=Ut.useCallback(($,xe,H)=>{let ke=Array.isArray(xe)?xe:[xe];if(ke.length===0)return null;let ze=El(x,{dimension:$,operator:"is",values:ke});if(H&&(!H.value||(ze=cu(ze,{dimension:H.dimension,operator:"is",values:[H.value]}),!ze.find(Ot=>Ot.dimension===H.dimension&&Ot.operator!=="is_not")?.values.includes(H.value))))return null;let gt=ze.find(st=>st.dimension===$&&st.operator!=="is_not");return ke.every(st=>gt?.values.includes(st))?JSON.stringify(ze)===JSON.stringify(x)?null:ze:null},[x]),h=Ut.useCallback(($,xe,H)=>T($,xe,H)!==null,[T]),P=Ut.useCallback(($,xe,H)=>{let ke=T($,xe,H);ke&&k(ke)},[T,k]),[_,E]=Ut.useState("visitors"),w=Ws(c,{refreshKey:a,breakdowns:Lp,filters:x}),I=w.status.data,O=w.reportedZone??I?.timezone,C=O??o??pr()??"UTC",{notCollecting:Y,awaitingFirstVisit:X,firstVisitTooRecent:q,holdingForFirstData:de}=go(I,{published:i}),ge=i===!1,ye=li({collecting:X||Y?!1:I?.collecting,statusFailed:w.status.error!=null,identity:I?.analytics_id}),D=Ut.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),W=Ut.useMemo(()=>{let $=w.breakdowns.sources?.data,xe={};if(!$||$.status!=="ok")return xe;for(let H of $.data){let ke=H.source,ze=H.sources;typeof ke=="string"&&Array.isArray(ze)&&ze.length>0&&(xe[ke]=ze)}return xe},[w.breakdowns.sources?.data]),B=Ut.useMemo(()=>{let $=(ke,ze)=>{let gt=w.breakdowns[ke]?.data;return!gt||gt.status!=="ok"?[]:[...new Set(gt.data.map(st=>st[ze]).filter(st=>typeof st=="string"&&st!==""))]};return{channel:w.channels.data?.status==="ok"?[...new Set(w.channels.data.data.map(ke=>ke.channel))]:[],source:$("sources","source"),campaign:$("utm/campaign","campaign"),page:$("pages","pathname"),entry_page:$("entry-pages","pathname"),exit_page:$("exit-pages","pathname"),country:$("countries","country"),browser:$("browsers","browser"),os:$("operating-systems","os"),device:$("devices","device")}},[w.breakdowns,w.channels.data]),[ue,me]=Ut.useState({}),We=JSON.stringify(B),[Ie,He]=Ut.useState(new Map),et=JSON.stringify(W);Ut.useEffect(()=>{let{suggestions:$,folds:xe}=du(D.current,{api:p,period:c},JSON.parse(We),JSON.parse(et));me($),He(xe)},[We,et,p,c]);let De=Ut.useCallback(($,xe)=>$!=="source"?xe:[...new Set(xe.flatMap(H=>{let ke=[...Ie.get(H)??[],...W[H]??[]];return ke.length>0?ke:[H]}))],[Ie,W]),Ke=Ut.useMemo(()=>{let $=w.conversions.error;return $ instanceof Gt&&$.details?.code==="goals_exceed_report_budget"?$.message:null},[w.conversions.error]),L=Ut.useMemo(()=>{let $=[w.summary,w.timeseries,w.channels,...Object.values(w.breakdowns)];for(let xe of $){let H=xe?.error;if(H instanceof Gt&&H.details?.code==="filter_unsupported")return H.message}return null},[w.summary,w.timeseries,w.channels,w.breakdowns]),V=($,xe,H,ke,ze,gt,st,Ot,Pe)=>()=>{let Ge=w.breakdowns[$];return(0,we.jsx)(rs,{sourced:Ge?.data??null,error:Ge?.error,isLoading:Ge?.isLoading,what:xe,collecting:I?.collecting,onRetry:w.refetch,children:yt=>{let Lt=Vt=>Ot?De(Ot,[Vt]):Vt;return(0,we.jsx)(Tl,{rows:yt,dimension:H,metric:ke,metricLabel:ze,secondary:gt,emptyCopy:x.length>0?"No data for this filter":st,canFilter:Ot?(Vt,it)=>h(Ot,Lt(Vt),Pe?{dimension:Pe,value:it}:void 0):()=>!1,onFilter:Ot?(Vt,it)=>P(Ot,Lt(Vt),Pe?{dimension:Pe,value:it}:void 0):void 0})}})};if(vo({status:I,holdingForFirstData:de,refetchStatus:w.refetchStatus,refetch:w.refetch}),Y){let $=!!l&&String(l).slice(0,10)<Dp;return(0,we.jsx)(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,we.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,we.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,we.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:ge?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":$?"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 X?(0,we.jsx)(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,we.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,we.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,we.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:"Your site is set up and analytics is running. The first visit shows up here shortly after someone lands on a published page."})]})}):q?(0,we.jsxs)(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:[(0,we.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,we.jsx)(Pl,{value:C,chosen:o,onChange:$=>{ko($),u($)}})}),(0,we.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,we.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,we.jsxs)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",I?.timezone?` ${I.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,we.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,we.jsx)(Il,{currentVisitors:ye.currentVisitors,asOf:ye.asOf,isStale:ye.isStale,isUnreachable:ye.isUnreachable||ye.error!==null,isInitialLoad:ye.isInitialLoad})})]})]}):(0,we.jsx)(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,we.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,we.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,we.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Op.map($=>(0,we.jsx)("button",{type:"button","aria-pressed":$.value===c,onClick:()=>d($.value),className:$.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:$.label},$.value))}),(0,we.jsx)(Pl,{value:C,chosen:o,onChange:$=>{ko($),u($)}}),(0,we.jsx)(Il,{currentVisitors:ye.currentVisitors,asOf:ye.asOf,isStale:ye.isStale,isUnreachable:ye.isUnreachable||ye.error!==null,isInitialLoad:ye.isInitialLoad,scopeIsSiteWide:x.length>0})]}),(0,we.jsx)(uu,{filters:x,onChange:k,suggestions:ue,expandValues:De,resetKey:p}),L?(0,we.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,we.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,we.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:L}),(0,we.jsx)("button",{type:"button",onClick:()=>k([]),className:"af-mt-4 af-rounded-md af-border af-border-border af-px-3 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Clear filters"})]}):null,!L&&I?.timezone_defaulted?(0,we.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,L?null:(0,we.jsxs)(we.Fragment,{children:[(0,we.jsx)(rs,{sourced:w.summary.data,error:w.summary.error,isLoading:w.summary.isLoading,what:"The traffic summary",collecting:I?.collecting,onRetry:w.refetch,children:$=>(0,we.jsxs)(we.Fragment,{children:[(0,we.jsx)(fu,{summary:$,selected:_,onSelect:E}),$.previous_unavailable?(0,we.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[$.previous_unavailable_reason==="filter"?"No comparison for this filter \u2014 the previous period has too many distinct traffic sources to resolve it. Try a shorter period, or filter by source instead.":"No comparison available right now \u2014 we couldn\u2019t check how far back this site\u2019s history goes. It should return on its own."," ","The numbers above are still for the period you selected."]}):null]})}),(0,we.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,we.jsx)(rs,{sourced:w.timeseries.data,error:w.timeseries.error,isLoading:w.timeseries.isLoading,what:"The visitors chart",collecting:I?.collecting,onRetry:w.refetch,children:$=>{let xe=w.timeseries.data?.status==="ok"?w.timeseries.data.window:{from:"",to:""};return(0,we.jsx)(wo,{rows:$,window:xe,metric:_,timeZone:O??"UTC"})}})}),(0,we.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,we.jsx)(fi,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,we.jsx)(rs,{sourced:w.channels.data,error:w.channels.error,isLoading:w.channels.isLoading,what:"Channels",collecting:I?.collecting,onRetry:w.refetch,children:$=>(0,we.jsx)(Tl,{rows:$,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:xe=>h("channel",xe),onFilter:xe=>P("channel",xe)})})},{id:"sources",label:"Sources",render:V("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:V("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,we.jsx)(fi,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:V("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:V("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:V("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,we.jsx)(fi,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:V("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:V("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:V("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,we.jsx)(fi,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:V("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:V("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:V("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,we.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,we.jsx)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:(0,we.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,we.jsxs)("div",{className:"af-px-3 af-py-2",children:[x.length>0?(0,we.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",x.length===1?"filter":"filters"," above."]}):null,Ke!==null?(0,we.jsxs)("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[(0,we.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,we.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:Ke})]}):(0,we.jsx)(rs,{sourced:w.conversions.data,error:w.conversions.error,isLoading:w.conversions.isLoading,what:"Conversions",collecting:I?.collecting,onRetry:w.refetch,children:$=>{let xe=w.conversions.data?.status==="ok"?w.conversions.data:null;return(0,we.jsx)(we.Fragment,{children:(0,we.jsx)(yo,{rows:$,primaryConversion:n,denominator:xe?.denominator??0,windowPrecedesCollection:xe?.window_precedes_collection??!1,coverageUnknown:xe?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var wu=le(require("react"),1),ua=require("lucide-react");var yn=le(require("react"),1),is=require("lucide-react");var Be=require("react/jsx-runtime"),vu=90,bu=100;function Bp(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function hu(e){return!!e.label&&e.label!==e.target}function Fp(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 pi(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function yu({current:e,onChange:t,onClose:a}){let{api:s}=G(),[n,r]=yn.useState(null),[i,l]=yn.useState(!1),[c,d]=yn.useState({at:"goals"}),[o,u]=yn.useState(null),[b,v]=yn.useState(null),[m,p]=yn.useState(!1),[f,g]=yn.useState(null),x=yn.useRef(0);yn.useEffect(()=>{let P=!0;return r(null),l(!1),d({at:"goals"}),u(null),v(null),p(!1),g(null),x.current+=1,s.getAnalyticsConversions(vu).then(_=>{if(P){if(_.status!=="ok"){l(!0);return}r(_.data)}}).catch(()=>{P&&l(!0)}),()=>{P=!1}},[s]);let k=P=>{d({at:"targets",row:P}),u(null),v(null),p(!1),g(null);let _=++x.current;s.getAnalyticsGoalTargets(P.goal,vu,bu).then(E=>{if(_===x.current){if(E.status!=="ok"){v("failed");return}u(E.data),p(E.truncated===!0),g(E.coverage??null)}}).catch(E=>{if(_!==x.current)return;let w=E instanceof Gt?E.details?.code:void 0;v(w==="goal_has_no_targets"?"no-values":"failed")})},T=P=>{t(P),a()};if(i)return(0,Be.jsx)("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return(0,Be.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,Be.jsx)(is.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Be.jsx)("span",{children:"Loading your conversions\u2026"})]});if(c.at==="targets"){let P=c.row,_=new Map;for(let E of o??[])_.set(E.label,(_.get(E.label)??0)+1);return(0,Be.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[(0,Be.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,Be.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>d({at:"goals"}),children:[(0,Be.jsx)(is.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,Be.jsx)("span",{children:"All conversions"})]})}),(0,Be.jsxs)("button",{type:"button","aria-current":e&&pi(P,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:P.goal,implicit:P.implicit}),children:[e&&pi(P,e)&&!e.target&&(0,Be.jsx)(is.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Be.jsxs)("span",{children:["Any ",P.goal.toLowerCase()]})]}),b==="no-values"&&(0,Be.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),b==="failed"&&(0,Be.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,Be.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,Be.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>k(P),children:"Try again"})]}),!o&&b===null&&(0,Be.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,Be.jsx)(is.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Be.jsx)("span",{children:"Loading\u2026"})]}),o&&(0,Be.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Fp(o.length,f,m)}),m&&(0,Be.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",bu,". If what you want isn\u2019t here, pick the conversion itself instead."]}),o?.some(hu)&&(0,Be.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),o?.map(E=>{let w=!!(e&&pi(P,e)&&e.target===E.target),I=_.get(E.label)>1;return hu(E)?(0,Be.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-3 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,Be.jsxs)("span",{className:"af-min-w-0",children:[(0,Be.jsx)("span",{className:"af-block af-truncate",children:E.label}),I&&(0,Be.jsx)("span",{className:"af-block af-truncate af-text-xs",children:E.target})]}),(0,Be.jsx)("span",{className:"af-shrink-0 af-text-xs",children:E.visitors.toLocaleString()})]},E.target):(0,Be.jsxs)("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:()=>T({goal:P.goal,implicit:P.implicit,target:E.target,...E.label&&E.label!==E.target?{label:E.label}:{}}),children:[(0,Be.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[w&&(0,Be.jsx)(is.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Be.jsxs)("span",{className:"af-min-w-0",children:[(0,Be.jsx)("span",{className:"af-block af-truncate",children:E.label}),I&&(0,Be.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:E.target})]})]}),(0,Be.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:E.visitors.toLocaleString()})]},E.target)})]})}let h=e?.goal&&!n.some(P=>pi(P,e));return(0,Be.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[h&&(0,Be.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&(0,Be.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(P=>{let _=e?pi(P,e):!1;return(0,Be.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,Be.jsxs)("button",{type:"button","aria-current":_?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:P.goal,implicit:P.implicit}),children:[(0,Be.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[_&&(0,Be.jsx)(is.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Be.jsx)("span",{className:"af-truncate",children:P.goal})]}),(0,Be.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:P.visitors.toLocaleString()})]}),Bp(P)&&(0,Be.jsx)(y,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${P.goal}`,onClick:()=>k(P),children:"Narrow"})]},P.goal)}),e?.goal&&(0,Be.jsx)("button",{type:"button",className:"af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm af-text-muted-foreground hover:af-bg-accent",onClick:()=>T(null),children:"No main conversion"})]})}var rn=require("react/jsx-runtime");function Mp(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 $p(e){if(Ol(e,"whatsapp"))return!0;let t=Mp(e);return t===null?!1:["wa.me","whatsapp.com"].some(a=>t===a||t.endsWith(`.${a}`))}function Ol(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var xu=[{goal:"Contact",target:e=>Ol(e,"tel"),icon:ua.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Ol(e,"mailto"),icon:ua.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:ua.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>$p(e),icon:ua.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:ua.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:ua.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:ua.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:ua.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:ua.Download,line:"This site is set up to get your file downloaded."}];function Su(e){let{goal:t,target:a}=e;return e.implicit!==!0?null:(a?xu.find(n=>n.goal===t&&n.target?.(a)):void 0)??xu.find(n=>n.goal===t&&!n.target)??null}function Up(e){return Su(e)?.icon??ua.Target}function Nu({primaryConversion:e,onChange:t}){let[a,s]=wu.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?Su(e):null,i=e?.label?.trim(),l=e?Up(e):ua.Target,c=e?.goal?i?`Your main conversion is ${i}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",d=(0,rn.jsxs)(rn.Fragment,{children:[(0,rn.jsx)(l,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,rn.jsx)("span",{children:c})]});return t?(0,rn.jsxs)(Ti,{open:a,onOpenChange:s,children:[(0,rn.jsx)(Ei,{asChild:!0,children:(0,rn.jsx)("button",{type:"button",className:"af-flex af-items-center af-gap-2 af-rounded af-text-left af-text-sm af-text-muted-foreground hover:af-text-foreground focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:d})}),(0,rn.jsx)(Lr,{align:"start",className:"af-w-80 af-p-1",children:a&&(0,rn.jsx)(yu,{current:e,onChange:t,onClose:()=>s(!1)})})]}):(0,rn.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:d})}var Sa=require("react/jsx-runtime");function Ru({refreshKey:e,onViewAll:t,primaryConversion:a}){let s=Ws(7,{refreshKey:e,breakdowns:[]}),n=s.status.data??void 0,{nothingToReport:r,notCollecting:i,holdingForFirstData:l}=go(n);return vo({status:n,holdingForFirstData:l,refetchStatus:s.refetchStatus,refetch:s.refetch}),(0,Sa.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Sa.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Sa.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,Sa.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?(0,Sa.jsx)("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:i?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):(0,Sa.jsxs)(Sa.Fragment,{children:[(0,Sa.jsx)(rs,{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(0,Sa.jsx)(wo,{rows:c,window:d?.window??{from:"",to:""},metric:"visitors",timeZone:d?.timezone,height:140})}}),(0,Sa.jsxs)("div",{className:"af-mt-3",children:[(0,Sa.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,Sa.jsx)(rs,{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(0,Sa.jsx)(yo,{rows:c,primaryConversion:a,denominator:d?.denominator??0,windowPrecedesCollection:d?.window_precedes_collection??!1,coverageUnknown:d?.first_seen_unavailable??!1})}})]})]})]})}var fa=require("react/jsx-runtime"),Ll=5;function Bl({title:e,viewAllLabel:t,onViewAll:a}){return(0,fa.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,fa.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),a&&(0,fa.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:a,children:t})]})}function _u({refreshKey:e,onBackToWebsite:t,primaryConversion:a,onChangePrimaryConversion:s,onOpenSurface:n,needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l}){let c=Os({refreshKey:e}),d=(c.summary?.products.count??0)>0||(c.summary?.commerce?.storefront_orders??!1),o=d||(c.summary?.commerce?.invoicing??!1);return(0,fa.jsx)(Ft,{title:"Dashboard",onBackToWebsite:t,children:(0,fa.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,fa.jsx)(Nu,{primaryConversion:a,onChange:s}),(0,fa.jsx)(Ru,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:a}),(0,fa.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,fa.jsx)(Bl,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),(0,fa.jsx)(jr,{refreshKey:e,maxRows:Ll,onViewAll:n&&(()=>n("leads"))})]}),d&&(0,fa.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,fa.jsx)(Bl,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),(0,fa.jsx)(Qn,{refreshKey:e,maxRows:Ll,onViewAll:n&&(()=>n("orders"))})]}),o&&(0,fa.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,fa.jsx)(Bl,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),(0,fa.jsx)(ts,{refreshKey:e,maxRows:Ll,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l})]})]})})}0&&(module.exports={AUDIENCE_PAGE_SIZE,AifeaturesApiError,AifeaturesProvider,AnalyticsView,ContactImport,CustomerDetail,CustomersList,DOUBLE_OPT_IN_HELP,DashboardView,EMAIL_ORG_ACTIONS,EMAIL_READINESS_TEXT,EmailView,ExportCsvButton,FormSettings,FormSubmissions,FormsDashboard,FormsList,IMPORT_ATTESTATION,InvoiceDetail,InvoiceLabelBadge,InvoiceSettingsPanel,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,NotificationRecipientsSettings,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,PromosPanel,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,StoreSettings,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,buildEmailOrgRequest,chargedTotal,createApiClient,emailReadinessText,formatPrice,isEmailOrgAction,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useAudience,useBroadcasts,useBusinessSummary,useCsvExport,useCustomers,useEmailDrafts,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSiteSettings,useSubmissions,useSubscriptions});
7
+ `);case"cart":return e.label}}function Sd(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 mm={...rl,text:"Markdown: **bold**, *italic*, [link](https://\u2026), blank line = new paragraph"};function Rd({block:e,isNew:t,busy:a,error:s,onPickImage:n,onDone:r,onRemove:i,onCancel:l,style:u,className:c}){let[o,f]=js.useState(e),[b,g]=js.useState(!1),m=p=>f(x=>({...x,...p})),v=js.useRef(null);js.useEffect(()=>v.current?.focus(),[]);let d=p=>{p&&!v.current&&(v.current=p)};return(0,ut.jsx)("form",{"data-testid":"section-editor",style:u,className:c,onSubmit:p=>{p.preventDefault(),Sd(o)&&r(o)},onKeyDown:p=>{p.key==="Escape"&&!a&&l()},children:(0,ut.jsxs)("div",{className:"af-space-y-2",children:[o.type==="heading"&&(0,ut.jsx)(de,{ref:d,"aria-label":"Heading",value:o.text,maxLength:200,onChange:p=>m({text:p.target.value})}),o.type==="text"&&(0,ut.jsx)("textarea",{ref:d,"aria-label":"Text",className:"af-min-h-[120px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-font-mono af-text-sm",value:o.text,maxLength:5e3,onChange:p=>m({text:p.target.value})}),o.type==="button"&&(0,ut.jsxs)("div",{className:"af-grid af-gap-2 sm:af-grid-cols-2",children:[(0,ut.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",(0,ut.jsx)(de,{ref:d,"aria-label":"Button label",value:o.label,maxLength:80,onChange:p=>m({label:p.target.value})})]}),(0,ut.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Opens",(0,ut.jsx)(de,{"aria-label":"Button link",type:"url",value:o.url,onChange:p=>m({url:p.target.value})})]})]}),o.type==="image"&&(0,ut.jsxs)("div",{className:"af-space-y-2",children:[n?(0,ut.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[o.url&&(0,ut.jsx)("img",{src:o.url,alt:"",className:"af-h-12 af-w-12 af-rounded af-object-cover"}),(0,ut.jsx)(y,{ref:d,type:"button",variant:"outline",size:"sm",disabled:b,onClick:async()=>{g(!0);try{let p=await n();p&&f(x=>({...x,url:p.url,alt:p.alt??(x.type==="image"?x.alt:"")}))}finally{g(!1)}},children:"Choose from your site's images\u2026"})]}):(0,ut.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Image address (https://\u2026)",(0,ut.jsx)(de,{ref:d,"aria-label":"Image URL",type:"url",value:o.url,onChange:p=>m({url:p.target.value})})]}),(0,ut.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Describe the image (for people who can't see it)",(0,ut.jsx)(de,{"aria-label":"Image description",value:o.alt??"",maxLength:200,onChange:p=>m({alt:p.target.value})})]})]}),o.type==="cart"&&(0,ut.jsxs)("div",{className:"af-space-y-2",children:[(0,ut.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Each shopper sees their own cart here. There's nothing to write but the button."}),(0,ut.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",(0,ut.jsx)(de,{ref:d,"aria-label":"Cart button label",value:o.label,maxLength:80,onChange:p=>m({label:p.target.value})})]})]}),s&&(0,ut.jsx)(he,{tone:"error",children:s}),(0,ut.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,ut.jsx)("span",{className:"af-grow af-text-xs af-text-muted-foreground",children:mm[o.type]}),!t&&(0,ut.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:i,children:"Remove"}),(0,ut.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:l,children:"Cancel"}),(0,ut.jsx)(y,{type:"submit",size:"sm",disabled:a||!Sd(o),children:"Done"})]})]})})}var _d=le(require("react"),1),kd=require("lucide-react");var Ce=require("react/jsx-runtime"),qn="standard",to={create:"Create an email template that ",copyStandard:"Create an email template based on Standard that ",update:e=>`Update the "${e}" template to be `};function ol({template:e}){return e?e.status==="archived"?(0,Ce.jsx)(ie,{variant:"secondary",children:"Archived"}):e.locked?(0,Ce.jsx)(ie,{variant:"secondary",children:"In use"}):null:(0,Ce.jsx)(ie,{variant:"secondary",children:"Built in"})}function ll(e){return e>0?`Used by ${e} draft${e===1?"":"s"}`:null}function Pd(e,t){let{api:a}=W(),{siteId:s,refreshKey:n,settings:r}=Xe(),i=JSON.stringify([r?.business_name,r?.postal_address,r?.brand]);return Mt(()=>a.previewEmailTemplate(s,e),`${s}|${e}|${t}|${n}|${i}`,`${s}|${e}|${t}`)}function ao({templateId:e,version:t,className:a,frame:s}){let n=Pd(e,t);return(0,Ce.jsx)("div",{"aria-hidden":!0,className:`af-pointer-events-none af-overflow-hidden af-bg-white ${a}`,children:n.data&&(0,Ce.jsx)("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:(0,Ce.jsx)("iframe",{title:"",tabIndex:-1,sandbox:"",srcDoc:n.data.html,style:{width:s.width,height:s.height,border:0,transform:`scale(${s.scale})`,transformOrigin:"top left"}})})})}function Cd({template:e,onBack:t,onOpenTemplate:a,onOpenDraft:s,onAskAssistant:n,reload:r,refreshKey:i}){let l=Pd(e?.id??qn,e?.updated_at??"builtin");return(0,Ce.jsxs)("div",{className:"af-space-y-4",children:[(0,Ce.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,Ce.jsx)(kd.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All templates"]}),(0,Ce.jsxs)("div",{className:"af-grid af-gap-4 md:af-grid-cols-[minmax(0,1fr)_280px]",children:[(0,Ce.jsxs)("div",{children:[l.data?(0,Ce.jsx)("iframe",{title:"Template preview",sandbox:"",srcDoc:l.data.html,className:"af-h-[520px] af-w-full af-rounded-md af-border af-bg-white"}):l.error?(0,Ce.jsxs)(he,{tone:"warning",children:[vs(l.error)==="postal_address_missing"?"Add your business postal address to preview your emails.":"Couldn't load this preview.",(0,Ce.jsx)(dr,{reason:vs(l.error)})]}):(0,Ce.jsx)(Q,{className:"af-h-[520px] af-w-full"}),(0,Ce.jsx)("p",{className:"af-mt-2 af-text-center af-text-xs af-text-muted-foreground",children:"Shown with a sample email"})]}),(0,Ce.jsxs)("div",{className:"af-space-y-3",children:[(0,Ce.jsx)(pm,{template:e,onOpenTemplate:a,onAskAssistant:n,reload:r}),(0,Ce.jsx)(gm,{templateId:e?.id??null,onOpenDraft:s,refreshKey:i})]})]})]})}function pm({template:e,onOpenTemplate:t,onAskAssistant:a,reload:s}){let{canWrite:n}=Xe(),r=bt(),[i,l]=_d.useState(null),u=e?.name??"Standard",c=async(d,p)=>{let x=await r.run(d,p);l(null),x.ok&&d==="deleteEmailTemplate"&&t(null),!x.ok&&Ba(x.error,"template_in_use")&&r.setError("Emails use this template now."),s()},o=async d=>{let p=await r.run("copyEmailTemplate",{templateId:d.id});p.ok&&(t(p.result.id),s())},f=d=>(0,Ce.jsx)(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:r.busy,onClick:()=>void o(d),children:"Make a copy"}),b=(0,Ce.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:r.busy,onClick:()=>l("delete"),children:"Delete"}),g=(0,Ce.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:r.busy,onClick:()=>l("archive"),children:"Archive"}),m=null;if(!n)m=null;else if(i&&e){let[d,p,x]=i==="delete"?["Delete this template?","Delete",()=>c("deleteEmailTemplate",{templateId:e.id})]:["Archive this template?","Archive",()=>c("archiveEmailTemplate",{templateId:e.id})];m=(0,Ce.jsxs)(Ce.Fragment,{children:[(0,Ce.jsx)("p",{className:"af-text-sm",children:d}),(0,Ce.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ce.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),(0,Ce.jsx)(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=(0,Ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,Ce.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:r.busy,onClick:()=>void c("unarchiveEmailTemplate",{templateId:e.id}),children:"Unarchive"}),f(e)]}):e.locked?m=(0,Ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_archive&&g,f(e)]}):m=(0,Ce.jsxs)(Ce.Fragment,{children:[a&&(0,Ce.jsx)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>a(to.update(e.name)),children:"\u2728 Change this template with the editor"}),(e.can_delete||e.can_archive)&&(0,Ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_delete&&b,e.can_archive&&g]})]}):m=a&&(0,Ce.jsx)(y,{type:"button",size:"sm",onClick:()=>a(to.copyStandard),children:"Make a copy"});let v=e&&e.status==="active"&&!e.locked?ll(e.usage.drafts):null;return(0,Ce.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Ce.jsx)("h3",{"data-testid":"template-title",className:"af-grow af-truncate af-text-sm af-font-semibold",children:u}),(0,Ce.jsx)(ol,{template:e})]}),v&&(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:v}),r.error&&(0,Ce.jsx)(he,{tone:"error",children:r.error}),m]})}function gm({templateId:e,onOpenDraft:t,refreshKey:a}){let{siteId:s}=Xe(),n=zs({siteId:s,kind:"broadcast",refreshKey:a}),r=Hs({siteId:s,refreshKey:a}),i=n.data?.filter(f=>(f.template?.id??null)===e)??null,l=r.data??[],u=Qi(n.data??[],l),c=new Set(l.flatMap(f=>f.draft_id&&f.status==="scheduled"?[f.draft_id]:[])),o=f=>u.has(f)?"Sent":c.has(f)?"Scheduled":"Draft";return(0,Ce.jsxs)("div",{"data-testid":"template-usage",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,Ce.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Emails using it"}),n.error||r.error?(0,Ce.jsx)(wt,{message:"Couldn't load the emails.",onRetry:()=>{n.refetch(),r.refetch()}}):!i||!r.data?(0,Ce.jsx)(Q,{className:"af-h-10 af-w-full"}):i.length===0?(0,Ce.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No emails use it."}):(0,Ce.jsx)("ul",{className:"af-space-y-1",children:i.map(f=>{let b=o(f.id),g=(0,Ce.jsxs)(Ce.Fragment,{children:[(0,Ce.jsx)("span",{className:"af-block af-truncate af-text-sm",children:f.subject||"(no subject)"}),(0,Ce.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["Broadcast \xB7 ",b]})]});return(0,Ce.jsx)("li",{children:b==="Sent"?(0,Ce.jsx)("div",{className:"af-rounded-md af-px-2 af-py-1",children:g}):(0,Ce.jsx)("button",{type:"button",onClick:()=>t(f.id),className:"af-w-full af-rounded-md af-px-2 af-py-1 af-text-left hover:af-bg-muted",children:g})},f.id)})})]})}var an=require("react/jsx-runtime");function Td({draft:e,disabled:t,onChanged:a}){let{api:s}=W(),{siteId:n,refreshKey:r}=Xe(),i=Mt(()=>s.getEmailTemplates(n),`${n}|${r}`,n),l=bt(),u=e.template?.id??qn,c=u===qn,o=(i.data??[]).filter(v=>v.status==="active"),f=o.find(v=>v.id===u),b=c?"Standard":e.template?.name??f?.name??"",g=c?"builtin":f?.updated_at??"current",m=async v=>{if(v===u)return;let d=await l.run("setDraftTemplate",{draftId:e.id,template_id:v===qn?null:v,expected_version:e.version});d.ok?await a():Ba(d.error,"template_missing_cart")?l.setError("This email shows the shopper's cart, and that template has no cart section. Pick another template, or keep this one."):Ba(d.error,"version_conflict")?(l.setError("This email changed meanwhile. We've loaded the latest version; switch again if you still want to."),await a()):Ba(d.error,"template_archived")&&(l.setError("That template is archived."),await i.refetch())};return(0,an.jsxs)("div",{"data-testid":"template-card",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,an.jsx)("div",{className:"af-text-sm af-font-semibold",children:"Template"}),(0,an.jsxs)("div",{className:"af-flex af-items-center af-gap-3",children:[(0,an.jsx)(ao,{templateId:u,version:g,className:"af-h-20 af-w-[72px] af-shrink-0 af-rounded af-border",frame:{width:600,height:670,scale:.12}}),(0,an.jsx)("div",{className:"af-min-w-0 af-grow af-truncate af-text-sm af-font-medium",children:b})]}),(0,an.jsxs)("label",{className:"af-grid af-gap-1 af-text-xs af-text-muted-foreground",children:["Switch to",(0,an.jsxs)("select",{"aria-label":"Switch to",value:u,disabled:t||l.busy,onChange:v=>void m(v.target.value),className:"af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-text-sm af-text-foreground",children:[(0,an.jsx)("option",{value:qn,children:"Standard"}),o.map(v=>(0,an.jsx)("option",{value:v.id,children:v.name},v.id)),!c&&!f&&(0,an.jsx)("option",{value:u,disabled:!0,children:b})]})]}),l.error&&(0,an.jsx)(he,{tone:"error",children:l.error})]})}var bs=require("react/jsx-runtime");function Ed({live:e,joinsOnSave:t,notice:a,onBackToCanvas:s}){return(0,bs.jsxs)("div",{"data-testid":"automation-step-panel",className:"af-space-y-2",children:[e?(0,bs.jsxs)(he,{tone:"success",children:[(0,bs.jsx)("span",{className:"af-font-medium",children:"Live."})," Saved changes send to the next people who reach this step."]}):t?(0,bs.jsx)(he,{children:"This email joins the automation when you save it with a subject and some content."}):null,a,(0,bs.jsx)("p",{className:"af-text-sm",children:(0,bs.jsx)(da,{onClick:s,children:"Back to the automation"})})]})}var Re=require("react/jsx-runtime"),vm={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"},bm=320,hm=600,ym=e=>({top:Math.max(0,e.y-24),left:e.x});function xm(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 no({draftId:e,renderCommit:t,automationStep:a,allowCart:s,onSaved:n,scheduled:r,onAskAssistant:i,onPickImage:l}){let{api:u}=W(),{siteId:c,canWrite:o,refreshKey:f,openSettings:b}=Xe(),g=o&&!r,m=Ye.useRef(g);m.current=g;let[v,d]=Ye.useState(null),[p,x]=Ye.useState(null),[R,T]=Ye.useState(null),[h,k]=Ye.useState(null),[P,I]=Ye.useState(null),[w,E]=Ye.useState(null),[L,C]=Ye.useState(null),[Y,G]=Ye.useState(null),[z,ce]=Ye.useState(null),[ve,xe]=Ye.useState({}),[D,q]=Ye.useState(ei.initial),[B,fe]=Ye.useState(!1),pe=bt(),We=bt(),Ie=Ye.useRef(null),$e=Ye.useRef(null),Qe=Ye.useRef(0),De=Ye.useRef(!1),ot=Ye.useRef(!1),O=Ye.useCallback(Te=>{De.current=Te!==null,E(Te)},[]);hd(w!==null);let V=Ye.useRef(v);V.current=v;let $=Ye.useRef(0),we=Ye.useCallback(async(Te={})=>{let Tt=++$.current,H=m.current,Oe=()=>H?u.previewEmailDraft(c,e,{editable:!0}):u.previewEmailDraft(c,e),[zt,xn]=await Promise.allSettled([u.getEmailDraft(c,e),Oe()]),se=xn,ia=()=>zt.status==="fulfilled"&&se.status==="fulfilled"&&se.value.version!==zt.value.version;if(ia()&&Tt===$.current&&([se]=await Promise.allSettled([Oe()])),Tt===$.current){if(Te.background&&De.current){ot.current=!0;return}if(k(null),T(null),zt.status==="rejected"){k(ur(zt.reason));return}d(zt.value),se.status==="fulfilled"?x({...se.value,editable:H&&!ia()}):(x(null),T(Ba(se.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:ur(se.reason),code:null}))}},[u,c,e]);Ye.useEffect(()=>{d(null),x(null),we()},[we]);let ne=Ye.useRef(g);Ye.useEffect(()=>{ne.current!==g&&(ne.current=g,g||O(null),we())},[g,we,O]);let me=Ye.useRef(f);Ye.useEffect(()=>{if(f!==me.current){if(me.current=f,De.current){ot.current=!0;return}we({background:!0})}},[f,we]);let qe=()=>{O(null),pe.setError(null),ot.current&&(ot.current=!1,we())},rt=async(Te,Tt,H)=>{let Oe=await pe.run("updateDraft",{draftId:e,expected_version:Te.version,...Tt});Oe.ok?(C(null),$e.current=null,ot.current=!1,O(null),await we(),n?.()):Ba(Oe.error,"version_conflict")&&(pe.setError(null),C(H),ot.current=!1,O(null),await we())},nt=Ye.useRef({frame:null,html:null,count:0}),[Ot,Pe]=Ye.useState(null),Ge=(Te,Tt)=>{let H=nt.current;H.frame!==Te.currentTarget||H.html!==Tt?nt.current={frame:Te.currentTarget,html:Tt,count:1}:++H.count>1&&Pe(Tt)},yt=p!==null&&Ot===p.html,Lt=g&&p?.editable===!0&&!yt;if(Ye.useEffect(()=>{if(!Lt)return;let Te=Tt=>{let H=V.current;if(!H)return;let Oe=xd(Tt,Ie.current?.contentWindow,H.blocks.length);if(Oe)switch(Oe.type){case"hover":ce(Oe.section===null?null:{section:Oe.section,rect:Oe.rect});return;case"focus":$e.current=Oe.section;return;case"open":if($e.current=Oe.section,De.current)return;G(null),fe(!1),O({kind:"section",base:H,index:Oe.section,block:H.blocks[Oe.section],isNew:!1,anchor:Oe.rect,key:++Qe.current});return;case"layout":q(wd(Oe.height));{let zt=Object.fromEntries(Oe.sections.map(xn=>[xn.section,xn.rect]));xe(xn=>xm(xn,zt)?xn:zt)}return;case"template":De.current||G(Oe.region);return}};return window.addEventListener("message",Te),()=>window.removeEventListener("message",Te)},[Lt,O]),h)return(0,Re.jsxs)(he,{tone:"error",children:["Couldn't load this email. ",h]});if(!v)return(0,Re.jsx)(Q,{className:"af-h-40 af-w-full"});let Vt={width:Ie.current?.clientWidth||hm,height:Lt?D:ei.initial},it=w?.kind==="section"?w:null,Qt=(()=>{if(!it)return null;if(!it.isNew)return ve[it.index]??it.anchor;let Te=ve[it.index-1];return Te?{x:Te.x,y:Te.y+Te.height,width:Te.width,height:0}:null})(),et=Qt?sl(Qt,Vt):null,Rt=s??v.kind==="recovery",Va=v.template?.name??"Standard",In=it&&(0,Re.jsx)(Rd,{block:it.block,isNew:it.isNew,busy:pe.busy,error:pe.error,onPickImage:l,onCancel:qe,onRemove:()=>{let{base:Te}=it;rt(Te,{subject:Te.subject,preheader:Te.preheader,blocks:Te.blocks.filter((Tt,H)=>H!==it.index)},il(it.block))},onDone:Te=>{let{base:Tt}=it,H=it.isNew?[...Tt.blocks.slice(0,it.index),Te,...Tt.blocks.slice(it.index)]:Tt.blocks.map((Oe,zt)=>zt===it.index?Te:Oe);rt(Tt,{subject:Tt.subject,preheader:Tt.preheader,blocks:H},il(Te))},className:et?"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:et?{top:et.y,left:et.x,width:Math.min(Math.max(et.width,bm),Vt.width)}:void 0},it.key);return(0,Re.jsxs)("div",{className:"af-grid af-gap-4 lg:af-grid-cols-[minmax(0,1fr)_300px]",children:[(0,Re.jsxs)("div",{className:"af-min-w-0 af-space-y-3",children:[w?.kind==="subject"?(0,Re.jsx)(wm,{draft:w.base,busy:pe.busy,error:pe.error,onCancel:qe,onDone:Te=>void rt(w.base,{...Te,blocks:w.base.blocks},[Te.subject,Te.preheader??""].join(`
8
+ `))}):Lt?(0,Re.jsx)("button",{type:"button","data-testid":"subject-line",onClick:()=>{De.current||(G(null),O({kind:"subject",base:v}))},className:"af-block af-w-full af-rounded-md af-border af-border-dashed af-px-3 af-py-2 af-text-left hover:af-border-primary",children:(0,Re.jsx)(Id,{draft:v})}):(0,Re.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:(0,Re.jsx)(Id,{draft:v})}),r&&(0,Re.jsxs)(he,{tone:"info",children:[(0,Re.jsxs)("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."]}),(0,Re.jsx)(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&&(0,Re.jsx)("p",{className:"af-mt-1 af-text-destructive",children:r.error})]}),L!==null&&(0,Re.jsxs)(he,{tone:"warning",children:[(0,Re.jsx)("p",{children:"This email changed while you were editing, so your change wasn't saved. Here is the latest version; your text is below to apply again."}),(0,Re.jsx)("textarea",{readOnly:!0,"aria-label":"Your unsaved text",value:L,className:"af-mt-2 af-min-h-[72px] af-w-full af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-font-mono af-text-xs af-text-foreground"}),(0,Re.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>C(null),children:"Dismiss"})]}),Y&&(0,Re.jsx)("div",{"data-testid":"template-hint",children:(0,Re.jsx)(he,{children:Y==="header"?(0,Re.jsxs)(Re.Fragment,{children:['The header is part of the "',Va,'" template. Switch templates on the right.']}):(0,Re.jsxs)(Re.Fragment,{children:["Every email ends with this footer. Your business name and address come from"," ",(0,Re.jsx)(da,{onClick:()=>b("sender"),children:"Settings"}),"."]})})}),yt&&g&&(0,Re.jsx)(he,{tone:"warning",children:"This template tried to open another page in the preview, so the preview can't be edited here."}),p?(0,Re.jsxs)("div",{className:"af-relative",children:[(0,Re.jsx)("iframe",{ref:Ie,title:"Email preview",sandbox:Lt?"allow-scripts":"",srcDoc:p.html,onLoad:Lt?Te=>Ge(Te,p.html):void 0,style:{height:Vt.height},className:"af-block af-w-full af-rounded-md af-border af-bg-white"},Lt?"editable":"read-only"),Lt&&z&&!w&&(0,Re.jsx)("div",{"aria-hidden":!0,className:"af-pointer-events-none af-absolute af-rounded af-bg-primary af-px-2 af-py-0.5 af-text-xs af-text-primary-foreground",style:ym(sl(z.rect,Vt)),children:vm[v.blocks[z.section]?.type??"text"]}),et&&In]}):R?(0,Re.jsxs)(he,{tone:"warning",children:[R.text,(0,Re.jsx)(dr,{reason:R.code})]}):(0,Re.jsx)(Q,{className:"af-h-40 af-w-full"}),!et&&In,Lt&&!w&&(0,Re.jsxs)("div",{className:"af-space-y-2",children:[(0,Re.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>fe(Te=>!Te),"aria-expanded":B,children:"+ Add a section"}),B&&(0,Re.jsx)("div",{"data-testid":"add-section-menu",className:"af-flex af-flex-wrap af-gap-2",children:["text","heading","button","image",...Rt?["cart"]:[]].map(Te=>(0,Re.jsx)(y,{type:"button",size:"sm",variant:"secondary",onClick:()=>{let Tt=$e.current!==null?$e.current+1:v.blocks.length;fe(!1),G(null),O({kind:"section",base:v,index:Tt,block:Nd(Te),isNew:!0,anchor:null,key:++Qe.current})},children:rl[Te]},Te))})]}),(0,Re.jsx)("p",{className:"af-text-center af-text-xs af-text-muted-foreground",children:"Header and footer come from your template."})]}),(0,Re.jsxs)("div",{className:"af-space-y-3",children:[(0,Re.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[(0,Re.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!o||We.busy,onClick:async()=>{I(null);let Te=await We.run("testSendDraft",{draftId:e});Te.ok&&I(Te.result?.sent_to??"your email")},children:"Send a test to me"}),P&&(0,Re.jsxs)(he,{tone:"success",children:["Test sent to ",P,"."]}),We.error&&(0,Re.jsx)(he,{tone:"error",children:We.error}),p&&!r&&t?.({draft:v,preview:p,reload:()=>we()}),a&&(0,Re.jsx)(Ed,{...a})]}),(0,Re.jsx)(Td,{draft:v,disabled:!g||w!==null,onChanged:async()=>{await we(),n?.()}}),i&&o&&(0,Re.jsx)(y,{type:"button",variant:"outline",className:"af-w-full",onClick:()=>i(`Update the "${v.subject}" email to `),children:"\u2728 Change this email with the editor"})]})]})}function Id({draft:e}){return(0,Re.jsxs)(Re.Fragment,{children:[(0,Re.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Subject "}),(0,Re.jsx)("span",{className:"af-font-medium",children:e.subject||"(no subject)"}),e.preheader&&(0,Re.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:[" \u2014 ",e.preheader]})]})}function wm({draft:e,busy:t,error:a,onDone:s,onCancel:n}){let[r,i]=Ye.useState(e.subject),[l,u]=Ye.useState(e.preheader??"");return(0,Re.jsxs)("form",{className:"af-space-y-2 af-rounded-md af-border af-p-3",onSubmit:c=>{c.preventDefault(),s({subject:r,preheader:l.trim()||null})},children:[(0,Re.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Subject",(0,Re.jsx)(de,{"aria-label":"Subject",value:r,maxLength:200,autoFocus:!0,onChange:c=>i(c.target.value)})]}),(0,Re.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Preview text (the grey line after the subject in the inbox)",(0,Re.jsx)(de,{"aria-label":"Preview text",value:l,maxLength:200,onChange:c=>u(c.target.value)})]}),a&&(0,Re.jsx)(he,{tone:"error",children:a}),(0,Re.jsxs)("div",{className:"af-flex af-justify-end af-gap-2",children:[(0,Re.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:t,onClick:n,children:"Cancel"}),(0,Re.jsx)(y,{type:"submit",size:"sm",disabled:t,children:"Done"})]})]})}var be=require("react/jsx-runtime"),Sm={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function Od({openDraftId:e,onOpenDraft:t,onAskAssistant:a,onPickImage:s}){let{siteId:n,canWrite:r,refreshKey:i}=Xe(),[l,u]=Pt.useState(0),c=l+i,o=zs({siteId:n,kind:"broadcast",refreshKey:c}),f=Hs({siteId:n,refreshKey:c}),b=bt(),g=bt(),m=Qi(o.data??[],f.data??[]),v=o.data?.filter(d=>!m.has(d.id))??null;if(e){let d=f.data?.find(p=>p.draft_id===e&&p.status==="scheduled");return(0,be.jsxs)("div",{className:"af-space-y-4",children:[(0,be.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>t(null),children:[(0,be.jsx)(Dd.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),!f.data&&!f.error||!o.data&&!o.error?(0,be.jsx)(Q,{className:"af-h-40 af-w-full"}):m.has(e)?(0,be.jsx)(he,{children:"This email has been sent, so it can't change. Duplicate it from the list to send it again."}):(0,be.jsx)(no,{draftId:e,onSaved:()=>u(p=>p+1),renderCommit:p=>(0,be.jsx)(km,{...p,onCommitted:()=>u(x=>x+1)}),scheduled:d?{sendsAt:d.scheduled_at,busy:b.busy,error:b.error,onUnschedule:async()=>{(await b.run("cancelBroadcast",{sendId:d.id})).ok&&u(x=>x+1)}}:void 0,onAskAssistant:a,onPickImage:s})]})}return(0,be.jsxs)("div",{children:[(0,be.jsx)(xa,{children:"Drafts"}),o.error?(0,be.jsx)(wt,{message:"Couldn't load drafts.",onRetry:()=>void o.refetch()}):v?v.length===0?(0,be.jsx)(la,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):(0,be.jsx)("ul",{"data-testid":"drafts",className:"af-divide-y af-rounded-md af-border",children:v.map(d=>(0,be.jsxs)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[(0,be.jsx)("span",{className:"af-truncate af-text-sm",children:d.subject||"(no subject)"}),(0,be.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(d.id),children:"Review"})]},d.id))}):(0,be.jsx)(Q,{className:"af-h-10 af-w-full"}),(0,be.jsx)(xa,{children:"Sent and scheduled"}),b.error&&(0,be.jsx)(he,{tone:"error",children:b.error}),g.error&&(0,be.jsx)(he,{tone:"error",children:g.error}),f.error?(0,be.jsx)(wt,{message:"Couldn't load broadcasts.",onRetry:()=>void f.refetch()}):f.data?f.data.length===0?(0,be.jsx)(la,{children:"Nothing sent yet."}):(0,be.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:f.data.map(d=>(0,be.jsx)(Nm,{broadcast:d,canCancel:r&&(d.status==="scheduled"||d.status==="unscheduled"||d.status==="sending"),busy:b.busy||g.busy,onCancel:async()=>{(await b.run("cancelBroadcast",{sendId:d.id})).ok&&u(x=>x+1)},onDuplicate:r&&d.draft_id&&tl(d)?async()=>{let p=await g.run("duplicateDraft",{draftId:d.draft_id});p.ok&&(u(x=>x+1),t(p.result.id))}:void 0},d.id))}):(0,be.jsx)(Q,{className:"af-h-10 af-w-full"})]})}function Nm({broadcast:e,canCancel:t,busy:a,onCancel:s,onDuplicate:n}){return(0,be.jsxs)("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[(0,be.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,be.jsx)("span",{className:"af-truncate af-text-sm af-font-medium",children:e.subject}),(0,be.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,be.jsx)(ie,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Sm[e.status]}),t&&(0,be.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:s,children:"Cancel"}),n&&(0,be.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:n,children:"Duplicate"})]})]}),(0,be.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",He(e.recipients.planned)," recipients \xB7 ",He(e.stats.delivered)," delivered \xB7 ",He(e.stats.opened)," opened \xB7"," ",He(e.stats.clicked)," clicked \xB7 ",He(e.stats.bounced)," bounced \xB7 ",He(e.stats.complained)," complaints \xB7"," ",He(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&(0,be.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:ss(e.status_reason)})]})}var Ld=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function Ad(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:Ld(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:s?Rm(a):"",suggested:t!==null||a!==null,timePassed:a!==null&&!s}}function Rm(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 _m=(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 km({draft:e,preview:t,reload:a,onCommitted:s}){let{api:n}=W(),{siteId:r,canWrite:i,settings:l,refreshKey:u}=Xe(),[c,o]=Pt.useState(null),[f,b]=Pt.useState(!1),[g,m]=Pt.useState(null),[v,d]=Pt.useState(()=>Ad(e)),[p,x]=Pt.useState(v.tagIds),[R,T]=Pt.useState(v.match),[h,k]=Pt.useState(v.scheduleAt),[P,I]=Pt.useState(0),w=!_m({tagIds:p,match:R,scheduleAt:h},v),E=Ld(e);Pt.useEffect(()=>{if(E===v.key||e.id===v.draftId&&w)return;let ne=Ad(e);d(ne),x(ne.tagIds),T(ne.match),k(ne.scheduleAt),I(0)},[E,e,v,w]);let L=Pt.useMemo(()=>c?new Set(c.map(ne=>ne.id)):null,[c]),C=L!==null&&p.every(ne=>L.has(ne));Pt.useEffect(()=>{if(!L||p.every(me=>L.has(me)))return;let ne=me=>me.filter(qe=>L.has(qe));I(me=>me+p.length-ne(p).length),x(ne(p)),d(me=>({...me,tagIds:ne(me.tagIds)}))},[L,p]);let[Y,G]=Pt.useState(null),[z,ce]=Pt.useState(null),[ve,xe]=Pt.useState(null),D=bt();Pt.useEffect(()=>{n.getMarketingTags(r).then(ne=>{o(ne),b(!1)},()=>{o(null),b(!0)}),n.getMarketingContactStats(r).then(m,()=>m(null))},[n,r,u]);let q=h?new Date(h).toISOString():null,B=JSON.stringify([p,R,q]),fe=Y?.plan??null,pe=Y!==null&&Y.key===B,We=Pt.useRef(0),Ie=Pt.useCallback(async()=>{let ne=++We.current;ce(null);try{let me=await n.estimateBroadcast(r,{targeting:{tag_ids:p,match:R},scheduled_at:q});ne===We.current&&G({key:B,plan:me})}catch(me){if(ne!==We.current)return;G(null),ce(ur(me))}},[n,r,p,R,q,B,u]),$e=Pt.useRef(!1);Pt.useEffect(()=>{if(!C&&p.length>0)return;if(!$e.current){$e.current=!0,Ie();return}let ne=setTimeout(()=>void Ie(),300);return()=>clearTimeout(ne)},[Ie,C,p.length]);let Qe=l&&!l.readiness.can_send?ss(l.readiness.reason):null,De=fe!==null&&!fe.fits,ot=g?Math.max(0,g.by_status.subscribed-g.mailable):null,O=g&&fe&&ot!==null?Math.max(0,g.total-fe.recipients-ot):null,V=!i||D.busy||!fe||!pe||De||fe.recipients===0||Qe!==null||f&&p.length>0,$=async()=>{xe(null);let ne=await D.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:p,match:R},scheduled_at:q});if(ne.ok){xe({tone:"success",text:q?"Scheduled.":"Sending now."}),s();return}Ba(ne.error,"version_conflict")?(D.setError(null),await a(),xe({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):Ba(ne.error,"over_allowance")&&await Ie()},we=ne=>x(me=>me.includes(ne)?me.filter(qe=>qe!==ne):[...me,ne]);return(0,be.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[v.suggested&&!w&&(0,be.jsx)(he,{children:"Suggested by your assistant \u2014 review before sending."}),(0,be.jsx)(xa,{children:"Who gets it"}),f&&(0,be.jsx)(he,{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."}),P>0&&(0,be.jsx)(he,{tone:"warning",children:P===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),c&&c.length>0?(0,be.jsxs)("div",{className:"af-space-y-2",children:[(0,be.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:c.map(ne=>(0,be.jsxs)("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[(0,be.jsx)("input",{type:"checkbox",checked:p.includes(ne.id),onChange:()=>we(ne.id)}),ne.label]},ne.id))}),p.length>1&&(0,be.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",(0,be.jsxs)("select",{"aria-label":"Tag match",value:R,onChange:ne=>T(ne.target.value),className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,be.jsx)("option",{value:"any",children:"any of these tags"}),(0,be.jsx)("option",{value:"all",children:"all of these tags"})]})]}),p.length===0&&(0,be.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):(0,be.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Everyone who can be emailed."}),(0,be.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,be.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),(0,be.jsx)(de,{"aria-label":"Schedule time",type:"datetime-local",value:h,onChange:ne=>k(ne.target.value)})]}),v.timePassed&&!h&&(0,be.jsx)(he,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),z?(0,be.jsxs)(he,{tone:"error",children:["Couldn't work out the audience. ",z]}):fe?(0,be.jsxs)("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[(0,be.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,be.jsx)(cl,{label:"Will receive it",value:fe.recipients}),(0,be.jsx)(cl,{label:"Suppressed (bounced or complained)",value:ot}),(0,be.jsx)(cl,{label:"Not included",value:O})]}),(0,be.jsxs)("p",{className:"af-text-muted-foreground",children:[He(fe.allowance.remaining)," of ",He(fe.allowance.monthly)," emails left this month."]}),fe.sample_size!==null&&(0,be.jsxs)(he,{children:["We'll send to ",He(fe.sample_size)," people first and check for bounces before sending the rest."]}),fe.ramp_days.length>1&&(0,be.jsxs)(he,{children:["Your domain is new, so this goes out over ",fe.ramp_days.length," days:"," ",fe.ramp_days.map(ne=>`${He(ne.recipients)} on ${ne.date}`).join(", "),"."]})]}):(0,be.jsx)(Q,{className:"af-h-12 af-w-full"}),De&&fe&&(0,be.jsxs)(he,{tone:"warning",children:["This send needs ",He(fe.recipients)," emails, but only ",He(fe.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),Qe&&(0,be.jsxs)(he,{tone:"warning",children:[Qe,(0,be.jsx)(dr,{reason:l?.readiness.reason})]}),ve&&(0,be.jsx)(he,{tone:ve.tone,children:ve.text}),D.error&&(0,be.jsx)(he,{tone:"error",children:D.error}),(0,be.jsx)(y,{type:"button",disabled:V,onClick:()=>void $(),children:q?"Schedule":"Send now"})]})}function cl({label:e,value:t}){return(0,be.jsxs)("div",{className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,be.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,be.jsx)("div",{className:"af-font-semibold",children:t===null?"\u2014":He(t)})]})}var Fa=le(require("react"),1);var hs=require("lucide-react");var qs=le(require("react"),1),Jt=require("lucide-react");var A=require("react/jsx-runtime"),Pm=[{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."}],Cm="hello";function ul(e){return`${Cm}@${e}`}function Bd({onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,onTurnOn:s,siteDomain:n,businessName:r,dnsManaged:i,renderSendingRecords:l}){let{api:u}=W(),{siteId:c,settings:o,canWrite:f,refreshKey:b,refetchSettings:g}=Xe(),m=Mt(()=>u.getMarketingContactStats(c),`${c}|${b}`,c),[v,d]=qs.useState(!1),[p,x]=qs.useState(null);if(!o)return null;let R=m.data?.by_status.subscribed??0,T={siteDomain:n,businessName:r};return Tm(o)?(0,A.jsx)(fl,{settings:o,site:T,waiting:R,children:f?s&&(0,A.jsxs)("div",{className:"af-space-y-2",children:[(0,A.jsxs)(y,{disabled:v,onClick:async()=>{d(!0),x(null);try{await s(),await g()}catch(h){x(h instanceof Error?h.message:"Couldn't turn on email. Try again.")}finally{d(!1)}},children:["Get started ",(0,A.jsx)(Jt.ArrowRight,{className:"af-ml-2 af-h-4 af-w-4","aria-hidden":!0})]}),p&&(0,A.jsx)(he,{tone:"error",children:p})]}):(0,A.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Only the site owner can set up email."})}):(0,A.jsx)(Em,{settings:o,site:T,waiting:R,onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,dnsManaged:i,renderSendingRecords:l})}function Tm(e){return e.readiness.reason==="sending_not_enabled"}function fl({settings:e,site:t,waiting:a=0,children:s}){return(0,A.jsx)("div",{className:"af-mx-auto af-max-w-3xl af-px-2 af-py-8",children:(0,A.jsxs)("div",{className:"af-grid af-items-center af-gap-10 md:af-grid-cols-[1fr_18rem]",children:[(0,A.jsxs)("div",{children:[(0,A.jsxs)("div",{className:"af-mb-3 af-inline-flex af-items-center af-gap-1.5 af-rounded-full af-bg-muted af-px-2.5 af-py-1 af-text-xs af-font-medium",children:[(0,A.jsx)(Jt.Mail,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0})," Email marketing"]}),(0,A.jsx)("h3",{className:"af-text-2xl af-font-semibold af-tracking-tight",children:"Turn visitors into regulars"}),(0,A.jsx)("p",{className:"af-mt-2 af-text-muted-foreground",children:"Build an email list from your website and reach those people directly, whenever you have something worth telling them."}),(0,A.jsx)("ol",{className:"af-mt-6 af-space-y-3",children:Pm.map((n,r)=>(0,A.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,A.jsx)("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-border af-text-xs af-font-semibold",children:r+1}),(0,A.jsxs)("p",{className:"af-text-sm",children:[(0,A.jsxs)("span",{className:"af-font-medium",children:[n.title,"."]})," ",(0,A.jsx)("span",{className:"af-text-muted-foreground",children:n.body})]})]},n.title))}),a>0&&(0,A.jsxs)("p",{className:"af-mt-5 af-rounded-md af-bg-amber-50 af-px-3 af-py-2 af-text-sm af-text-amber-900",children:[(0,A.jsxs)("span",{className:"af-font-semibold",children:[He(a)," ",a===1?"person has":"people have"]})," ","already signed up and ",a===1?"is":"are"," waiting for your first email."]}),(0,A.jsx)("div",{className:"af-mt-6",children:s})]}),(0,A.jsx)(so,{settings:e,site:t,className:"af-rotate-1"})]})})}function Fd({onUpgradePlan:e}){return(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-border-violet-200 af-bg-gradient-to-r af-from-violet-50 af-to-white af-p-4",children:[(0,A.jsx)(Jt.Lock,{className:"af-h-5 af-w-5 af-shrink-0 af-text-violet-700","aria-hidden":!0}),(0,A.jsxs)("div",{className:"af-flex-1",children:[(0,A.jsx)("div",{className:"af-text-sm af-font-semibold af-text-violet-900",children:"Email marketing is part of Pro"}),(0,A.jsx)("div",{className:"af-text-sm af-text-violet-900/80",children:"Collect subscribers and send newsletters from your own domain."})]}),e&&(0,A.jsx)(y,{size:"sm",onClick:e,children:"Upgrade to Pro"})]})}function Em({settings:e,site:t,waiting:a,onStartDomainSetup:s,onConnectDomain:n,onAskAssistant:r,dnsManaged:i,renderSendingRecords:l}){let{refetchSettings:u,canWrite:c}=Xe(),[o,f]=qs.useState(null),b=p=>f(x=>x===p?null:p),{siteDomain:g}=t,m=ti(e),v=g===null&&!e.domain.sending_domain,d=!!e.postal_address;return(0,A.jsxs)("div",{className:"af-mx-auto af-max-w-4xl af-py-4",children:[(0,A.jsxs)("div",{className:"af-mb-6 af-flex af-items-start af-justify-between af-gap-6",children:[(0,A.jsxs)("div",{children:[(0,A.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Set up email"}),(0,A.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Newsletters to your subscribers, sent from ",g??"your own domain","."]})]}),a>0&&(0,A.jsxs)("div",{className:"af-text-right",children:[(0,A.jsx)("div",{className:"af-text-2xl af-font-semibold",children:He(a)}),(0,A.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[a===1?"subscriber":"subscribers"," waiting"]})]})]}),!c&&(0,A.jsx)(he,{className:"af-mb-4",children:"Only the site owner can finish setup."}),(0,A.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_16rem]",children:[(0,A.jsxs)("div",{className:"af-space-y-4",children:[(0,A.jsxs)(dl,{title:g??"Your domain",sub:"One domain for your website and your email.",children:[g&&(0,A.jsx)(En,{icon:Jt.Globe,label:"Website",value:g,status:(0,A.jsx)(Tn,{tone:"green",children:"Live"})}),v?(0,A.jsx)(En,{icon:Jt.Mail,label:"Email sending",value:"Needs a custom domain",status:(0,A.jsx)(Tn,{tone:"gray",children:"Not available"}),action:n&&c?{label:"Connect domain",onClick:n}:void 0}):(0,A.jsxs)(En,{icon:Jt.Mail,label:"Email sending",value:e.domain.sending_domain??(g?`news.${g}`:"news.yourdomain.com"),status:ml(e),action:!m&&c?{label:e.domain.sending_domain?"Details":"Set up",onClick:()=>b("sending")}:void 0,expanded:o==="sending",children:[!e.domain.sending_domain&&(0,A.jsxs)("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:["Emails go out from a subdomain of your site's domain, so they reach inboxes and are clearly from you."," ",i?"We manage your domain's DNS, so we add the records for you. Nothing to copy.":i===!1?"You'll get a few records to copy into your DNS provider.":"If we manage your domain's DNS we add the records; otherwise you'll get a few to copy into your DNS provider."]}),(0,A.jsx)(pl,{settings:e,canWrite:c,onStartDomainSetup:s,onChanged:u,dnsManaged:i,renderSendingRecords:l})]})]}),(0,A.jsx)(dl,{title:"Sender",sub:"Who your emails are from. The mailing address is legally required in every email.",children:(0,A.jsx)(En,{icon:Jt.PenLine,label:d?e.business_name??"Sender":"Not set",value:e.postal_address??"Name, mailing address and reply-to",status:d?(0,A.jsx)(Tn,{tone:"green",children:"Done"}):(0,A.jsx)(Tn,{tone:"gray",children:"Needed"}),action:c?{label:d?"Edit":"Add",onClick:()=>b("sender")}:void 0,expanded:o==="sender",children:(0,A.jsx)(Im,{settings:e,businessName:t.businessName,onSaved:async()=>{await u(),f(null)}})})}),(0,A.jsx)(dl,{title:"How people join your list",sub:"Only people who asked to hear from you get your emails.",children:(0,A.jsx)(Lm,{onAskAssistant:c?r:void 0})})]}),(0,A.jsxs)("aside",{className:"af-space-y-3",children:[(0,A.jsx)("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails will look like"}),(0,A.jsx)(so,{settings:e,site:t})]})]})]})}function dl({title:e,sub:t,children:a}){return(0,A.jsxs)("section",{className:"af-rounded-xl af-border af-bg-background",children:[(0,A.jsxs)("div",{className:"af-px-5 af-pb-3 af-pt-4",children:[(0,A.jsx)("h4",{className:"af-text-sm af-font-semibold",children:e}),(0,A.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:t})]}),(0,A.jsx)("div",{className:"af-space-y-2 af-px-3 af-pb-3",children:a})]})}function En({icon:e,marker:t,markerSpace:a=!1,label:s,value:n,mono:r=!0,hint:i,status:l,action:u,expanded:c=!1,children:o}){return(0,A.jsxs)("div",{className:"af-rounded-lg af-border af-bg-muted/30",children:[(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-p-3",children:[t?(0,A.jsxs)("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-xs af-font-semibold af-text-background",children:[(0,A.jsx)("span",{"aria-hidden":!0,children:t}),(0,A.jsxs)("span",{className:"af-sr-only",children:["Shown at ",t," in the preview"]})]}):a?(0,A.jsx)("span",{className:"af-h-6 af-w-6 af-shrink-0","aria-hidden":!0}):e&&(0,A.jsx)("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-background",children:(0,A.jsx)(e,{className:"af-h-4 af-w-4","aria-hidden":!0})}),(0,A.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,A.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:s}),(0,A.jsx)("div",{className:X("af-truncate af-text-sm",r&&"af-font-mono"),children:n}),i&&(0,A.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:i})]}),l,u&&(0,A.jsxs)(y,{size:"sm",variant:c?"secondary":"outline","aria-expanded":o?c:void 0,onClick:u.onClick,children:[u.label,o&&(0,A.jsx)(Jt.ChevronDown,{className:X("af-ml-1 af-h-3.5 af-w-3.5 af-transition-transform",c&&"af-rotate-180"),"aria-hidden":!0})]})]}),c&&o&&(0,A.jsx)("div",{className:"af-border-t af-bg-background af-p-4",children:o})]})}function Tn({tone:e,children:t}){return(0,A.jsx)("span",{className:X("af-inline-flex af-shrink-0 af-items-center af-rounded-full af-px-2 af-py-0.5 af-text-xs af-font-medium",e==="green"&&"af-bg-green-100 af-text-green-800",e==="amber"&&"af-bg-amber-100 af-text-amber-900",e==="gray"&&"af-bg-muted af-text-muted-foreground",e==="red"&&"af-bg-red-100 af-text-red-800"),children:t})}function ti(e){return e.domain.status==="verified"&&e.domain.dmarc_status==="ok"}function ml(e){let{sending_domain:t,status:a}=e.domain;return!t||a==="none"?(0,A.jsx)(Tn,{tone:"gray",children:"Not set up"}):a==="verified"?ti(e)?(0,A.jsx)(Tn,{tone:"green",children:"Live"}):(0,A.jsx)(Tn,{tone:"amber",children:"DMARC record missing"}):a==="failed"?(0,A.jsx)(Tn,{tone:"red",children:"Records not found"}):(0,A.jsx)(Tn,{tone:"amber",children:"Waiting for DNS"})}function Im({settings:e,businessName:t,onSaved:a}){let{canWrite:s}=Xe(),[n,r]=qs.useState(e.business_name??t??""),[i,l]=qs.useState(e.postal_address??""),[u,c]=qs.useState(e.reply_to??""),o=bt();return(0,A.jsxs)("form",{className:"af-space-y-3",onSubmit:async f=>{f.preventDefault(),(await o.run("updateSettings",{business_name:n.trim()||null,postal_address:i.trim()||null,reply_to:u.trim()||null,double_opt_in:e.double_opt_in})).ok&&await a()},children:[(0,A.jsx)(Am,{name:n,address:i}),(0,A.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,A.jsx)("span",{className:"af-text-sm af-font-medium",children:"Sender name"}),(0,A.jsx)(de,{"aria-label":"Business name",value:n,disabled:!s,onChange:f=>r(f.target.value)})]}),(0,A.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,A.jsx)("span",{className:"af-text-sm af-font-medium",children:"Mailing address"}),(0,A.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:i,disabled:!s,onChange:f=>l(f.target.value)}),(0,A.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Anti-spam law requires it at the bottom of every email. A PO box works."})]}),(0,A.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,A.jsx)("span",{className:"af-text-sm af-font-medium",children:"Replies go to (optional)"}),(0,A.jsx)(de,{"aria-label":"Reply-to email",type:"email",value:u,disabled:!s,onChange:f=>c(f.target.value)}),(0,A.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Your account email or an address on your domain."})]}),o.error&&(0,A.jsx)(he,{tone:"error",children:o.error}),s&&(0,A.jsx)(y,{type:"submit",size:"sm",disabled:o.busy||!i.trim(),children:"Save sender details"})]})}function Am({name:e,address:t}){return(0,A.jsxs)("div",{className:"af-rounded-lg af-bg-muted/50 af-px-4 af-py-4 af-text-center af-text-xs af-leading-relaxed af-text-muted-foreground",children:[(0,A.jsx)("div",{className:"af-mb-1 af-text-[10px] af-uppercase af-tracking-wide",children:"Footer of every email"}),(0,A.jsxs)("div",{children:["\xA9 ",new Date().getFullYear()," ",(0,A.jsx)("span",{className:"af-font-medium af-text-foreground",children:e.trim()||"Your business"})]}),(0,A.jsx)("div",{className:X(!t.trim()&&"af-italic af-text-amber-700"),children:t.trim()||"No mailing address yet"}),(0,A.jsxs)("div",{children:[(0,A.jsx)("span",{className:"af-underline",children:"Manage preferences"})," | ",(0,A.jsx)("span",{className:"af-underline",children:"Unsubscribe"})]})]})}var Dm={1:"From",2:"Subject and body",3:"Footer"};function so({settings:e,site:t,className:a,numbered:s=!1,highlight:n=null,postalAddress:r}){let i=e?.business_name||t.businessName||"Your business",l=e?.domain.sending_domain??(t.siteDomain?`news.${t.siteDomain}`:"news.yourdomain.com"),u={backgroundColor:e?.brand.color??"hsl(var(--primary))"},c=r!==void 0?r.trim()||null:e?.postal_address,o=(f,b,g)=>s?(0,A.jsxs)("div",{"data-preview-region":f,"data-highlighted":n===f,className:X("af-relative af-rounded-md af-pl-7 af-transition-shadow",n===f&&"af-ring-2 af-ring-primary af-ring-offset-2",b),children:[(0,A.jsxs)("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:[(0,A.jsx)("span",{"aria-hidden":!0,children:f}),(0,A.jsxs)("span",{className:"af-sr-only",children:[f,". ",Dm[f],":"]})]}),g]}):(0,A.jsx)("div",{className:b,children:g});return(0,A.jsxs)("div",{className:X("af-rounded-lg af-border af-bg-background af-p-4 af-shadow-sm",a),"aria-hidden":s?void 0:!0,"aria-label":s?"Email preview":void 0,role:s?"group":void 0,children:[o(1,"af-flex af-items-start af-gap-3",(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-sm af-font-semibold af-text-white",style:u,children:i.slice(0,1).toUpperCase()}),(0,A.jsxs)("div",{className:"af-min-w-0",children:[(0,A.jsx)("div",{className:"af-truncate af-text-sm af-font-semibold",children:i}),(0,A.jsxs)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:["<",ul(l),">"]}),(0,A.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:"to me"})]})]})),o(2,"af-mt-4 af-space-y-2",(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)("div",{className:"af-text-sm af-font-medium",children:"What's new this month"}),(0,A.jsx)("div",{className:"af-h-2 af-w-full af-rounded af-bg-muted"}),(0,A.jsx)("div",{className:"af-h-2 af-w-5/6 af-rounded af-bg-muted"}),(0,A.jsx)("div",{className:"af-h-2 af-w-2/3 af-rounded af-bg-muted"})]})),o(3,"af-mt-4 af-border-t af-pt-2 af-text-center af-text-[10px] af-leading-snug af-text-muted-foreground",(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)("div",{children:c??(0,A.jsx)("span",{className:"af-italic af-text-amber-700",children:"Mailing address goes here"})}),(0,A.jsx)("div",{className:"af-underline",children:"Unsubscribe"})]}))]})}var Om="Add a newsletter signup to my footer";function Lm({onAskAssistant:e}){let t=gl();if(!t.data)return null;let{signups:a,optIns:s,others:n}=vl(t.data);return(0,A.jsxs)("div",{className:"af-space-y-3",children:[a.length===0?(0,A.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-gap-2 af-rounded-lg af-border af-border-dashed af-px-6 af-py-6 af-text-center",children:[(0,A.jsx)("div",{className:"af-flex af-h-10 af-w-10 af-items-center af-justify-center af-rounded-full af-bg-muted",children:(0,A.jsx)(Jt.Mail,{className:"af-h-5 af-w-5","aria-hidden":!0})}),(0,A.jsx)("div",{className:"af-text-sm af-font-medium",children:"Add a signup form to your site"}),(0,A.jsx)("p",{className:"af-max-w-sm af-text-xs af-text-muted-foreground",children:`A short "Get our news" form, usually in the footer. It's how most of your list will find you.`}),e&&(0,A.jsxs)(y,{type:"button",size:"sm",className:"af-mt-1",onClick:()=>e(Om),children:[(0,A.jsx)(Jt.Sparkles,{className:"af-mr-1.5 af-h-3.5 af-w-3.5","aria-hidden":!0}),"Add signup form"]})]}):(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[(0,A.jsx)(Jt.Check,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),(0,A.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,A.jsx)("span",{className:"af-font-medium",children:"Signup form is live"}),(0,A.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",a.map(r=>r.name).join(", ")]})]})]}),s.length>0&&(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[(0,A.jsx)(Jt.Check,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),(0,A.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,A.jsx)("span",{className:"af-font-medium",children:"Opt-in checkbox"}),(0,A.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",s.map(r=>r.name).join(", ")]})]})]}),a.length===0&&n.length>0&&(0,A.jsxs)("p",{className:"af-px-2 af-text-xs af-text-muted-foreground",children:["Your ",n.length===1?"form":"forms"," ",n.map(r=>`"${r.name}"`).join(", "),' can also add people, with a "Send me news" checkbox.',e&&(0,A.jsxs)(A.Fragment,{children:[" ",(0,A.jsx)("button",{type:"button",className:"af-font-medium af-text-foreground af-underline af-underline-offset-2",onClick:()=>e(bl(n)),children:"Add the checkbox"})]})]})]})}var ee=require("react/jsx-runtime"),ai="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 Bm(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 hl({onStartDomainSetup:e,onAskAssistant:t,dnsManaged:a,renderSendingRecords:s}){let{settings:n,refetchSettings:r,canWrite:i,settingsSection:l,onOpenBrandSettings:u}=Xe(),[c,o]=Fa.useState(null),[f,b]=Fa.useState(null),[g,m]=Fa.useState(""),v=n!==null;if(Fa.useEffect(()=>{v&&l&&document.getElementById(Yr(l))?.scrollIntoView?.({block:"start"})},[v,l]),!n)return(0,ee.jsx)(Q,{className:"af-h-40 af-w-full"});let d=I=>b(w=>w===I?null:I),p=()=>b(null),x=async()=>{await r(),p()},R=(I,w,E)=>({id:E,"data-settings-row":I,onMouseEnter:()=>o(w),onMouseLeave:()=>o(null),onFocus:()=>o(w),onBlur:()=>o(null)}),T=ti(n),{sending_domain:h,status:k}=n.domain,P=I=>i?{expanded:f===I}:{};return(0,ee.jsx)("div",{className:"af-@container",children:(0,ee.jsxs)("div",{className:"af-grid af-items-start af-gap-6 @2xl:af-grid-cols-[minmax(0,17rem)_minmax(0,1fr)]",children:[(0,ee.jsxs)("aside",{className:"af-space-y-3 af-pl-3",children:[(0,ee.jsx)("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails look like this"}),(0,ee.jsx)(so,{settings:n,site:{},numbered:!0,highlight:c,postalAddress:f==="address"?g:void 0}),(0,ee.jsx)(Hm,{settings:n})]}),(0,ee.jsxs)("div",{children:[(0,ee.jsx)(xa,{children:"From"}),(0,ee.jsxs)("div",{className:"af-space-y-2",children:[(0,ee.jsx)("div",{...R("Sending domain",1,Yr("domain")),children:(0,ee.jsx)(En,{markerSpace:!0,label:"Sending from",value:h?ul(h):"No sending domain yet",status:ml(n),action:!T&&i?{label:h?k==="verified"||k==="failed"?"Fix":"Details":"Set up",onClick:()=>d("domain")}:void 0,...P("domain"),children:(0,ee.jsx)(pl,{settings:n,canWrite:i,onStartDomainSetup:e,onChanged:r,dnsManaged:a,renderSendingRecords:s})})}),(0,ee.jsx)("div",{...R("Sender name and replies",1),children:(0,ee.jsx)(En,{marker:1,label:"Sender name and replies",mono:!1,value:`${n.business_name??"No sender name"} \xB7 replies to ${n.reply_to??"your account email"}`,action:i?{label:"Edit",onClick:()=>d("sender")}:void 0,...P("sender"),children:(0,ee.jsx)(Fm,{settings:n,onSaved:x,onCancel:p})})})]}),(0,ee.jsx)(xa,{children:"Brand"}),(0,ee.jsx)("div",{...R("Logo",2),children:(0,ee.jsx)(En,{marker:2,label:"Logo",mono:!1,value:n.brand.logo_url?"Your logo, from Brand settings":"No logo yet",hint:"Emails use your site's logo. Colors come from the email's template.",action:u?{label:"Brand settings",onClick:u}:void 0})}),(0,ee.jsx)(xa,{children:"Footer"}),(0,ee.jsx)("div",{...R("Mailing address",3,Yr("sender")),children:(0,ee.jsx)(En,{marker:3,label:"Mailing address",mono:!1,value:n.postal_address??"Not set",hint:"Anti-spam law requires it at the bottom of every email. A PO box works.",status:n.postal_address?void 0:(0,ee.jsx)(Tn,{tone:"amber",children:"Needed"}),action:i?{label:n.postal_address?"Edit":"Add",onClick:()=>{m(n.postal_address??""),d("address")}}:void 0,...P("address"),children:(0,ee.jsx)(Mm,{settings:n,draft:g,onDraft:m,onSaved:x,onCancel:p})})}),(0,ee.jsxs)("div",{id:Yr("signups"),children:[(0,ee.jsx)(xa,{children:"Who gets it"}),(0,ee.jsxs)("div",{className:"af-space-y-2",children:[(0,ee.jsx)("div",{...R("Double opt-in",null),children:(0,ee.jsx)($m,{settings:n,canWrite:i,onSaved:r})}),(0,ee.jsx)(zm,{onAskAssistant:i?t:void 0})]})]})]})]})})}function yl(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 $d({busy:e,error:t,canSave:a=!0,onSave:s,onCancel:n,children:r}){return(0,ee.jsxs)("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),await s()},children:[r,t&&(0,ee.jsx)(he,{tone:"error",children:t}),(0,ee.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ee.jsx)(y,{type:"submit",size:"sm",disabled:e||!a,children:"Save"}),(0,ee.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Cancel"})]})]})}function Fm({settings:e,onSaved:t,onCancel:a}){let[s,n]=Fa.useState(e.business_name??""),[r,i]=Fa.useState(e.reply_to??""),l=bt();return(0,ee.jsxs)($d,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",yl(e,{business_name:s.trim()||null,reply_to:r.trim()||null}))).ok&&await t()},children:[(0,ee.jsx)(Md,{label:"Sender name",children:(0,ee.jsx)(de,{"aria-label":"Business name",value:s,onChange:u=>n(u.target.value)})}),(0,ee.jsx)(Md,{label:"Replies go to (your account email or an address on your domain)",children:(0,ee.jsx)(de,{"aria-label":"Reply-to email",type:"email",value:r,onChange:u=>i(u.target.value)})})]})}function Mm({settings:e,draft:t,onDraft:a,onSaved:s,onCancel:n}){let r=bt();return(0,ee.jsx)($d,{busy:r.busy,error:r.error,canSave:!!t.trim(),onCancel:n,onSave:async()=>{(await r.run("updateSettings",yl(e,{postal_address:t.trim()}))).ok&&await s()},children:(0,ee.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:t,onChange:i=>a(i.target.value)})})}function $m({settings:e,canWrite:t,onSaved:a}){let[s,n]=Fa.useState(null),[r,i]=Fa.useState(!1),l=bt(),u=s??e.double_opt_in;return(0,ee.jsxs)("div",{className:"af-space-y-2",children:[(0,ee.jsx)(En,{icon:hs.ShieldCheck,label:"Double opt-in",mono:!1,value:u?"New subscribers confirm by email first":"New subscribers join straight away",status:(0,ee.jsxs)("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[(0,ee.jsx)("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:ai,className:"af-inline-flex af-h-4 af-w-4 af-cursor-help af-items-center af-justify-center af-rounded-full af-border af-text-[10px]",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:"?"}),(0,ee.jsx)("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!r,className:"af-absolute af-right-0 af-top-6 af-z-10 af-w-72 af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:ai}),(0,ee.jsx)("input",{"aria-label":"Double opt-in",type:"checkbox",role:"switch",checked:u,disabled:!t||l.busy,onChange:async c=>{let o=c.target.checked;n(o),(await l.run("updateSettings",yl(e,{double_opt_in:o}))).ok&&await a(),n(null)}})]})}),l.error&&(0,ee.jsx)(he,{tone:"error",children:l.error})]})}function pl({settings:e,canWrite:t,onStartDomainSetup:a,onChanged:s,dnsManaged:n,renderSendingRecords:r}){let[i,l]=Fa.useState(null),[u,c]=Fa.useState(!1),[o,f]=Fa.useState(null),[b,g]=Fa.useState(0),m=ti(e),{sending_domain:v,status:d}=e.domain,x=i?.status==="managed"||i?.status==="external"?i?.status==="managed":!!n,R=i?.records??[],T=x&&v&&!m&&d!=="verified"?(0,ee.jsx)(Um,{failed:d==="failed"}):null;return(0,ee.jsxs)("div",{children:[T??(0,ee.jsx)("p",{className:"af-text-sm",children:Bm(e)}),!m&&a&&(0,ee.jsx)(y,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||u,onClick:async()=>{c(!0),f(null);try{l(await a()),g(h=>h+1),await s()}catch(h){f(h instanceof Error?h.message:"Couldn't start domain setup.")}finally{c(!1)}},children:v?"Check domain setup":"Set up sending domain"}),o&&(0,ee.jsx)(he,{tone:"error",className:"af-mt-2",children:o}),r?(v||i)&&(0,ee.jsx)("div",{className:"af-mt-3",children:r()},b):R.length>0&&(0,ee.jsxs)("div",{className:"af-mt-3 af-space-y-1",children:[(0,ee.jsx)("p",{className:"af-text-sm",children:x?"The records we added to your DNS:":"Add these records at your domain provider:"}),(0,ee.jsxs)("table",{className:"af-w-full af-text-left af-text-xs",children:[(0,ee.jsx)("thead",{children:(0,ee.jsxs)("tr",{children:[(0,ee.jsx)("th",{className:"af-py-1 af-pr-2",children:"Type"}),(0,ee.jsx)("th",{className:"af-py-1 af-pr-2",children:"Name"}),(0,ee.jsx)("th",{className:"af-py-1 af-pr-2",children:"Value"}),(0,ee.jsx)("th",{className:"af-py-1",children:"Priority"})]})}),(0,ee.jsx)("tbody",{children:R.map((h,k)=>(0,ee.jsxs)("tr",{className:"af-border-t af-align-top",children:[(0,ee.jsx)("td",{className:"af-py-1 af-pr-2",children:h.type}),(0,ee.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:h.name}),(0,ee.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:h.value}),(0,ee.jsx)("td",{className:"af-py-1",children:h.priority??""})]},k))})]})]}),i&&!T&&(0,ee.jsx)(Vm,{result:i})]})}function Um({failed:e}){return e?(0,ee.jsxs)(he,{tone:"warning",children:[(0,ee.jsx)("div",{className:"af-font-medium",children:"Verification is taking longer than usual. Nothing for you to change."}),(0,ee.jsx)("div",{children:"We added the records and will keep checking. If it isn't live within a day, contact support and we'll sort it out."})]}):(0,ee.jsx)(he,{tone:"success",children:(0,ee.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ee.jsx)(hs.ShieldCheck,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0","aria-hidden":!0}),(0,ee.jsxs)("div",{children:[(0,ee.jsx)("div",{className:"af-font-medium",children:"We added these records to your DNS for you. Nothing to do."}),(0,ee.jsx)("div",{children:"Verification usually finishes within a few hours."})]})]})})}function Vm({result:e}){return e.status==="no_domain"?(0,ee.jsx)(he,{tone:"warning",className:"af-mt-2",children:"Emails send from your own domain, so this site needs a custom domain first. Connect one, then come back to finish here."}):e.status==="not_available"?(0,ee.jsx)(he,{tone:"warning",className:"af-mt-2",children:"Email sending isn't available for this site. It needs the Pro plan."}):e.records&&e.records.length>0?null:(0,ee.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",children:"We added the DNS records for you. Verification usually finishes within a few hours."})}function Hm({settings:e}){let{monthly:t,sent:a,reserved:s}=e.allowance,n=a+s;return(0,ee.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[He(n)," of ",He(t)," emails used this month (",He(Math.max(0,t-n))," left). Receipts and form notifications don't count."]})}function gl(){let{api:e}=W(),{siteId:t,refreshKey:a}=Xe();return Mt(async()=>Promise.all((await e.getForms()).map(s=>e.getForm(s.id))),`${t}|${a}`,t)}function vl(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 bl(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 zm({onAskAssistant:e}){let t=gl();if(!t.data||t.data.length===0)return null;let{signups:a,optIns:s,others:n}=vl(t.data),r=[{id:"signup",label:"Signup forms",note:"Submitting one subscribes the visitor.",forms:a,icon:hs.Check},{id:"opt_in",label:'Forms with a "Send me news" checkbox',note:"Visitors who tick the box join your list.",forms:s,icon:hs.Check},{id:"other",label:"Other forms",note:"These don't add anyone to your list.",forms:n,icon:hs.FileText,action:a.length===0&&e?{label:"Add the checkbox",onClick:()=>e(bl(n))}:void 0}];return(0,ee.jsx)(ee.Fragment,{children:r.filter(i=>i.forms.length>0).map(i=>(0,ee.jsx)("div",{"data-form-group":i.id,children:(0,ee.jsx)(En,{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 Md({label:e,children:t}){return(0,ee.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,ee.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}var ro=le(require("react"),1);var ht=require("react/jsx-runtime");function Vd({templateId:e,onOpenTemplate:t,onOpenDraft:a,onAskAssistant:s}){let{api:n}=W(),{siteId:r,canWrite:i,refreshKey:l}=Xe(),[u,c]=ro.useState(0),o=u+l,f=Mt(()=>n.getEmailTemplates(r),`${r}|${o}`,r),b=ro.useCallback(()=>c(d=>d+1),[]),g=i?s:void 0;if(e){let d=e===qn?null:f.data?.find(p=>p.id===e);if(d!==void 0)return(0,ht.jsx)(Cd,{template:d,onBack:()=>t(null),onOpenTemplate:t,onOpenDraft:a,onAskAssistant:g,reload:b,refreshKey:o},e);if(f.isLoading)return(0,ht.jsx)(Q,{className:"af-h-96 af-w-full"})}let m=f.data?.filter(d=>d.status!=="archived")??[],v=f.data?.filter(d=>d.status==="archived")??[];return(0,ht.jsxs)("div",{children:[(0,ht.jsxs)("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[(0,ht.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Templates"}),g&&(0,ht.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(to.create),children:"\u2728 New template with the editor"})]}),(0,ht.jsxs)(Ud,{children:[(0,ht.jsx)(xl,{template:null,onOpen:()=>t(qn)}),m.map(d=>(0,ht.jsx)(xl,{template:d,onOpen:()=>t(d.id)},d.id))]}),f.error&&!f.data?(0,ht.jsx)("div",{className:"af-mt-3",children:(0,ht.jsx)(wt,{message:"Couldn't load your templates.",onRetry:()=>void f.refetch()})}):!f.data&&(0,ht.jsx)(Q,{className:"af-mt-3 af-h-10 af-w-full"}),v.length>0&&(0,ht.jsxs)("div",{"data-testid":"archived-templates",children:[(0,ht.jsx)(xa,{children:"Archived"}),(0,ht.jsx)(Ud,{children:v.map(d=>(0,ht.jsx)(xl,{template:d,onOpen:()=>t(d.id)},d.id))})]})]})}function Ud({children:e}){return(0,ht.jsx)("ul",{className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:e})}function jm(e){let t=[ll(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 xl({template:e,onOpen:t}){let a=e?.name??"Standard",s=e&&jm(e);return(0,ht.jsxs)("li",{"data-testid":"template-card",className:"af-relative af-overflow-hidden af-rounded-md af-border hover:af-border-primary",children:[(0,ht.jsx)(ao,{templateId:e?.id??qn,version:e?.updated_at??"builtin",className:"af-h-40 af-border-b",frame:{width:600,height:400,scale:.4}}),(0,ht.jsxs)("div",{className:"af-space-y-1 af-p-2",children:[(0,ht.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ht.jsx)("span",{"data-testid":"template-name",className:"af-grow af-truncate af-text-sm af-font-medium",children:a}),(0,ht.jsx)(ol,{template:e})]}),s&&(0,ht.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:s})]}),(0,ht.jsx)("button",{type:"button","aria-label":`Open ${a}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}var nn=le(require("react"),1),co=require("lucide-react");var Ma=le(require("react"),1),wa=require("lucide-react");var ge=require("react/jsx-runtime"),qm=365*24,Wm=[1,24,48,72,168];function oo(e){return e.map(t=>t.type==="send"?{type:"send",draft_id:t.draft_id}:{type:"wait",wait_hours:t.wait_hours})}function ys(e){return e%168===0?Us(e/168,"week"):e%24===0?Us(e/24,"day"):Us(e,"hour")}var si={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 ri(e,t){return e.slice(0,t+1).filter(a=>a.type==="send").length}var io=300,Hd=64,Gm=24,ni={trigger:72,send:104,wait:64,waitEditing:196,exit:44};function Km(e,t){let a=[],s=0,n=r=>{a.push({...r,y:s}),s+=r.height+Hd};return n({id:"trigger",kind:"trigger",height:ni.trigger}),e.forEach((r,i)=>n({id:r.step_key,kind:r.type,index:i,height:r.type==="send"?ni.send:r.step_key===t?ni.waitEditing:ni.wait})),n({id:"exit",kind:"exit",height:ni.exit}),{nodes:a,height:s-Hd}}var jd=Ma.createContext(null);function ii(){let e=Ma.useContext(jd);if(!e)throw new Error("Canvas nodes render inside AutomationCanvas");return e}function wl(e,t){let a=e[t];return a.type==="send"?`email ${ri(e,t)}`:`the ${ys(a.wait_hours)} wait`}function qd(e){let{automation:t,onChangeSteps:a}=e,s=t.steps,[n,r]=Ma.useState(null),[i,l]=Ma.useState(null),[u,c]=Ma.useState(null),o=(m,v)=>{c(null),r(null),l(null),a(m,v)},f=oo(s),b={...e,insertAt:n,setInsertAt:m=>{c(null),r(m)},editingWait:i,setEditingWait:l,insertWait:m=>{if(!f.slice(m).some(v=>v.type==="send")){r(null),c("A wait after the last email does nothing, so it wasn't added.");return}o([...f.slice(0,m),{type:"wait",wait_hours:24},...f.slice(m)],"Add a 1 day wait")},setWait:(m,v)=>o(f.map((d,p)=>p===m?{type:"wait",wait_hours:v}:d),`Change ${wl(s,m)} to ${ys(v)}`),move:(m,v)=>{let d=[...f];[d[m],d[m+v]]=[d[m+v],d[m]],o(d,`Move ${wl(s,m)} ${v<0?"up":"down"}`)},remove:m=>o(f.filter((v,d)=>d!==m),`Remove ${wl(s,m)}`)},g=Km(s,i);return(0,ge.jsxs)(jd.Provider,{value:b,children:[u&&(0,ge.jsx)(he,{className:"af-mb-2",children:u}),(0,ge.jsx)("div",{"data-testid":"automation-canvas",className:"af-rounded-md af-border af-bg-muted/40",style:{height:g.height+2*Gm},children:(0,ge.jsx)(Ma.Suspense,{fallback:(0,ge.jsx)(Q,{className:"af-h-full af-w-full"}),children:(0,ge.jsx)(Zm,{layout:g,steps:s})})})]})}var Zm=Ma.lazy(async()=>({default:Ym(await import("@xyflow/react"))}));function Ym(e){let t=l=>[{type:"target",position:e.Position.Top,x:io/2,y:0,width:1,height:1},{type:"source",position:e.Position.Bottom,x:io/2,y:l,width:1,height:1}],a=()=>(0,ge.jsxs)(ge.Fragment,{children:[(0,ge.jsx)(e.Handle,{type:"target",position:e.Position.Top,isConnectable:!1,className:"!af-opacity-0"}),(0,ge.jsx)(e.Handle,{type:"source",position:e.Position.Bottom,isConnectable:!1,className:"!af-opacity-0"})]}),s=l=>(0,ge.jsxs)(ge.Fragment,{children:[l,(0,ge.jsx)(a,{})]}),n={trigger:()=>s((0,ge.jsx)(zd,{kind:"trigger"})),send:({data:l})=>s((0,ge.jsx)(Jm,{index:l.index,step:l.step})),wait:({data:l})=>s((0,ge.jsx)(Xm,{index:l.index,step:l.step})),exit:()=>s((0,ge.jsx)(zd,{kind:"exit"}))};function r({id:l,sourceX:u,sourceY:c,targetX:o,targetY:f,data:b}){let[g,m,v]=e.getStraightPath({sourceX:u,sourceY:c,targetX:o,targetY:f});return(0,ge.jsxs)(ge.Fragment,{children:[(0,ge.jsx)(e.BaseEdge,{id:l,path:g}),(0,ge.jsx)(e.EdgeLabelRenderer,{children:(0,ge.jsx)("div",{className:"nodrag nopan af-pointer-events-auto af-absolute",style:{transform:`translate(-50%, -50%) translate(${m}px, ${v}px)`},children:(0,ge.jsx)(ep,{index:b.insertAt})})})]})}let i={insert:r};return function({layout:u,steps:c}){let o=u.nodes.map(b=>({id:b.id,type:b.kind,position:{x:0,y:b.y},width:io,height:b.height,style:{width:io,height:b.height,pointerEvents:"all"},handles:t(b.height),data:"index"in b?{index:b.index,step:c[b.index]}:{index:-1,step:null},draggable:!1,selectable:!1,connectable:!1,focusable:!1})),f=u.nodes.slice(1).map((b,g)=>({id:`${u.nodes[g].id}->${b.id}`,source:u.nodes[g].id,target:b.id,type:"insert",data:{insertAt:g},selectable:!1,focusable:!1}));return(0,ge.jsx)(e.ReactFlow,{nodes:o,edges:f,nodeTypes:n,edgeTypes:i,proOptions:{hideAttribution:!0},fitView:!0,fitViewOptions:{padding:.05,maxZoom:1,minZoom:.5},minZoom:.5,maxZoom:1,nodesDraggable:!1,nodesConnectable:!1,nodesFocusable:!1,edgesFocusable:!1,elementsSelectable:!1,panOnDrag:!1,panOnScroll:!1,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,preventScrolling:!1,deleteKeyCode:null,selectionKeyCode:null,multiSelectionKeyCode:null})}}function zd({kind:e}){let{automation:t}=ii();return e==="exit"?(0,ge.jsx)("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"}):(0,ge.jsxs)("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:[(0,ge.jsx)(wa.Zap,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ge.jsxs)("div",{className:"af-min-w-0",children:[(0,ge.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:"Trigger"}),(0,ge.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:si[t.trigger_type].title})]})]})}function Wd({index:e,label:t}){let{automation:a,editable:s,move:n,remove:r}=ii();if(!s)return null;let i=a.steps.length-1;return(0,ge.jsxs)("div",{className:"af-flex af-shrink-0 af-gap-0.5",children:[(0,ge.jsx)(Sl,{label:`Move ${t} up`,disabled:e===0,onClick:()=>n(e,-1),children:(0,ge.jsx)(wa.ArrowUp,{})}),(0,ge.jsx)(Sl,{label:`Move ${t} down`,disabled:e===i,onClick:()=>n(e,1),children:(0,ge.jsx)(wa.ArrowDown,{})}),(0,ge.jsx)(Sl,{label:`Remove ${t}`,onClick:()=>r(e),children:(0,ge.jsx)(wa.Trash2,{})})]})}function Sl({label:e,disabled:t,onClick:a,children:s}){return(0,ge.jsx)(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 Jm({index:e,step:t}){let{automation:a,statsByStep:s,onOpenEmail:n}=ii(),r=ri(a.steps,e),i=s[t.step_key];return(0,ge.jsxs)("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:[(0,ge.jsxs)("div",{className:"af-flex af-items-start af-gap-2",children:[(0,ge.jsx)(wa.Mail,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0"}),(0,ge.jsxs)("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:[(0,ge.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Email ",r]}),(0,ge.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:t.subject||"(no subject)"})]}),a.status==="on"&&t.live&&(0,ge.jsx)(ie,{variant:"success",children:"Live"}),(0,ge.jsx)(Wd,{index:e,label:`email ${r}`})]}),(0,ge.jsx)("p",{"data-testid":"canvas-email-stats",className:"af-text-xs af-text-muted-foreground",children:i?`Sent ${He(i.sent)} \xB7 Opened ${He(i.opened)} \xB7 Clicked ${He(i.clicked)}`:"Not sent yet"})]})}function Xm({index:e,step:t}){let{editable:a,editingWait:s,setEditingWait:n,setWait:r}=ii(),i=`the ${ys(t.wait_hours)} wait`,l=a&&s===t.step_key;return(0,ge.jsxs)("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:[(0,ge.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ge.jsx)(wa.Clock,{className:"af-h-4 af-w-4 af-shrink-0"}),a?(0,ge.jsxs)("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 ",ys(t.wait_hours)]}):(0,ge.jsxs)("span",{className:"af-grow af-text-sm",children:["Wait ",ys(t.wait_hours)]}),(0,ge.jsx)(Wd,{index:e,label:i})]}),l&&(0,ge.jsx)(Qm,{hours:t.wait_hours,onSave:u=>r(e,u),onCancel:()=>n(null)})]})}function Qm({hours:e,onSave:t,onCancel:a}){let s=e%24===0,[n,r]=Ma.useState(String(s?e/24:e)),[i,l]=Ma.useState(s?"days":"hours"),u=Number(n)*(i==="days"?24:1),c=Number.isInteger(u)&&u>=1&&u<=qm;return(0,ge.jsxs)("div",{"data-testid":"wait-editor",className:"nodrag af-space-y-2",children:[(0,ge.jsx)("div",{className:"af-flex af-flex-wrap af-gap-1",children:Wm.map(o=>(0,ge.jsx)(y,{type:"button",size:"sm",variant:o===e?"default":"outline",className:"af-h-7 af-px-2",onClick:()=>t(o),children:ys(o)},o))}),(0,ge.jsxs)("form",{className:"af-flex af-items-center af-gap-1",onSubmit:o=>{o.preventDefault(),c&&t(u)},children:[(0,ge.jsx)(de,{"aria-label":"Custom wait",type:"number",min:1,value:n,onChange:o=>r(o.target.value),className:"af-h-7 af-w-20"}),(0,ge.jsxs)("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:[(0,ge.jsx)("option",{value:"hours",children:"hours"}),(0,ge.jsx)("option",{value:"days",children:"days"})]}),(0,ge.jsx)(y,{type:"submit",size:"sm",className:"af-h-7 af-px-2",disabled:!c,children:"Save"}),(0,ge.jsx)(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:a,children:"Cancel"})]}),!c&&(0,ge.jsx)("p",{className:"af-text-xs af-text-destructive",children:"A wait is 1 hour to 365 days."})]})}function ep({index:e}){let{editable:t,insertAt:a,setInsertAt:s,insertWait:n,onInsertEmail:r}=ii();if(!t)return null;let i=a===e;return(0,ge.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,ge.jsx)("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:X("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:(0,ge.jsx)(wa.Plus,{className:"af-h-3.5 af-w-3.5"})}),i&&(0,ge.jsxs)("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:[(0,ge.jsxs)(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:()=>n(e),children:[(0,ge.jsx)(wa.Clock,{})," Wait"]}),(0,ge.jsxs)(y,{type:"button",size:"sm",variant:"ghost",className:"af-h-7 af-px-2",onClick:()=>{s(null),r(e)},children:[(0,ge.jsx)(wa.Mail,{})," Email"]})]})]})}var j=require("react/jsx-runtime"),tp="Create an automation that ",ap={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 Gd({automation:e}){let[t,a]=e.status==="on"?e.available?["success","On"]:["warning","Unavailable"]:["secondary",e.status==="draft"?"Draft":"Off"];return(0,j.jsx)(ie,{"data-testid":"automation-state",variant:t,children:a})}function np(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 ${ri(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 ss(e)??"Something went wrong. Try again."}}function Nl(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 oi({code:e,automation:t,stepKey:a,onOpenEmail:s}){let{openSettings:n,openSetup:r,onOpenStoreSettings:i}=Xe(),l=t&&a?t.steps.find(c=>c.step_key===a):void 0,u=null;return e==="postal_address_missing"?u=(0,j.jsx)(da,{onClick:()=>n("sender"),children:"Add it in Settings"}):e==="checkout_consent_off"&&i?u=(0,j.jsx)(da,{onClick:i,children:"Open Store settings"}):e==="email_empty"&&l?.type==="send"&&s?u=(0,j.jsx)(da,{onClick:()=>s(l.draft_id),children:"Open the email"}):e==="domain_not_verified"||e==="dmarc_missing"?u=(0,j.jsx)(da,{onClick:()=>n("domain"),children:"Fix in Settings"}):e==="sending_not_enabled"&&(u=(0,j.jsx)(da,{onClick:r,children:"Finish setup"})),(0,j.jsxs)(j.Fragment,{children:[np(e,t,a),u&&(0,j.jsxs)(j.Fragment,{children:[" ",u]})]})}function Kd({automationId:e,onOpenAutomation:t,list:a,onAskAssistant:s,onPickImage:n}){let{canWrite:r}=Xe(),i=r?s:void 0;if(e){let l=a.data?.automations.find(u=>u.id===e);if(l)return(0,j.jsx)(ip,{automation:l,reload:a.refetch,onBack:()=>t(null),onAskAssistant:i,onPickImage:n},l.id);if(!a.data&&!a.error)return(0,j.jsx)(Q,{className:"af-h-96 af-w-full"})}return(0,j.jsxs)("div",{children:[(0,j.jsxs)("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[(0,j.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Automations"}),i&&(0,j.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i(tp),children:"\u2728 New automation with the editor"})]}),a.error&&!a.data?(0,j.jsx)(wt,{message:"Couldn't load your automations.",onRetry:()=>void a.refetch()}):a.data?(0,j.jsxs)(j.Fragment,{children:[a.data.capabilities.suggestions.length>0&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(xa,{children:"Suggested"}),(0,j.jsx)("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=>(0,j.jsx)(rp,{suggestion:l,list:a.data,reload:a.refetch,onOpenAutomation:t},l))})]}),(0,j.jsx)(xa,{children:"Your automations"}),a.data.automations.length===0?(0,j.jsx)(la,{children:"No automations yet. Turn on a suggestion above, or ask the editor to build one."}):(0,j.jsx)("ul",{"data-testid":"automations",className:"af-divide-y af-rounded-md af-border",children:a.data.automations.map(l=>(0,j.jsx)(sp,{automation:l,onOpen:()=>t(l.id)},l.id))})]}):(0,j.jsx)(Q,{className:"af-h-24 af-w-full"})]})}function Zd(e){return[si[e.trigger_type].title,...e.steps.map(t=>t.type==="send"?"Email":`Wait ${ys(t.wait_hours)}`)].join(" \u2192 ")}function Yd(e){let{api:t}=W(),{siteId:a,refreshKey:s}=Xe(),n=e.status==="draft",r=Mt(()=>n?Promise.resolve([]):t.getAutomationStats(a,e.id),`${a}|${e.id}|${e.version}|${e.status}|${s}`,`${a}|${e.id}`);return nn.useMemo(()=>Object.fromEntries((r.data??[]).map(i=>[i.step_key,i])),[r.data])}function sp({automation:e,onOpen:t}){let a=Object.values(Yd(e)),s=n=>He(a.reduce((r,i)=>r+i[n],0));return(0,j.jsxs)("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:[(0,j.jsxs)("div",{className:"af-min-w-0 af-grow af-space-y-0.5",children:[(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,j.jsx)("span",{className:"af-truncate af-text-sm af-font-medium",children:e.name}),(0,j.jsx)(Gd,{automation:e})]}),(0,j.jsx)("p",{"data-testid":"automation-chain",className:"af-truncate af-text-xs af-text-muted-foreground",children:Zd(e)}),a.length>0&&(0,j.jsxs)("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")]})]}),(0,j.jsx)(co.ChevronRight,{className:"af-h-4 af-w-4 af-shrink-0 af-text-muted-foreground"}),(0,j.jsx)("button",{type:"button","aria-label":`Open ${e.name}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}function rp({suggestion:e,list:t,reload:a,onOpenAutomation:s}){let{api:n}=W(),{siteId:r,canWrite:i,onOpenStoreSettings:l}=Xe(),u=bt(),[c,o]=nn.useState(!1),[f,b]=nn.useState(null),g=ap[e],m=t.automations.find(x=>x.trigger_type===g.trigger&&x.list_tag_id===null),v=e==="recovery"&&t.capabilities.checkout_consent==="off_available",d=async()=>{o(!1),b(null);let x=await u.run("addSuggestedAutomation",{key:e}),R=x.ok?x.result:null;if(!x.ok){let h=Ba(x.error,"automation_exists")?x.error:null,k=h?.automation_id??h?.details?.automation_id;if(!k)return;if(u.setError(null),R=await n.getAutomation(r,k).catch(()=>null),!R)return void a()}let T=await u.run("turnOnAutomation",{automationId:R.id,expected_version:R.version});T.ok||(u.setError(null),b({code:vs(T.error),stepKey:Nl(T.error)})),await a()},p=()=>m?(0,j.jsx)("p",{className:"af-text-sm",children:(0,j.jsx)(da,{onClick:()=>s(m.id),children:"Open the automation"})}):i?c?(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsxs)("p",{className:"af-text-sm",children:['Turn on "',g.title,'"? It sends ',Us(g.emails,"email")," to each person who ",si[g.trigger].phrase,"."]}),(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>o(!1),children:"Cancel"}),(0,j.jsx)(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:u.busy,onClick:()=>void d(),children:"Turn on"})]})]}):v?(0,j.jsxs)("div",{className:"af-space-y-1",children:[(0,j.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Needs the marketing consent box at checkout, in Store settings."}),(0,j.jsx)(y,{type:"button",size:"sm",disabled:!l,onClick:()=>l?.(),children:"Turn on"})]}):(0,j.jsx)("div",{children:(0,j.jsx)(y,{type:"button",size:"sm",disabled:u.busy,onClick:()=>o(!0),children:"Turn on"})}):null;return(0,j.jsxs)("li",{"data-testid":"suggestion-card",className:"af-flex af-flex-col af-gap-2 af-rounded-md af-border af-p-3",children:[(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,j.jsx)("span",{"data-testid":"suggestion-title",className:"af-grow af-text-sm af-font-medium",children:g.title}),m&&(0,j.jsx)(ie,{variant:"secondary",children:"Added"})]}),(0,j.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:g.description}),f&&(0,j.jsxs)(he,{tone:"warning",children:["Not turned on. ",(0,j.jsx)(oi,{code:f.code,automation:m,stepKey:f.stepKey})]}),u.error&&(0,j.jsx)(he,{tone:"error",children:u.error}),p()]})}var lo={on:{message:(e,t)=>`Turn on "${e.name}"? It sends ${Us(t,"email")} to each person who ${si[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 ip({automation:e,reload:t,onBack:a,onAskAssistant:s,onPickImage:n}){let{api:r}=W(),{siteId:i,canWrite:l}=Xe(),u=Yd(e),c=bt(),o=bt(),f=bt(),[b,g]=nn.useState(null),[m,v]=nn.useState(null),[d,p]=nn.useState(null),[x,R]=nn.useState(null),[T,h]=nn.useState(null),[k,P]=nn.useState(!1),I=e.status==="on",w=e.steps.filter(D=>D.type==="send").length,E=async D=>{P(!0);try{await D()}finally{P(!1)}},L=(D,q)=>E(async()=>{p(null),R(null);let B=await c.run("updateAutomation",{automationId:e.id,expected_version:e.version,steps:D});if(!B.ok){let fe=vs(B.error);fe==="version_conflict"?(c.setError(null),p(q)):(fe==="email_empty"||fe==="postal_address_missing")&&(c.setError(null),R({code:fe,stepKey:Nl(B.error)}))}await t()}),C=D=>E(async()=>{let q=await c.run("createDraft",{kind:"automation",automation_id:e.id,subject:"",blocks:[]});if(!q.ok)return;let B=q.result.id;if(I)return h({draftId:B,joinAt:D});let fe=oo(e.steps);await L([...fe.slice(0,D),{type:"send",draft_id:B},...fe.slice(D)],"Add an email")}),Y=nn.useRef(Promise.resolve()),G=D=>{let q=Y.current.then(async()=>{let B=await r.getEmailDraft(i,D.draftId).catch(()=>null);if(!B||!B.subject.trim()||B.blocks.length===0)return;let fe=await r.getAutomation(i,e.id).catch(()=>null);if(!fe)return;if(fe.steps.some($e=>$e.type==="send"&&$e.draft_id===D.draftId))return h({draftId:D.draftId});let pe=oo(fe.steps),We=Math.min(D.joinAt,pe.length);(await f.run("updateAutomation",{automationId:e.id,expected_version:fe.version,steps:[...pe.slice(0,We),{type:"send",draft_id:D.draftId},...pe.slice(We)]})).ok&&h({draftId:D.draftId}),await t()});return Y.current=q.catch(()=>{}),q},z=async D=>{g(null),v(null);let q=D==="turnOnAutomation"?{automationId:e.id,expected_version:e.version}:{automationId:e.id},B=await o.run(D,q);!B.ok&&D==="turnOnAutomation"&&(o.setError(null),v({code:vs(B.error),stepKey:Nl(B.error)})),B.ok&&D==="deleteAutomation"&&a(),await t()},ce=D=>(0,j.jsxs)("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:[(0,j.jsx)(da,{onClick:a,children:"Automations"}),(0,j.jsx)(co.ChevronRight,{className:"af-h-3.5 af-w-3.5"}),D===void 0?(0,j.jsx)("span",{className:"af-font-medium af-text-foreground",children:e.name}):(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(da,{onClick:()=>h(null),children:e.name}),(0,j.jsx)(co.ChevronRight,{className:"af-h-3.5 af-w-3.5"}),(0,j.jsx)("span",{className:"af-font-medium af-text-foreground",children:D})]})]});if(T){let D=e.steps.findIndex(B=>B.type==="send"&&B.draft_id===T.draftId),q=T.joinAt!==void 0;return(0,j.jsxs)("div",{children:[ce(D>=0?`Email ${ri(e.steps,D)}`:"New email"),(0,j.jsx)(no,{draftId:T.draftId,allowCart:e.trigger_type==="abandoned_checkout",automationStep:{live:I&&!q,joinsOnSave:I&&q,notice:f.error&&(0,j.jsxs)(he,{tone:"error",children:["Couldn't add this email to the automation. ",f.error]}),onBackToCanvas:()=>h(null)},onSaved:()=>{T.joinAt!==void 0?G({draftId:T.draftId,joinAt:T.joinAt}):t()},onAskAssistant:s,onPickImage:n},T.draftId)]})}let ve=e.blocked_by[0]??null,xe=I&&!e.available;return(0,j.jsxs)("div",{className:"af-space-y-3",children:[ce(),(0,j.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,j.jsx)("h3",{"data-testid":"automation-title",className:"af-grow af-truncate af-text-base af-font-semibold",children:e.name}),(0,j.jsx)(Gd,{automation:e}),l&&!b&&(0,j.jsx)(j.Fragment,{children:I?(0,j.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:o.busy,onClick:()=>g("off"),children:"Turn off"}):(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:o.busy,onClick:()=>g("delete"),children:"Delete"}),(0,j.jsx)(y,{type:"button",size:"sm",disabled:o.busy,onClick:()=>g("on"),children:"Turn on"})]})})]}),(0,j.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:Zd(e)}),b&&(0,j.jsxs)("div",{"data-testid":"automation-confirm",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,j.jsx)("p",{className:"af-text-sm",children:lo[b].message(e,w)}),(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(null),children:"Cancel"}),(0,j.jsx)(y,{type:"button",size:"sm",variant:lo[b].variant,className:"af-ml-auto",disabled:o.busy,onClick:()=>void z(lo[b].action),children:lo[b].label})]})]}),m&&(0,j.jsxs)(he,{tone:"warning",children:[(0,j.jsx)("span",{className:"af-font-medium",children:"Not turned on."})," ",(0,j.jsx)(oi,{code:m.code,automation:e,stepKey:m.stepKey,onOpenEmail:D=>h({draftId:D})})]}),o.error&&(0,j.jsx)(he,{tone:"error",children:o.error}),xe?(0,j.jsxs)(he,{tone:"warning",children:[(0,j.jsx)("span",{className:"af-font-medium",children:"Unavailable."})," ",(0,j.jsx)(oi,{code:ve??"trigger_unavailable",automation:e})," Nobody new enters it; people already in it still get their remaining emails."]}):ve&&!m&&(0,j.jsxs)(he,{tone:"warning",children:[I?"Not sending right now.":"Won't send yet."," ",(0,j.jsx)(oi,{code:ve,automation:e})]}),I&&!xe&&(0,j.jsxs)(he,{tone:"success",children:[(0,j.jsx)("span",{className:"af-font-medium",children:"Live."})," Changes you make here, and saves to its emails, go out to the next people who reach each step."]}),d&&(0,j.jsxs)(he,{tone:"warning",children:["This automation changed while you were editing, so your change wasn't saved: ",(0,j.jsx)("span",{className:"af-font-medium",children:d}),". Here is the latest version; make the change again if you still want it."]}),x&&(0,j.jsxs)(he,{tone:"warning",children:["Not saved. ",(0,j.jsx)(oi,{code:x.code,automation:e,stepKey:x.stepKey,onOpenEmail:D=>h({draftId:D})})]}),c.error&&(0,j.jsx)(he,{tone:"error",children:c.error}),(0,j.jsx)(qd,{automation:e,statsByStep:u,editable:l&&!c.busy&&!k,onChangeSteps:(D,q)=>void L(D,q),onInsertEmail:D=>void C(D),onOpenEmail:D=>h({draftId:D})})]})}var Je=require("react/jsx-runtime"),op=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"automations",label:"Automations"},{id:"templates",label:"Templates"},{id:"settings",label:"Settings"}];function Wn(e,t={}){return{tab:e,draftId:null,templateId:null,automationId:null,...t}}var Jd=e=>!!(e.tab||e.draftId||e.templateId||e.automationId);function Xd(e){return e.draftId?Wn("broadcasts"):e.templateId?Wn("templates",{templateId:e.templateId}):e.automationId?Wn("automations",{automationId:e.automationId}):Wn(e.tab==="template"?"templates":e.tab??"audience")}var lp={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function Rl(e){return(0,Je.jsx)(cp,{...e},e.siteId)}function cp({siteId:e,isOwnerSide:t,needsPaidPlan:a,initialDraftId:s,initialTab:n,initialAutomationId:r,templateId:i,showViewNonce:l,onOrgAction:u,onRequestReview:c,onStartDomainSetup:o,dnsManaged:f,renderSendingRecords:b,onBackToWebsite:g,onUpgradePlan:m,onConnectDomain:v,onAskAssistant:d,onPickImage:p,onTurnOn:x,siteDomain:R,businessName:T,onOpenStoreSettings:h,onOpenBrandSettings:k,refreshKey:P=0,className:I}){let{api:w}=W(),E=Mt(()=>w.getMarketingSettings(e),`${e}|${P}`,e),L=Mt(()=>w.getAutomations(e),`${e}|${P}`,e),C={tab:n,draftId:s,templateId:i,automationId:r},[Y,G]=Xt.useState(()=>Xd(C)),[z,ce]=Xt.useState(s??null),[ve,xe]=Xt.useState(Jd(C)),[D,q]=Xt.useState(null),[B,fe]=Xt.useState(!1),pe=Xt.useCallback(()=>xe(!1),[]),We=Xt.useCallback(me=>{G(Wn("settings")),q(me??null)},[]),Ie=me=>{G(Wn(me)),q(null)},$e=Xt.useCallback(me=>G(Wn("broadcasts",{draftId:me})),[]),Qe=Xt.useCallback(me=>G(Wn("templates",{templateId:me})),[]),De=Xt.useCallback(me=>G(Wn("automations",{automationId:me})),[]),ot=!ve&&E.data!==null&&dp(E.data),O=Y.tab,V=E.data&&!E.error?up(E.data):null,$=JSON.stringify([l??null,n??null,s??null,i??null,r??null]),we=Xt.useRef($);Xt.useEffect(()=>{if($===we.current||B)return;we.current=$;let me={tab:n,draftId:s,templateId:i,automationId:r};Jd(me)&&(G(Xd(me)),ce(me.draftId??null),q(null),xe(!0))},[$,B,n,s,i,r]),Xt.useEffect(()=>{if(!z||a)return;let me=!0,qe=rt=>{me&&(G(Wn("broadcasts",{draftId:rt})),ce(null))};return w.getEmailDraft(e,z).then(rt=>qe(rt.kind==="broadcast"?rt.id:null),()=>qe(null)),()=>{me=!1}},[w,e,z,a]);let ne=Xt.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:u,settings:E.data,refetchSettings:E.refetch,refreshKey:P,openSetup:pe,openSettings:We,settingsSection:D,onOpenStoreSettings:h,onOpenBrandSettings:k,setInlineEditOpen:fe}),[e,t,u,E.data,E.refetch,P,pe,We,D,h,k]);return a?(0,Je.jsx)(Ft,{title:"Email Marketing",onBackToWebsite:g,className:I,children:(0,Je.jsx)(fl,{settings:E.data,site:{siteDomain:R,businessName:T},children:(0,Je.jsx)(Fd,{onUpgradePlan:m})})}):(0,Je.jsx)(Ft,{title:"Email Marketing",onBackToWebsite:g,className:I,children:(0,Je.jsx)(el.Provider,{value:ne,children:ot?(0,Je.jsx)(Bd,{onStartDomainSetup:o,dnsManaged:f,renderSendingRecords:b,onConnectDomain:v,onAskAssistant:d,onTurnOn:x,siteDomain:R,businessName:T}):(0,Je.jsxs)(Je.Fragment,{children:[E.error&&!E.data&&(0,Je.jsx)(wt,{message:"Couldn't load email settings.",onRetry:()=>void E.refetch()}),V&&(0,Je.jsx)(mp,{reason:V,pauseReason:E.data?.paused.reason??null,onRequestReview:c}),!t&&(0,Je.jsx)(he,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),(0,Je.jsx)("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:op.map(me=>(0,Je.jsxs)("button",{type:"button",role:"tab","aria-selected":O===me.id,onClick:()=>Ie(me.id),className:X("af-border-b-2 af-px-3 af-py-2 af-text-sm",O===me.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:[me.label,me.id==="settings"&&V&&(0,Je.jsx)("span",{"data-testid":"settings-dot",role:"img","aria-label":"Sending is on hold",className:"af-ml-1.5 af-inline-block af-h-1.5 af-w-1.5 af-rounded-full af-bg-amber-600 af-align-middle"})]},me.id))}),(0,Je.jsx)("div",{role:"tabpanel",children:z?(0,Je.jsx)(Q,{className:"af-h-24 af-w-full"}):O==="audience"?(0,Je.jsx)(yd,{}):O==="broadcasts"?(0,Je.jsx)(Od,{openDraftId:Y.draftId,onOpenDraft:$e,onAskAssistant:d,onPickImage:p}):O==="automations"?(0,Je.jsx)(Kd,{automationId:Y.automationId,onOpenAutomation:De,list:L,onAskAssistant:d,onPickImage:p}):O==="templates"?(0,Je.jsx)(Vd,{templateId:Y.templateId,onOpenTemplate:Qe,onOpenDraft:$e,onAskAssistant:d}):(0,Je.jsx)(hl,{onStartDomainSetup:o,onAskAssistant:d,dnsManaged:f,renderSendingRecords:b})})]})})})}function dp(e){return!e.paused.paused_at&&!e.readiness.can_send&&Kr.has(e.readiness.reason??"")}function up(e){if(e.paused.paused_at)return"paused";let t=e.readiness.reason;return!e.readiness.can_send&&t&&Kr.has(t)?t:null}var fp={domain_not_verified:"domain",dmarc_missing:"domain",postal_address_missing:"sender"};function mp({reason:e,pauseReason:t,onRequestReview:a}){let{openSetup:s,openSettings:n}=Xe(),[r,i]=Xt.useState("idle");if(e==="paused")return(0,Je.jsx)("div",{"data-testid":"email-hold",className:"af-mb-3",children:(0,Je.jsxs)(he,{tone:"warning",children:[(0,Je.jsx)("div",{className:"af-font-medium",children:"Sending is paused."}),(0,Je.jsxs)("p",{children:[lp[t??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),a&&(r==="sent"?(0,Je.jsx)("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):(0,Je.jsx)(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{i("sending");try{await a(),i("sent")}catch{i("failed")}},children:"Request review"})),r==="failed"&&(0,Je.jsx)("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]})});let l=fp[e];return(0,Je.jsx)("div",{"data-testid":"email-hold",className:"af-mb-3",children:(0,Je.jsxs)(he,{tone:"warning",children:["Sending is on hold. ",ss(e)," ",l?(0,Je.jsx)(da,{onClick:()=>n(l),children:"Fix in Settings"}):(0,Je.jsx)(da,{onClick:s,children:"Finish setup"})]})})}var sa=le(require("react"),1);var pp=2e3,ga=()=>({data:null,error:null,isLoading:!0});function Ws(e,{refreshKey:t,breakdowns:a=[],filters:s=[]}={}){let{api:n}=W(),[r,i]=sa.useState(ga),[l,u]=sa.useState(ga),[c,o]=sa.useState(ga),[f,b]=sa.useState(ga),[g,m]=sa.useState(ga),v=D=>Object.fromEntries(D.map(q=>[q,ga()])),[d,p]=sa.useState(()=>v(a)),x=sa.useRef(0),R=sa.useRef(0),T=sa.useRef("idle"),h=a.join(","),k=os()??"",P=JSON.stringify(s),I=`${e}:${h}:${P}:${k}`,[w,E]=sa.useState({api:n,fetchIdentity:I});(w.api!==n||w.fetchIdentity!==I)&&(E({api:n,fetchIdentity:I}),x.current+=1,i(ga),u(ga),o(ga),b(ga),p(v(h?h.split(","):[])));let L=`${e}:${String(t??"")}:${k}`,[C,Y]=sa.useState({api:n,conversionsIdentity:L});(C.api!==n||C.conversionsIdentity!==L)&&(Y({api:n,conversionsIdentity:L}),R.current+=1,T.current="idle",m(ga));let G=sa.useCallback(async D=>{let q=++x.current,B=h?h.split(","):[];i(ga),u(ga),o(ga),b(ga),p(Object.fromEntries(B.map(O=>[O,ga()])));let fe=T.current!=="pending"&&(D?.force===!0||T.current==="idle"),pe=(O,V)=>V.then($=>{q===x.current&&O({data:$,error:null,isLoading:!1})},$=>{q===x.current&&O({data:null,error:$ instanceof Error?$:new Error("Failed to fetch report"),isLoading:!1})}),We=n.getAnalyticsStatus(),Ie=pe(i,We),$e=Symbol("status-timeout"),Qe,De=await Promise.race([We.then(O=>O,()=>null),new Promise(O=>{Qe=setTimeout(()=>O($e),pp)})]);if(clearTimeout(Qe),q!==x.current)return;if(De===$e&&i({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),De!==null&&De!==$e&&(De.collecting!==!0||De.first_seen===null&&!De.first_seen_unavailable||De.first_seen!==null&&De.first_seen_in_reports===!1)){let O={data:null,error:null,isLoading:!1};u(O),o(O),b(O),p(Object.fromEntries(B.map(V=>[V,{...O}]))),fe&&(m(O),T.current="done"),await Ie;return}await Promise.all([De===$e?Promise.resolve():Ie,pe(u,n.getAnalyticsSummary(e,s)),pe(o,n.getAnalyticsTimeseries(e,s)),pe(b,n.getAnalyticsChannels(e,s)),fe?(()=>{T.current="pending";let O=++R.current;return m(ga),n.getAnalyticsConversions(e).then(V=>{O===R.current&&(m({data:V,error:null,isLoading:!1}),T.current="done")},V=>{O===R.current&&(m({data:null,error:V instanceof Error?V:new Error("Failed to fetch report"),isLoading:!1}),T.current="done")})})():Promise.resolve(),...B.map(O=>n.getAnalyticsBreakdown(O,e,s).then(V=>{q===x.current&&p($=>({...$,[O]:{data:V,error:null,isLoading:!1}}))},V=>{q===x.current&&p($=>({...$,[O]:{data:null,error:V instanceof Error?V:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,P,L,k]),z=sa.useCallback(async()=>{let D=x.current;try{let q=await n.getAnalyticsStatus();if(D!==x.current)return;i({data:q,error:null,isLoading:!1})}catch(q){if(D!==x.current)return;i(B=>({data:B.data,error:q instanceof Error?q:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),ce=sa.useCallback(()=>G({force:!0}),[G]);sa.useEffect(()=>{G()},[G,t]);let ve=r.isLoading||l.isLoading||c.isLoading||f.isLoading||g.isLoading||Object.values(d).some(D=>D.isLoading),xe=[c,l,f,g,...Object.values(d)].map(D=>D.data?.status==="ok"?D.data.timezone:void 0).find(D=>D!==void 0);return{status:r,summary:l,timeseries:c,channels:f,conversions:g,breakdowns:d,reportedZone:xe,isLoading:ve,refetch:ce,refetchStatus:z}}var ra=le(require("react"),1);var uo=3e4,fo=3;function li(e={}){let t="collecting"in e,{collecting:a,statusFailed:s=!1,identity:n}=e,{api:r}=W(),[i,l]=ra.useState(null),[u,c]=ra.useState(null),[o,f]=ra.useState(!1),[b,g]=ra.useState(null),[m,v]=ra.useState(!1),[d,p]=ra.useState(!0),[x,R]=ra.useState(0),T=ra.useRef(0),h=ra.useRef(0),k=ra.useRef(void 0);a!==void 0&&(k.current=a);let P=t?k.current===!0||k.current===void 0&&s:!0,[I,w]=ra.useState({api:r,identity:n}),E=n!==void 0&&n!==I.identity;(I.api!==r||E)&&(k.current=void 0,w({api:r,identity:n}),h.current+=1,T.current=0,l(null),c(null),f(!1),g(null),v(!1),p(!0),R(0));let L=ra.useRef(()=>{}),C=ra.useRef(null),Y=ra.useCallback(async()=>{if(C.current!==null&&C.current===h.current)return;let G=++h.current;C.current=G;try{let z=await r.getAnalyticsRealtime();if(G!==h.current)return;if(z.status==="unreachable"){v(!0),f(!0),p(!1),R(ce=>ce+1);return}T.current=0,v(!1),l(z.data.current_visitors),c(z.as_of),f(!1),g(null),p(!1),R(ce=>ce+1)}catch(z){if(G!==h.current)return;T.current+=1,p(!1),R(ce=>ce+1),f(!0),T.current>=fo&&g(z instanceof Error?z:new Error("Realtime unavailable"))}finally{C.current===G&&(C.current=null)}},[r]);return L.current=()=>void Y(),ra.useEffect(()=>{let G,z=()=>{G===void 0&&(G=setInterval(()=>L.current(),uo))},ce=()=>{G!==void 0&&(clearInterval(G),G=void 0)},ve=()=>{typeof document<"u"&&document.hidden?ce():(L.current(),z())};return P?((typeof document>"u"||!document.hidden)&&(L.current(),z()),document?.addEventListener("visibilitychange",ve),()=>{ce(),document?.removeEventListener("visibilitychange",ve),h.current+=1}):()=>{document?.removeEventListener("visibilitychange",ve)}},[I.api,I.identity,P]),{currentVisitors:i,asOf:u,isStale:o,error:b,isUnreachable:m,isInitialLoad:d,polls:x}}var Ut=le(require("react"),1);var Qd=le(require("react"),1);var Gs=require("react/jsx-runtime");function gp(){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 _l({value:e,chosen:t,onChange:a}){let s=pr(),n=t===null&&s!==null&&e===s,r=Qd.useMemo(()=>{let i=gp();return i.includes(e)?i:[e,...i]},[e]);return(0,Gs.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,Gs.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,Gs.jsxs)("select",{value:n?"":e,onChange:i=>a(i.target.value===""?null:i.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[(0,Gs.jsx)("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(i=>(0,Gs.jsx)("option",{value:i,children:i.replace(/_/g," ")},i))]})]})}var mo=(e,{published:t}={})=>{let a=t===!1,s=e!=null&&(!e.collecting||a&&e.first_seen===null&&!e.first_seen_unavailable),n=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,i=n||r;return{notCollecting:s,awaitingFirstVisit:n,firstVisitTooRecent:r,holdingForFirstData:i,nothingToReport:s||i}};var ci=le(require("react"),1),vp=3e4;function po({status:e,holdingForFirstData:t,refetchStatus:a,refetch:s}){ci.useEffect(()=>{if(!t)return;let r,i=()=>{r===void 0&&(r=setInterval(()=>void a(),vp))},l=()=>{r!==void 0&&(clearInterval(r),r=void 0)},u=()=>{typeof document<"u"&&document.hidden?l():(a(),i())};return(typeof document>"u"||!document.hidden)&&i(),document?.addEventListener("visibilitychange",u),()=>{l(),document?.removeEventListener("visibilitychange",u)}},[t,a]);let n=ci.useRef(void 0);ci.useEffect(()=>{if(!e){n.current=void 0;return}let r=n.current;n.current=t,r===!0&&!t&&s()},[e,t,s])}var Ks=le(require("react"),1);var bp=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ka(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?ka(i*s):`${i}${n}`}return String(e)}function fr(e){return`${(e*100).toFixed(1)}%`}function di(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 tu(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`:di(t)}function au(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function nu(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 ui(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function su(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 kl(e){let t=Number(e.slice(5,7)),a=Number(e.slice(8,10));return`${bp[t-1]} ${a}`}function eu(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function hp(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function ru(e,t,a="UTC"){let s=new Map(t.map(i=>[i.date,i])),n=[],r=eu(e.to,a);for(let i=eu(e.from,a);i<r;i=hp(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 iu(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=new Date(`${e}T00:00:00Z`);if(Number.isNaN(s.getTime()))return e;let n=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${n} ${a[s.getUTCMonth()]}`}var sn=require("react/jsx-runtime");function ou({what:e="This report",onRetry:t,collecting:a}){return(0,sn.jsxs)("div",{role:"status",className:"af-flex af-flex-col af-items-center af-gap-1 af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-8 af-text-center",children:[(0,sn.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,sn.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:a===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),t?(0,sn.jsx)("button",{type:"button",onClick:t,className:"af-mt-2 af-rounded-md af-border af-border-border af-px-3 af-py-1 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Try again"}):null]})}function go({what:e="No data"}){return(0,sn.jsx)("div",{className:"af-flex af-items-center af-justify-center af-rounded-md af-px-4 af-py-8 af-text-center af-text-xs af-text-muted-foreground",children:e})}function rs({sourced:e,error:t,isLoading:a,what:s,onRetry:n,collecting:r,children:i}){return a?(0,sn.jsx)("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,sn.jsx)(ou,{what:s,onRetry:n,collecting:r}):!e||e.status==="unreachable"?(0,sn.jsx)(ou,{what:s,onRetry:n,collecting:r}):(0,sn.jsx)(sn.Fragment,{children:i(e.data)})}var Ct=require("react/jsx-runtime");function Pl({rows:e,dimension:t,metric:a,metricLabel:s,secondary:n,emptyCopy:r="No data for this period",onFilter:i,canFilter:l,maxRows:u=9}){let[c,o]=Ks.useState(!1);if(e.length===0)return(0,Ct.jsx)(go,{what:r});let f=e.reduce((m,v)=>Math.max(m,Number(v[a]??0)),0)||1,b=Math.max(0,e.length-u),g=c?e:e.slice(0,u);return(0,Ct.jsxs)(Ct.Fragment,{children:[(0,Ct.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Ct.jsx)("thead",{children:(0,Ct.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Ct.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,Ct.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),(0,Ct.jsx)("tbody",{children:g.map((m,v)=>{let d=Number(m[a]??0),p=m[t]??null,x=ui(p),R=n?m[n]:null,T=p!==null&&(l?l(p,R):!0);return(0,Ct.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,Ct.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,Ct.jsx)("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,d/f*100)}%`}}),p!==null&&i&&T?(0,Ct.jsx)("button",{type:"button",onClick:()=>i(p,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}):(0,Ct.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:x}),R?(0,Ct.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:R}):null]}),(0,Ct.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:ka(d)})]},`${x}-${R??""}-${v}`)})})]}),b>0?(0,Ct.jsx)("button",{type:"button",onClick:()=>o(m=>!m),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:c?"Show fewer":`Show all ${e.length}`}):null]})}function fi({title:e,tabs:t,defaultTabId:a,headerRight:s}){let[n,r]=Ks.useState(a),i=t.find(g=>g.id===n)??t[0],l=Ks.useId(),u=g=>`${l}-tab-${g}`,c=g=>`${l}-panel-${g}`,o=Ks.useRef(null),f=(g,m)=>{g.preventDefault();let v=(m+t.length)%t.length;r(t[v].id),o.current?.querySelectorAll('[role="tab"]')?.[v]?.focus()};return(0,Ct.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,Ct.jsxs)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:[(0,Ct.jsx)("div",{ref:o,role:"tablist","aria-label":e,onKeyDown:g=>{let m=t.findIndex(v=>v.id===n);g.key==="ArrowRight"&&f(g,m+1),g.key==="ArrowLeft"&&f(g,m-1),g.key==="Home"&&f(g,0),g.key==="End"&&f(g,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(g=>(0,Ct.jsx)("button",{id:u(g.id),role:"tab",type:"button","aria-selected":g.id===n,"aria-controls":c(g.id),tabIndex:g.id===n?0:-1,onClick:()=>r(g.id),className:g.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:g.label},g.id))}),s]}),i?(0,Ct.jsx)("div",{id:c(i.id),role:"tabpanel","aria-labelledby":u(i.id),tabIndex:0,className:"af-px-3 af-py-2",children:i.render()},i.id):null]})}var $a=le(require("react"),1),Ss=le(require("@radix-ui/react-popover"),1);var xs=3,ws=100;var st=require("react/jsx-runtime"),mi={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"},yp=Object.keys(mi);function lu(e){let t=mi[e.dimension],a=e.operator==="is_not"?"is not":"is",s=e.values.map(n=>ui(n)).join(" or ");return`${t} ${a} ${s}`}function Cl(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>ws||s.length===e[a].values.length?e:e.map((n,r)=>r===a?{...n,values:s}:n)}return t.values.length>ws||e.length>=xs?e:[...e,t]}function xp(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 cu(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>ws||e.length>=xs?e:[...e,t]}function wp(e){return{dimension:e,operator:"is",search:"",picked:[]}}function du(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=xp(e.byDimension,a);for(let[r,i]of Object.entries(s)){let l=e.foldsByLabel.get(r)??new Set;for(let u of i)l.add(u);e.foldsByLabel.set(r,l)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([r,i])=>[r,[...i]]))}}function uu(e){let{filters:t,onChange:a}=e,s=t.length>=xs;return $a.useEffect(()=>{if(t.length===0)return;let n=r=>{let i=r.target;i&&(i.tagName==="INPUT"||i.closest('[role="dialog"]'))||r.key==="Escape"&&a([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[t.length,a]),(0,st.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,r)=>(0,st.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-1 af-rounded-full af-border af-border-border af-bg-muted af-py-1 af-pl-3 af-pr-1 af-text-xs",children:[(0,st.jsx)("span",{className:"af-text-foreground",children:lu(n)}),(0,st.jsx)("button",{type:"button","aria-label":`Remove filter ${lu(n)}`,onClick:()=>a(t.filter((i,l)=>l!==r)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),(0,st.jsx)(Sp,{...e,disabled:s}),t.length>0?(0,st.jsx)("button",{type:"button",onClick:()=>a([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Sp({filters:e,onChange:t,suggestions:a,resetKey:s,disabled:n,expandValues:r}){let[i,l]=$a.useState(!1),u=$a.useRef(null),[c,o]=$a.useState(null);$a.useEffect(()=>{o(u.current?.closest(".aifeatures-admin")??null)},[]);let[f,b]=$a.useState(null),[g,m]=$a.useState("is"),[v,d]=$a.useState(""),[p,x]=$a.useState([]);$a.useEffect(()=>{i||(b(null),m("is"),d(""),x([]))},[i]);let R=$a.useRef(s);R.current!==s&&(R.current=s,i&&l(!1),f!==null&&b(null),p.length>0&&x([]),v!==""&&d(""),g!=="is"&&m("is"));let T=E=>{let L=wp(E);b(L.dimension),x(L.picked),d(L.search),m(L.operator)},k=(f?a[f]??[]:[]).filter(E=>E.toLowerCase().includes(v.trim().toLowerCase())),P=f===null||p.length===0?null:Cl(e,{dimension:f,operator:g,values:r?r(f,p):p}),I=P!==null&&P!==e,w=()=>{let E=P;!E||E===e||(t(E),l(!1))};return(0,st.jsxs)(Ss.Root,{open:i,onOpenChange:l,children:[(0,st.jsx)(Ss.Trigger,{asChild:!0,children:(0,st.jsx)("button",{ref:u,type:"button",disabled:!1,title:n?`At most ${xs} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),(0,st.jsx)(Ss.Portal,{container:c,children:(0,st.jsx)(Ss.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:f===null?(0,st.jsxs)("div",{children:[(0,st.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,st.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:yp.filter(E=>a[E]!==void 0).map(E=>{let L=a[E]?.length??0,C=!e.some(Y=>Y.dimension===E)&&e.length>=xs;return(0,st.jsxs)("button",{type:"button",onClick:()=>T(E),disabled:L===0||C,className:"af-flex af-w-full af-items-center af-justify-between af-rounded-md af-px-2 af-py-1.5 af-text-left af-text-xs af-text-foreground hover:af-bg-muted disabled:af-text-muted-foreground disabled:hover:af-bg-transparent",children:[(0,st.jsx)("span",{children:mi[E]}),(0,st.jsx)("span",{className:"af-text-muted-foreground",children:L===0?"no data":C?"no room":L})]},E)})})]}):(0,st.jsxs)("div",{children:[(0,st.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,st.jsx)("button",{type:"button",onClick:()=>T(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,st.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:mi[f]}),(0,st.jsxs)("select",{"aria-label":"Operator",value:g,onChange:E=>m(E.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,st.jsx)("option",{value:"is",children:"is"}),(0,st.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,st.jsx)("input",{type:"text",value:v,onChange:E=>d(E.target.value),placeholder:"Search\u2026","aria-label":`Search ${mi[f]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),(0,st.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:k.length===0?(0,st.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",v,"\u201D."]}):k.map(E=>(0,st.jsxs)("label",{className:"af-flex af-cursor-pointer af-items-center af-gap-2 af-rounded-md af-px-2 af-py-1.5 af-text-xs af-text-foreground hover:af-bg-muted",children:[(0,st.jsx)("input",{type:"checkbox",checked:p.includes(E),disabled:!p.includes(E)&&p.length>=ws,onChange:L=>x(C=>L.target.checked?[...C,E]:C.filter(Y=>Y!==E))}),(0,st.jsx)("span",{className:"af-break-all",children:ui(E)})]},E))}),(0,st.jsx)("button",{type:"button",onClick:w,disabled:!I,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:p.length<=1?"Apply filter":p.length>=ws?`Apply filter (${p.length} values \u2014 the maximum)`:`Apply filter (${p.length} values)`})]})})})]})}var $t=require("react/jsx-runtime"),Np=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:ka,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:ka,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:ka,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:di,chart:"visit_duration_seconds"}];function Rp({current:e,previous:t,downIsGood:a}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let n=s>0,r=a?!n:n,i=`${n?"+":""}${(s*100).toFixed(1)}%`;return(0,$t.jsx)("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:i})}function fu({summary:e,selected:t,onSelect:a}){return(0,$t.jsx)("div",{className:"af-@container",children:(0,$t.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Np.map(s=>{let n=s.chart===t,r=a!==void 0,i=(0,$t.jsxs)($t.Fragment,{children:[(0,$t.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),(0,$t.jsxs)("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[(0,$t.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?(0,$t.jsx)(Rp,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?(0,$t.jsx)("button",{type:"button","aria-pressed":n,onClick:()=>a(s.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:i},s.key):(0,$t.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:i},s.key)})})})}function Tl({currentVisitors:e,asOf:t,isStale:a,isUnreachable:s,isInitialLoad:n=!1,scopeIsSiteWide:r=!1}){if(n&&!s)return(0,$t.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1","aria-hidden":"true",children:[(0,$t.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,$t.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return(0,$t.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let i=t?su(t):"freshness unknown",l=r?" across the whole site, not the current filter,":"",u=a?`${e} current visitors${l} ${i} (not updating)`:`${e} current visitors${l} ${i}`;return(0,$t.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:u,children:[(0,$t.jsx)("span",{"aria-hidden":"true",className:a?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),(0,$t.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,$t.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),(0,$t.jsx)("span",{className:"af-sr-only",children:u})]})}var mu=le(require("react"),1),pu=require("lucide-react");var ct=require("react/jsx-runtime");function vo(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function bo({rows:e,denominator:t,windowPrecedesCollection:a=!1,coverageUnknown:s=!1,emptyCopy:n="No conversions in this period",maxRows:r=9,primaryConversion:i}){let[l,u]=mu.useState(!1),c=e.filter(d=>!d.implicit||d.visitors>0||d.events>0||vo(d,i)),o=a?(0,ct.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This period starts before we began collecting for this site, so these counts cover less time than the dates suggest."}):s?(0,ct.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null;if(c.length===0)return(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(go,{what:n}),o]});let f=c.slice(0,r),b=i?c.find(d=>vo(d,i)):void 0,g=b&&!f.includes(b)?c.filter(d=>f.includes(d)||d===b).slice(0,Math.max(0,r-1)).concat(b):f,m=l?e:g,v=Math.max(0,e.length-g.length);return(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,ct.jsx)("thead",{children:(0,ct.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,ct.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,ct.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,ct.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,ct.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,ct.jsx)("tbody",{children:m.map((d,p)=>(0,ct.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":vo(d,i)?"true":void 0,children:[(0,ct.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:vo(d,i)?(0,ct.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,ct.jsx)(pu.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,ct.jsx)("span",{className:"af-font-medium af-text-foreground",children:d.goal}),(0,ct.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):d.goal}),(0,ct.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:ka(d.visitors)}),(0,ct.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:ka(d.events)}),(0,ct.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:d.conversion_rate===null?(0,ct.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):fr(d.conversion_rate)})]},`${d.goal}-${p}`))})]}),v>0?(0,ct.jsx)("button",{type:"button",onClick:()=>u(d=>!d),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length} goals`}):null,(0,ct.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",ka(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),o]})}var Ua=require("recharts");var Ht=require("react/jsx-runtime"),ho={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Il={visitors:ka,visits:ka,pageviews:ka,views_per_visit:e=>e.toFixed(2),bounce_rate:fr,visit_duration_seconds:di},_p=31,kp=new Set(["visitors","visits","pageviews"]),Pp={...Il,bounce_rate:au,visit_duration_seconds:tu},El=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Cp=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Tp=[.01,.02,.05,.1,.2,.25,.5,1],Ep=[.25,.5,1,2,5,10,25,50],Ip={visitors:El,visits:El,pageviews:El,views_per_visit:Ep,bounce_rate:Tp,visit_duration_seconds:Cp};function Ap({active:e,payload:t,label:a,metric:s}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return(0,Ht.jsxs)("div",{className:"af-rounded-lg af-border af-border-border af-bg-popover af-px-3 af-py-2 af-text-popover-foreground af-shadow-md",children:[(0,Ht.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:ho[s]}),(0,Ht.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,Ht.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,Ht.jsx)("span",{className:"af-text-muted-foreground",children:iu(String(a))}),(0,Ht.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Il[s](Number(n[s]??0))})]})]})}function yo({rows:e,window:t,metric:a,timeZone:s="UTC",height:n=260}){let r=ru(t,e,s),i=Il[a],l=Pp[a],u=nu(r.reduce((o,f)=>Math.max(o,Number(f[a]??0)),0),Ip[a]),c=`${ho[a]} by day: ${r.map(o=>`${kl(o.date)}: ${i(Number(o[a]??0))}`).join("; ")}.`;return(0,Ht.jsxs)("figure",{"aria-label":`${ho[a]} over time`,className:"af-m-0",children:[(0,Ht.jsx)(Ua.ResponsiveContainer,{width:"100%",height:n,children:(0,Ht.jsxs)(Ua.AreaChart,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,Ht.jsx)("defs",{children:(0,Ht.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,Ht.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,Ht.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,Ht.jsx)(Ua.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,Ht.jsx)(Ua.XAxis,{dataKey:"date",tickFormatter:kl,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,Ht.jsx)(Ua.YAxis,{allowDecimals:!kp.has(a),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...u?{ticks:u,domain:[0,u[u.length-1]]}:{},tickFormatter:o=>l(o),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,Ht.jsx)(Ua.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,Ht.jsx)(Ap,{metric:a})}),(0,Ht.jsx)(Ua.Area,{type:"linear",dataKey:a,name:ho[a],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=_p?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,Ht.jsx)("figcaption",{className:"af-sr-only",children:c})]})}var Se=require("react/jsx-runtime"),Dp="2026-08-13",Op=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Lp=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function gu({filters:e,onFiltersChange:t,refreshKey:a,onBackToWebsite:s,primaryConversion:n,className:r,published:i,lastPublishedAt:l}){let[u,c]=Ut.useState(30),[o,f]=Ut.useState(()=>No()),b=e!==void 0&&t!==void 0,[g,m]=Ut.useState(e??[]),{api:v}=W(),[d,p]=Ut.useState(v);d!==v&&(p(v),!b&&g.length>0&&m([]));let x=b?e:g,R=Ut.useCallback($=>{t&&t($),b||m($)},[t,b]),T=Ut.useCallback(($,we,ne)=>{let me=Array.isArray(we)?we:[we];if(me.length===0)return null;let qe=Cl(x,{dimension:$,operator:"is",values:me});if(ne&&(!ne.value||(qe=cu(qe,{dimension:ne.dimension,operator:"is",values:[ne.value]}),!qe.find(Ot=>Ot.dimension===ne.dimension&&Ot.operator!=="is_not")?.values.includes(ne.value))))return null;let rt=qe.find(nt=>nt.dimension===$&&nt.operator!=="is_not");return me.every(nt=>rt?.values.includes(nt))?JSON.stringify(qe)===JSON.stringify(x)?null:qe:null},[x]),h=Ut.useCallback(($,we,ne)=>T($,we,ne)!==null,[T]),k=Ut.useCallback(($,we,ne)=>{let me=T($,we,ne);me&&R(me)},[T,R]),[P,I]=Ut.useState("visitors"),w=Ws(u,{refreshKey:a,breakdowns:Lp,filters:x}),E=w.status.data,L=w.reportedZone??E?.timezone,C=L??o??pr()??"UTC",{notCollecting:Y,awaitingFirstVisit:G,firstVisitTooRecent:z,holdingForFirstData:ce}=mo(E,{published:i}),ve=i===!1,xe=li({collecting:G||Y?!1:E?.collecting,statusFailed:w.status.error!=null,identity:E?.analytics_id}),D=Ut.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),q=Ut.useMemo(()=>{let $=w.breakdowns.sources?.data,we={};if(!$||$.status!=="ok")return we;for(let ne of $.data){let me=ne.source,qe=ne.sources;typeof me=="string"&&Array.isArray(qe)&&qe.length>0&&(we[me]=qe)}return we},[w.breakdowns.sources?.data]),B=Ut.useMemo(()=>{let $=(me,qe)=>{let rt=w.breakdowns[me]?.data;return!rt||rt.status!=="ok"?[]:[...new Set(rt.data.map(nt=>nt[qe]).filter(nt=>typeof nt=="string"&&nt!==""))]};return{channel:w.channels.data?.status==="ok"?[...new Set(w.channels.data.data.map(me=>me.channel))]:[],source:$("sources","source"),campaign:$("utm/campaign","campaign"),page:$("pages","pathname"),entry_page:$("entry-pages","pathname"),exit_page:$("exit-pages","pathname"),country:$("countries","country"),browser:$("browsers","browser"),os:$("operating-systems","os"),device:$("devices","device")}},[w.breakdowns,w.channels.data]),[fe,pe]=Ut.useState({}),We=JSON.stringify(B),[Ie,$e]=Ut.useState(new Map),Qe=JSON.stringify(q);Ut.useEffect(()=>{let{suggestions:$,folds:we}=du(D.current,{api:v,period:u},JSON.parse(We),JSON.parse(Qe));pe($),$e(we)},[We,Qe,v,u]);let De=Ut.useCallback(($,we)=>$!=="source"?we:[...new Set(we.flatMap(ne=>{let me=[...Ie.get(ne)??[],...q[ne]??[]];return me.length>0?me:[ne]}))],[Ie,q]),ot=Ut.useMemo(()=>{let $=w.conversions.error;return $ instanceof Gt&&$.details?.code==="goals_exceed_report_budget"?$.message:null},[w.conversions.error]),O=Ut.useMemo(()=>{let $=[w.summary,w.timeseries,w.channels,...Object.values(w.breakdowns)];for(let we of $){let ne=we?.error;if(ne instanceof Gt&&ne.details?.code==="filter_unsupported")return ne.message}return null},[w.summary,w.timeseries,w.channels,w.breakdowns]),V=($,we,ne,me,qe,rt,nt,Ot,Pe)=>()=>{let Ge=w.breakdowns[$];return(0,Se.jsx)(rs,{sourced:Ge?.data??null,error:Ge?.error,isLoading:Ge?.isLoading,what:we,collecting:E?.collecting,onRetry:w.refetch,children:yt=>{let Lt=Vt=>Ot?De(Ot,[Vt]):Vt;return(0,Se.jsx)(Pl,{rows:yt,dimension:ne,metric:me,metricLabel:qe,secondary:rt,emptyCopy:x.length>0?"No data for this filter":nt,canFilter:Ot?(Vt,it)=>h(Ot,Lt(Vt),Pe?{dimension:Pe,value:it}:void 0):()=>!1,onFilter:Ot?(Vt,it)=>k(Ot,Lt(Vt),Pe?{dimension:Pe,value:it}:void 0):void 0})}})};if(po({status:E,holdingForFirstData:ce,refetchStatus:w.refetchStatus,refetch:w.refetch}),Y){let $=!!l&&String(l).slice(0,10)<Dp;return(0,Se.jsx)(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,Se.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,Se.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:ve?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":$?"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 G?(0,Se.jsx)(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,Se.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,Se.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:"Your site is set up and analytics is running. The first visit shows up here shortly after someone lands on a published page."})]})}):z?(0,Se.jsxs)(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:[(0,Se.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,Se.jsx)(_l,{value:C,chosen:o,onChange:$=>{Ro($),f($)}})}),(0,Se.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,Se.jsxs)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",E?.timezone?` ${E.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,Se.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,Se.jsx)(Tl,{currentVisitors:xe.currentVisitors,asOf:xe.asOf,isStale:xe.isStale,isUnreachable:xe.isUnreachable||xe.error!==null,isInitialLoad:xe.isInitialLoad})})]})]}):(0,Se.jsx)(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,Se.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,Se.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Se.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Op.map($=>(0,Se.jsx)("button",{type:"button","aria-pressed":$.value===u,onClick:()=>c($.value),className:$.value===u?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:$.label},$.value))}),(0,Se.jsx)(_l,{value:C,chosen:o,onChange:$=>{Ro($),f($)}}),(0,Se.jsx)(Tl,{currentVisitors:xe.currentVisitors,asOf:xe.asOf,isStale:xe.isStale,isUnreachable:xe.isUnreachable||xe.error!==null,isInitialLoad:xe.isInitialLoad,scopeIsSiteWide:x.length>0})]}),(0,Se.jsx)(uu,{filters:x,onChange:R,suggestions:fe,expandValues:De,resetKey:v}),O?(0,Se.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,Se.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:O}),(0,Se.jsx)("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,!O&&E?.timezone_defaulted?(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,O?null:(0,Se.jsxs)(Se.Fragment,{children:[(0,Se.jsx)(rs,{sourced:w.summary.data,error:w.summary.error,isLoading:w.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:w.refetch,children:$=>(0,Se.jsxs)(Se.Fragment,{children:[(0,Se.jsx)(fu,{summary:$,selected:P,onSelect:I}),$.previous_unavailable?(0,Se.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[$.previous_unavailable_reason==="filter"?"No comparison for this filter \u2014 the previous period has too many distinct traffic sources to resolve it. Try a shorter period, or filter by source instead.":"No comparison available right now \u2014 we couldn\u2019t check how far back this site\u2019s history goes. It should return on its own."," ","The numbers above are still for the period you selected."]}):null]})}),(0,Se.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,Se.jsx)(rs,{sourced:w.timeseries.data,error:w.timeseries.error,isLoading:w.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:w.refetch,children:$=>{let we=w.timeseries.data?.status==="ok"?w.timeseries.data.window:{from:"",to:""};return(0,Se.jsx)(yo,{rows:$,window:we,metric:P,timeZone:L??"UTC"})}})}),(0,Se.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,Se.jsx)(fi,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,Se.jsx)(rs,{sourced:w.channels.data,error:w.channels.error,isLoading:w.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:w.refetch,children:$=>(0,Se.jsx)(Pl,{rows:$,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=>k("channel",we)})})},{id:"sources",label:"Sources",render:V("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:V("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,Se.jsx)(fi,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:V("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:V("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:V("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,Se.jsx)(fi,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:V("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:V("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:V("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,Se.jsx)(fi,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:V("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:V("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:V("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,Se.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,Se.jsx)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:(0,Se.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,Se.jsxs)("div",{className:"af-px-3 af-py-2",children:[x.length>0?(0,Se.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",x.length===1?"filter":"filters"," above."]}):null,ot!==null?(0,Se.jsxs)("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,Se.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:ot})]}):(0,Se.jsx)(rs,{sourced:w.conversions.data,error:w.conversions.error,isLoading:w.conversions.isLoading,what:"Conversions",collecting:E?.collecting,onRetry:w.refetch,children:$=>{let we=w.conversions.data?.status==="ok"?w.conversions.data:null;return(0,Se.jsx)(Se.Fragment,{children:(0,Se.jsx)(bo,{rows:$,primaryConversion:n,denominator:we?.denominator??0,windowPrecedesCollection:we?.window_precedes_collection??!1,coverageUnknown:we?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var wu=le(require("react"),1),ua=require("lucide-react");var yn=le(require("react"),1),is=require("lucide-react");var Be=require("react/jsx-runtime"),vu=90,bu=100;function Bp(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function hu(e){return!!e.label&&e.label!==e.target}function Fp(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 pi(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function yu({current:e,onChange:t,onClose:a}){let{api:s}=W(),[n,r]=yn.useState(null),[i,l]=yn.useState(!1),[u,c]=yn.useState({at:"goals"}),[o,f]=yn.useState(null),[b,g]=yn.useState(null),[m,v]=yn.useState(!1),[d,p]=yn.useState(null),x=yn.useRef(0);yn.useEffect(()=>{let k=!0;return r(null),l(!1),c({at:"goals"}),f(null),g(null),v(!1),p(null),x.current+=1,s.getAnalyticsConversions(vu).then(P=>{if(k){if(P.status!=="ok"){l(!0);return}r(P.data)}}).catch(()=>{k&&l(!0)}),()=>{k=!1}},[s]);let R=k=>{c({at:"targets",row:k}),f(null),g(null),v(!1),p(null);let P=++x.current;s.getAnalyticsGoalTargets(k.goal,vu,bu).then(I=>{if(P===x.current){if(I.status!=="ok"){g("failed");return}f(I.data),v(I.truncated===!0),p(I.coverage??null)}}).catch(I=>{if(P!==x.current)return;let w=I instanceof Gt?I.details?.code:void 0;g(w==="goal_has_no_targets"?"no-values":"failed")})},T=k=>{t(k),a()};if(i)return(0,Be.jsx)("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return(0,Be.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,Be.jsx)(is.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Be.jsx)("span",{children:"Loading your conversions\u2026"})]});if(u.at==="targets"){let k=u.row,P=new Map;for(let I of o??[])P.set(I.label,(P.get(I.label)??0)+1);return(0,Be.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[(0,Be.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,Be.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>c({at:"goals"}),children:[(0,Be.jsx)(is.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,Be.jsx)("span",{children:"All conversions"})]})}),(0,Be.jsxs)("button",{type:"button","aria-current":e&&pi(k,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:k.goal,implicit:k.implicit}),children:[e&&pi(k,e)&&!e.target&&(0,Be.jsx)(is.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Be.jsxs)("span",{children:["Any ",k.goal.toLowerCase()]})]}),b==="no-values"&&(0,Be.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),b==="failed"&&(0,Be.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,Be.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,Be.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(k),children:"Try again"})]}),!o&&b===null&&(0,Be.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,Be.jsx)(is.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Be.jsx)("span",{children:"Loading\u2026"})]}),o&&(0,Be.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Fp(o.length,d,m)}),m&&(0,Be.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",bu,". If what you want isn\u2019t here, pick the conversion itself instead."]}),o?.some(hu)&&(0,Be.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),o?.map(I=>{let w=!!(e&&pi(k,e)&&e.target===I.target),E=P.get(I.label)>1;return hu(I)?(0,Be.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-3 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,Be.jsxs)("span",{className:"af-min-w-0",children:[(0,Be.jsx)("span",{className:"af-block af-truncate",children:I.label}),E&&(0,Be.jsx)("span",{className:"af-block af-truncate af-text-xs",children:I.target})]}),(0,Be.jsx)("span",{className:"af-shrink-0 af-text-xs",children:I.visitors.toLocaleString()})]},I.target):(0,Be.jsxs)("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:()=>T({goal:k.goal,implicit:k.implicit,target:I.target,...I.label&&I.label!==I.target?{label:I.label}:{}}),children:[(0,Be.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[w&&(0,Be.jsx)(is.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Be.jsxs)("span",{className:"af-min-w-0",children:[(0,Be.jsx)("span",{className:"af-block af-truncate",children:I.label}),E&&(0,Be.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:I.target})]})]}),(0,Be.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:I.visitors.toLocaleString()})]},I.target)})]})}let h=e?.goal&&!n.some(k=>pi(k,e));return(0,Be.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[h&&(0,Be.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&(0,Be.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(k=>{let P=e?pi(k,e):!1;return(0,Be.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,Be.jsxs)("button",{type:"button","aria-current":P?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:k.goal,implicit:k.implicit}),children:[(0,Be.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[P&&(0,Be.jsx)(is.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Be.jsx)("span",{className:"af-truncate",children:k.goal})]}),(0,Be.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:k.visitors.toLocaleString()})]}),Bp(k)&&(0,Be.jsx)(y,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${k.goal}`,onClick:()=>R(k),children:"Narrow"})]},k.goal)}),e?.goal&&(0,Be.jsx)("button",{type:"button",className:"af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm af-text-muted-foreground hover:af-bg-accent",onClick:()=>T(null),children:"No main conversion"})]})}var rn=require("react/jsx-runtime");function Mp(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 $p(e){if(Al(e,"whatsapp"))return!0;let t=Mp(e);return t===null?!1:["wa.me","whatsapp.com"].some(a=>t===a||t.endsWith(`.${a}`))}function Al(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var xu=[{goal:"Contact",target:e=>Al(e,"tel"),icon:ua.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Al(e,"mailto"),icon:ua.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:ua.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>$p(e),icon:ua.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:ua.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:ua.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:ua.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:ua.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:ua.Download,line:"This site is set up to get your file downloaded."}];function Su(e){let{goal:t,target:a}=e;return e.implicit!==!0?null:(a?xu.find(n=>n.goal===t&&n.target?.(a)):void 0)??xu.find(n=>n.goal===t&&!n.target)??null}function Up(e){return Su(e)?.icon??ua.Target}function Nu({primaryConversion:e,onChange:t}){let[a,s]=wu.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?Su(e):null,i=e?.label?.trim(),l=e?Up(e):ua.Target,u=e?.goal?i?`Your main conversion is ${i}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",c=(0,rn.jsxs)(rn.Fragment,{children:[(0,rn.jsx)(l,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,rn.jsx)("span",{children:u})]});return t?(0,rn.jsxs)(Ti,{open:a,onOpenChange:s,children:[(0,rn.jsx)(Ei,{asChild:!0,children:(0,rn.jsx)("button",{type:"button",className:"af-flex af-items-center af-gap-2 af-rounded af-text-left af-text-sm af-text-muted-foreground hover:af-text-foreground focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:c})}),(0,rn.jsx)(Lr,{align:"start",className:"af-w-80 af-p-1",children:a&&(0,rn.jsx)(yu,{current:e,onChange:t,onClose:()=>s(!1)})})]}):(0,rn.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:c})}var Sa=require("react/jsx-runtime");function Ru({refreshKey:e,onViewAll:t,primaryConversion:a}){let s=Ws(7,{refreshKey:e,breakdowns:[]}),n=s.status.data??void 0,{nothingToReport:r,notCollecting:i,holdingForFirstData:l}=mo(n);return po({status:n,holdingForFirstData:l,refetchStatus:s.refetchStatus,refetch:s.refetch}),(0,Sa.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Sa.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Sa.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,Sa.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?(0,Sa.jsx)("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:i?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):(0,Sa.jsxs)(Sa.Fragment,{children:[(0,Sa.jsx)(rs,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let c=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return(0,Sa.jsx)(yo,{rows:u,window:c?.window??{from:"",to:""},metric:"visitors",timeZone:c?.timezone,height:140})}}),(0,Sa.jsxs)("div",{className:"af-mt-3",children:[(0,Sa.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,Sa.jsx)(rs,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let c=s.conversions.data?.status==="ok"?s.conversions.data:null;return(0,Sa.jsx)(bo,{rows:u,primaryConversion:a,denominator:c?.denominator??0,windowPrecedesCollection:c?.window_precedes_collection??!1,coverageUnknown:c?.first_seen_unavailable??!1})}})]})]})]})}var fa=require("react/jsx-runtime"),Dl=5;function Ol({title:e,viewAllLabel:t,onViewAll:a}){return(0,fa.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,fa.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),a&&(0,fa.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:a,children:t})]})}function _u({refreshKey:e,onBackToWebsite:t,primaryConversion:a,onChangePrimaryConversion:s,onOpenSurface:n,needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l}){let u=Ls({refreshKey:e}),c=(u.summary?.products.count??0)>0||(u.summary?.commerce?.storefront_orders??!1),o=c||(u.summary?.commerce?.invoicing??!1);return(0,fa.jsx)(Ft,{title:"Dashboard",onBackToWebsite:t,children:(0,fa.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,fa.jsx)(Nu,{primaryConversion:a,onChange:s}),(0,fa.jsx)(Ru,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:a}),(0,fa.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,fa.jsx)(Ol,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),(0,fa.jsx)(jr,{refreshKey:e,maxRows:Dl,onViewAll:n&&(()=>n("leads"))})]}),c&&(0,fa.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,fa.jsx)(Ol,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),(0,fa.jsx)(Qn,{refreshKey:e,maxRows:Dl,onViewAll:n&&(()=>n("orders"))})]}),o&&(0,fa.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,fa.jsx)(Ol,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),(0,fa.jsx)(ts,{refreshKey:e,maxRows:Dl,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l})]})]})})}0&&(module.exports={AUDIENCE_PAGE_SIZE,AifeaturesApiError,AifeaturesProvider,AnalyticsView,ContactImport,CustomerDetail,CustomersList,DOUBLE_OPT_IN_HELP,DashboardView,EMAIL_ORG_ACTIONS,EMAIL_READINESS_TEXT,EmailView,ExportCsvButton,FormSettings,FormSubmissions,FormsDashboard,FormsList,IMPORT_ATTESTATION,InvoiceDetail,InvoiceLabelBadge,InvoiceSettingsPanel,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,NotificationRecipientsSettings,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,PromosPanel,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,StoreSettings,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,buildEmailOrgRequest,chargedTotal,createApiClient,emailReadinessText,formatPrice,isEmailOrgAction,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useAudience,useBroadcasts,useBusinessSummary,useCsvExport,useCustomers,useEmailDrafts,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSiteSettings,useSubmissions,useSubscriptions});