@aifeatures/admin-react 0.23.0 → 0.25.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 +7 -4
- package/dist/index.d.cts +140 -9
- package/dist/index.d.ts +140 -9
- package/dist/index.js +7 -4
- package/dist/styles.css +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var tu=Object.create;var Fr=Object.defineProperty;var au=Object.getOwnPropertyDescriptor;var su=Object.getOwnPropertyNames;var nu=Object.getPrototypeOf,ru=Object.prototype.hasOwnProperty;var iu=(e,t)=>{for(var s in t)Fr(e,s,{get:t[s],enumerable:!0})},$o=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of su(t))!ru.call(e,a)&&a!==s&&Fr(e,a,{get:()=>t[a],enumerable:!(n=au(t,a))||n.enumerable});return e};var ie=(e,t,s)=>(s=e!=null?tu(nu(e)):{},$o(t||!e||!e.__esModule?Fr(s,"default",{value:e,enumerable:!0}):s,e)),ou=e=>$o(Fr({},"__esModule",{value:!0}),e);var Af={};iu(Af,{AUDIENCE_PAGE_SIZE:()=>hn,AifeaturesApiError:()=>Dt,AifeaturesProvider:()=>Wo,AnalyticsView:()=>zc,ContactImport:()=>Rr,CustomerDetail:()=>mr,CustomersList:()=>pr,DOUBLE_OPT_IN_HELP:()=>kr,DashboardView:()=>Qc,EMAIL_ORG_ACTIONS:()=>xi,EMAIL_READINESS_TEXT:()=>bo,EmailView:()=>Ro,ExportCsvButton:()=>Zt,FormSettings:()=>sr,FormSubmissions:()=>Xn,FormsDashboard:()=>zi,FormsList:()=>jn,IMPORT_ATTESTATION:()=>Ri,InvoiceDetail:()=>oi,InvoiceLabelBadge:()=>Tn,InvoiceSettingsPanel:()=>Sr,InvoicesList:()=>Ls,InvoicesView:()=>vo,LeadsView:()=>yr,MAX_ANALYTICS_FILTERS:()=>Js,MAX_ANALYTICS_FILTER_VALUES:()=>Xs,NotificationRecipientsSettings:()=>go,OrderDetail:()=>dr,OrderStatusBadge:()=>Gs,OrdersList:()=>Ds,OrdersView:()=>so,PaymentsDashboard:()=>ao,PaymentsSetup:()=>dn,ProductSettings:()=>or,ProductsList:()=>rr,ProductsView:()=>no,PromosPanel:()=>nn,REALTIME_FAILURES_BEFORE_ERROR:()=>Ci,REALTIME_POLL_MS:()=>Pi,RetainerStatusBadge:()=>ci,RetainersPanel:()=>un,StoreSettings:()=>po,SubmissionDetail:()=>Yn,SubscriptionsView:()=>oo,VariantsEditor:()=>ir,ViewShell:()=>St,WebhookDeliveries:()=>tr,WebhookSettings:()=>ar,buildEmailOrgRequest:()=>bc,chargedTotal:()=>vs,createApiClient:()=>$r,emailReadinessText:()=>yn,formatPrice:()=>Z,isEmailOrgAction:()=>vc,isZeroDecimalCurrency:()=>Fa,toMajorUnits:()=>mt,toMinorUnits:()=>zt,useAifeatures:()=>W,useAifeaturesContext:()=>W,useAnalytics:()=>xn,useAudience:()=>wr,useBroadcasts:()=>_r,useBusinessSummary:()=>pn,useCsvExport:()=>Jn,useCustomers:()=>fr,useEmailDrafts:()=>Pr,useEventDestinations:()=>Qn,useForms:()=>tn,useInvoices:()=>cn,useOrders:()=>lr,usePaymentsStatus:()=>Ts,usePeople:()=>vr,usePerson:()=>br,useProducts:()=>fn,useRealtimeVisitors:()=>Er,useRetainers:()=>mn,useSiteSettings:()=>Os,useSubmissions:()=>Kn,useSubscriptions:()=>hr});module.exports=ou(Af);var zs=ie(require("react"),1);var Ui="aifeatures:analytics:timezone",Mi;function Hn(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function Vo(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function Vs(){return $i()??Hn()}function $i(){if(Mi!==void 0)return Mi;try{let e=window.localStorage.getItem(Ui);return Vo(e)?e:null}catch{return null}}function Vi(e){if(!(e!==null&&!Vo(e))){Mi=e;try{e===null?window.localStorage.removeItem(Ui):window.localStorage.setItem(Ui,e)}catch{}}}function Ur(e,t){let s=new URLSearchParams({period:String(e)}),n=Vs();return n&&s.set("timezone",n),t&&t.length>0&&s.set("filters",JSON.stringify(t)),s.toString()}var Dt=class extends Error{constructor(s,n,a){super(s);this.status=n;this.details=a;this.name="AifeaturesApiError"}};function Mr(e,t){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${t}`}function zn(e,t){let s=t.toString();return s?`${e}?${s}`:e}function Ho(e){let t=new URLSearchParams;return e.status&&t.set("status",e.status),e.source&&t.set("source",e.source),e.excludeStatus?.length&&t.set("exclude_status",e.excludeStatus.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),e.from&&t.set("from",e.from),e.to&&t.set("to",e.to),e.unfulfilledOnly&&t.set("unfulfilled_only","true"),t}function zo(e){let t=new URLSearchParams;return e.statuses?.length&&t.set("status",e.statuses.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),t}function $r(e,t="https://aifeatures.dev"){async function s(a,r={}){let o=`${t}${a}`,c=await fetch(o,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!c.ok){let d;try{d=await c.json()}catch{}throw new Dt(Mr(d?.error,c.status),c.status,d)}if(c.status!==204)return c.json()}async function n(a){let r=await fetch(`${t}${a}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let o;try{o=await r.json()}catch{}throw new Dt(Mr(o?.error,r.status),r.status,o)}return r.blob()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(a){return s(`/api/v1/forms/${a}`)},async createForm(a){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,r){return s(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(a){await s(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,r={}){let o=new URLSearchParams;r.limit!==void 0&&o.set("limit",String(r.limit)),r.offset!==void 0&&o.set("offset",String(r.offset));let c=o.toString(),d=`/api/v1/forms/${a}/submissions${c?`?${c}`:""}`;return s(d)},async getSubmission(a){return s(`/api/v1/submissions/${a}`)},async exportSubmissionsCsv(a,r={}){let o=new URLSearchParams;return r.includeSpam&&o.set("include_spam","true"),n(zn(`/api/v1/forms/${encodeURIComponent(a)}/submissions/export`,o))},async deleteSubmission(a){await s(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,r){let o=typeof r=="string"?{name:r}:r,c=o.name,d=o.id??o.name,l=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(d)}`,i=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){let u;try{u=await i.json()}catch{}throw new Dt(Mr(u?.error,i.status),i.status,u)}let m=await i.blob(),v=URL.createObjectURL(m),g=document.createElement("a");g.href=v,g.download=c,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(v)},async getSite(a){return s(`/api/v1/sites/${encodeURIComponent(a)}`)},async updateSite(a,r){return s(`/api/v1/sites/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return s("/api/v1/payments/status")},getPromos(a){let r=new URLSearchParams({limit:"10"});return a&&r.set("cursor",a),s(`/api/v1/promos?${r}`)},getPromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return s("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,r){return s(`/api/v1/promos/${encodeURIComponent(a)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(a={}){let r=new URLSearchParams;a.include&&r.set("include",a.include);let o=r.toString();return(await s(`/api/v1/products${o?`?${o}`:""}`)).products},async getProduct(a){return s(`/api/v1/products/${a}`)},async createProduct(a){return s("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,r){return s(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(a){await s(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,r){let o=new FormData;o.append("file",r);let c=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:o});if(!c.ok){let d;try{d=await c.json()}catch{}throw new Dt(Mr(d?.error,c.status),c.status,d)}return c.json()},async attachProductFileFromUrl(a,r){return s(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(a,r){return s(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(a,r){return s(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(a){await s(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,r){return s(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(a,r){return s(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(a){await s(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,r){return s(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(a,r){return s(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(a={}){let r=new URLSearchParams;a.email?r.set("email",a.email):a.q&&r.set("q",a.q),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/customers${o?`?${o}`:""}`)},async getCustomer(a){return s(`/api/v1/customers/${a}`)},async exportProductsCsv(){return n("/api/v1/products/export")},async exportCustomersCsv(){return n("/api/v1/customers/export")},async getOrders(a={}){let r=Ho(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/orders${o?`?${o}`:""}`)},async exportOrdersCsv(a={}){return n(zn("/api/v1/orders/export",Ho(a)))},async getOrder(a){return s(`/api/v1/orders/${a}`)},async getInvoices(a={}){let r=new URLSearchParams;a.labels?.length&&r.set("label",a.labels.join(",")),a.customerEmail&&r.set("customer_email",a.customerEmail),a.customerId&&r.set("customer_id",a.customerId),a.q&&r.set("q",a.q),a.from&&r.set("from",a.from),a.to&&r.set("to",a.to),a.includeAggregates&&r.set("include","aggregates"),a.retainerId&&r.set("retainer_id",a.retainerId),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/invoices${o?`?${o}`:""}`)},async getInvoice(a){return s(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return s(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(a={}){let r=zo(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/retainers${o?`?${o}`:""}`)},async exportRetainersCsv(a={}){return n(zn("/api/v1/retainers/export",zo(a)))},async getRetainer(a){return s(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await s(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return s(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,r){return s(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(a={}){let r=new URLSearchParams;a.status&&r.set("status",a.status),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/subscriptions${o?`?${o}`:""}`)},async exportSubscriptionsCsv(a={}){let r=new URLSearchParams;return a.status&&r.set("status",a.status),n(zn("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let a=new URLSearchParams,r=Vs();r&&a.set("timezone",r);let o=a.toString();return s(`/api/v1/analytics/status${o?`?${o}`:""}`)},async getAnalyticsSummary(a,r){return s(`/api/v1/analytics/summary?${Ur(a,r)}`)},async getAnalyticsTimeseries(a,r){return s(`/api/v1/analytics/timeseries?${Ur(a,r)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,r){return s(`/api/v1/analytics/channels?${Ur(a,r)}`)},async getAnalyticsConversions(a){return s((()=>{let r=new URLSearchParams({period:String(a)}),o=Vs();return o&&r.set("timezone",o),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(a,r,o){let c=new URLSearchParams({goal:a,period:String(r)}),d=Vs();return d&&c.set("timezone",d),o!==void 0&&c.set("limit",String(o)),s(`/api/v1/analytics/conversions/targets?${c.toString()}`)},async getAnalyticsBreakdown(a,r,o){let c=a.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${c}?${Ur(r,o)}`)},async getBusinessSummary(a){let r=new URLSearchParams;r.set("tz_offset_minutes",String(a.tzOffsetMinutes));let o=Vs();return o&&r.set("timezone",o),s(`/api/v1/summary?${r.toString()}`)},async getPeople(a={}){let r=new URLSearchParams;a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/people${o?`?${o}`:""}`)},async exportPeopleCsv(a={}){let r=new URLSearchParams;return a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),n(zn("/api/v1/people/export",r))},async getPerson(a){return s(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(a){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,r){return s(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(a){await s(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return s(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await s(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,r){let o=r===void 0?"":`?limit=${r}`;return(await s(`/api/v1/event-destinations/${a}/deliveries${o}`)).deliveries},async retryEventDelivery(a,r){return s(`/api/v1/event-destinations/${a}/deliveries/${r}/retry`,{method:"POST"})},async getMarketingSettings(a){return s(`${ns(a)}/marketing`)},async getMarketingContacts(a,r={}){let o=new URLSearchParams;r.q&&o.set("q",r.q),r.limit&&o.set("limit",String(r.limit)),r.offset&&o.set("offset",String(r.offset));let c=o.toString();return s(`${ns(a)}/contacts${c?`?${c}`:""}`)},async getMarketingContactStats(a){return s(`${ns(a)}/contacts/stats`)},async getMarketingTags(a){return(await s(`${ns(a)}/contact-tags`)).tags},async getEmailDrafts(a,r){let o=r?`?kind=${r}`:"";return(await s(`${ns(a)}/marketing/drafts${o}`)).drafts},async getEmailDraft(a,r){return s(`${ns(a)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(a,r){return s(`${ns(a)}/marketing/drafts/${encodeURIComponent(r)}/preview`)},async getBroadcasts(a){return(await s(`${ns(a)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(a,r){return s(`${ns(a)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getWelcomeSequence(a){return s(`${ns(a)}/marketing/welcome`)},async getRecoveryFlow(a){return s(`${ns(a)}/marketing/recovery`)}}}function ns(e){return`/api/v1/sites/${encodeURIComponent(e)}`}var Hs=require("react/jsx-runtime"),qo=zs.createContext(null);function lu(e){return e?e.startsWith("sk_")?"Invalid token type: You passed an organization API key (sk_xxx) but AifeaturesProvider requires a site token (st_xxx). Site tokens are returned when you create a site via the API.":e.startsWith("st_")?null:`Invalid token format: Expected a site token starting with "st_" but got "${e.slice(0,10)}...". Site tokens are returned when you create a site via the API.`:"No siteToken provided to AifeaturesProvider"}function Wo({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:s=!1,className:n,children:a}){let r=zs.useMemo(()=>lu(e),[e]),o=zs.useMemo(()=>$r(e,t),[e,t]),c=zs.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return r?(0,Hs.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${n||""}`,children:(0,Hs.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Hs.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Hs.jsx)("p",{className:"af-text-sm af-text-destructive",children:r})]})}):(0,Hs.jsx)(qo.Provider,{value:c,children:(0,Hs.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${n||""}`,children:a})})}function W(){let e=zs.useContext(qo);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var ks=ie(require("react"),1),_n=require("lucide-react");var Vr=ie(require("react"),1),rs=ie(require("@radix-ui/react-tabs"),1);var jo=require("clsx"),Go=require("tailwind-merge"),cu=(0,Go.extendTailwindMerge)({prefix:"af-"});function J(...e){return cu((0,jo.clsx)(e))}var zr=require("react/jsx-runtime"),Hr=rs.Root,qn=Vr.forwardRef(({className:e,...t},s)=>(0,zr.jsx)(rs.List,{ref:s,className:J("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));qn.displayName=rs.List.displayName;var is=Vr.forwardRef(({className:e,...t},s)=>(0,zr.jsx)(rs.Trigger,{ref:s,className:J("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));is.displayName=rs.Trigger.displayName;var os=Vr.forwardRef(({className:e,...t},s)=>(0,zr.jsx)(rs.Content,{ref:s,className:J("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));os.displayName=rs.Content.displayName;var Ko=ie(require("react"),1),Zo=require("@radix-ui/react-slot"),Yo=require("class-variance-authority");var Jo=require("react/jsx-runtime"),uu=(0,Yo.cva)("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),x=Ko.forwardRef(({className:e,variant:t,size:s,asChild:n=!1,...a},r)=>(0,Jo.jsx)(n?Zo.Slot:"button",{className:J(uu({variant:t,size:s,className:e})),ref:r,...a}));x.displayName="Button";var Wn=require("lucide-react");var Ps=ie(require("react"),1);var ms=require("react/jsx-runtime"),et=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,ms.jsx)("table",{ref:s,className:J("af-w-full af-caption-bottom af-text-sm",e),...t})}));et.displayName="Table";var tt=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("thead",{ref:s,className:J("[&_tr]:af-border-b",e),...t}));tt.displayName="TableHeader";var at=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("tbody",{ref:s,className:J("[&_tr:last-child]:af-border-0",e),...t}));at.displayName="TableBody";var du=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("tfoot",{ref:s,className:J("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));du.displayName="TableFooter";var Ie=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("tr",{ref:s,className:J("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Ie.displayName="TableRow";var j=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("th",{ref:s,className:J("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));j.displayName="TableHead";var G=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("td",{ref:s,className:J("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));G.displayName="TableCell";var fu=Ps.forwardRef(({className:e,...t},s)=>(0,ms.jsx)("caption",{ref:s,className:J("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));fu.displayName="TableCaption";var ls=ie(require("react"),1);function tn(){let{api:e}=W(),[t,s]=ls.useState([]),[n,a]=ls.useState(!0),[r,o]=ls.useState(null),c=ls.useCallback(async()=>{try{a(!0),o(null);let m=await e.getForms();s(m)}catch(m){o(m instanceof Error?m:new Error("Failed to fetch forms"))}finally{a(!1)}},[e]);ls.useEffect(()=>{c()},[c]);let d=ls.useCallback(async m=>{let v=await e.createForm(m);return s(g=>[...g,v]),v},[e]),l=ls.useCallback(async(m,v)=>{let g=await e.updateForm(m,v);return s(u=>u.map(f=>f.id===m?g:f)),g},[e]),i=ls.useCallback(async m=>{await e.deleteForm(m),s(v=>v.filter(g=>g.id!==m))},[e]);return{forms:t,isLoading:n,error:r,refetch:c,createForm:d,updateForm:l,deleteForm:i}}var ut=require("react/jsx-runtime");function jn({onSelectForm:e,className:t}){let{forms:s,isLoading:n,error:a}=tn();return n?(0,ut.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ut.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):a?(0,ut.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ut.jsxs)("div",{className:"af-text-destructive",children:["Error: ",a.message]})}):s.length===0?(0,ut.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,ut.jsx)(Wn.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ut.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,ut.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,ut.jsx)("div",{className:t,children:(0,ut.jsxs)(et,{children:[(0,ut.jsx)(tt,{children:(0,ut.jsxs)(Ie,{children:[(0,ut.jsx)(j,{children:"Name"}),(0,ut.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,ut.jsx)(at,{children:s.map(r=>(0,ut.jsxs)(Ie,{children:[(0,ut.jsx)(G,{className:"af-font-medium",children:r.name}),(0,ut.jsx)(G,{className:"af-text-right",children:(0,ut.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,ut.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[(0,ut.jsx)(Wn.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,ut.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[(0,ut.jsx)(Wn.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}var el=require("lucide-react");var Xo=require("class-variance-authority");var Qo=require("react/jsx-runtime"),mu=(0,Xo.cva)("af-inline-flex af-items-center af-rounded-md af-border af-px-2.5 af-py-0.5 af-text-xs af-font-semibold af-transition-colors focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2",{variants:{variant:{default:"af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",secondary:"af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",destructive:"af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",outline:"af-text-foreground",success:"af-border-transparent af-bg-green-100 af-text-green-800",warning:"af-border-transparent af-bg-yellow-100 af-text-yellow-800"}},defaultVariants:{variant:"default"}});function oe({className:e,variant:t,...s}){return(0,Qo.jsx)("div",{className:J(mu({variant:t}),e),...s})}var Ca=require("react/jsx-runtime"),pu={form_notification:"Form notification",purchase_receipt:"Buyer receipt",merchant_sale:"Sale notification",subscription_payment_failed:"Payment reminder",subscription_cancellation:"Cancellation confirmation",subscription_address_change:"Address change confirmation",merchant_subscription_canceled:"Subscription cancellation notice",account_login:"Sign-in email",oversell_refund:"Refund notification",merchant_oversell:"Stock issue notification",dispute_opened:"Dispute notification"};function qr(e){switch(e.state){case"sending":return{label:"Sending",variant:"secondary",detail:null};case"sent":return{label:"Sent",variant:"secondary",detail:"Accepted for sending. Delivery has not been confirmed yet."};case"delivered":return{label:"Delivered",variant:"success",detail:"Accepted by the recipient\u2019s email server. This does not confirm it was read."};case"delivery_delayed":return{label:"Delayed",variant:"warning",detail:"Delivery is delayed. The email provider is still trying."};case"bounced":return{label:"Bounced",variant:"destructive",detail:"A receiving email server rejected this message."};case"complained":return{label:"Marked as spam",variant:"destructive",detail:"A recipient marked this email as spam. Do not resend it to that recipient."};case"suppressed":return{label:"Delivery blocked",variant:"destructive",detail:"The email provider blocked delivery to a recipient after a previous delivery problem or spam complaint."};case"failed":return{label:"Send failed",variant:"destructive",detail:"The email provider reported a sending failure."};case"unknown":return{label:"Delivery unconfirmed",variant:"warning",detail:"We could not confirm whether the email was sent. Check with the recipient before sending it again."}}}function Hi(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function gu(e){return["sending","sent","delivered","delivery_delayed","unknown","complained"].includes(e.state)?null:e.kind==="form_notification"?"Check this form\u2019s notification email addresses in its settings. The submission is saved here.":e.kind==="merchant_sale"||e.kind==="merchant_oversell"?"Check your notification email addresses. You can view and fulfill this order here.":e.kind==="dispute_opened"?"Check your notification email addresses and review this dispute in Stripe.":e.kind==="merchant_subscription_canceled"?"Check your notification email addresses. The subscription status is still shown here.":e.kind==="account_login"?"Ask the customer to confirm their email address and request a new sign-in link once the delivery problem is resolved.":e.kind==="purchase_receipt"?"Contact the buyer another way to confirm their email address. Payment and download details are still available on this order.":"Contact the customer another way to confirm their email address. Email delivery does not change their subscription or payment status."}function Gn({deliveries:e,label:t="Email needs attention"}){return Hi(e)?(0,Ca.jsxs)("span",{className:"af-mt-1 af-flex af-items-center af-gap-1 af-text-xs af-font-normal af-text-amber-800 dark:af-text-amber-300",children:[(0,Ca.jsx)(el.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function ps({deliveries:e,problemsOnly:t=!1,className:s=""}){let n=(e??[]).filter(a=>!t||Hi([a]));return n.length?(0,Ca.jsx)("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:n.map(a=>{let r=qr(a),o=gu(a);return(0,Ca.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Ca.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Ca.jsx)("span",{className:"af-font-medium",children:pu[a.kind]??"Email notification"}),(0,Ca.jsx)(oe,{variant:r.variant,children:r.label})]}),(0,Ca.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",a.recipients.join(", ")]}),a.recipients.length>1&&Hi([a])&&(0,Ca.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This status applies to the message sent to this group. It does not mean every recipient had a delivery problem."}),r.detail&&(0,Ca.jsx)("p",{className:"af-mt-1",children:r.detail}),o&&(0,Ca.jsx)("p",{className:"af-mt-1",children:o})]},a.id)})}):null}var Ws=ie(require("react"),1),Ga=require("lucide-react");var qs=ie(require("react"),1),$e=ie(require("@radix-ui/react-select"),1),an=require("lucide-react");var kt=require("react/jsx-runtime"),qa=$e.Root;var Wa=$e.Value,ka=qs.forwardRef(({className:e,children:t,...s},n)=>(0,kt.jsxs)($e.Trigger,{ref:n,className:J("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[t,(0,kt.jsx)($e.Icon,{asChild:!0,children:(0,kt.jsx)(an.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));ka.displayName=$e.Trigger.displayName;var tl=qs.forwardRef(({className:e,...t},s)=>(0,kt.jsx)($e.ScrollUpButton,{ref:s,className:J("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,kt.jsx)(an.ChevronUp,{className:"af-h-4 af-w-4"})}));tl.displayName=$e.ScrollUpButton.displayName;var al=qs.forwardRef(({className:e,...t},s)=>(0,kt.jsx)($e.ScrollDownButton,{ref:s,className:J("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,kt.jsx)(an.ChevronDown,{className:"af-h-4 af-w-4"})}));al.displayName=$e.ScrollDownButton.displayName;var Ta=qs.forwardRef(({className:e,children:t,position:s="popper",...n},a)=>(0,kt.jsx)($e.Portal,{children:(0,kt.jsxs)($e.Content,{ref:a,className:J("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...n,children:[(0,kt.jsx)(tl,{}),(0,kt.jsx)($e.Viewport,{className:J("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,kt.jsx)(al,{})]})}));Ta.displayName=$e.Content.displayName;var vu=qs.forwardRef(({className:e,...t},s)=>(0,kt.jsx)($e.Label,{ref:s,className:J("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));vu.displayName=$e.Label.displayName;var dt=qs.forwardRef(({className:e,children:t,...s},n)=>(0,kt.jsxs)($e.Item,{ref:n,className:J("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...s,children:[(0,kt.jsx)("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:(0,kt.jsx)($e.ItemIndicator,{children:(0,kt.jsx)(an.Check,{className:"af-h-4 af-w-4"})})}),(0,kt.jsx)($e.ItemText,{children:t})]}));dt.displayName=$e.Item.displayName;var bu=qs.forwardRef(({className:e,...t},s)=>(0,kt.jsx)($e.Separator,{ref:s,className:J("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));bu.displayName=$e.Separator.displayName;var oa=ie(require("react"),1);function Kn({formId:e,initialPageSize:t=25}){let{api:s}=W(),[n,a]=oa.useState([]),[r,o]=oa.useState(0),[c,d]=oa.useState(!0),[l,i]=oa.useState(null),[m,v]=oa.useState(0),[g,u]=oa.useState(t),f=oa.useRef(0),p=oa.useCallback(async()=>{if(!e)return;let T=++f.current;try{d(!0),i(null);let y={limit:g,offset:m*g},C=await s.getSubmissions(e,y);if(T!==f.current)return;if(C.submissions.length===0&&m>0){v(Math.max(0,Math.ceil(C.total/g)-1));return}a(C.submissions),o(C.total)}catch(y){if(T!==f.current)return;i(y instanceof Error?y:new Error("Failed to fetch submissions"))}finally{T===f.current&&d(!1)}},[s,e,m,g]);oa.useEffect(()=>{p()},[p]);let b=oa.useRef(p);b.current=p;let w=oa.useCallback(async T=>{await s.deleteSubmission(T),b.current()},[s]),P=Math.ceil(r/g);return{submissions:n,total:r,isLoading:c,error:l,page:m,pageSize:g,hasNextPage:m<P-1,hasPreviousPage:m>0,setPage:v,setPageSize:T=>{u(T),v(0)},refetch:p,deleteSubmission:w}}var Wr=ie(require("react"),1),rl=require("lucide-react");var Zn=ie(require("react"),1),Ft=ie(require("@radix-ui/react-dialog"),1),sl=require("lucide-react");var ga=require("react/jsx-runtime"),ja=Ft.Root;var yu=Ft.Portal;var nl=Zn.forwardRef(({className:e,...t},s)=>(0,ga.jsx)(Ft.Overlay,{ref:s,className:J("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));nl.displayName=Ft.Overlay.displayName;var Ea=Zn.forwardRef(({className:e,children:t,...s},n)=>(0,ga.jsx)(yu,{children:(0,ga.jsxs)("div",{className:"aifeatures-admin",children:[(0,ga.jsx)(nl,{}),(0,ga.jsxs)(Ft.Content,{ref:n,className:J("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[t,(0,ga.jsxs)(Ft.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[(0,ga.jsx)(sl.X,{className:"af-h-4 af-w-4"}),(0,ga.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Ea.displayName=Ft.Content.displayName;var Ia=({className:e,...t})=>(0,ga.jsx)("div",{className:J("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Ia.displayName="DialogHeader";var Da=({className:e,...t})=>(0,ga.jsx)("div",{className:J("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Da.displayName="DialogFooter";var Aa=Zn.forwardRef(({className:e,...t},s)=>(0,ga.jsx)(Ft.Title,{ref:s,className:J("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Aa.displayName=Ft.Title.displayName;var La=Zn.forwardRef(({className:e,...t},s)=>(0,ga.jsx)(Ft.Description,{ref:s,className:J("af-text-sm af-text-muted-foreground",e),...t}));La.displayName=Ft.Description.displayName;var Qt=require("react/jsx-runtime");function Nn({onDelete:e,iconOnly:t}){let[s,n]=Wr.useState(!1),[a,r]=Wr.useState(!1),[o,c]=Wr.useState(null);return(0,Qt.jsxs)(Qt.Fragment,{children:[(0,Qt.jsxs)(x,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{c(null),n(!0)},children:[(0,Qt.jsx)(rl.Trash2,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),(0,Qt.jsx)(ja,{open:s,onOpenChange:l=>{!l&&!a&&n(!1)},children:(0,Qt.jsxs)(Ea,{children:[(0,Qt.jsxs)(Ia,{children:[(0,Qt.jsx)(Aa,{children:"Delete this submission?"}),(0,Qt.jsx)(La,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),o&&(0,Qt.jsx)("p",{className:"af-text-sm af-text-destructive",children:o}),(0,Qt.jsxs)(Da,{children:[(0,Qt.jsx)(x,{variant:"outline",onClick:()=>n(!1),disabled:a,children:"Cancel"}),(0,Qt.jsx)(x,{variant:"destructive",onClick:async()=>{r(!0),c(null);try{await e(),n(!1)}catch(l){c(l instanceof Error?l.message:"Failed to delete submission")}finally{r(!1)}},disabled:a,children:a?"Deleting...":"Delete"})]})]})})]})}var ol=ie(require("react"),1),ea=require("lucide-react");var Pe=require("react/jsx-runtime");function il(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function hu(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,n)).toFixed(1))} ${s[n]}`}function Yn({submission:e,onBack:t,onDelete:s}){let{api:n}=W(),[a,r]=ol.useState(null),o=l=>l.id??l.name,c=async l=>{r(o(l));try{await n.downloadAttachment(e.id,l)}catch(i){console.error("Download failed:",i)}finally{r(null)}},d=Object.entries(e.data).filter(([l])=>!l.startsWith("_"));return(0,Pe.jsxs)("div",{children:[(0,Pe.jsxs)("div",{className:"af-mb-6",children:[(0,Pe.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,Pe.jsx)(ea.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,Pe.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Pe.jsxs)("div",{children:[(0,Pe.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,Pe.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",il(e.metadata.submitted_at)]})]}),s&&(0,Pe.jsx)(Nn,{onDelete:s})]})]}),(0,Pe.jsxs)("div",{className:"af-space-y-6",children:[(0,Pe.jsx)(ps,{deliveries:e.email_deliveries}),(0,Pe.jsxs)("div",{children:[(0,Pe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,Pe.jsxs)("div",{className:"af-space-y-3",children:[d.map(([l,i])=>(0,Pe.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,Pe.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:l.replace(/_/g," ")}),(0,Pe.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof i=="string"&&i.includes(`
|
|
3
|
-
`)?(0,Pe.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:i}):String(i)})]},l)),d.length===0&&(0,Pe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,Pe.jsxs)("div",{children:[(0,Pe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,Pe.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((l,i)=>(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Pe.jsx)(ea.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,Pe.jsx)("span",{className:"af-text-sm",children:l.name}),(0,Pe.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",hu(l.size),")"]})]}),(0,Pe.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>c(l),disabled:a===o(l),children:[a===o(l)?(0,Pe.jsx)(ea.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Pe.jsx)(ea.Download,{className:"af-h-4 af-w-4 af-mr-1"}),a===o(l)?"Downloading...":"Download"]})]},i))})]}),(0,Pe.jsxs)("div",{children:[(0,Pe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,Pe.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Pe.jsx)(ea.Clock,{className:"af-h-4 af-w-4"}),(0,Pe.jsx)("span",{children:il(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Pe.jsx)(ea.Globe,{className:"af-h-4 af-w-4"}),(0,Pe.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,Pe.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,Pe.jsx)(ea.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,Pe.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,Pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,Pe.jsx)(ea.Mail,{className:"af-h-4 af-w-4"}),(0,Pe.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var cl=require("lucide-react");var sn=ie(require("react"),1);var xu=/^\+[1-9]\d{1,14}$/;function ll(e){let t=e==null?"":String(e),s=!xu.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),n=s?`'${t}`:t;return s||/[",;\r\n]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function jr(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function Gr(e,t){if(typeof document>"u")return;let s=URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}function Jn({fetchCsv:e,filename:t}){let[s,n]=sn.useState(!1),[a,r]=sn.useState(null),o=sn.useRef(!1);return{exportCsv:sn.useCallback(async()=>{if(!o.current){o.current=!0,n(!0),r(null);try{let d=await e();Gr(d,jr(t))}catch(d){r(d instanceof Error?d:new Error("Export failed"))}finally{o.current=!1,n(!1)}}},[e,t]),exporting:s,error:a}}var Rn=require("react/jsx-runtime");function Zt({fetchCsv:e,filename:t,label:s="Export CSV",disabled:n,className:a}){let{exportCsv:r,exporting:o,error:c}=Jn({fetchCsv:e,filename:t});return(0,Rn.jsxs)("span",{className:a,children:[(0,Rn.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:n||o,"aria-busy":o,children:[(0,Rn.jsx)(cl.Download,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Exporting\u2026":s]}),c&&(0,Rn.jsx)("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}var be=require("react/jsx-runtime");function Su(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function wu(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let s of t)if(typeof e[s]=="string")return e[s];return null}var Nu=["message","comments","comment","inquiry","question","details","body","notes"];function Ru(e){let t=Object.entries(e).filter(([r,o])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),s=new Map(t.map(([r,o])=>[r.toLowerCase(),o])),a=(Nu.map(r=>s.get(r)).find(Boolean)??t.reduce((r,[,o])=>o.length>r.length?o:r,"")).trim().replace(/\s+/g," ");return a.length>80?a.slice(0,80)+"\u2026":a}function Xn({formId:e,className:t,defaultSubmissionId:s,submissionId:n,onSelectSubmission:a}){let{api:r}=W(),{submissions:o,total:c,isLoading:d,error:l,page:i,pageSize:m,hasNextPage:v,hasPreviousPage:g,setPage:u,setPageSize:f,deleteSubmission:p}=Kn({formId:e}),b=Ws.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[w,P]=Ws.useState(s??null),T=a?n??null:w,y=a??P,C=z=>!!z&&z.id===T&&z.form_id===e,k=o.find(C),[I,N]=Ws.useState(null),E=C(I)?I:null,[D,_]=Ws.useState(null);if(Ws.useEffect(()=>{if(_(null),!T||k||E)return;let z=!1;return r.getSubmission(T).then(le=>{if(!z){if(le.form_id!==e){_("This submission could not be found.");return}N(le)}}).catch(()=>{z||_("This submission could not be found.")}),()=>{z=!0}},[r,e,T,k,E]),T){let z=k??E;return z?(0,be.jsx)("div",{className:t,children:(0,be.jsx)(Yn,{submission:z,onBack:()=>y(null),onDelete:async()=>{await p(z.id),y(null)}})}):D?(0,be.jsxs)("div",{className:t,children:[(0,be.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>y(null),className:"af-mb-2 af--ml-2",children:[(0,be.jsx)(Ga.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,be.jsx)("p",{className:"af-text-sm af-text-destructive",children:D})]}):(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(d)return(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(l)return(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,be.jsxs)("div",{className:"af-text-destructive",children:["Error: ",l.message]})});if(o.length===0&&i===0)return(0,be.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,be.jsx)(Ga.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,be.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,be.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let Y=i*m+1,Q=Math.min((i+1)*m,c);return(0,be.jsxs)("div",{className:t,children:[(0,be.jsx)("div",{className:"af-mb-2 af-flex af-justify-end",children:(0,be.jsx)(Zt,{fetchCsv:b,filename:"submissions"})}),(0,be.jsxs)(et,{children:[(0,be.jsx)(tt,{children:(0,be.jsxs)(Ie,{children:[(0,be.jsx)(j,{children:"Email"}),(0,be.jsx)(j,{children:"Preview"}),(0,be.jsx)(j,{children:"Date"}),(0,be.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,be.jsx)(at,{children:o.map(z=>{let le=wu(z.data),fe=Ru(z.data);return(0,be.jsxs)(Ie,{children:[(0,be.jsxs)(G,{className:"af-font-medium",children:[(0,be.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[le||(0,be.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),z.attachments.length>0&&(0,be.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${z.attachments.length} attachment(s)`,children:[(0,be.jsx)(Ga.Paperclip,{className:"af-h-3 af-w-3"}),(0,be.jsx)("span",{className:"af-text-xs",children:z.attachments.length})]})]}),(0,be.jsx)(Gn,{deliveries:z.email_deliveries,label:"Notification email needs attention"})]}),(0,be.jsx)(G,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:fe||(0,be.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,be.jsx)(G,{className:"af-text-muted-foreground",children:Su(z.metadata.submitted_at)}),(0,be.jsxs)(G,{className:"af-text-right",children:[(0,be.jsx)(x,{variant:"ghost",size:"icon",onClick:()=>y(z.id),title:"View details",children:(0,be.jsx)(Ga.Eye,{className:"af-h-4 af-w-4"})}),(0,be.jsx)(Nn,{iconOnly:!0,onDelete:()=>p(z.id)})]})]},z.id)})})]}),(0,be.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,be.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,be.jsxs)("span",{children:["Showing ",Y,"-",Q," of ",c]}),(0,be.jsxs)(qa,{value:String(m),onValueChange:z=>f(Number(z)),children:[(0,be.jsx)(ka,{className:"af-w-[70px] af-h-8",children:(0,be.jsx)(Wa,{})}),(0,be.jsxs)(Ta,{children:[(0,be.jsx)(dt,{value:"10",children:"10"}),(0,be.jsx)(dt,{value:"25",children:"25"}),(0,be.jsx)(dt,{value:"50",children:"50"}),(0,be.jsx)(dt,{value:"100",children:"100"})]})]}),(0,be.jsx)("span",{children:"per page"})]}),(0,be.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,be.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>u(i-1),disabled:!g,children:[(0,be.jsx)(Ga.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,be.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>u(i+1),disabled:!v,children:["Next",(0,be.jsx)(Ga.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ba=ie(require("react"),1),js=require("lucide-react");var ul=ie(require("react"),1);var dl=require("react/jsx-runtime"),re=ul.forwardRef(({className:e,type:t,...s},n)=>(0,dl.jsx)("input",{type:t,className:J("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:n,...s}));re.displayName="Input";var fl=ie(require("react"),1),ml=require("class-variance-authority");var pl=require("react/jsx-runtime"),_u=(0,ml.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Oe=fl.forwardRef(({className:e,...t},s)=>(0,pl.jsx)("label",{ref:s,className:J(_u(),e),...t}));Oe.displayName="Label";var Ka=ie(require("react"),1),ta=require("lucide-react");var Oa=ie(require("react"),1);function Qn(){let{api:e}=W(),[t,s]=Oa.useState([]),[n,a]=Oa.useState(!0),[r,o]=Oa.useState(null),c=Oa.useCallback(async()=>{try{a(!0),o(null),s(await e.getEventDestinations())}catch(g){o(g instanceof Error?g:new Error("Failed to fetch webhooks"))}finally{a(!1)}},[e]);Oa.useEffect(()=>{c()},[c]);let d=Oa.useCallback(async g=>{let u=await e.createEventDestination(g);return s(f=>[u,...f]),u},[e]),l=Oa.useCallback(async(g,u)=>{let f=await e.updateEventDestination(g,u);return s(p=>p.map(b=>b.id===g?f:b)),f},[e]),i=Oa.useCallback(async g=>{await e.deleteEventDestination(g),s(u=>u.filter(f=>f.id!==g))},[e]),m=Oa.useCallback(async g=>{let u=await e.rotateEventDestinationSecret(g);return s(f=>f.map(p=>p.id===g?u:p)),u},[e]),v=Oa.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:n,error:r,refetch:c,createDestination:d,updateDestination:l,deleteDestination:i,rotateSecret:m,getSecret:v}}var Cs=ie(require("react"),1),er=require("lucide-react");var Ut=require("react/jsx-runtime");function tr({destinationId:e,limit:t=25,className:s}){let{api:n}=W(),[a,r]=Cs.useState([]),[o,c]=Cs.useState(!0),[d,l]=Cs.useState(null),[i,m]=Cs.useState(null),v=Cs.useCallback(async()=>{try{c(!0),l(null),r(await n.getEventDeliveries(e,t))}catch(u){l(u instanceof Error?u.message:"Failed to load deliveries")}finally{c(!1)}},[n,e,t]);Cs.useEffect(()=>{v()},[v]);let g=async u=>{try{m(u.id),l(null);let f=await n.retryEventDelivery(e,u.id);r(p=>p.map(b=>b.id===u.id?f:b))}catch(f){l(f instanceof Error?f.message:"Retry failed")}finally{m(null)}};return o?(0,Ut.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,Ut.jsx)(er.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):d?(0,Ut.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:d}):a.length===0?(0,Ut.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):(0,Ut.jsx)("div",{className:s,children:(0,Ut.jsx)("div",{className:"af-divide-y af-border af-rounded",children:a.map(u=>{let f=u.delivered_at!==null;return(0,Ut.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,Ut.jsxs)("div",{className:"af-min-w-0",children:[(0,Ut.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[f?(0,Ut.jsx)(oe,{variant:"secondary",children:u.last_status??200}):(0,Ut.jsx)(oe,{variant:"destructive",children:u.last_status??"failed"}),(0,Ut.jsx)("span",{className:"af-text-sm af-truncate",children:u.type})]}),(0,Ut.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[u.event_id," \xB7 ",u.created_at,u.attempts>0&&` \xB7 ${u.attempts} failed ${u.attempts===1?"attempt":"attempts"}`]}),!f&&u.last_error&&(0,Ut.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),(0,Ut.jsx)(x,{variant:"ghost",size:"sm",title:"Send this event again",disabled:i===u.id,onClick:()=>g(u),children:i===u.id?(0,Ut.jsx)(er.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ut.jsx)(er.RotateCw,{className:"af-h-4 af-w-4"})})]},u.id)})})})}var Se=require("react/jsx-runtime");function ar({formId:e,topics:t,description:s,className:n}){let{destinations:a,isLoading:r,error:o,createDestination:c,updateDestination:d,deleteDestination:l,rotateSecret:i,getSecret:m}=Qn(),[v,g]=Ka.useState(""),[u,f]=Ka.useState(!1),[p,b]=Ka.useState(null),[w,P]=Ka.useState(null),[T,y]=Ka.useState(null),[C,k]=Ka.useState(!1),[I,N]=Ka.useState(null),[E,D]=Ka.useState(null),[_,Y]=Ka.useState(null),Q=Ka.useMemo(()=>a.filter(U=>U.form_id===e),[a,e]),z=async()=>{let U=v.trim();if(U){if(!U.startsWith("https://")){b("Webhook URLs must start with https://");return}try{f(!0),b(null),await c({url:U,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(ve){b(ve instanceof Error?ve.message:"Failed to add webhook")}finally{f(!1)}}},le=async U=>{try{D(U.id),b(null),await i(U.id),k(!1),y(await m(U.id))}catch(ve){b(ve instanceof Error?ve.message:"Failed to rotate secret")}finally{D(null)}},fe=async U=>{try{D(U.id),b(null),await d(U.id,{status:"active"})}catch(ve){b(ve instanceof Error?ve.message:"Failed to re-enable")}finally{D(null)}},he=async()=>{if(I)try{D(I.id),await l(I.id),N(null)}catch(U){b(U instanceof Error?U.message:"Failed to delete")}finally{D(null)}},M=async U=>{if(w===U.id){P(null),y(null);return}try{D(U.id),b(null),k(!1),P(U.id),y(await m(U.id))}catch(ve){P(null),b(ve instanceof Error?ve.message:"Failed to read secret")}finally{D(null)}},ee=async()=>{if(T)try{await navigator.clipboard.writeText(T),k(!0)}catch{}};return(0,Se.jsxs)("div",{className:n,children:[(0,Se.jsxs)("div",{className:"af-space-y-1",children:[(0,Se.jsx)(Oe,{children:"Webhooks"}),(0,Se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:s??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),(0,Se.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,Se.jsx)(re,{value:v,placeholder:"https://hooks.zapier.com/...",onChange:U=>g(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),z())},disabled:u}),(0,Se.jsxs)(x,{onClick:z,disabled:u||!v.trim(),children:[u?(0,Se.jsx)(ta.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Se.jsx)(ta.Plus,{className:"af-h-4 af-w-4"}),(0,Se.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(p||o)&&(0,Se.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:p||o?.message}),(0,Se.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[r&&(0,Se.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Se.jsx)(ta.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&Q.length===0&&(0,Se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),Q.map(U=>(0,Se.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,Se.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Se.jsxs)("div",{className:"af-min-w-0",children:[(0,Se.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Se.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:U.url}),U.status==="disabled"?(0,Se.jsx)(oe,{variant:"destructive",children:"Disabled"}):(0,Se.jsx)(oe,{variant:"secondary",children:"Active"})]}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:U.topics.includes("*")?"All events":U.topics.join(", ")})]}),(0,Se.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,Se.jsx)(x,{variant:"ghost",size:"sm",onClick:()=>Y(_===U.id?null:U.id),children:_===U.id?"Hide log":"Deliveries"}),(0,Se.jsx)(x,{variant:"ghost",size:"sm",onClick:()=>M(U),disabled:E===U.id,children:w===U.id?"Hide secret":"Show secret"}),(0,Se.jsx)(x,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:E===U.id,onClick:()=>N(U),children:(0,Se.jsx)(ta.Trash2,{className:"af-h-4 af-w-4"})})]})]}),U.status==="disabled"&&(0,Se.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[(0,Se.jsx)(ta.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,Se.jsxs)("div",{className:"af-text-sm",children:[(0,Se.jsxs)("p",{children:["We stopped sending after repeated failures."," ",U.disabled_reason]}),(0,Se.jsx)(x,{variant:"outline",size:"sm",className:"af-mt-2",disabled:E===U.id,onClick:()=>fe(U),children:"Re-enable"})]})]}),w===U.id&&T&&(0,Se.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Optional. Use this if you want your endpoint to check that a delivery really came from us. Rotating replaces it."}),(0,Se.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Se.jsx)(re,{readOnly:!0,value:T,className:"af-font-mono"}),(0,Se.jsx)(x,{variant:"outline",title:"Copy signing secret",onClick:ee,children:C?(0,Se.jsx)(ta.Check,{className:"af-h-4 af-w-4"}):(0,Se.jsx)(ta.Copy,{className:"af-h-4 af-w-4"})}),(0,Se.jsx)(x,{variant:"outline",title:"Rotate signing secret",disabled:E===U.id,onClick:()=>le(U),children:E===U.id?(0,Se.jsx)(ta.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Se.jsx)(ta.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),_===U.id&&(0,Se.jsx)(tr,{destinationId:U.id})]},U.id))]}),(0,Se.jsx)(ja,{open:!!I,onOpenChange:U=>{!U&&!E&&N(null)},children:(0,Se.jsxs)(Ea,{children:[(0,Se.jsxs)(Ia,{children:[(0,Se.jsx)(Aa,{children:"Delete this webhook?"}),(0,Se.jsxs)(La,{children:["New submissions will stop being sent to ",I?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),(0,Se.jsxs)(Da,{children:[(0,Se.jsx)(x,{variant:"outline",onClick:()=>N(null),disabled:!!E,children:"Cancel"}),(0,Se.jsx)(x,{variant:"destructive",onClick:he,disabled:!!E,children:E?"Deleting...":"Delete"})]})]})})]})}var Le=require("react/jsx-runtime");function sr({form:e,onSaved:t,className:s}){let{updateForm:n}=tn(),[a,r]=Ba.useState(!1),[o,c]=Ba.useState(null),[d,l]=Ba.useState(null),[i,m]=Ba.useState(e.name),[v,g]=Ba.useState(e.redirect_url||""),[u,f]=Ba.useState(e.email_recipients),[p,b]=Ba.useState("");Ba.useEffect(()=>{m(e.name),g(e.redirect_url||""),f(e.email_recipients),l(null)},[e]);let w=Ba.useCallback(async k=>{try{r(!0),l(null);let I=await n(e.id,k);c(new Date),t?.(I)}catch(I){l(I instanceof Error?I.message:"Failed to save")}finally{r(!1)}},[e.id,n,t]);Ba.useEffect(()=>{if(o){let k=setTimeout(()=>c(null),2e3);return()=>clearTimeout(k)}},[o]);let P=async()=>{let k=p.trim().toLowerCase();if(!k)return;if(!k.includes("@")){l("Please enter a valid email address");return}if(u.includes(k)){l("This email is already added");return}let I=[...u,k];f(I),b(""),l(null),await w({email_recipients:I})},T=async k=>{let I=u.filter(N=>N!==k);f(I),await w({email_recipients:I})},y=async()=>{i!==e.name&&await w({name:i})},C=async()=>{let k=v||null;k!==e.redirect_url&&await w({redirect_url:k})};return(0,Le.jsxs)("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(a||o)&&(0,Le.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:a?(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-background af-border af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,Le.jsx)(js.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,Le.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,Le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-green-50 af-border af-border-green-200 af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,Le.jsx)(js.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,Le.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{htmlFor:"form-name",children:"Form Name"}),(0,Le.jsx)(re,{id:"form-name",value:i,onChange:k=>m(k.target.value),onBlur:y,placeholder:"Contact Form"}),(0,Le.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{children:"Email Recipients"}),(0,Le.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,Le.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(k=>(0,Le.jsxs)(oe,{variant:"secondary",className:"af-gap-1",children:[k,(0,Le.jsx)("button",{type:"button",onClick:()=>T(k),className:"af-ml-1 hover:af-text-destructive",disabled:a,children:(0,Le.jsx)(js.X,{className:"af-h-3 af-w-3"})})]},k)),u.length===0&&(0,Le.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,Le.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Le.jsx)(re,{type:"email",value:p,onChange:k=>b(k.target.value),placeholder:"Add email address",onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),P())},disabled:a}),(0,Le.jsx)(x,{type:"button",variant:"outline",onClick:P,disabled:!p.trim()||a,children:(0,Le.jsx)(js.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,Le.jsx)(re,{id:"redirect-url",value:v,onChange:k=>g(k.target.value),onBlur:C,placeholder:"/thank-you"}),(0,Le.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Where to send visitors after a successful submission. Use a site path (/thank-you) or a full URL (https://example.com/thank-you). Leave empty for a default success page."})]}),(0,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{children:"Form Endpoint"}),(0,Le.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Le.jsx)("code",{className:"af-flex-1 af-text-xs af-bg-muted af-px-3 af-py-2 af-rounded af-border",children:e.endpoint_url})}),(0,Le.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,Le.jsxs)("div",{className:"af-space-y-2",children:[(0,Le.jsx)(Oe,{children:"Captcha Protection"}),(0,Le.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Le.jsx)(oe,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,Le.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,Le.jsx)(ar,{formId:e.id}),d&&(0,Le.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})]})}var it=require("react/jsx-runtime");function zi({className:e,location:t,onNavigate:s,submissionId:n}){let{api:a}=W(),[r,o]=ks.useState({submissionId:n});ks.useEffect(()=>{n&&o({submissionId:n})},[n]);let c=s?t??{}:r,d=s??o,[l,i]=ks.useState(null),m=`${c.formId??""}|${c.submissionId??""}`,[v,g]=ks.useState(null),u=v?.key===m?v.message:null,f=c.formId??(l&&l.submissionId===c.submissionId?l.formId:void 0);ks.useEffect(()=>{let k=c.submissionId;if(!k||c.formId)return;let I=!1;return a.getSubmission(k).then(N=>{I||(g(null),i({submissionId:k,formId:N.form_id}))}).catch(()=>{I||g({key:m,message:"This submission could not be found."})}),()=>{I=!0}},[a,c.submissionId,c.formId,m]);let[p,b]=ks.useState(null);ks.useEffect(()=>{if(!f||p?.id===f)return;let k=!1;return a.getForm(f).then(I=>{k||(g(null),b(I))}).catch(()=>{k||g({key:m,message:"This form could not be found."})}),()=>{k=!0}},[a,f,p?.id,m]);let w=(k,I)=>{b(k),d({formId:k.id,tab:I})},P=()=>d({});if(!c.formId&&!c.submissionId)return(0,it.jsxs)("div",{className:e,children:[(0,it.jsxs)("div",{className:"af-mb-6",children:[(0,it.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,it.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,it.jsx)(jn,{onSelectForm:w})]});let y=(0,it.jsxs)(x,{variant:"ghost",size:"sm",onClick:P,className:"af-mb-2 af--ml-2",children:[(0,it.jsx)(_n.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(u)return(0,it.jsxs)("div",{className:e,children:[y,(0,it.jsx)("p",{className:"af-text-sm af-text-destructive",children:u})]});if(!f||p?.id!==f)return(0,it.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,it.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let C=c.submissionId?"submissions":c.tab??"submissions";return(0,it.jsxs)("div",{className:e,children:[(0,it.jsxs)("div",{className:"af-mb-6",children:[y,(0,it.jsx)("h2",{className:"af-text-lg af-font-semibold",children:p.name})]}),(0,it.jsxs)(Hr,{value:C,onValueChange:k=>d({formId:f,tab:k}),children:[(0,it.jsxs)(qn,{className:"af-mb-4",children:[(0,it.jsxs)(is,{value:"submissions",className:"af-gap-2",children:[(0,it.jsx)(_n.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,it.jsxs)(is,{value:"settings",className:"af-gap-2",children:[(0,it.jsx)(_n.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,it.jsx)(os,{value:"submissions",children:(0,it.jsx)(Xn,{formId:f,submissionId:c.submissionId,onSelectSubmission:k=>d({formId:f,tab:"submissions",submissionId:k??void 0})})}),(0,it.jsx)(os,{value:"settings",children:(0,it.jsx)(sr,{form:p,onSaved:b})})]})]})}var Xe=ie(require("react"),1);var gs=ie(require("react"),1);function Ts(){let{api:e}=W(),[t,s]=gs.useState(null),[n,a]=gs.useState(!0),[r,o]=gs.useState(null),c=gs.useRef(0),d=gs.useCallback(async()=>{let l=++c.current;try{a(!0),o(null);let i=await e.getPaymentsStatus();if(l!==c.current)return;s(i)}catch(i){if(l!==c.current)return;o(i instanceof Error?i:new Error("Failed to fetch payments status"))}finally{l===c.current&&a(!1)}},[e]);return gs.useEffect(()=>{d()},[d]),{status:t,isLoading:n,error:r,refetch:d}}var Pu=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Fa(e){return Pu.has(e.toLowerCase())}function Z(e,t,s){let n=Fa(t)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:t.toUpperCase()}).format(n)}catch{return`${n} ${t.toUpperCase()}`}}function vs(e){let t=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+t}function zt(e,t){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let n=Fa(t)?s:s*100;return Math.round(n)}function mt(e,t){return Fa(t)?e:e/100}function Kr(e){return e.amount_paid??Math.max(0,vs(e)-(e.credit_applied??0))}var ge=require("react/jsx-runtime");function nr(e){return e instanceof Dt&&e.status===404?"Promo management is not available yet. Try again after the service is updated.":e instanceof Error?e.message:"Could not complete the request."}function gl(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${Z(e.amount_off,e.currency)} off`:"Discount unavailable"}function nn(){let{api:e,siteToken:t}=W();return(0,ge.jsx)(Cu,{api:e},t)}function Cu({api:e}){let{status:t,error:s}=Ts(),[n,a]=Xe.useState([]),[r,o]=Xe.useState(null),[c,d]=Xe.useState(null),[l,i]=Xe.useState(!1),[m,v]=Xe.useState(!1),[g,u]=Xe.useState(""),[f,p]=Xe.useState(null),[b,w]=Xe.useState(null),[P,T]=Xe.useState(!1),y=Xe.useRef(0),C=Xe.useCallback(async N=>{let E=++y.current;i(!0),u("");try{let D=await e.getPromos(N);if(E!==y.current)return;a(_=>N?[..._,...D.promos.filter(Y=>!_.some(Q=>Q.id===Y.id))]:D.promos),o(D.next_cursor),d(D.checkout_enabled)}catch(D){E===y.current&&u(nr(D))}finally{E===y.current&&i(!1)}},[e]);Xe.useEffect(()=>(C(),()=>{y.current++}),[C]);async function k(N){let E=++y.current;i(!0),u(""),T(!1);try{let D=await e.getPromo(N);E===y.current&&p(D)}catch(D){E===y.current&&u(nr(D))}finally{E===y.current&&i(!1)}}async function I(){if(f){v(!0),i(!0),u("");try{let N=await e.disablePromo(f.id);if(p(N),!["inactive","expired","exhausted"].includes(N.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");T(!1),await C()}catch(N){u(nr(N))}finally{v(!1),i(!1)}}}return b?(0,ge.jsx)(ku,{currency:t?.currency??void 0,replaces:b.replaces,onCancel:()=>w(null),onSave:async N=>{let E=b.replaces?await e.replacePromo(b.replaces.id,N):await e.createPromo(N),D=await e.getPromo(E.id);if(D.status==="pending"||D.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(D),w(null),await C()}}):(0,ge.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,ge.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,ge.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,ge.jsx)(x,{disabled:l||!t?.currency,onClick:()=>{u(""),w({})},children:"Create promo code"})]}),(0,ge.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),c===!1&&(0,ge.jsx)("p",{role:"status",className:"af-rounded-md af-border af-p-3 af-text-sm",children:"Checkout code entry is not enabled yet. You can prepare codes, but buyers cannot enter them in our checkout until it is enabled."}),!t?.currency&&(0,ge.jsx)("p",{className:"af-text-sm",children:s?nr(s):"Connect Stripe and set the payment currency before creating codes."}),g&&(0,ge.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",(0,ge.jsx)(x,{variant:"outline",disabled:l,onClick:()=>f?void k(f.id):void C(),children:"Refresh"})]}),f?(0,ge.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,ge.jsx)(x,{variant:"ghost",disabled:m,onClick:()=>{p(null),T(!1),C()},children:"Back to codes"}),(0,ge.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[f.code," \xB7 ",f.name]}),(0,ge.jsxs)("p",{children:[gl(f)," \xB7 ",f.status]}),(0,ge.jsxs)("p",{className:"af-text-sm",children:[f.times_redeemed==null?"Usage unavailable":`${f.times_redeemed} redemptions`,f.max_redemptions!=null?` / ${f.max_redemptions} maximum`:""]}),(0,ge.jsxs)("p",{className:"af-text-sm",children:[f.minimum_amount!=null&&f.currency?`Minimum order: ${Z(f.minimum_amount,f.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,ge.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",f.duration==="repeating"?`${f.duration_in_months} months`:f.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,ge.jsx)("p",{className:"af-text-sm",children:f.expires_at?`Expires ${new Date(f.expires_at).toLocaleString()}`:"No expiry"}),(0,ge.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ge.jsx)(x,{variant:"outline",disabled:l,onClick:()=>void k(f.id),children:"Refresh details"}),(0,ge.jsx)(x,{variant:"outline",disabled:l||f.status==="pending"||f.status==="unavailable"||!t?.currency,onClick:()=>w({replaces:f}),children:"Replace with new code"}),(0,ge.jsx)(x,{variant:"outline",disabled:l||!["active","pending","unavailable"].includes(f.status),onClick:()=>T(!0),children:f.status==="pending"?"Cancel pending offer":"Disable code"})]}),P&&(0,ge.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,ge.jsxs)("p",{className:"af-text-sm",children:[f.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${f.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,ge.jsx)(x,{disabled:l,onClick:()=>void I(),children:f.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,ge.jsx)(x,{variant:"ghost",disabled:l,onClick:()=>T(!1),children:"Cancel"})]})]}):(0,ge.jsxs)(ge.Fragment,{children:[n.map(N=>(0,ge.jsxs)("button",{type:"button",disabled:l,onClick:()=>void k(N.id),className:"af-w-full af-rounded-lg af-border af-p-4 af-text-left hover:af-bg-muted focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[(0,ge.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,ge.jsx)("span",{className:"af-font-semibold af-break-all",children:N.code}),(0,ge.jsx)("span",{className:"af-text-sm",children:N.status})]}),(0,ge.jsxs)("div",{className:"af-text-sm",children:[gl(N)," \xB7"," ",N.times_redeemed==null?"Usage unavailable":`${N.times_redeemed} redemptions`]})]},N.id)),!l&&!g&&n.length===0&&(0,ge.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),l&&(0,ge.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),r&&(0,ge.jsx)(x,{variant:"outline",disabled:l,onClick:()=>void C(r),children:"Load more"})]})]})}function ku({currency:e,replaces:t,onCancel:s,onSave:n}){let[a,r]=Xe.useState(""),[o,c]=Xe.useState(t?.name??""),[d,l]=Xe.useState(t?.amount_off!=null?"fixed":"percent"),[i,m]=Xe.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(mt(t.amount_off,e)):"")),[v,g]=Xe.useState(t?.minimum_amount!=null&&e?String(mt(t.minimum_amount,e)):""),[u,f]=Xe.useState(()=>{if(!t?.expires_at)return"";let fe=new Date(t.expires_at);return Number.isFinite(fe.getTime())?new Date(fe.getTime()-fe.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,b]=Xe.useState(t?.max_redemptions?.toString()??""),[w,P]=Xe.useState(t?.duration??"once"),[T,y]=Xe.useState(t?.duration_in_months?.toString()??"3"),[C,k]=Xe.useState(null),[I,N]=Xe.useState(!1),[E,D]=Xe.useState(""),_=Xe.useRef(!1),Y=e&&Fa(e)?"1":"0.01";async function Q(fe){if(fe.preventDefault(),_.current)return;D("");let he=C;if(!he){if(!e){D("Payment currency is not available.");return}if(t&&a.trim().toUpperCase()===t.code.toUpperCase()){D("Choose a different code for the replacement.");return}let M=zt(i,e),ee=v?zt(v,e):null;if(d==="fixed"&&(!M||M>999999999999)||v&&(!ee||ee>999999999999)){D("Enter a positive amount within the supported range.");return}if(u&&new Date(u).getTime()<=Date.now()){D("Choose a future expiry.");return}he={request_id:crypto.randomUUID(),code:a.trim().toUpperCase(),name:o.trim(),duration:w,...d==="percent"?{percent_off:Number(i)}:{amount_off:M,currency:e},...v?{minimum_amount:ee,currency:e}:{},...u?{expires_at:new Date(u).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...w==="repeating"?{duration_in_months:Number(T)}:{}},k(he)}_.current=!0,N(!0);try{await n(he)}catch(M){D(nr(M)),M instanceof Dt&&M.status>=400&&M.status<500&&M.details?.retryable!==!0&&k(null)}finally{_.current=!1,N(!1)}}let z=(fe,he,M,ee={})=>(0,ge.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[fe,(0,ge.jsx)(re,{"aria-label":fe,value:he,onChange:U=>M(U.target.value),...ee})]}),le="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,ge.jsxs)("form",{onSubmit:Q,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,ge.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,ge.jsx)("p",{className:"af-text-sm",children:"Use a different code. The old code will be disabled only after the replacement is created. Existing subscription discounts continue."}),(0,ge.jsxs)("fieldset",{disabled:I||!!C,className:"af-grid af-gap-4",children:[z("Code",a,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),z("Name",o,c,{required:!0,maxLength:40}),(0,ge.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,ge.jsxs)("select",{"aria-label":"Discount type",className:le,value:d,onChange:fe=>l(fe.target.value),children:[(0,ge.jsx)("option",{value:"percent",children:"Percentage"}),(0,ge.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),z("Discount",i,m,{type:"number",required:!0,min:d==="percent"?"0.01":Y,max:d==="percent"?"100":void 0,step:d==="percent"?"0.01":Y}),z("Minimum order amount",v,g,{type:"number",min:Y,step:Y,placeholder:e?.toUpperCase()}),(0,ge.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),z("Expires at (local time)",u,f,{type:"datetime-local",step:1}),z("Maximum redemptions",p,b,{type:"number",min:1,max:1e6,step:1}),(0,ge.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,ge.jsxs)("select",{"aria-label":"Subscription duration",className:le,value:w,onChange:fe=>P(fe.target.value),children:[(0,ge.jsx)("option",{value:"once",children:"First invoice only"}),(0,ge.jsx)("option",{value:"forever",children:"Every invoice"}),(0,ge.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),w==="repeating"&&z("Months",T,y,{type:"number",required:!0,min:1,max:36,step:1})]}),E&&(0,ge.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:E}),C&&!I&&(0,ge.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,ge.jsx)("span",{className:"af-break-all",children:C.request_id})]}),(0,ge.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ge.jsx)(x,{type:"submit",disabled:I,children:I?"Saving\u2026":C?"Retry same request":t?"Create replacement":"Create code"}),(0,ge.jsx)(x,{type:"button",variant:"ghost",disabled:I||!!C,onClick:s,children:"Cancel"})]})]})}var En=ie(require("react"),1),Xa=require("lucide-react");var Zr=ie(require("react"),1),Es=require("lucide-react");var Te=require("react/jsx-runtime");function Tu(e){if(e.allow_custom_amount){let t=e.min_amount!==null?Z(e.min_amount,e.currency):"?",s=e.max_amount!==null?Z(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${s})`}return e.unit_amount===null?"Varies by variant":Z(e.unit_amount,e.currency)}function Eu(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function rr({productsState:e,onSelectProduct:t,onCreateProduct:s,className:n}){let{products:a,isLoading:r,error:o,deleteProduct:c}=e,[d,l]=Zr.useState(null),[i,m]=Zr.useState(!1),[v,g]=Zr.useState(null),u=async()=>{if(d)try{m(!0),g(null),await c(d.id),l(null)}catch(f){g(f instanceof Error?f.message:"Failed to delete product")}finally{m(!1)}};return r?(0,Te.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:(0,Te.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,Te.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:(0,Te.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):a.length===0?(0,Te.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${n||""}`,children:[(0,Te.jsx)(Es.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Te.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,Te.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,Te.jsxs)(x,{variant:"outline",onClick:()=>s?.(),children:[(0,Te.jsx)(Es.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,Te.jsxs)("div",{className:n,children:[(0,Te.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,Te.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[(0,Te.jsx)(Es.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,Te.jsxs)(et,{children:[(0,Te.jsx)(tt,{children:(0,Te.jsxs)(Ie,{children:[(0,Te.jsx)(j,{children:"Name"}),(0,Te.jsx)(j,{children:"Price"}),(0,Te.jsx)(j,{children:"Fulfillment"}),(0,Te.jsx)(j,{children:"Status"}),(0,Te.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,Te.jsx)(at,{children:a.map(f=>(0,Te.jsxs)(Ie,{children:[(0,Te.jsx)(G,{className:"af-font-medium",children:f.name}),(0,Te.jsx)(G,{children:Tu(f)}),(0,Te.jsx)(G,{className:"af-text-muted-foreground",children:Eu(f)}),(0,Te.jsx)(G,{children:(0,Te.jsx)(oe,{variant:f.active?"success":"secondary",children:f.active?"Active":"Inactive"})}),(0,Te.jsx)(G,{className:"af-text-right",children:(0,Te.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Te.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>t?.(f),children:[(0,Te.jsx)(Es.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,Te.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>{g(null),l(f)},children:[(0,Te.jsx)(Es.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},f.id))})]}),(0,Te.jsx)(ja,{open:!!d,onOpenChange:f=>{!f&&!i&&l(null)},children:(0,Te.jsxs)(Ea,{children:[(0,Te.jsxs)(Ia,{children:[(0,Te.jsx)(Aa,{children:"Delete product?"}),(0,Te.jsxs)(La,{children:['"',d?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),v&&(0,Te.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),(0,Te.jsxs)(Da,{children:[(0,Te.jsx)(x,{variant:"outline",onClick:()=>l(null),disabled:i,children:"Cancel"}),(0,Te.jsx)(x,{variant:"destructive",onClick:u,disabled:i,children:i?"Deleting...":"Delete"})]})]})})]})}var pt=ie(require("react"),1),Ua=require("lucide-react");var At=ie(require("react"),1),Za=require("lucide-react");var O=require("react/jsx-runtime");function qi(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function ir({productId:e,currency:t,className:s}){let{api:n}=W(),a=Fa(t)?"1":"0.01",[r,o]=At.useState(null),[c,d]=At.useState(!0),[l,i]=At.useState(null),[m,v]=At.useState(null),[g,u]=At.useState(!1),f=At.useRef(!0);At.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]);let p=At.useCallback(async()=>{try{let L=await n.getProduct(e);if(!f.current)return;o(L)}catch(L){if(!f.current)return;i(L instanceof Error?L.message:"Failed to load product")}finally{f.current&&d(!1)}},[n,e]);At.useEffect(()=>{p()},[p]);let b=async L=>{v(null),u(!0);try{await L(),await p()}catch($){f.current&&v($ instanceof Error?$.message:"Something went wrong")}finally{f.current&&u(!1)}},[w,P]=At.useState(""),[T,y]=At.useState(""),[C,k]=At.useState({}),I=()=>b(async()=>{let L=w.trim(),$=T.split(",").map(F=>F.trim()).filter(Boolean);if(!L)throw new Error("Option name is required");if($.length===0)throw new Error("Add at least one value");await n.createOption(e,{title:L,values:$}),f.current&&(P(""),y(""))}),N=L=>b(async()=>{let $=(C[L.id]??"").trim();if(!$)throw new Error("Enter a value");await n.updateOption(L.id,{add_values:[$]}),f.current&&k(F=>({...F,[L.id]:""}))}),E=(L,$)=>b(()=>n.updateOption(L.id,{remove_values:[$]})),D=L=>b(()=>n.deleteOption(L.id)),[_,Y]=At.useState(null),[Q,z]=At.useState(null),[le,fe]=At.useState(!1),[he,M]=At.useState(null),ee=r?.options??[],U=r?.variants??[],ve=()=>{z(null),Y({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(ee.map(L=>[L.id,L.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},me=L=>{z(null);let $=L.inventory?.on_hand??0,F=$<0?"":String($);Y({variant:L,title:L.title??"",sku:L.sku??"",unitAmount:L.unit_amount!=null?String(mt(L.unit_amount,t)):"",compareAt:L.compare_at_amount!=null?String(mt(L.compare_at_amount,t)):"",active:L.active,optionValues:{},tracked:L.inventory?.tracked??!1,onHand:F,initialOnHand:F,allowBackorder:L.inventory?.allow_backorder??!1})},Qe=async()=>{if(!_)return;z(null);let L=_.variant?.allow_custom_amount??!1,$=null,F=null;if(!L){if($=zt(_.unitAmount,t),$===null||$<=0){z("Enter a valid price");return}if(_.compareAt.trim()&&(F=zt(_.compareAt,t),F===null||F<=$)){z("Compare-at price must be greater than the price");return}}let Re=_.onHand.trim()!==_.initialOnHand.trim(),te=parseInt(_.onHand,10);if(_.tracked&&Re&&(!Number.isFinite(te)||te<0)){z("On-hand quantity must be zero or more");return}try{if(fe(!0),_.variant)await n.updateVariant(_.variant.id,{title:_.title.trim()||null,sku:_.sku.trim()||null,...L?{}:{unit_amount:$,compare_at_amount:F},active:_.active}),await n.setVariantInventory(_.variant.id,{tracked:_.tracked,on_hand:_.tracked&&Re?te:void 0,allow_backorder:_.allowBackorder});else{let we={};for(let He of ee){let bt=_.optionValues[He.id];if(!bt){z(`Choose a ${He.title}`),fe(!1);return}we[He.title]=bt}await n.createVariant(e,{title:_.title.trim()||null,sku:_.sku.trim()||null,unit_amount:$,compare_at_amount:F,active:_.active,option_values:ee.length>0?we:void 0,inventory:_.tracked?{tracked:!0,on_hand:te,allow_backorder:_.allowBackorder}:{tracked:!1,allow_backorder:_.allowBackorder}})}await p(),f.current&&Y(null)}catch(we){if(f.current&&z(we instanceof Error?we.message:"Failed to save variant"),_.variant)try{let He=await n.getProduct(e);f.current&&o(He)}catch{}}finally{f.current&&fe(!1)}},ke=()=>b(async()=>{he&&(await n.deleteVariant(he.id),f.current&&M(null))}),Ge=_?.variant?.allow_custom_amount??!1,Je=_?.variant!=null&&_.variant.option_values.length===0&&ee.length>0&&!_.variant.active,Fe=_?.variant?.inventory!=null&&_.variant.inventory.on_hand<0?-_.variant.inventory.on_hand:null;function _t(L){let $=L.inventory;if(!$||!$.tracked)return(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let F=$.available??$.on_hand;return F<0?(0,O.jsxs)("span",{children:[-F," backordered"]}):(0,O.jsxs)("span",{children:[F," in stock",$.allow_backorder&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return c?(0,O.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:(0,O.jsx)(Za.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):l?(0,O.jsx)("div",{className:s,children:(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l})}):(0,O.jsxs)("div",{className:`af-space-y-6 ${s||""}`,children:[(0,O.jsxs)("div",{className:"af-space-y-3",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)(Oe,{children:"Options"}),(0,O.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),ee.length>0&&(0,O.jsx)("div",{className:"af-space-y-3",children:ee.map(L=>(0,O.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)("span",{className:"af-text-sm af-font-medium",children:L.title}),(0,O.jsx)(x,{variant:"ghost",size:"sm",onClick:()=>D(L),disabled:g,children:(0,O.jsx)(Za.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,O.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:L.values.map($=>(0,O.jsxs)(oe,{variant:"secondary",className:"af-gap-1",children:[$.value,(0,O.jsx)("button",{type:"button",onClick:()=>E(L,$.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:(0,O.jsx)(Za.X,{className:"af-h-3 af-w-3"})})]},$.id))}),(0,O.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,O.jsx)(re,{value:C[L.id]??"",onChange:$=>k(F=>({...F,[L.id]:$.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),N(L))},disabled:g}),(0,O.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>N(L),disabled:g||!(C[L.id]??"").trim(),children:(0,O.jsx)(Za.Plus,{className:"af-h-4 af-w-4"})})]})]},L.id))}),(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,O.jsx)(re,{id:"new-option-title",value:w,onChange:L=>P(L.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),(0,O.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,O.jsx)(Oe,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,O.jsx)(re,{id:"new-option-values",value:T,onChange:L=>y(L.target.value),placeholder:"S, M, L",disabled:g})]}),(0,O.jsxs)(x,{type:"button",variant:"outline",onClick:I,disabled:g||!w.trim()||!T.trim(),children:[(0,O.jsx)(Za.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,O.jsxs)("div",{className:"af-space-y-3",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)(Oe,{children:"Variants"}),(0,O.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:ve,disabled:g||ee.length===0,children:[(0,O.jsx)(Za.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ee.length===0&&(0,O.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),U.length===0?(0,O.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,O.jsxs)(et,{children:[(0,O.jsx)(tt,{children:(0,O.jsxs)(Ie,{children:[(0,O.jsx)(j,{children:"Variant"}),(0,O.jsx)(j,{children:"SKU"}),(0,O.jsx)(j,{children:"Price"}),(0,O.jsx)(j,{children:"Stock"}),(0,O.jsx)(j,{children:"Status"}),(0,O.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,O.jsx)(at,{children:U.map(L=>(0,O.jsxs)(Ie,{children:[(0,O.jsx)(G,{className:"af-font-medium",children:qi(L)}),(0,O.jsx)(G,{className:"af-text-muted-foreground",children:L.sku||"-"}),(0,O.jsx)(G,{children:L.unit_amount!=null?(0,O.jsxs)("span",{children:[L.compare_at_amount!=null&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:Z(L.compare_at_amount,L.currency)}),Z(L.unit_amount,L.currency)]}):L.allow_custom_amount?(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,O.jsx)(G,{children:_t(L)}),(0,O.jsx)(G,{children:(0,O.jsx)(oe,{variant:L.active?"success":"secondary",children:L.active?"Active":"Inactive"})}),(0,O.jsx)(G,{className:"af-text-right",children:(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,O.jsx)(x,{variant:"ghost",size:"sm",onClick:()=>me(L),disabled:g,children:"Edit"}),(0,O.jsx)(x,{variant:"ghost",size:"icon",onClick:()=>M(L),disabled:g,title:"Delete variant",children:(0,O.jsx)(Za.Trash2,{className:"af-h-4 af-w-4"})})]})})]},L.id))})]})]}),m&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m}),(0,O.jsx)(ja,{open:_!==null,onOpenChange:L=>{!L&&!le&&Y(null)},children:(0,O.jsxs)(Ea,{children:[(0,O.jsxs)(Ia,{children:[(0,O.jsx)(Aa,{children:_?.variant?"Edit variant":"Add variant"}),(0,O.jsx)(La,{children:"Price, markdown, and stock live on the variant."})]}),_&&(0,O.jsxs)("div",{className:"af-space-y-3",children:[_.variant?_.variant.option_values.length>0&&(0,O.jsxs)("div",{className:"af-text-sm",children:[(0,O.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),qi(_.variant)]}):ee.map(L=>(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{className:"af-text-xs af-text-muted-foreground",children:L.title}),(0,O.jsxs)(qa,{value:_.optionValues[L.id]??"",onValueChange:$=>Y(F=>F&&{...F,optionValues:{...F.optionValues,[L.id]:$}}),children:[(0,O.jsx)(ka,{children:(0,O.jsx)(Wa,{placeholder:`Choose ${L.title}`})}),(0,O.jsx)(Ta,{children:L.values.map($=>(0,O.jsx)(dt,{value:$.value,children:$.value},$.id))})]})]},L.id)),Ge?(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,O.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,O.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsxs)(Oe,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,O.jsx)(re,{id:"variant-price",type:"number",min:"0",step:a,value:_.unitAmount,onChange:L=>Y($=>$&&{...$,unitAmount:L.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,O.jsx)(re,{id:"variant-compare",type:"number",min:"0",step:a,value:_.compareAt,onChange:L=>Y($=>$&&{...$,compareAt:L.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,O.jsx)(re,{id:"variant-sku",value:_.sku,onChange:L=>Y($=>$&&{...$,sku:L.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,O.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,O.jsx)("input",{type:"checkbox",checked:_.tracked,onChange:L=>Y($=>$&&{...$,tracked:L.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),_.tracked&&(0,O.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,O.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(Oe,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,O.jsx)(re,{id:"variant-onhand",type:"number",min:"0",step:"1",value:_.onHand,onChange:L=>Y($=>$&&{...$,onHand:L.target.value}),placeholder:Fe!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,O.jsx)("input",{type:"checkbox",checked:_.allowBackorder,onChange:L=>Y($=>$&&{...$,allowBackorder:L.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Fe!=null&&(0,O.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Fe," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,O.jsx)("input",{type:"checkbox",checked:_.active,onChange:L=>Y($=>$&&{...$,active:L.target.checked}),className:"af-h-4 af-w-4",disabled:Je}),"Active (buyers can purchase this variant)"]}),Je&&(0,O.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),Q&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Q})]}),(0,O.jsxs)(Da,{children:[(0,O.jsx)(x,{variant:"outline",onClick:()=>Y(null),disabled:le,children:"Cancel"}),(0,O.jsxs)(x,{onClick:Qe,disabled:le,children:[le?(0,O.jsx)(Za.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,_?.variant?"Save":"Add variant"]})]})]})}),(0,O.jsx)(ja,{open:he!==null,onOpenChange:L=>{!L&&!g&&M(null)},children:(0,O.jsxs)(Ea,{children:[(0,O.jsxs)(Ia,{children:[(0,O.jsx)(Aa,{children:"Delete variant?"}),(0,O.jsx)(La,{children:he&&`"${qi(he)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,O.jsxs)(Da,{children:[(0,O.jsx)(x,{variant:"outline",onClick:()=>M(null),disabled:g,children:"Cancel"}),(0,O.jsx)(x,{variant:"destructive",onClick:ke,disabled:g,children:"Delete"})]})]})})]})}var X=require("react/jsx-runtime");function Iu(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,n)).toFixed(1))} ${s[n]}`}function or({productsState:e,product:t,currency:s,onSaved:n,className:a}){let{createProduct:r,updateProduct:o,attachProductFile:c,attachProductFileFromUrl:d}=e,l=!!t,i=t?.currency??s,m=Fa(i)?"1":"0.01",v=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,u]=pt.useState(!1),[f,p]=pt.useState(null),b=pt.useRef(!0);pt.useEffect(()=>(b.current=!0,()=>{b.current=!1}),[]);let[w,P]=pt.useState(t?.name??""),[T,y]=pt.useState(t?.description??""),[C,k]=pt.useState(t?.allow_custom_amount?"custom":"fixed"),[I,N]=pt.useState(t?.unit_amount!=null?String(mt(t.unit_amount,i)):""),[E,D]=pt.useState(t?.min_amount!=null?String(mt(t.min_amount,i)):""),[_,Y]=pt.useState(t?.max_amount!=null?String(mt(t.max_amount,i)):""),[Q,z]=pt.useState(String(t?.max_quantity??10)),le=pt.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(mt(t.unit_amount,i)):"",minAmount:t?.min_amount!=null?String(mt(t.min_amount,i)):"",maxAmount:t?.max_amount!=null?String(mt(t.max_amount,i)):"",maxQuantity:String(t?.max_quantity??10)}).current,[fe,he]=pt.useState(t?.collect_shipping_address??!1),[M,ee]=pt.useState(t?.active??!0),[U,ve]=pt.useState(t?.images??[]),[me,Qe]=pt.useState(""),[ke,Ge]=pt.useState(t?.fulfillment??null),[Je,Fe]=pt.useState(!1),[_t,L]=pt.useState(""),[$,F]=pt.useState(null),Re=pt.useRef(null),te=g||Je,we=()=>{let xe=me.trim();if(xe){if(U.includes(xe)){p("This image URL is already added");return}ve(Me=>[...Me,xe]),Qe(""),p(null)}},He=xe=>{ve(Me=>Me.filter(yt=>yt!==xe))},bt=async()=>{if(p(null),!w.trim()){p("Product name is required");return}let xe=null,Me=null,yt=null,Pa=!l||C!==le.pricingMode||(C==="fixed"?I!==le.unitAmount:E!==le.minAmount||_!==le.maxAmount),Kt=!l||Q!==le.maxQuantity,fa=v||C==="fixed";if(!(v||!Pa))if(C==="fixed"){if(xe=zt(I,i),xe===null||xe<=0){p("Enter a valid price");return}}else{if(Me=zt(E,i),yt=zt(_,i),Me===null||yt===null){p("Enter valid minimum and maximum amounts");return}if(yt<Me){p("Maximum amount must be at least the minimum amount");return}}let Xt=parseInt(Q,10);if(fa&&Kt&&(!Number.isFinite(Xt)||Xt<1)){p("Max quantity must be at least 1");return}try{u(!0);let rt;if(l&&t){let ht={name:w.trim(),description:T.trim()||null,images:U,collect_shipping_address:fe,active:M};!v&&Pa&&(ht.allow_custom_amount=C==="custom",C==="fixed"?ht.unit_amount=xe:(ht.min_amount=Me,ht.max_amount=yt)),fa&&Kt&&(ht.max_quantity=Xt),rt=await o(t.id,ht),le.pricingMode=rt.allow_custom_amount?"custom":"fixed",le.unitAmount=rt.unit_amount!=null?String(mt(rt.unit_amount,i)):"",le.minAmount=rt.min_amount!=null?String(mt(rt.min_amount,i)):"",le.maxAmount=rt.max_amount!=null?String(mt(rt.max_amount,i)):"",le.maxQuantity=String(rt.max_quantity)}else{let ht={name:w.trim(),allow_custom_amount:C==="custom",collect_shipping_address:fe,active:M};T.trim()&&(ht.description=T.trim()),U.length>0&&(ht.images=U),C==="fixed"?(ht.unit_amount=xe,ht.max_quantity=Xt):(ht.min_amount=Me,ht.max_amount=yt),rt=await r(ht)}if(!b.current)return;Ge(rt.fulfillment),n?.(rt)}catch(rt){if(!b.current)return;p(rt instanceof Error?rt.message:"Failed to save product")}finally{b.current&&u(!1)}},Ze=async xe=>{let Me=xe.target.files?.[0];if(!(!Me||!t))try{Fe(!0),F(null);let yt=await c(t.id,Me);if(!b.current)return;Ge(yt.fulfillment),n?.(yt)}catch(yt){if(!b.current)return;F(yt instanceof Error?yt.message:"Failed to upload file")}finally{b.current&&(Fe(!1),Re.current&&(Re.current.value=""))}},Ct=async()=>{let xe=_t.trim();if(!(!xe||!t))try{Fe(!0),F(null);let Me=await d(t.id,xe);if(!b.current)return;Ge(Me.fulfillment),L(""),n?.(Me)}catch(Me){if(!b.current)return;F(Me instanceof Error?Me.message:"Failed to fetch file")}finally{b.current&&Fe(!1)}};return(0,X.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{htmlFor:"product-name",children:"Name"}),(0,X.jsx)(re,{id:"product-name",value:w,onChange:xe=>P(xe.target.value),placeholder:"My product"})]}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{htmlFor:"product-description",children:"Description"}),(0,X.jsx)("textarea",{id:"product-description",value:T,onChange:xe=>y(xe.target.value),rows:3,placeholder:"Shown on the Stripe checkout page.",className:"af-flex af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring"})]}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{children:"Pricing"}),v?(0,X.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(qa,{value:C,onValueChange:xe=>k(xe),children:[(0,X.jsx)(ka,{className:"af-w-[260px]",children:(0,X.jsx)(Wa,{})}),(0,X.jsxs)(Ta,{children:[(0,X.jsx)(dt,{value:"fixed",children:"Fixed price"}),(0,X.jsx)(dt,{value:"custom",children:"Buyer chooses the amount"})]})]}),C==="fixed"?(0,X.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsxs)(Oe,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",i.toUpperCase(),")"]}),(0,X.jsx)(re,{id:"product-price",type:"number",min:"0",step:m,value:I,onChange:xe=>N(xe.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsxs)(Oe,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",i.toUpperCase(),")"]}),(0,X.jsx)(re,{id:"product-min-amount",type:"number",min:"0",step:m,value:E,onChange:xe=>D(xe.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsxs)(Oe,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",i.toUpperCase(),")"]}),(0,X.jsx)(re,{id:"product-max-amount",type:"number",min:"0",step:m,value:_,onChange:xe=>Y(xe.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,X.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Buyers pick their own amount within these bounds (tip jar, pay-what-you-want). Quantity is always 1."})]}),(0,X.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",i.toUpperCase(),"), which follows the country of your payment account."]})]}),(v||C==="fixed")&&(0,X.jsxs)("div",{className:"af-space-y-1",children:[(0,X.jsx)(Oe,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,X.jsx)(re,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:Q,onChange:xe=>z(xe.target.value),className:"af-w-[140px]"})]})]}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{children:"Images"}),(0,X.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,X.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[U.map(xe=>(0,X.jsxs)(oe,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,X.jsx)("span",{className:"af-truncate",children:xe}),(0,X.jsx)("button",{type:"button",onClick:()=>He(xe),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:(0,X.jsx)(Ua.X,{className:"af-h-3 af-w-3"})})]},xe)),U.length===0&&(0,X.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,X.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,X.jsx)(re,{type:"url",value:me,onChange:xe=>Qe(xe.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:xe=>{xe.key==="Enter"&&(xe.preventDefault(),we())},disabled:g}),(0,X.jsx)(x,{type:"button",variant:"outline",onClick:we,disabled:!me.trim()||g,children:(0,X.jsx)(Ua.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{children:"Digital File"}),(0,X.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, Word, Excel, PowerPoint, CSV, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),l?(0,X.jsxs)("div",{className:"af-space-y-3",children:[ke?.type==="download"&&(0,X.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,X.jsx)(Ua.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,X.jsx)("span",{className:"af-text-sm",children:ke.filename}),ke.size!=null&&(0,X.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Iu(ke.size),")"]})]}),ke?.type==="redirect"&&ke.url&&(0,X.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,X.jsx)(Ua.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,X.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",ke.url]})]}),(0,X.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,X.jsx)("input",{ref:Re,type:"file",onChange:Ze,className:"af-hidden",disabled:te}),(0,X.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>Re.current?.click(),disabled:te,children:[Je?(0,X.jsx)(Ua.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,X.jsx)(Ua.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),ke?.type==="download"?"Replace file":"Upload file"]}),(0,X.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,X.jsx)(re,{type:"url",value:_t,onChange:xe=>L(xe.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Je}),(0,X.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:Ct,disabled:!_t.trim()||te,children:"Fetch from URL"})]}),$&&(0,X.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:$})]}):(0,X.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsx)(Oe,{children:"Settings"}),(0,X.jsxs)("div",{className:"af-space-y-2",children:[(0,X.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,X.jsx)("input",{type:"checkbox",checked:fe,onChange:xe=>he(xe.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,X.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,X.jsx)("input",{type:"checkbox",checked:M,onChange:xe=>ee(xe.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),l&&t&&(0,X.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,X.jsx)(Oe,{children:"Options & Variants"}),(0,X.jsx)(ir,{productId:t.id,currency:i})]}),f&&(0,X.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f}),(0,X.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,X.jsxs)(x,{type:"button",onClick:bt,disabled:te,children:[g?(0,X.jsx)(Ua.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,l?"Save changes":"Create product"]})})]})}var Mt=ie(require("react"),1),Ma=require("lucide-react");var xt=ie(require("react"),1);var Du=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function lr({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=W(),[n,a]=xt.useState([]),[r,o]=xt.useState(0),[c,d]=xt.useState(!0),[l,i]=xt.useState(null),[m,v]=xt.useState(0),[g,u]=xt.useState(e),[f,p]=xt.useState(void 0),[b,w]=xt.useState(""),[P,T]=xt.useState(""),[y,C]=xt.useState(""),[k,I]=xt.useState(!1),[N,E]=xt.useState(!1),[D,_]=xt.useState(void 0),Y=D?D.join(","):"",Q=xt.useMemo(()=>{if(!Y)return;let M=new Set(Y.split(","));return Du.filter(ee=>!M.has(ee))},[Y]),z=xt.useMemo(()=>{let M={};return f?M.status=f:Q?M.excludeStatus=Q:k||(M.excludeStatus=["pending","expired"]),b.trim()&&(M.customerEmail=b.trim()),P.trim()&&(M.from=P.trim()),y.trim()&&(M.to=y.trim()),N&&(M.unfulfilledOnly=!0),M},[f,Q,k,b,P,y,N]),le=xt.useRef(0),fe=xt.useCallback(async()=>{let M=++le.current;try{d(!0),i(null);let ee={...z,limit:g,offset:m*g},U=await s.getOrders(ee);if(M!==le.current)return;a(U.orders),o(U.total)}catch(ee){if(M!==le.current)return;i(ee instanceof Error?ee:new Error("Failed to fetch orders"))}finally{M===le.current&&d(!1)}},[s,m,g,z,t]);xt.useEffect(()=>{fe()},[fe]);let he=Math.ceil(r/g);return{orders:n,total:r,isLoading:c,error:l,page:m,pageSize:g,hasNextPage:m<he-1,hasPreviousPage:m>0,setPage:v,setPageSize:M=>{u(M),v(0)},status:f,setStatus:M=>{p(M),v(0)},statusIn:D,setStatusIn:M=>{_(M&&M.length>0?M:void 0),v(0)},customerEmail:b,setCustomerEmail:M=>{w(M),v(0)},from:P,setFrom:M=>{T(M),v(0)},to:y,setTo:M=>{C(M),v(0)},showAbandoned:k,setShowAbandoned:M=>{I(M),v(0)},unfulfilledOnly:N,setUnfulfilledOnly:M=>{E(M),v(0)},clearFilters:()=>{p(void 0),_(void 0),I(!1),E(!1),w(""),T(""),C(""),v(0)},filters:z,refetch:fe}}var Tt=ie(require("react"),1),ze=require("lucide-react");var vl=ie(require("react"),1),bs=ie(require("@radix-ui/react-popover"),1);var Yr=require("react/jsx-runtime"),Jr=bs.Root,Xr=bs.Trigger;var cr=vl.forwardRef(({className:e,align:t="end",sideOffset:s=4,...n},a)=>(0,Yr.jsx)(bs.Portal,{children:(0,Yr.jsx)("div",{className:"aifeatures-admin",children:(0,Yr.jsx)(bs.Content,{ref:a,align:t,sideOffset:s,className:J("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...n})})}));cr.displayName=bs.Content.displayName;var ur=require("react/jsx-runtime"),Au={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Lu(e){return Au[e]??e}function bl(e){switch(e){case"paid":return"success";case"pending":return"secondary";case"refunded":case"partially_refunded":return"warning";case"disputed":return"destructive";default:return"outline"}}function rn({status:e,className:t}){return(0,ur.jsx)(oe,{variant:bl(e),className:t,children:Lu(e)})}function Gs({status:e}){return(0,ur.jsx)(rn,{status:e})}function Pn({order:e,className:t}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,ur.jsx)(oe,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,ur.jsx)(oe,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Is(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var h=require("react/jsx-runtime"),Sl="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",on="af-text-xs af-text-muted-foreground";function Wi(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Ou(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wl(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var Qr=24,Bu=["paid","partially_refunded"],Fu=["paid","partially_refunded","disputed"],Uu=/^[A-Za-z0-9 _-]*$/,yl=100;function Ki(e,t,s,n,a){let r=Bu.includes(n);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${Qr} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${Qr} tries used). Nothing is being retried while the order is ${n.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?s<Qr&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:s<Qr&&e==="buyer"&&!a?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${s} attempt${s===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${n==="refunded"?"because the order was refunded":n==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function hl({title:e,recipient:t,status:s,attempts:n,side:a,orderStatus:r,action:o,delivery:c}){if(c)return(0,h.jsxs)("div",{children:[(0,h.jsx)(ps,{deliveries:[c]}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]});let d=Ki(a,s,n,r,t);return(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsx)("div",{className:"af-text-sm",children:e}),t&&(0,h.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,h.jsx)(oe,{variant:d.variant,className:"af-shrink-0",children:d.label})]}),d.detail&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:d.detail}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]})}function xl(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let s=Ou(e.address)?e.address:null;if(s){for(let a of["line1","line2"]){let r=s[a];typeof r=="string"&&r&&t.push(r)}let n=["city","state","postal_code"].map(a=>s[a]).filter(a=>typeof a=="string"&&!!a).join(", ");n&&t.push(n),typeof s.country=="string"&&s.country&&t.push(s.country)}return t.length>0?t:Object.entries(e).map(([n,a])=>`${n}: ${wl(a)}`)}function Mu(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Zi({value:e,label:t,children:s,className:n,size:a="icon"}){let[r,o]=Tt.useState(!1);if(!Mu())return null;let c=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},d=r?(0,h.jsx)(ze.Check,{className:"af-h-3 af-w-3"}):(0,h.jsx)(ze.Copy,{className:"af-h-3 af-w-3"});return a==="icon"?(0,h.jsx)(x,{variant:"ghost",size:"icon",className:J("af-h-6 af-w-6 af-shrink-0",n),onClick:c,title:t,"aria-label":t,children:d}):(0,h.jsxs)(x,{variant:"outline",size:"sm",className:n,onClick:c,"aria-label":t,children:[r?(0,h.jsx)(ze.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,h.jsx)(ze.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":s]})}function ji({label:e,value:t}){return(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:on,children:e}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,h.jsx)(Zi,{value:t,label:`Copy ${e}`})]})]})}function $u({src:e}){let[t,s]=Tt.useState(!1);return!e||t?(0,h.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-10 af-w-10 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-muted",children:(0,h.jsx)(ze.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,h.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>s(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function ys({title:e,action:t,children:s,className:n}){return(0,h.jsxs)("section",{className:J("af-rounded-lg af-border af-p-4",n),children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,h.jsx)("h4",{className:Sl,children:e}),t]}),(0,h.jsx)("div",{className:"af-mt-3",children:s})]})}function va({label:e,emphasis:t,divider:s,children:n}){return(0,h.jsxs)("div",{className:J("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[(0,h.jsx)("span",{className:t?"af-text-base af-font-semibold":on,children:e}),(0,h.jsx)("span",{className:J("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:n})]})}function Gi({onSelect:e,disabled:t,icon:s,children:n}){return(0,h.jsxs)(x,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,h.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),n]})}function Vu(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?t.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${Z(Kr(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(a=>a.kind==="purchase_receipt"),n=s?qr(s):Ki("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(a=>a.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${n.label.toLowerCase()}`,at:null,tone:n.variant==="destructive"?"destructive":n.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(a=>a.kind==="merchant_sale"),n=s?qr(s):Ki("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(a=>a.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${n.label.toLowerCase()}`,at:null,tone:n.variant==="destructive"?"destructive":n.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${Z(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function dr({order:e,onBack:t,onRefund:s,onOrderUpdated:n,allowFulfillment:a=!1,onPrevOrder:r,onNextOrder:o,hasPrevOrder:c=!1,hasNextOrder:d=!1}){let{api:l}=W(),[i,m]=Tt.useState(e),[v,g]=Tt.useState(null),[u,f]=Tt.useState(null),[p,b]=Tt.useState(!1),[w,P]=Tt.useState(!1),[T,y]=Tt.useState(!1),[C,k]=Tt.useState(!1),[I,N]=Tt.useState(""),[E,D]=Tt.useState(!1),[_,Y]=Tt.useState(null),[Q,z]=Tt.useState(!1),[le,fe]=Tt.useState(""),[he,M]=Tt.useState([]),[ee,U]=Tt.useState(!1),[ve,me]=Tt.useState(!1),[Qe,ke]=Tt.useState(null);Tt.useEffect(()=>{m(e)},[e]);let Ge=B=>{let Ke=B.id===i.id&&B.email_deliveries===void 0?{...B,email_deliveries:i.email_deliveries}:B;m(Ke),n?.(Ke)},Je=Object.entries(i.metadata??{}),Fe=Math.max(0,Kr(i)-i.amount_refunded),_t=(i.status==="paid"||i.status==="partially_refunded")&&Fe>0,L=i.exclusive_tax_total!=null,$=B=>typeof B.amountNet=="number"?B.amountNet+(B.exclusiveTax??0):(typeof B.unitAmount=="number"?B.unitAmount:0)*(typeof B.quantity=="number"&&B.quantity>0?B.quantity:1),F=Math.max(0,(i.shipping_total??0)-(i.shipping_refunded??0)),Re=he.reduce((B,Ke)=>B+$(i.line_items[Ke]??{}),0)+(ee?F:0),te=i.tax_total??0,we=Math.max(0,(i.exclusive_tax_total??0)-i.line_items.reduce((B,Ke)=>B+(Ke.exclusiveTax??0),0)),He=L?ee&&F>0?we:0:i.automatic_tax&&i.tax_behavior==="exclusive"&&te>0&&i.amount_total+(i.shipping_total??0)>0?Math.min(Math.max(0,te-(i.tax_refunded??0)),Math.round(te*Re/(i.amount_total+(i.shipping_total??0)))):0,bt=i.source==="subscription"&&(i.credit_applied??0)>0&&i.line_items.length===1?Math.min(Re+He,Fe):Re+He,Ze=he.length>0||ee,Ct=Ze?bt:zt(le,i.currency),xe=Fa(i.currency)?"1":"0.01",Me=async()=>{try{b(!0),g(null),f(null),await l.resendOrderReceipt(i.id);let B=await l.getOrder(i.id);Ge(B),f("Receipt email queued.")}catch(B){g(B instanceof Error?B.message:"Failed to resend receipt")}finally{b(!1)}},yt=async()=>{try{P(!0),g(null),f(null);let B=await l.resetOrderDownloads(i.id);Ge(B),y(!1),f("Download count reset.")}catch(B){g(B instanceof Error?B.message:"Failed to reset downloads")}finally{P(!1)}},Pa=i.line_items.some(B=>B.collectShippingAddress===!0&&!B.refunded&&!B.unavailableReason),Kt=typeof i.merchant_fulfilled_at=="string",fa=Fu.includes(i.status)||i.status==="refunded"&&i.line_items.some(B=>B.collectShippingAddress===!0&&B.amountNet===0&&!B.refunded&&!B.unavailableReason),Xt=I.trim(),rt=Uu.test(Xt)&&Xt.length<=yl,ht=async B=>{try{D(!0),Y(null),f(null);let Ke=await l.setOrderFulfillment(i.id,{fulfilled:B,...B&&Xt?{trackingNumber:Xt}:{}});Ge(Ke),N(""),f(B?"Marked as shipped.":"Marked as not shipped.")}catch(Ke){Ke instanceof Dt&&Ke.status===409?Y(`This order is ${i.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Y(Ke instanceof Error?Ke.message:"Failed to update the order")}finally{D(!1)}},ss=()=>{ke(null),fe(String(mt(Fe,i.currency))),M([]),U(!1),z(!0)},en=B=>M(Ke=>Ke.includes(B)?Ke.filter(pa=>pa!==B):[...Ke,B]),ma=async(B,Ke)=>{if(s)try{me(!0),ke(null),await s(i,B,Ke);let pa=await l.getOrder(i.id);Ge(pa),z(!1),f("Refund issued.")}catch(pa){ke(pa instanceof Error?pa.message:"Refund failed")}finally{me(!1)}},Oi=async()=>{if(Ze){if(bt<=0){ke("The lines you picked were charged nothing");return}if(bt>Fe){ke(`That selection exceeds the refundable remainder (${Z(Fe,i.currency)})`);return}await ma(bt,{...he.length>0?{line_items:[...he].sort((Ke,pa)=>Ke-pa)}:{},...ee?{shipping:!0}:{}});return}let B=zt(le,i.currency);if(B===null||B<=0){ke("Enter a valid refund amount");return}if(B>Fe){ke(`Amount exceeds the refundable remainder (${Z(Fe,i.currency)})`);return}await ma(B,{amount:B})},K=()=>ma(Fe,{full:!0}),ct=!i.subscription_history_only&&i.fulfillment_type==="download",fs=!i.subscription_history_only&&a&&Pa,Bi=Vu(i),se=i.shipping_address?xl(i.shipping_address).join(`
|
|
4
|
-
`):"",ia=i.shipping_total!=null,Fi=i.exclusive_tax_total??(i.automatic_tax&&i.tax_behavior==="exclusive"?i.tax_total??0:0),Oo=i.exclusive_tax_total!=null?Math.max(0,(i.tax_total??0)-Fi):i.automatic_tax&&i.tax_behavior==="exclusive"?0:i.tax_total??0,Bo=Fi>0,eu=Oo>0,Fo=i.amount_subtotal!=null||ia||Bo||(i.discount_total??0)>0,Vn=[];return i.subscription_history_only||Vn.push((0,h.jsx)(Gi,{icon:p?(0,h.jsx)(ze.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,h.jsx)(ze.Mail,{className:"af-h-4 af-w-4"}),disabled:p||i.fulfillment_status!=="fulfilled",onSelect:()=>{k(!1),Me()},children:"Resend receipt"},"resend")),ct&&Vn.push((0,h.jsx)(Gi,{icon:(0,h.jsx)(ze.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:w,onSelect:()=>{k(!1),y(!0)},children:"Reset download count"},"reset")),_t&&Vn.push((0,h.jsxs)("div",{children:[(0,h.jsx)(Gi,{icon:(0,h.jsx)(ze.Undo2,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{k(!1),ss()},children:"Refund\u2026"}),!s&&(0,h.jsx)("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-mb-6",children:[(0,h.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,h.jsx)(ze.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("h3",{className:"af-text-xl af-font-semibold",children:Is(i)}),(0,h.jsx)(rn,{status:i.status}),a&&!i.subscription_history_only&&(0,h.jsx)(Pn,{order:i}),i.is_test&&(0,h.jsx)(oe,{variant:"outline",children:"Test"})]}),(0,h.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Wi(i.created_at)]}),i.is_test&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||o)&&(0,h.jsxs)("div",{className:"af-flex af-items-center",children:[(0,h.jsx)(x,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!c,"aria-label":"Previous order",children:(0,h.jsx)(ze.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,h.jsx)(x,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!d,"aria-label":"Next order",children:(0,h.jsx)(ze.ChevronRight,{className:"af-h-4 af-w-4"})})]}),fs&&(Kt?(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",i.merchant_fulfilled_at?` \xB7 ${Wi(i.merchant_fulfilled_at)}`:""]}),fa&&(0,h.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>ht(!1),disabled:E,children:[E?(0,h.jsx)(ze.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(ze.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):fa?(0,h.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,h.jsx)(re,{value:I,onChange:B=>N(B.target.value),placeholder:"Tracking number (optional)",maxLength:yl,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:E}),(0,h.jsxs)(x,{variant:"default",className:"af-shrink-0",onClick:()=>ht(!0),disabled:E||!rt,children:[E?(0,h.jsx)(ze.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(ze.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Vn.length>0&&(0,h.jsxs)(Jr,{open:C,onOpenChange:k,children:[(0,h.jsx)(Xr,{asChild:!0,children:(0,h.jsx)(x,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,h.jsx)(ze.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,h.jsx)(cr,{children:(0,h.jsx)("div",{className:"af-space-y-0.5",children:Vn})})]})]})]}),fs&&!Kt&&!rt&&(0,h.jsx)("p",{className:"af-mt-2 af-text-xs af-text-destructive",children:"Tracking numbers can use letters, numbers, spaces, dashes and underscores \u2014 up to 100 characters."}),_&&(0,h.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:_}),u&&(0,h.jsx)("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:u}),v&&(0,h.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:v})]}),(0,h.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,h.jsxs)("div",{className:"af-space-y-6",children:[i.line_items.length>0&&(0,h.jsx)(ys,{title:"Items",children:(0,h.jsx)("ul",{className:"af-space-y-3",children:i.line_items.map((B,Ke)=>{let pa=typeof B.name=="string"&&B.name?B.name:"Item",Uo=typeof B.quantity=="number"&&B.quantity>0?B.quantity:1,Mo=typeof B.unitAmount=="number";return(0,h.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,h.jsx)($u,{src:typeof B.imageUrl=="string"&&B.imageUrl?B.imageUrl:void 0}),(0,h.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,h.jsxs)("div",{className:"af-text-sm af-font-medium",children:[pa,typeof B.variantTitle=="string"&&B.variantTitle&&(0,h.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",B.variantTitle]})]}),(0,h.jsxs)("div",{className:on,children:[Uo," \xD7"," ",Mo?Z(B.unitAmount,i.currency):"\u2014"]}),B.unavailableReason==="oversold"&&!B.refunded&&(0,h.jsx)(oe,{variant:"secondary",className:"af-mt-1",children:B.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),B.refunded===!0&&(0,h.jsx)(oe,{variant:"secondary",className:"af-mt-1",children:B.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,h.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof B.amountNet=="number"||Mo?Z(B.amountNet??B.unitAmount*Uo,i.currency):"\u2014"})]},Ke)})})}),Je.length>0&&(0,h.jsx)(ys,{title:"Order details",children:(0,h.jsx)("dl",{className:"af-space-y-2",children:Je.map(([B,Ke])=>(0,h.jsxs)("div",{children:[(0,h.jsx)("dt",{className:J(on,"af-capitalize"),children:B.replace(/_/g," ")}),(0,h.jsx)("dd",{className:"af-text-sm af-break-words",children:wl(Ke)})]},B))})}),(0,h.jsx)(ys,{title:"Totals",children:(0,h.jsxs)("div",{className:"af-w-full",children:[Fo&&(0,h.jsx)(va,{label:"Subtotal",children:Z(i.amount_subtotal??i.amount_total+(i.discount_total??0),i.currency)}),(i.discount_total??0)>0&&(0,h.jsxs)(va,{label:"Discount",children:["\u2212",Z(i.discount_total,i.currency)]}),ia&&(0,h.jsx)(va,{label:"Shipping",children:i.shipping_total===0?"Free":Z(i.shipping_total??0,i.currency)}),Bo&&(0,h.jsx)(va,{label:"Tax",children:Z(Fi,i.currency)}),(0,h.jsx)(va,{label:"Total",emphasis:!0,divider:Fo,children:Z(vs(i),i.currency)}),(i.credit_applied??0)>0&&(0,h.jsxs)(va,{label:"Credit applied",children:["\u2212",Z(i.credit_applied,i.currency)]}),i.amount_paid!=null&&(0,h.jsx)(va,{label:"Amount paid",children:Z(i.amount_paid,i.currency)}),eu&&(0,h.jsx)(va,{label:"incl. tax",children:Z(Oo,i.currency)}),i.base_currency!=null&&i.base_amount_total!=null&&(0,h.jsxs)(va,{label:"Your price",children:[Z(i.base_amount_total,i.base_currency),(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",i.currency.toUpperCase()]})]}),i.amount_refunded>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(va,{label:"Refunded",children:["\u2212",Z(i.amount_refunded,i.currency),(i.shipping_refunded??0)>0&&(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",Z(i.shipping_refunded??0,i.currency)," ","shipping"]})]}),(0,h.jsx)(va,{label:"Net",children:(0,h.jsx)("span",{className:"af-font-medium",children:Z(Math.max(0,Kr(i)-i.amount_refunded),i.currency)})})]})]})}),i.application_fee_state&&(0,h.jsxs)(ys,{title:"Platform fee",children:[i.application_fee_original!=null&&(0,h.jsx)(va,{label:"Collected",children:Z(i.application_fee_original,i.application_fee_currency??i.currency)}),i.application_fee_returned!=null&&(0,h.jsx)(va,{label:"Returned",children:Z(i.application_fee_returned,i.application_fee_currency??i.currency)}),i.application_fee_retained!=null&&(0,h.jsx)(va,{label:"Retained",children:Z(i.application_fee_retained,i.application_fee_currency??i.currency)}),i.application_fee_state!=="complete"&&(0,h.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:i.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,h.jsx)(ys,{title:"Timeline",children:(0,h.jsx)("ol",{className:"af-space-y-3",children:Bi.map(B=>(0,h.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,h.jsx)("span",{"aria-hidden":"true",className:J("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",B.tone==="destructive"?"af-bg-destructive":B.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsx)("div",{className:"af-text-sm af-break-words",children:B.text}),B.at&&(0,h.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:Wi(B.at)})]})]},B.key))})})]}),(0,h.jsxs)("div",{className:"af-space-y-6",children:[(0,h.jsx)(ys,{title:"Customer",children:(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:on,children:"Email"}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:i.customer_email||(0,h.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),i.customer_email&&(0,h.jsx)(Zi,{value:i.customer_email,label:"Copy email"})]})]}),i.customer_name&&(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:on,children:"Name"}),(0,h.jsx)("div",{className:"af-text-sm",children:i.customer_name})]}),i.customer&&(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:on,children:"Customer record"}),(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("span",{className:"af-break-all af-text-sm",children:i.customer.name||i.customer.email}),(0,h.jsx)(oe,{variant:"secondary",children:"Linked"})]})]})]})}),i.shipping_address&&(0,h.jsx)(ys,{title:"Ship to",action:(0,h.jsx)(Zi,{value:se,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,h.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:xl(i.shipping_address).map((B,Ke)=>(0,h.jsx)("div",{children:B},Ke))})}),i.subscription_history_only?(0,h.jsx)(ys,{title:"Subscription history",children:(0,h.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This renewal had no payment due. No items were fulfilled and no purchase receipt was sent."})}):(0,h.jsxs)(ys,{title:"Emails",children:[(0,h.jsx)(ps,{deliveries:i.email_deliveries?.filter(B=>!["purchase_receipt","merchant_sale"].includes(B.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,h.jsxs)("div",{className:"af-space-y-4",children:[(0,h.jsx)(hl,{side:"buyer",title:"Receipt to buyer",delivery:i.email_deliveries?.find(B=>B.kind==="purchase_receipt"),recipient:i.customer_email,status:i.buyer_email_status,attempts:i.buyer_email_attempts,orderStatus:i.status,action:(0,h.jsxs)(x,{variant:"outline",size:"sm",onClick:Me,disabled:p||i.fulfillment_status!=="fulfilled",children:[p?(0,h.jsx)(ze.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(ze.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,h.jsx)(hl,{side:"merchant",title:"Sale alert to you",delivery:i.email_deliveries?.find(B=>B.kind==="merchant_sale"),recipient:null,status:i.merchant_email_status,attempts:i.merchant_email_attempts,orderStatus:i.status})]})]}),ct&&(0,h.jsx)(ys,{title:"Download",children:(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,h.jsx)(ze.Download,{className:"af-h-4 af-w-4"}),(0,h.jsxs)("span",{children:["Downloaded ",i.download_count," time",i.download_count===1?"":"s"]})]}),i.download_url&&(0,h.jsx)("a",{href:i.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,h.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,h.jsx)("summary",{className:J(Sl,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,h.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,h.jsx)(ji,{label:"Order ID",value:i.id}),i.stripe_checkout_session_id&&(0,h.jsx)(ji,{label:"Checkout session",value:i.stripe_checkout_session_id}),i.stripe_payment_intent_id&&(0,h.jsx)(ji,{label:"Payment",value:i.stripe_payment_intent_id})]})]})]})]}),(0,h.jsx)(ja,{open:T,onOpenChange:B=>{!B&&!w&&y(!1)},children:(0,h.jsxs)(Ea,{children:[(0,h.jsxs)(Ia,{children:[(0,h.jsx)(Aa,{children:"Reset download count?"}),(0,h.jsx)(La,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,h.jsxs)(Da,{children:[(0,h.jsx)(x,{variant:"outline",onClick:()=>y(!1),disabled:w,children:"Cancel"}),(0,h.jsx)(x,{onClick:yt,disabled:w,children:w?"Resetting...":"Reset"})]})]})}),(0,h.jsx)(ja,{open:Q,onOpenChange:B=>{!B&&!ve&&z(!1)},children:(0,h.jsxs)(Ea,{children:[(0,h.jsxs)(Ia,{children:[(0,h.jsx)(Aa,{children:"Refund order"}),(0,h.jsxs)(La,{children:["Refund up to ",Z(Fe,i.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,h.jsxs)("div",{className:"af-space-y-4",children:[(i.line_items.length>0||F>0)&&(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsx)(Oe,{children:"Items"}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[i.line_items.map((B,Ke)=>{let pa=B.refunded===!0;return(0,h.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,h.jsx)("input",{type:"checkbox",checked:he.includes(Ke),onChange:()=>en(Ke),disabled:ve||pa||!!B.unavailableReason||$(B)<=0,className:"af-h-4 af-w-4"}),(0,h.jsxs)("span",{className:pa?"af-text-muted-foreground af-line-through":void 0,children:[typeof B.name=="string"&&B.name?B.name:"Item",typeof B.variantTitle=="string"&&B.variantTitle?` \u2014 ${B.variantTitle}`:"",typeof B.quantity=="number"&&B.quantity>1?` \xD7 ${B.quantity}`:""]}),(0,h.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:pa?"Refunded":Z($(B),i.currency)})]},Ke)}),F>0&&(0,h.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,h.jsx)("input",{type:"checkbox",checked:ee,onChange:B=>U(B.target.checked),disabled:ve,className:"af-h-4 af-w-4"}),(0,h.jsx)("span",{children:"Shipping"}),(0,h.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Z(F,i.currency)})]})]})]}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)(Oe,{htmlFor:"refund-amount",children:["Amount (",i.currency.toUpperCase(),")"]}),(0,h.jsx)(re,{id:"refund-amount",type:"number",min:"0",step:xe,value:Ze?String(mt(bt,i.currency)):le,onChange:B=>fe(B.target.value),disabled:ve||Ze}),Ze&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Qe&&(0,h.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Qe}),(0,h.jsxs)(Da,{children:[(0,h.jsx)(x,{variant:"outline",onClick:()=>z(!1),disabled:ve,children:"Cancel"}),(0,h.jsx)(x,{variant:"outline",onClick:K,disabled:ve,children:"Refund everything"}),(0,h.jsx)(x,{variant:"destructive",onClick:Oi,disabled:ve,children:ve?"Refunding...":Ct!==null&&Ct>0?`Refund ${Z(Ct,i.currency)}`:"Refund"})]})]})})]})}var ei=ie(require("react"),1),ti=require("lucide-react");var gt=require("react/jsx-runtime");function St({title:e,onBackToWebsite:t,hideBackButton:s=!1,children:n,className:a}){let r=ei.useRef(null);return ei.useEffect(()=>{r.current?.focus()},[]),(0,gt.jsxs)("div",{className:J("af-bg-background",a),children:[(0,gt.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,gt.jsx)("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!s&&(0,gt.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,gt.jsx)(ti.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,gt.jsx)("div",{className:"af-p-4",children:n})]})}function ae({className:e}){return(0,gt.jsx)("div",{"aria-hidden":"true",className:J("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function st({label:e,children:t,detail:s,valueClassName:n}){return(0,gt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,gt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,gt.jsx)("div",{className:J("af-mt-1 af-text-lg af-font-semibold",n),children:t}),s&&(0,gt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function Lt({message:e,onRetry:t}){return(0,gt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,gt.jsx)("span",{children:e}),(0,gt.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,gt.jsx)(ti.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function aa({icon:e,children:t}){return(0,gt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,gt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function Ks({icon:e,heading:t,body:s,action:n,className:a,children:r}){return(0,gt.jsxs)("div",{className:J("af-px-6 af-py-10 af-text-center",a),children:[(0,gt.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,gt.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,gt.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:s}),n&&(0,gt.jsx)(x,{type:"button",className:"af-mt-4",onClick:n.onClick,children:n.label}),r]})}var A=require("react/jsx-runtime"),Hu={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Nl={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Rl(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function _l(e){let t=Array.isArray(e.line_items)?e.line_items:[],s=t[0];if(!s)return"\u2014";let n=typeof s.name=="string"&&s.name?s.name:"Item",a=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,r=a>1?`${n} \xD7${a}`:n;return t.length>1?`${r} +${t.length-1} more`:r}function ai(e){return e.customer?.name||e.customer_name||null}function zu({onRefund:e,className:t,refreshKey:s,initialOrderId:n,showFulfillment:a=!1,emptyMessage:r,onDetailOpenChange:o,maxRows:c,onViewAll:d}){let l=typeof c=="number",{api:i}=W(),m=lr({refreshKey:s}),{orders:v,total:g,isLoading:u,error:f,page:p,pageSize:b,hasNextPage:w,hasPreviousPage:P,setPage:T,setPageSize:y,customerEmail:C,setCustomerEmail:k,setStatusIn:I,from:N,setFrom:E,to:D,setTo:_,showAbandoned:Y,setShowAbandoned:Q,setUnfulfilledOnly:z,filters:le,refetch:fe}=m,he=Mt.useCallback(()=>i.exportOrdersCsv(le),[i,le]),[M,ee]=Mt.useState("list"),[U,ve]=Mt.useState(null),[me,Qe]=Mt.useState(""),[ke,Ge]=Mt.useState(""),[Je,Fe]=Mt.useState(!l&&a?"needs_shipping":"all"),[_t,L]=Mt.useState(!1),[$,F]=Mt.useState(!!n&&!l),[Re,te]=Mt.useState(null);Mt.useEffect(()=>{if(!n||l)return;let se=!1;return F(!0),te(null),i.getOrder(n).then(ia=>{se||(ve(ia),ee("detail"))}).catch(()=>{se||te("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{se||F(!1)}),()=>{se=!0}},[i,n,l]);let we=Mt.useCallback(se=>{Fe(se);let ia=Nl[se];I(ia.statusIn),z(ia.unfulfilledOnly)},[I,z]);Mt.useEffect(()=>{a&&!l&&z(!0)},[]);let He=Mt.useRef(!a);Mt.useEffect(()=>{He.current||u||(He.current=!0,v.length===0&&we("all"))},[u,v.length,we]);let bt=M==="detail"&&!!U;Mt.useEffect(()=>{o?.(bt)},[bt,o]);let Ze=(N?1:0)+(D?1:0)+(Y?1:0),Ct=Ze>0||!!C||!!ke,xe=!!N&&!!D&&N>D,Me=!l||!!d,yt=se=>{if(l){d?.();return}ve(se),ee("detail")},Pa=()=>{ee("list"),ve(null),fe()},Kt=se=>{let ia=se.trim();if(!ia){Ge(""),C&&k("");return}if(ia.startsWith("#")||/^\d+$/.test(ia)){Ge(ia),C&&k("");return}Ge(""),k(ia)},fa=()=>{Qe(""),Ge(""),k(""),E(""),_(""),Q(!1),L(!1)},Xt=ke.replace(/^#/,"").toLowerCase(),rt=Xt?v.filter(se=>String(se.order_number??"")===Xt||se.id.toLowerCase().startsWith(Xt)):v,ht=l?rt.slice(0,c):rt,ss=U?v.findIndex(se=>se.id===U.id):-1,en=ss>0,ma=ss>=0&&ss<v.length-1;if($)return(0,A.jsx)("div",{className:t,children:(0,A.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,A.jsx)(Ma.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(M==="detail"&&U)return(0,A.jsx)("div",{className:t,children:(0,A.jsx)(dr,{order:U,onBack:Pa,onRefund:e,onOrderUpdated:se=>ve(se),allowFulfillment:a,onPrevOrder:en?()=>ve(v[ss-1]):void 0,onNextOrder:ma?()=>ve(v[ss+1]):void 0,hasPrevOrder:en,hasNextOrder:ma},U.id)});let K=(0,A.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[Re&&(0,A.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:Re}),(0,A.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,A.jsx)("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(a?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(se=>(0,A.jsx)("button",{type:"button","aria-pressed":Je===se,onClick:()=>we(se),className:J("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Je===se?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Hu[se]},se))}),(0,A.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,A.jsx)(Ma.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,A.jsx)(re,{type:"text",value:me,onChange:se=>Qe(se.target.value),onBlur:()=>Kt(me),onKeyDown:se=>{se.key==="Enter"&&(se.preventDefault(),Kt(me))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,A.jsxs)(x,{type:"button",variant:Ze>0?"secondary":"ghost",size:"sm",onClick:()=>L(se=>!se),"aria-expanded":_t,children:[(0,A.jsx)(Ma.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ze>0&&(0,A.jsx)(oe,{variant:"secondary",className:"af-ml-2",children:Ze})]}),Ct&&(0,A.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:fa,children:"Clear filters"}),(0,A.jsx)(Zt,{fetchCsv:he,filename:"orders",disabled:!!ke,className:"af-ml-auto"})]}),(_t||!!N||!!D)&&(0,A.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2",children:[(0,A.jsx)(Oe,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,A.jsx)(re,{id:"orders-from",type:"date",value:N,max:D||void 0,onChange:se=>E(se.target.value),className:"af-w-[170px]"}),(0,A.jsx)(Oe,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,A.jsx)(re,{id:"orders-to",type:"date",value:D,min:N||void 0,onChange:se=>_(se.target.value),className:"af-w-[170px]"}),!Nl[Je].statusIn&&(0,A.jsx)(x,{type:"button",variant:Y?"secondary":"ghost",size:"sm",onClick:()=>Q(!Y),"aria-pressed":Y,children:Y?"Hide abandoned":"Show abandoned"})]}),xe&&(0,A.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(u)return(0,A.jsxs)("div",{className:t,children:[l?null:K,(0,A.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(se=>(0,A.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,A.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,A.jsx)(ae,{className:"af-h-4 af-w-16"}),(0,A.jsx)(ae,{className:"af-h-4 af-w-14"})]}),(0,A.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-40"}),(0,A.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-24"})]},se))}),(0,A.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,A.jsxs)(et,{children:[(0,A.jsx)(tt,{children:(0,A.jsxs)(Ie,{children:[(0,A.jsx)(j,{children:"Order"}),(0,A.jsx)(j,{children:"Date"}),(0,A.jsx)(j,{children:"Customer"}),(0,A.jsx)(j,{children:"Items"}),(0,A.jsx)(j,{className:"af-text-right",children:"Total"}),(0,A.jsx)(j,{children:"Status"}),(0,A.jsx)(j,{className:"af-w-8"})]})}),(0,A.jsx)(at,{"aria-hidden":"true",children:[0,1,2,3,4].map(se=>(0,A.jsxs)(Ie,{children:[(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-4 af-w-14"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-4 af-w-40"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-4 af-w-32"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,A.jsx)(G,{children:(0,A.jsx)(ae,{className:"af-h-5 af-w-16"})}),(0,A.jsx)(G,{})]},se))})]})}),(0,A.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(f)return(0,A.jsxs)("div",{className:t,children:[l?null:K,(0,A.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,A.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,A.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>fe(),children:"Try again"})]})]});let ct=Je!=="all";if(rt.length===0&&p===0)return Ct||ct?(0,A.jsxs)("div",{className:t,children:[!l&&K,(0,A.jsx)(aa,{children:"No orders match these filters."})]}):(0,A.jsx)("div",{className:t,children:(0,A.jsx)(Ks,{icon:Ma.Receipt,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!l&&(0,A.jsx)(x,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>Q(!0),children:"Show abandoned checkouts"})})});let fs=p*b+1,Bi=Math.min((p+1)*b,g);return(0,A.jsxs)("div",{className:t,children:[l?null:K,(0,A.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ht.map(se=>(0,A.jsxs)("button",{type:"button",onClick:()=>yt(se),disabled:!Me,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Me?" hover:af-bg-muted/50":""}`,children:[(0,A.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,A.jsx)("span",{className:"af-font-medium",children:Is(se)}),(0,A.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:Z(vs(se),se.currency)})]}),(0,A.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,A.jsxs)("div",{className:"af-truncate af-text-sm",children:[se.customer_email||(0,A.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),ai(se)&&(0,A.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",ai(se)]})]}),(0,A.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:_l(se)}),se.amount_refunded>0&&(0,A.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Z(se.amount_refunded,se.currency)," refunded"]})]}),(0,A.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,A.jsx)(rn,{status:se.status}),(0,A.jsx)(Gn,{deliveries:se.email_deliveries}),se.is_test&&(0,A.jsx)(oe,{variant:"outline",children:"Test"}),a&&(0,A.jsx)(Pn,{order:se}),(0,A.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Rl(se.created_at)})]})]},se.id))}),(0,A.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,A.jsxs)(et,{children:[(0,A.jsx)(tt,{children:(0,A.jsxs)(Ie,{children:[(0,A.jsx)(j,{children:"Order"}),(0,A.jsx)(j,{children:"Date"}),(0,A.jsx)(j,{children:"Customer"}),(0,A.jsx)(j,{children:"Items"}),(0,A.jsx)(j,{className:"af-text-right",children:"Total"}),(0,A.jsx)(j,{children:"Status"}),(0,A.jsx)(j,{className:"af-w-8"})]})}),(0,A.jsx)(at,{children:ht.map(se=>(0,A.jsxs)(Ie,{onClick:Me?()=>yt(se):void 0,className:Me?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,A.jsxs)(G,{className:"af-whitespace-nowrap af-font-medium",children:[(0,A.jsx)("button",{type:"button",onClick:ia=>{ia.stopPropagation(),yt(se)},disabled:!Me,"aria-label":`Open order ${Is(se)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Me?" hover:af-underline":""}`,children:Is(se)}),se.is_test&&(0,A.jsx)(oe,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,A.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Rl(se.created_at)}),(0,A.jsxs)(G,{className:"af-max-w-[220px]",children:[(0,A.jsx)("div",{className:"af-truncate",children:se.customer_email||(0,A.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),ai(se)&&(0,A.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ai(se)})]}),(0,A.jsx)(G,{className:"af-max-w-[220px]",children:(0,A.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:_l(se)})}),(0,A.jsxs)(G,{className:"af-whitespace-nowrap af-text-right",children:[(0,A.jsx)("div",{className:"af-font-medium af-tabular-nums",children:Z(vs(se),se.currency)}),se.amount_refunded>0&&(0,A.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Z(se.amount_refunded,se.currency)," ","refunded"]})]}),(0,A.jsx)(G,{children:(0,A.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,A.jsx)(rn,{status:se.status}),(0,A.jsx)(Gn,{deliveries:se.email_deliveries}),a&&(0,A.jsx)(Pn,{order:se})]})}),(0,A.jsx)(G,{className:"af-w-8 af-text-right",children:(0,A.jsx)(Ma.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},se.id))})]})}),l?null:(0,A.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,A.jsx)("span",{children:Xt?`${rt.length} matching this page`:`Showing ${fs}-${Bi} of ${g}`}),(0,A.jsxs)(qa,{value:String(b),onValueChange:se=>y(Number(se)),children:[(0,A.jsx)(ka,{className:"af-w-[70px] af-h-8",children:(0,A.jsx)(Wa,{})}),(0,A.jsxs)(Ta,{children:[(0,A.jsx)(dt,{value:"10",children:"10"}),(0,A.jsx)(dt,{value:"25",children:"25"}),(0,A.jsx)(dt,{value:"50",children:"50"}),(0,A.jsx)(dt,{value:"100",children:"100"})]})]}),(0,A.jsx)("span",{children:"per page"})]}),(0,A.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,A.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>T(p-1),disabled:!P,children:[(0,A.jsx)(Ma.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,A.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>T(p+1),disabled:!w,children:["Next",(0,A.jsx)(Ma.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function Ds(e){return(0,A.jsx)(zu,{...e},e.maxRows==null?"full":"compact")}var Cn=ie(require("react"),1),hs=require("lucide-react");var ba=ie(require("react"),1);function fr({initialPageSize:e=25}={}){let{api:t}=W(),[s,n]=ba.useState([]),[a,r]=ba.useState(0),[o,c]=ba.useState(!0),[d,l]=ba.useState(null),[i,m]=ba.useState(0),[v,g]=ba.useState(e),[u,f]=ba.useState(""),p=ba.useRef(0),b=ba.useCallback(async()=>{let P=++p.current;try{c(!0),l(null);let T={limit:v,offset:i*v};u.trim()&&(T.email=u.trim());let y=await t.getCustomers(T);if(P!==p.current)return;n(y.customers),r(y.total)}catch(T){if(P!==p.current)return;l(T instanceof Error?T:new Error("Failed to fetch customers"))}finally{P===p.current&&c(!1)}},[t,i,v,u]);ba.useEffect(()=>{b()},[b]);let w=Math.ceil(a/v);return{customers:s,total:a,isLoading:o,error:d,page:i,pageSize:v,hasNextPage:i<w-1,hasPreviousPage:i>0,setPage:m,setPageSize:P=>{g(P),m(0)},email:u,setEmail:P=>{f(P),m(0)},refetch:b}}var ln=ie(require("react"),1),si=require("lucide-react");var _e=require("react/jsx-runtime");function Pl(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function qu(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&t.push(s),e.country&&t.push(e.country),t}function mr({customer:e,onBack:t,className:s}){let{api:n}=W(),[a,r]=ln.useState(null),[o,c]=ln.useState([]),[d,l]=ln.useState(!0),[i,m]=ln.useState(null);ln.useEffect(()=>{let u=!1;return l(!0),m(null),Promise.all([n.getCustomer(e.id),n.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([f,p])=>{u||(r(f),c(p.orders))}).catch(f=>{u||m(f instanceof Error?f.message:"Failed to load customer")}).finally(()=>{u||l(!1)}),()=>{u=!0}},[n,e.id,e.email]);let v=a?.addresses??[],g=a?.order_count??o.length;return(0,_e.jsxs)("div",{className:s,children:[(0,_e.jsxs)("div",{className:"af-mb-6",children:[(0,_e.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,_e.jsx)(si.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,_e.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,_e.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Pl(e.created_at)]})]}),d?(0,_e.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,_e.jsx)(si.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):i?(0,_e.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i}):(0,_e.jsxs)("div",{className:"af-space-y-6",children:[(0,_e.jsx)(ps,{deliveries:a?.email_deliveries}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,_e.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,_e.jsx)("span",{children:e.email})]}),e.name&&(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,_e.jsx)("span",{children:e.name})]}),e.phone&&(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,_e.jsx)("span",{children:e.phone})]}),(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,_e.jsx)("span",{children:g})]})]})]}),v.length>0&&(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,_e.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:v.map(u=>(0,_e.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&(0,_e.jsx)(oe,{variant:"secondary",className:"af-mb-1",children:"Default"}),qu(u).map((f,p)=>(0,_e.jsx)("div",{children:f},p))]},u.id))})]}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,_e.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,_e.jsxs)(et,{children:[(0,_e.jsx)(tt,{children:(0,_e.jsxs)(Ie,{children:[(0,_e.jsx)(j,{children:"Date"}),(0,_e.jsx)(j,{children:"Amount"}),(0,_e.jsx)(j,{children:"Status"})]})}),(0,_e.jsx)(at,{children:o.map(u=>(0,_e.jsxs)(Ie,{children:[(0,_e.jsx)(G,{className:"af-text-muted-foreground",children:Pl(u.created_at)}),(0,_e.jsx)(G,{children:Z(vs(u),u.currency)}),(0,_e.jsx)(G,{children:(0,_e.jsx)(Gs,{status:u.status})})]},u.id))})]})]})]})]})}var ye=require("react/jsx-runtime");function Wu(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function pr({className:e}){let{customers:t,total:s,isLoading:n,error:a,page:r,pageSize:o,hasNextPage:c,hasPreviousPage:d,setPage:l,setPageSize:i,email:m,setEmail:v,refetch:g}=fr(),{api:u}=W(),f=Cn.useCallback(()=>u.exportCustomersCsv(),[u]),[p,b]=Cn.useState("list"),[w,P]=Cn.useState(null),[T,y]=Cn.useState(""),C=D=>{P(D),b("detail")},k=()=>{b("list"),P(null),g()};if(p==="detail"&&w)return(0,ye.jsx)("div",{className:e,children:(0,ye.jsx)(mr,{customer:w,onBack:k})});let I=(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,ye.jsx)(re,{type:"email",value:T,onChange:D=>y(D.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),v(T.trim()))}}),(0,ye.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>v(T.trim()),children:[(0,ye.jsx)(hs.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),m&&(0,ye.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>{y(""),v("")},children:"Clear"}),(0,ye.jsx)(Zt,{fetchCsv:f,filename:"customers",className:"af-ml-auto"})]});if(n)return(0,ye.jsxs)("div",{className:e,children:[I,(0,ye.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ye.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(a)return(0,ye.jsxs)("div",{className:e,children:[I,(0,ye.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ye.jsxs)("div",{className:"af-text-destructive",children:["Error: ",a.message]})})]});if(t.length===0&&r===0)return(0,ye.jsxs)("div",{className:e,children:[m&&I,(0,ye.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,ye.jsx)(hs.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ye.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:m?"No customers match that email.":(0,ye.jsxs)(ye.Fragment,{children:["No customers yet.",(0,ye.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let N=r*o+1,E=Math.min((r+1)*o,s);return(0,ye.jsxs)("div",{className:e,children:[I,(0,ye.jsxs)(et,{children:[(0,ye.jsx)(tt,{children:(0,ye.jsxs)(Ie,{children:[(0,ye.jsx)(j,{children:"Email"}),(0,ye.jsx)(j,{children:"Name"}),(0,ye.jsx)(j,{children:"Phone"}),(0,ye.jsx)(j,{children:"Customer since"}),(0,ye.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,ye.jsx)(at,{children:t.map(D=>(0,ye.jsxs)(Ie,{children:[(0,ye.jsx)(G,{className:"af-font-medium",children:D.email}),(0,ye.jsx)(G,{children:D.name||(0,ye.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ye.jsx)(G,{children:D.phone||(0,ye.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ye.jsx)(G,{className:"af-text-muted-foreground",children:Wu(D.created_at)}),(0,ye.jsx)(G,{className:"af-text-right",children:(0,ye.jsx)(x,{variant:"ghost",size:"icon",onClick:()=>C(D),title:"View customer",children:(0,ye.jsx)(hs.Eye,{className:"af-h-4 af-w-4"})})})]},D.id))})]}),(0,ye.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ye.jsxs)("span",{children:["Showing ",N,"-",E," of ",s]}),(0,ye.jsxs)(qa,{value:String(o),onValueChange:D=>i(Number(D)),children:[(0,ye.jsx)(ka,{className:"af-w-[70px] af-h-8",children:(0,ye.jsx)(Wa,{})}),(0,ye.jsxs)(Ta,{children:[(0,ye.jsx)(dt,{value:"10",children:"10"}),(0,ye.jsx)(dt,{value:"25",children:"25"}),(0,ye.jsx)(dt,{value:"50",children:"50"}),(0,ye.jsx)(dt,{value:"100",children:"100"})]})]}),(0,ye.jsx)("span",{children:"per page"})]}),(0,ye.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ye.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>l(r-1),disabled:!d,children:[(0,ye.jsx)(hs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ye.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>l(r+1),disabled:!c,children:["Next",(0,ye.jsx)(hs.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ve=ie(require("react"),1),Bt=require("lucide-react");var Ot=ie(require("react"),1);function cn({initialPageSize:e=25,refreshKey:t,includeAggregates:s=!1}={}){let{api:n}=W(),[a,r]=Ot.useState([]),[o,c]=Ot.useState(0),[d,l]=Ot.useState(null),[i,m]=Ot.useState(!0),[v,g]=Ot.useState(null),[u,f]=Ot.useState(0),[p,b]=Ot.useState(e),[w,P]=Ot.useState(void 0),[T,y]=Ot.useState(""),[C,k]=Ot.useState(""),[I,N]=Ot.useState(""),[E,D]=Ot.useState(""),[_,Y]=Ot.useState(""),Q=w?w.join(","):"",z=Ot.useRef(0),le=Ot.useCallback(async()=>{let he=++z.current;m(!0),g(null);try{let M={labels:Q?Q.split(","):void 0,customerEmail:T||void 0,q:C||void 0,from:I||void 0,to:E||void 0,retainerId:_||void 0,includeAggregates:s,limit:p,offset:u*p},ee=await n.getInvoices(M);if(he!==z.current)return;if(u>0&&u*p>=ee.total){f(Math.max(0,Math.ceil(ee.total/p)-1));return}r(ee.invoices),c(ee.total),s&&l(ee.aggregates??null)}catch(M){if(he!==z.current)return;g(M instanceof Error?M:new Error("Failed to fetch invoices"))}finally{he===z.current&&m(!1)}},[n,Q,T,C,I,E,_,u,p,s]);Ot.useEffect(()=>{le()},[le,t]);let fe=he=>M=>{f(0),he(M)};return{invoices:a,total:o,aggregates:d,isLoading:i,error:v,page:u,pageSize:p,hasNextPage:(u+1)*p<o,hasPreviousPage:u>0,setPage:f,setPageSize:fe(b),labels:w,setLabels:fe(P),customerEmail:T,setCustomerEmail:fe(y),q:C,setQ:fe(k),from:I,setFrom:fe(N),to:E,setTo:fe(D),retainerId:_,setRetainerId:fe(Y),clearFilters:()=>{f(0),P(void 0),y(""),k(""),N(""),D(""),Y("")},refetch:le}}var S=require("react/jsx-runtime"),ju={creating:"Creating",failed:"Failed",awaiting_payment:"Awaiting payment",overdue:"Overdue",payment_processing:"Payment processing",awaiting_authentication:"Awaiting authentication",paid:"Paid",paid_outside_stripe:"Paid outside Stripe",paid_by_credit:"Paid by credit",partially_refunded:"Partially refunded",refunded:"Refunded",disputed:"Disputed",voided:"Voided",uncollectible:"Marked uncollectible"};function Qi(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:ju[e.label]??e.label}function Gu(e){switch(e){case"paid":case"paid_outside_stripe":case"paid_by_credit":return"success";case"overdue":case"disputed":case"failed":return"destructive";case"partially_refunded":case"refunded":case"payment_processing":case"awaiting_authentication":return"warning";case"awaiting_payment":return"secondary";default:return"outline"}}var Xi={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Ku={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Tn({invoice:e,className:t}){return(0,S.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,S.jsx)(oe,{variant:Gu(e.label),className:t,children:Qi(e)}),e.collection_method==="charge_automatically"&&(0,S.jsx)(oe,{variant:"secondary",children:"Managed in Stripe"})]})}function ii({delivery:e,className:t}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,S.jsx)(oe,{variant:s,className:t,children:Xi[e.state]??e.state})}function kn(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function Ja(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Cl={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},ni={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},Yi=100,Ji=5e3;async function Zu(e,t){let s=[],n=0;for(let a=0;a<Ji;a+=Yi){let r=await e.getInvoices({...t,limit:Yi,offset:a});if(n=r.total,s.push(...r.invoices),r.invoices.length<Yi||s.length>=n)break}return{invoices:s.slice(0,Ji),total:n,truncated:n>s.length||n>Ji}}function Tl(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],s=e.map(n=>[n.id,kn(n),Qi(n),n.customer_name??"",n.customer_email??"",n.created_at,n.due_at??"",n.paid_at??"",n.currency.toUpperCase(),Z(n.amount_subtotal,n.currency),Z(n.tax_total,n.currency),Z(n.amount_total,n.currency),n.amount_due===null?"":Z(n.amount_due,n.currency),n.amount_paid===null?"":Z(n.amount_paid,n.currency),Z(n.amount_refunded,n.currency),n.payment_method??"",n.pay_url??"",n.retainer_id??"",n.replaces_order_id??"",n.replaced_by_order_id??"",n.tax_behavior??"",n.discount_total===void 0?"":Z(n.discount_total,n.currency),n.collection_method??""]);return[t,...s].map(n=>n.map(ll).join(",")).join(`
|
|
5
|
-
`)}function Yu(e){Gr(new Blob([Tl(e)],{type:"text/csv;charset=utf-8"}),jr("invoices"))}function Ju({className:e,refreshKey:t,initialInvoiceId:s,onDetailOpenChange:n,onConnectStripe:a,onUpgradePlan:r,needsPaidPlan:o=!1,retainerFilter:c=null,onClearRetainerFilter:d,maxRows:l,onViewAll:i}){let m=typeof l=="number",{api:v}=W(),{invoices:g,total:u,isLoading:f,error:p,page:b,pageSize:w,hasNextPage:P,hasPreviousPage:T,setPage:y,labels:C,setLabels:k,customerEmail:I,setCustomerEmail:N,q:E,setQ:D,from:_,setFrom:Y,to:Q,setTo:z,retainerId:le,setRetainerId:fe,refetch:he}=cn({refreshKey:t}),[M,ee]=Ve.useState(typeof l=="number"?"all":"open"),[U,ve]=Ve.useState(""),[me,Qe]=Ve.useState(null),ke=Ve.useRef(0),Ge=!m||!!i,Je=Ve.useCallback(K=>{if(m){i?.();return}ke.current++,_t(!1),Qe(K)},[m,i]),[Fe,_t]=Ve.useState(!1),[L,$]=Ve.useState(0),[F,Re]=Ve.useState(null),[te,we]=Ve.useState(!1),[He,bt]=Ve.useState(0);Ve.useEffect(()=>{Qe(K=>{if(!K)return K;let ct=g.find(fs=>fs.id===K.id);return ct&&ct!==K?ct:K})},[g]);let[Ze,Ct]=Ve.useState(!1),[xe,Me]=Ve.useState(null),yt=async()=>{if(!Ze){Ct(!0),Me(null);try{let{invoices:K,total:ct,truncated:fs}=await Zu(v,{labels:C,customerEmail:I,q:E,from:_,to:Q,retainerId:le});Yu(K),Me(fs?`Exported the first ${K.length.toLocaleString()} of ${ct.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Me("Couldn't export \u2014 try again.")}finally{Ct(!1)}}},Pa=!I&&!E&&!_&&!Q&&!le,[Kt,fa]=Ve.useState(null);Ve.useEffect(()=>{if(f||u>0||!Pa||M!=="open")return;let K=!1;return v.getInvoices({limit:1}).then(ct=>{K||fa(ct.total>0)}).catch(()=>{K||fa(!0)}),()=>{K=!0}},[v,f,u,Pa,M,t]),Ve.useEffect(()=>{k(m?ni.all:ni.open)},[]),Ve.useEffect(()=>{let K=c?.id??"";K!==le&&(fe(K),K&&(ee("all"),k(ni.all),N(""),D(""),ve(""),Y(""),z("")))},[c?.id]),Ve.useEffect(()=>{let K=!1;return we(!1),v.getInvoiceSettings().then(ct=>{K||Re({payments_active:ct.payments_active,blocked:ct.blocked})}).catch(()=>{K||we(!0)}),()=>{K=!0}},[v,t,He]),Ve.useEffect(()=>{if(!s||m)return;let K=!1,ct=ke.current;return _t(!1),v.getInvoice(s).then(fs=>{!K&&ct===ke.current&&Qe(fs)}).catch(()=>{!K&&ct===ke.current&&_t(!0)}),()=>{K=!0}},[v,s,L,m]),Ve.useEffect(()=>{n?.(me!==null)},[me,n]);let Xt=K=>{ee(K),k(ni[K])},rt=K=>{let ct=K.trim();if(!ct){E&&D(""),I&&N("");return}if(ct.includes("@")){E&&D(""),N(ct);return}I&&N(""),D(ct.replace(/^#/,""))},ht=g,ss=m?ht.slice(0,l):ht,en=Fe&&(0,S.jsxs)("div",{role:"alert",className:"af-mb-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't open the requested invoice. ",(0,S.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:()=>$(K=>K+1),children:"Retry opening invoice"})]});if(me)return(0,S.jsxs)("div",{className:e,children:[en,(0,S.jsx)(oi,{invoice:me,refreshKey:t,onBack:()=>{Je(null),he()}},me.id)]});let ma=(0,S.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[te&&(0,S.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,S.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:()=>bt(K=>K+1),children:"Retry setup check"})]}),en,F?.blocked&&(0,S.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",F.blocked.reason?`: ${F.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),c&&(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,S.jsxs)(oe,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",c.label]}),d&&(0,S.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:d,children:"Clear schedule filter"})]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.jsx)("div",{role:"group","aria-label":"Invoice views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Object.keys(Cl).map(K=>(0,S.jsx)("button",{type:"button","aria-pressed":M===K,onClick:()=>Xt(K),className:J("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",M===K?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Cl[K]},K))}),(0,S.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,S.jsx)(Bt.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,S.jsx)(re,{type:"text",value:U,onChange:K=>ve(K.target.value),onBlur:()=>rt(U),onKeyDown:K=>{K.key==="Enter"&&(K.preventDefault(),rt(U))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,S.jsx)(Oe,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,S.jsx)(re,{id:"invoices-from",type:"date",value:_,max:Q||void 0,onChange:K=>Y(K.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,S.jsx)(Oe,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,S.jsx)(re,{id:"invoices-to",type:"date",value:Q,min:_||void 0,onChange:K=>z(K.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,S.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>void yt(),disabled:Ze||f||!!p||u===0,"aria-busy":Ze,children:[(0,S.jsx)(Bt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),Ze?"Exporting\u2026":"Export CSV (all matching)"]})]}),xe&&(0,S.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:xe})]});return f?(0,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(K=>(0,S.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,S.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,S.jsx)(ae,{className:"af-h-4 af-w-20"}),(0,S.jsx)(ae,{className:"af-h-4 af-w-16"})]}),(0,S.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-40"})]},K))})]}):p?(0,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,S.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:()=>void he(),children:"Retry"})]})]}):u===0&&Pa&&(M==="all"||Kt===!1)&&(M==="open"||M==="all")?F?.blocked?(0,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)(ri,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)(ri,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):F&&!F.payments_active?(0,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)(ri,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:a?{label:"Payment setup",onClick:a}:void 0})]}):(0,S.jsxs)("div",{className:e,children:[m?null:ma,(0,S.jsx)(ri,{heading:"No invoices yet",body:!F||te?"Once invoice setup is ready, you can send invoices from the chat.":"Ask in the chat to send an invoice to a client for your services."})]}):(0,S.jsxs)("div",{className:e,children:[m?null:ma,ss.length===0?(0,S.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:"No invoices match."}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ss.map(K=>(0,S.jsxs)("button",{type:"button",onClick:()=>Je(K),disabled:!Ge,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ge?" hover:af-bg-muted/50":""}`,children:[(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,S.jsx)("span",{className:"af-font-medium",children:kn(K)}),(0,S.jsx)(Tn,{invoice:K})]}),(0,S.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:K.customer_name??K.customer_email??"\u2014"}),K.delivery&&(0,S.jsx)("div",{className:"af-mt-1",children:(0,S.jsx)(ii,{delivery:K.delivery})}),(0,S.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[(0,S.jsx)("span",{children:K.collection_method==="charge_automatically"?"Automatic collection":K.due_at?`Due ${Ja(K.due_at)}`:"Due on receipt"}),(0,S.jsx)("span",{className:"af-font-medium af-tabular-nums",children:Z(K.amount_due??K.amount_total,K.currency)})]})]},K.id))}),(0,S.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,S.jsxs)(et,{children:[(0,S.jsx)(tt,{children:(0,S.jsxs)(Ie,{children:[(0,S.jsx)(j,{children:"Invoice"}),(0,S.jsx)(j,{children:"Created"}),(0,S.jsx)(j,{children:"Customer"}),(0,S.jsx)(j,{children:"Due"}),(0,S.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,S.jsx)(j,{children:"Status"}),(0,S.jsx)(j,{children:"Delivery"}),(0,S.jsx)(j,{className:"af-w-8"})]})}),(0,S.jsx)(at,{children:ss.map(K=>(0,S.jsxs)(Ie,{className:Ge?"af-cursor-pointer":void 0,onClick:Ge?()=>Je(K):void 0,children:[(0,S.jsx)(G,{className:"af-font-medium",children:(0,S.jsx)("button",{type:"button",disabled:!Ge,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ge?" hover:af-underline":""}`,onClick:ct=>{ct.stopPropagation(),Je(K)},"aria-label":`Open invoice ${kn(K)}`,children:kn(K)})}),(0,S.jsx)(G,{children:Ja(K.created_at)}),(0,S.jsxs)(G,{children:[(0,S.jsx)("div",{children:K.customer_name??"\u2014"}),(0,S.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:K.customer_email})]}),(0,S.jsx)(G,{children:K.collection_method==="charge_automatically"?"Automatic":K.due_at?Ja(K.due_at):"On receipt"}),(0,S.jsx)(G,{className:"af-text-right af-tabular-nums",children:Z(K.amount_due??K.amount_total,K.currency)}),(0,S.jsx)(G,{children:(0,S.jsx)(Tn,{invoice:K})}),(0,S.jsx)(G,{children:(0,S.jsx)(ii,{delivery:K.delivery})}),(0,S.jsx)(G,{children:(0,S.jsx)(Bt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},K.id))})]})}),m?null:(0,S.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,S.jsxs)("span",{children:[u," invoice",u===1?"":"s"]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b-1),disabled:!T,"aria-label":"Previous page",children:(0,S.jsx)(Bt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,S.jsxs)("span",{className:"af-tabular-nums",children:[b*w+1,"\u2013",Math.min((b+1)*w,u)]}),(0,S.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b+1),disabled:!P,"aria-label":"Next page",children:(0,S.jsx)(Bt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function ri({heading:e,body:t,action:s}){return(0,S.jsx)(Ks,{icon:Bt.FileText,heading:e,body:t,action:s})}function Ls(e){return(0,S.jsx)(Ju,{...e},e.maxRows==null?"full":"compact")}var As="af-text-xs af-text-muted-foreground";function kl(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function oi({invoice:e,onBack:t,refreshKey:s,className:n}){let{api:a}=W(),r=Ve.useRef(null);Ve.useEffect(()=>{r.current?.focus()},[e.id]);let[o,c]=Ve.useState(!1),[d,l]=Ve.useState(null),[i,m]=Ve.useState(!1),[v,g]=Ve.useState(!1),u=Ve.useRef(0),[f,p]=Ve.useState(null),[b,w]=Ve.useState(!1),[P,T]=Ve.useState(0);Ve.useEffect(()=>{let _=!1;return w(!1),a.getInvoice(e.id).then(Y=>{_||p({source:e,value:Y})}).catch(()=>{_||w(!0)}),()=>{_=!0}},[a,e,s,P]);let y=f?.source===e?f.value:e,C=y.collection_method==="charge_automatically";Ve.useEffect(()=>(u.current++,l(null),m(!1),g(!1),c(!1),()=>{u.current++}),[a,y,s]);let k=_=>_==null?"\u2014":Z(_,y.currency),I=async()=>{if(!(!y.pay_url||!kl()))try{await navigator.clipboard.writeText(y.pay_url),c(!0),setTimeout(()=>c(!1),1500)}catch{}},N=async()=>{if(d){l(null);return}let _=++u.current;g(!1),m(!0);try{let Y=await a.getInvoicePreview(y.id);_===u.current&&l(Y)}catch{_===u.current&&g(!0)}finally{_===u.current&&m(!1)}},E=y.bill_to,D=E?[E.company,E.name,E.address?.line1,E.address?.line2,[E.address?.city,E.address?.state,E.address?.postal_code].filter(Boolean).join(", "),E.address?.country,E.tax_id?`${E.tax_id.value}`:null,E.po_number?`PO ${E.po_number}`:null,E.service_period?`Service period: ${E.service_period}`:null].filter(_=>!!_&&_.length>0):[];return(0,S.jsxs)("div",{className:n,children:[(0,S.jsxs)("div",{className:"af-mb-4",children:[(0,S.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,S.jsx)(Bt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.jsxs)("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",kn(y)]}),(0,S.jsx)(Tn,{invoice:y}),(0,S.jsx)(ii,{delivery:y.delivery})]}),(0,S.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[y.customer_name??y.customer_email,y.customer_name&&y.customer_email?` \xB7 ${y.customer_email}`:""]})]}),b&&(0,S.jsxs)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't refresh this invoice. These details may be out of date. ",(0,S.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:()=>T(_=>_+1),children:"Retry details"})]}),y.label==="failed"&&(0,S.jsx)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),y.label==="creating"&&(0,S.jsx)("p",{role:"status",className:"af-mb-4 af-text-sm af-text-muted-foreground",children:"This invoice is still being created. Its final details will appear when it is ready."}),(0,S.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,S.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,S.jsxs)(et,{children:[(0,S.jsx)(tt,{children:(0,S.jsxs)(Ie,{children:[(0,S.jsx)(j,{children:"Description"}),(0,S.jsx)(j,{className:"af-text-right",children:"Qty"}),(0,S.jsx)(j,{className:"af-text-right",children:"Amount"})]})}),(0,S.jsx)(at,{children:y.line_items.map((_,Y)=>(0,S.jsxs)(Ie,{children:[(0,S.jsx)(G,{style:{overflowWrap:"anywhere"},children:_.description}),(0,S.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_.quantity}),(0,S.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:k(_.amount)})]},Y))})]}),(0,S.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,S.jsx)(Zs,{label:"Subtotal",value:k(y.amount_subtotal)}),(y.discount_total??0)>0&&(0,S.jsx)(Zs,{label:"Discount",value:`-${k(y.discount_total)}`}),y.tax_total>0&&(0,S.jsx)(Zs,{label:y.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:k(y.tax_total)}),(0,S.jsx)(Zs,{label:"Total",value:k(y.amount_total),strong:!0}),y.credit_applied>0&&(0,S.jsx)(Zs,{label:"Credit applied",value:`-${k(y.credit_applied)}`}),y.amount_due!==null&&y.amount_due!==y.amount_total&&(0,S.jsx)(Zs,{label:"Amount due",value:k(y.amount_due),strong:!0}),y.amount_paid!==null&&y.amount_paid>0&&(0,S.jsx)(Zs,{label:"Amount paid",value:k(y.amount_paid)}),y.amount_refunded>0&&(0,S.jsx)(Zs,{label:"Refunded",value:k(y.amount_refunded)})]}),y.credit_notes?.length>0&&(0,S.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,S.jsx)("div",{className:As,children:"Credit notes"}),y.credit_notes.map(_=>(0,S.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,S.jsxs)("span",{className:"af-text-muted-foreground",children:[Ja(_.created_at)," \xB7 ",_.origin==="dashboard"?"issued in Stripe":"refund",_.stripe_credit_note_id?"":" \xB7 being created"]}),(0,S.jsxs)("span",{className:"af-tabular-nums",children:["-",Z(_.amount,_.currency)]})]},_.id))]})]}),(y.note||y.footer)&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[y.note&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:As,children:"Note"}),(0,S.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:y.note})]}),y.footer&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:As,children:"Footer"}),(0,S.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:y.footer})]})]}),d&&!C&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,S.jsxs)("div",{className:J(As,"af-break-words"),children:["Email preview \u2014 ",d.subject]}),(0,S.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,S.jsx)("iframe",{title:"Invoice email preview",srcDoc:d.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,S.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,S.jsx)(Ya,{label:"Created",value:Ja(y.created_at)}),(0,S.jsx)(Ya,{label:"Due",value:y.collection_method==="charge_automatically"?"Managed in Stripe":y.due_at?Ja(y.due_at):"On receipt"}),y.paid_at&&(0,S.jsx)(Ya,{label:"Paid",value:Ja(y.paid_at)}),y.payment_method&&(0,S.jsx)(Ya,{label:"Paid by",value:y.paid_out_of_band?`${y.payment_method} (recorded outside Stripe)`:y.payment_method}),y.payment_state!=="none"&&(0,S.jsx)(Ya,{label:"Payment",value:y.payment_state==="processing"?"Processing":y.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),y.delivery&&(0,S.jsx)(Ya,{label:"Delivery",value:`${Xi[y.delivery.state]} \xB7 ${y.delivery.recipient}`}),y.marked_uncollectible_at&&(0,S.jsx)(Ya,{label:"Written off",value:Ja(y.marked_uncollectible_at)}),y.correction_reason&&(0,S.jsx)(Ya,{label:"Correction",value:y.correction_reason}),y.replaced_by_order_id&&(0,S.jsx)(Ya,{label:"Replaced by",value:y.replaced_by_order_id}),y.collection_method==="charge_automatically"?(0,S.jsx)(Ya,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):y.retainer_id&&(0,S.jsx)(Ya,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),y.replaces_order_id&&(0,S.jsx)(Ya,{label:"Replaces",value:y.replaces_order_id})]}),(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,S.jsx)("div",{className:As,children:"Reminders"}),C?(0,S.jsx)("div",{children:"View automatic payment reminders in Stripe."}):y.reminders.disabled?(0,S.jsx)("div",{children:"Off for this invoice."}):y.reminders.paused_until?(0,S.jsxs)("div",{children:["Paused until ",Ja(y.reminders.paused_until),"."]}):y.reminders.next_at?(0,S.jsxs)("div",{children:["Next on ",Ja(y.reminders.next_at),"."]}):y.reminders.final_sent_at?(0,S.jsxs)("div",{children:["Final reminder sent ",Ja(y.reminders.final_sent_at),"."]}):(0,S.jsx)("div",{children:"None scheduled."}),!C&&(0,S.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",y.reminders.schedule.length===0?"none":y.reminders.schedule.map(_=>_<0?`${-_}d before`:_===0?"due day":`${_}d after`).join(", ")]})]}),y.communications&&y.communications.length>0&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,S.jsx)("div",{className:As,children:"Email delivery history"}),y.communications.map(_=>(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,S.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[Ku[_.kind]??_.kind,_.kind==="reminder"&&_.slot!==null?` #${_.slot}`:"",(0,S.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",_.recipient]})]}),(0,S.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Xi[_.state]??_.state," \xB7 ",Ja(_.state_at??_.created_at)]})]},_.id))]}),D.length>0&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,S.jsx)("div",{className:As,children:"Bill to"}),D.map((_,Y)=>(0,S.jsx)("div",{className:"af-break-words",children:_},Y))]}),(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[y.pay_url&&(0,S.jsxs)(x,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void I(),disabled:!kl(),children:[(0,S.jsx)(Bt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":C?"Copy invoice link":"Copy pay link"]}),y.pdf_url&&(0,S.jsx)(x,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,S.jsxs)("a",{href:y.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,S.jsx)(Bt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!C&&(0,S.jsxs)(x,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void N(),disabled:i,children:[i?(0,S.jsx)(Bt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(Bt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),d?"Hide email preview":v?"Retry email preview":"Show email preview"]}),v&&!C&&(0,S.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),y.pay_url&&(0,S.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:y.pay_url}),(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:C?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function Ya({label:e,value:t}){return(0,S.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,S.jsx)("span",{className:J(As,"af-shrink-0"),children:e}),(0,S.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function Zs({label:e,value:t,strong:s}){return(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,S.jsx)("dt",{className:J(As,s&&"af-font-medium af-text-foreground"),children:e}),(0,S.jsx)("dd",{className:J("af-tabular-nums",s&&"af-font-semibold"),children:t})]})}var Il=require("lucide-react");var qe=require("react/jsx-runtime"),Xu={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},El={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Qu(e){switch(e){case"active":return"success";case"paused":case"canceling":return"warning";case"failed":return"destructive";case"canceled":return"outline";default:return"secondary"}}function Dl(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>El[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>El[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Xu[e.status]}function Al(e){let t=e.interval==="year"?"every year":"every month";return`${Z(e.amount,e.currency)} ${t}`}function ed(e){return e.status==="canceled"?`Ended ${li(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${li(e.next_cycle_at)}`:"Ends this period":e.collection_method==="charge_automatically"?"Billing schedule managed in Stripe":e.status==="paused"?"Future invoices paused":e.status==="failed"||e.status==="creating"?"Next invoice not scheduled yet":e.skip_next_cycle?e.next_cycle_at?`Skipping ${li(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${li(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function li(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(t);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ci({retainer:e,className:t}){return(0,qe.jsx)(oe,{variant:Qu(e.status),className:J("af-max-w-full af-whitespace-normal af-break-words",t),children:Dl(e)})}function un({retainers:e,isLoading:t,error:s,onRetry:n,onShowCycles:a,activeRetainerId:r,total:o,endedTotal:c=0,isLoadingMore:d=!1,onLoadMore:l,includeEnded:i=!1,onIncludeEndedChange:m,exportCsv:v,className:g}){let u=!!m;if(!t&&!s&&e.length===0&&!(u&&(i||c>0)))return null;let f=o!==void 0?Math.max(0,o-e.length):0;return(0,qe.jsxs)("section",{className:J("af-mb-6",g),"aria-label":"Recurring invoices",children:[(0,qe.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,qe.jsx)(Il.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,qe.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,qe.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),u&&(0,qe.jsx)(x,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":i,onClick:()=>m?.(!i),children:i?"Hide ended recurring invoices":c>0&&e.length===0?`Show ended recurring invoices (${c})`:"Show ended recurring invoices"}),v&&(0,qe.jsx)(Zt,{fetchCsv:v,filename:"retainers",className:u?void 0:"af-ml-auto"})]}),s?(0,qe.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",(0,qe.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:n,children:"Retry"})]}):t?(0,qe.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(p=>(0,qe.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,qe.jsx)(ae,{className:"af-h-4 af-w-48"}),(0,qe.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-32"})]},p))}):e.length===0?(0,qe.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:i?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,qe.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(p=>{let b=r===p.id;return(0,qe.jsxs)("li",{className:J("af-rounded-md af-border af-p-3",b&&"af-border-primary af-bg-muted/40"),children:[(0,qe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,qe.jsxs)("div",{className:"af-min-w-0",children:[(0,qe.jsx)("div",{className:"af-truncate af-font-medium",children:p.customer_name??p.customer_email??"\u2014"}),(0,qe.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:p.description})]}),(0,qe.jsx)(ci,{retainer:p})]}),p.collection_method==="charge_automatically"?(0,qe.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,qe.jsx)(oe,{variant:"secondary",children:"Managed in Stripe"}),(0,qe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Automatic charging is enabled in Stripe. View or change the billing terms there. To edit this schedule from the chat, switch it back to sending invoices in Stripe."})]}):(0,qe.jsx)("div",{className:"af-mt-2 af-text-sm",children:Al(p)}),(0,qe.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-text-xs af-text-muted-foreground",children:[(0,qe.jsxs)("span",{children:[ed(p)," \xB7 ",p.cycles.count===0?"no invoices yet":`${p.cycles.paid} paid${p.cycles.open>0?`, ${p.cycles.open} open`:""}`]}),p.cycles.count>0&&(0,qe.jsx)(x,{type:"button",variant:b?"secondary":"ghost",size:"sm",onClick:()=>a(p),"aria-pressed":b,children:b?"Showing invoices":"View invoices"})]}),p.status==="failed"&&p.operation?.last_error&&(0,qe.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",p.operation.last_error,". Ask in the chat to try again."]})]},p.id)})}),!t&&!s&&f>0&&l&&(0,qe.jsx)("div",{className:"af-mt-2",children:(0,qe.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:d,children:d?"Loading\u2026":`Load more (${f} more)`})})]})}var Ll=ie(require("react"),1),$a=require("lucide-react");var De=require("react/jsx-runtime");function dn({onConnectStripe:e,onUpgradePlan:t,whenActive:s,className:n}){let{status:a,isLoading:r,error:o,refetch:c}=Ts(),[d,l]=Ll.useState(!1),i=async()=>{l(!0);try{await c()}finally{l(!1)}};return r&&!a?(0,De.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:(0,De.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):o||!a?(0,De.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:(0,De.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o?.message||"Failed to load payment status"]})}):a.status==="active"?s!==void 0?(0,De.jsx)("div",{className:n,children:s}):(0,De.jsx)("div",{className:n,children:(0,De.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-green-50 af-border af-border-green-200 af-rounded-lg af-p-4",children:[(0,De.jsx)($a.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,De.jsxs)("div",{children:[(0,De.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,De.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",a.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,De.jsxs)("div",{className:`af-space-y-4 ${n||""}`,children:[a.reason==="needs_stripe"&&(0,De.jsxs)("div",{className:"af-space-y-3",children:[(0,De.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,De.jsx)($a.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,De.jsxs)("div",{children:[(0,De.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,De.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"It only takes a few minutes. You'll enter your details with Stripe, who handle the payments, and money from sales goes straight to your own bank."})]})]}),e?(0,De.jsxs)(x,{onClick:e,children:[(0,De.jsx)($a.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,De.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),a.reason==="needs_paid_plan"&&(0,De.jsxs)("div",{className:"af-space-y-3",children:[(0,De.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,De.jsx)($a.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,De.jsxs)("div",{children:[(0,De.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,De.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your products are saved as drafts. Upgrade to a paid plan to start accepting payments on your site."})]})]}),t?(0,De.jsx)(x,{onClick:t,children:"Upgrade plan"}):(0,De.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),a.reason==="account_disabled"&&(0,De.jsxs)("div",{className:"af-space-y-3",children:[(0,De.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-yellow-50 af-border af-border-yellow-200 af-rounded-lg af-p-4",children:[(0,De.jsx)($a.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,De.jsxs)("div",{children:[(0,De.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?(0,De.jsx)("p",{className:"af-text-sm af-text-yellow-800",children:"Your Stripe account can't currently accept charges. Check your Stripe account for outstanding requirements or notifications \u2014 once Stripe re-enables charges, payments resume here automatically."}):(0,De.jsx)("p",{className:"af-text-sm af-text-yellow-800",children:"Payments are currently paused for this site. If you think this is a mistake, get in touch with support and we'll look into it with you."})]})]}),(0,De.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&(0,De.jsxs)(x,{onClick:e,children:[(0,De.jsx)($a.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,De.jsxs)(x,{variant:"outline",onClick:i,disabled:d,children:[d?(0,De.jsx)($a.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,De.jsx)($a.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var la=ie(require("react"),1);function eo(e,t,s){return e.map(n=>n.id===t?{...n,...s}:n)}function fn({includeStats:e=!1,refreshKey:t}={}){let{api:s}=W(),[n,a]=la.useState([]),[r,o]=la.useState(!0),[c,d]=la.useState(null),l=la.useRef(0),i=la.useCallback(async()=>{let p=++l.current;try{o(!0),d(null);let b=await s.getProducts(e?{include:"stats"}:{});if(p!==l.current)return;a(b)}catch(b){if(p!==l.current)return;d(b instanceof Error?b:new Error("Failed to fetch products"))}finally{p===l.current&&o(!1)}},[s,e,t]);la.useEffect(()=>{i()},[i]);let m=la.useCallback(async p=>{let b=await s.createProduct(p);return a(w=>[b,...w]),b},[s]),v=la.useCallback(async(p,b)=>{let w=await s.updateProduct(p,b);return a(P=>eo(P,p,w)),w},[s]),g=la.useCallback(async p=>{await s.deleteProduct(p),a(b=>b.filter(w=>w.id!==p))},[s]),u=la.useCallback(async(p,b)=>{let w=await s.attachProductFile(p,b);return a(P=>eo(P,p,w)),w},[s]),f=la.useCallback(async(p,b)=>{let w=await s.attachProductFileFromUrl(p,b);return a(P=>eo(P,p,w)),w},[s]);return{products:n,isLoading:r,error:c,refetch:i,createProduct:m,updateProduct:v,deleteProduct:g,attachProductFile:u,attachProductFileFromUrl:f}}var ca=ie(require("react"),1);var to=["creating","active","paused","canceling"],td=["canceled","failed"],ad={statuses:to},sd={};function mn({refreshKey:e,includeEnded:t=!1,limit:s=50}={}){let{api:n}=W(),[a,r]=ca.useState([]),[o,c]=ca.useState(0),[d,l]=ca.useState(0),[i,m]=ca.useState(!0),[v,g]=ca.useState(!1),[u,f]=ca.useState(null),[p,b]=ca.useState(t),w=ca.useRef(0),P=ca.useCallback(async()=>{let y=++w.current;m(!0),g(!1),f(null);try{let C=await n.getRetainers({statuses:p?void 0:to,limit:s,offset:0});if(y!==w.current)return;if(r(C.retainers),c(C.total),!p&&C.total===0){let k=await n.getRetainers({statuses:td,limit:1,offset:0});if(y!==w.current)return;l(k.total)}else l(0)}catch(C){if(y!==w.current)return;f(C instanceof Error?C:new Error("Failed to fetch retainers"))}finally{y===w.current&&m(!1)}},[n,p,s]);ca.useEffect(()=>{P()},[P,e]);let T=ca.useCallback(async()=>{if(i||v||a.length>=o)return;let y=w.current;g(!0);try{let C=await n.getRetainers({statuses:p?void 0:to,limit:s,offset:a.length});if(y!==w.current)return;r(k=>{let I=new Set(k.map(N=>N.id));return[...k,...C.retainers.filter(N=>!I.has(N.id))]}),c(C.total)}catch(C){if(y!==w.current)return;f(C instanceof Error?C:new Error("Failed to fetch retainers"))}finally{y===w.current&&g(!1)}},[n,p,s,i,v,a.length,o]);return{retainers:a,total:o,endedTotal:d,hasMore:a.length<o,isLoading:i,isLoadingMore:v,error:u,includeEnded:p,setIncludeEnded:b,loadMore:T,refetch:P,filters:p?sd:ad}}var Ee=require("react/jsx-runtime");function ao({className:e,defaultTab:t="products",onConnectStripe:s,onRefund:n,onUpgradePlan:a}){let[r,o]=En.useState(t),[c,d]=En.useState("list"),[l,i]=En.useState(null),m=fn(),{status:v,error:g}=Ts(),u=v?.currency,f=P=>{i(P),d("edit")},p=()=>{i(null),d("create")},b=()=>{d("list"),i(null)},w=P=>{i(P),d("edit")};return(0,Ee.jsxs)("div",{className:e,children:[(0,Ee.jsxs)("div",{className:"af-mb-6",children:[(0,Ee.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Ee.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Ee.jsxs)(Hr,{value:r,onValueChange:P=>o(P),children:[(0,Ee.jsxs)(qn,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Ee.jsxs)(is,{value:"products",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Ee.jsxs)(is,{value:"orders",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Ee.jsxs)(is,{value:"invoices",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Ee.jsxs)(is,{value:"customers",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Ee.jsx)(is,{value:"promos",children:"Promo codes"}),(0,Ee.jsxs)(is,{value:"setup",className:"af-gap-2",children:[(0,Ee.jsx)(Xa.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Ee.jsx)(os,{value:"products",children:c==="list"?(0,Ee.jsx)(rr,{productsState:m,onSelectProduct:f,onCreateProduct:p}):(0,Ee.jsxs)("div",{children:[(0,Ee.jsxs)("div",{className:"af-mb-6",children:[(0,Ee.jsxs)(x,{variant:"ghost",size:"sm",onClick:b,className:"af-mb-2 af--ml-2",children:[(0,Ee.jsx)(Xa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Ee.jsx)("h3",{className:"af-text-lg af-font-semibold",children:c==="create"?"New Product":l?.name})]}),c==="create"&&!u?(0,Ee.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?(0,Ee.jsxs)("div",{className:"af-text-destructive",children:["Error: ",g.message]}):(0,Ee.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Ee.jsx)(or,{productsState:m,product:c==="edit"?l:null,currency:u??"usd",onSaved:w},c==="edit"?l?.id??"edit":"new")]})}),(0,Ee.jsx)(os,{value:"orders",children:(0,Ee.jsx)(Ds,{onRefund:n})}),(0,Ee.jsx)(os,{value:"invoices",children:(0,Ee.jsx)(nd,{onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:v?.reason==="needs_paid_plan"})}),(0,Ee.jsx)(os,{value:"customers",children:(0,Ee.jsx)(pr,{})}),(0,Ee.jsx)(os,{value:"promos",children:(0,Ee.jsx)(nn,{})}),(0,Ee.jsx)(os,{value:"setup",children:(0,Ee.jsx)(dn,{onConnectStripe:s,onUpgradePlan:a})})]})]})}function nd({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s}){let n=mn(),[a,r]=En.useState(null),[o,c]=En.useState(!1);return(0,Ee.jsxs)(Ee.Fragment,{children:[!o&&(0,Ee.jsx)(un,{retainers:n.retainers,isLoading:n.isLoading,error:n.error,onRetry:()=>void n.refetch(),activeRetainerId:a?.id??null,onShowCycles:d=>r(l=>l?.id===d.id?null:d),total:n.total,endedTotal:n.endedTotal,isLoadingMore:n.isLoadingMore,onLoadMore:()=>void n.loadMore(),includeEnded:n.includeEnded,onIncludeEndedChange:n.setIncludeEnded}),(0,Ee.jsx)(Ls,{onDetailOpenChange:c,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s,retainerFilter:a?{id:a.id,label:`${a.customer_name??a.customer_email??"Recurring invoices"} \u2014 ${a.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}var Bl=ie(require("react"),1);var xs=ie(require("react"),1);function pn({refreshKey:e}={}){let{api:t}=W(),[s,n]=xs.useState(null),[a,r]=xs.useState(!0),[o,c]=xs.useState(null),d=xs.useRef(0),l=xs.useCallback(async()=>{let i=++d.current;try{r(!0),c(null);let m=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(i!==d.current)return;n(m)}catch(m){if(i!==d.current)return;c(m instanceof Error?m:new Error("Failed to fetch summary"))}finally{i===d.current&&r(!1)}},[t,e]);return xs.useEffect(()=>{l()},[l]),{summary:s,isLoading:a,error:o,refetch:l}}var nt=require("react/jsx-runtime");function Ol(e,t){if(e.settled.complete)return{headline:Z(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:Z(s.gross,s.currency),extra:e.totals.slice(1).map(n=>`+ ${Z(n.gross,n.currency)} in ${n.currency.toUpperCase()}`)}:{headline:Z(0,t),extra:[]}}function so({refreshKey:e,initialOrderId:t,isOwner:s=!1,onRefund:n,onBackToWebsite:a,className:r}){let{summary:o,isLoading:c,error:d,refetch:l}=pn({refreshKey:e}),[i,m]=Bl.useState(!1),v=(0,nt.jsx)("div",{className:"af-mb-6",children:d&&!o?(0,nt.jsx)(Lt,{message:"Couldn't load your revenue summary.",onRetry:()=>l()}):(0,nt.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:c||!o?(0,nt.jsxs)(nt.Fragment,{children:[(0,nt.jsx)(st,{label:"This week",children:(0,nt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,nt.jsx)(st,{label:"Today",children:(0,nt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,nt.jsx)(st,{label:"Needs attention",children:(0,nt.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,nt.jsx)(nt.Fragment,{children:(()=>{let g=Ol(o.revenue.d7,o.currency),u=Ol(o.revenue.today,o.currency);return(0,nt.jsxs)(nt.Fragment,{children:[(0,nt.jsx)(st,{label:"This week",detail:g.extra.length>0?(0,nt.jsx)("div",{children:g.extra.map(f=>(0,nt.jsx)("div",{children:f},f))}):void 0,children:g.headline}),(0,nt.jsx)(st,{label:"Today",detail:u.extra.length>0?(0,nt.jsx)("div",{children:u.extra.map(f=>(0,nt.jsx)("div",{children:f},f))}):void 0,children:u.headline}),(0,nt.jsx)(st,{label:"Needs attention",valueClassName:o.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:o.needs_attention.count===0?"All clear":o.needs_attention.items[0]?.title??void 0,children:o.needs_attention.count})]})})()})})});return(0,nt.jsxs)(St,{title:"Orders",onBackToWebsite:a,hideBackButton:i,className:r,children:[v,(0,nt.jsx)(Ds,{refreshKey:e,initialOrderId:t,onDetailOpenChange:m,showFulfillment:!0,onRefund:s?n:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Qa=ie(require("react"),1),In=require("lucide-react");var Ss=ie(require("react"),1),gi=require("lucide-react");var qt=require("react/jsx-runtime"),Fl="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ys="af-text-xs af-text-muted-foreground",ui="af-text-sm af-font-medium af-tabular-nums",rd=3;function id(e){let t=e.pricing,s=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let d=e.min_amount??t?.min_amount??null,l=e.max_amount??t?.max_amount??null;return d!==null&&l!==null?{text:`Buyer chooses (${Z(d,s)} \u2013 ${Z(l,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let a=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(a===null||r===null)return{text:"Varies by variant",compareAt:null};let o=a===r?Z(a,s):`${Z(a,s)} \u2013 ${Z(r,s)}`,c=t?.compare_at_amount??null;return{text:o,compareAt:c!==null&&c>r?Z(c,s):null}}function di({product:e,className:t}){let s=id(e);return(0,qt.jsxs)("div",{className:t,children:[(0,qt.jsx)("span",{className:ui,children:s.text}),s.compareAt&&(0,qt.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function fi({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,qt.jsx)(oe,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,qt.jsxs)(oe,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,qt.jsx)(oe,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,qt.jsxs)(oe,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,qt.jsx)(oe,{variant:"warning",children:"Low stock"}):null}function mi(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function pi(e){return e.map(t=>Z(t.amount,t.currency)).join(" + ")}function Ul(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${Z(e.min_amount,e.currency)} \u2013 ${Z(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":Z(e.unit_amount,e.currency)}function Ml({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,qt.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=t.available??0;return t.allow_backorder?(0,qt.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,qt.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,s)}),(0,qt.jsx)(oe,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?(0,qt.jsx)(oe,{variant:"destructive",children:"Out of stock"}):(0,qt.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,qt.jsx)("span",{className:"af-tabular-nums",children:s}),s<=rd&&(0,qt.jsx)(oe,{variant:"warning",children:"Low"})]})}var ne=require("react/jsx-runtime");function gr({title:e,children:t,className:s}){return(0,ne.jsxs)("section",{className:J("af-rounded-lg af-border af-p-4",s),children:[(0,ne.jsx)("h4",{className:Fl,children:e}),(0,ne.jsx)("div",{className:"af-mt-3",children:t})]})}function $l({src:e,className:t}){let[s,n]=Ss.useState(!1);return Ss.useEffect(()=>n(!1),[e]),!e||s?(0,ne.jsx)("div",{"aria-hidden":"true",className:J("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,ne.jsx)(gi.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,ne.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>n(!0),className:J("af-object-cover",t)})}function Vl({product:e,showStats:t=!1,onBack:s}){let{api:n}=W(),[a,r]=Ss.useState(null),[o,c]=Ss.useState(!0),[d,l]=Ss.useState(null),[i,m]=Ss.useState(0),[v,g]=Ss.useState(0);Ss.useEffect(()=>{let y=!1;return c(!0),l(null),n.getProduct(e.id).then(C=>{y||r(C)}).catch(C=>{y||l(C instanceof Error?C:new Error("Failed to load product"))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[n,e.id,i]);let u=a?{...e,...a}:e,f=u.images.length>0?u.images:e.images,p=f[v]??f[0],b=mi(u),w=t?u.stats:void 0,P=a?.variants??[],T=P.length>1;return(0,ne.jsxs)("div",{children:[(0,ne.jsxs)("div",{className:"af-mb-6",children:[(0,ne.jsxs)(x,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,ne.jsx)(gi.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,ne.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,ne.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),(0,ne.jsx)(oe,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),(0,ne.jsx)(fi,{product:u})]}),(0,ne.jsx)(di,{product:u,className:"af-mt-1"}),!u.active&&(0,ne.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),(0,ne.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,ne.jsxs)("div",{className:"af-space-y-2",children:[(0,ne.jsx)($l,{src:p,className:"af-h-48 af-w-full af-rounded-md af-border"}),f.length>1&&(0,ne.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:f.map((y,C)=>(0,ne.jsx)("button",{type:"button",onClick:()=>g(C),"aria-label":`Show photo ${C+1} of ${f.length}`,"aria-pressed":C===v,className:J("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",C===v?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,ne.jsx)($l,{src:y,className:"af-h-12 af-w-12 af-rounded-md"})},`${y}-${C}`))})]}),(0,ne.jsxs)("div",{className:"af-space-y-6",children:[u.description&&(0,ne.jsx)(gr,{title:"Description",children:(0,ne.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?(0,ne.jsxs)(gr,{title:"Variants",children:[(0,ne.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(y=>(0,ne.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,ne.jsx)(ae,{className:"af-h-4 af-w-28"}),(0,ne.jsx)(ae,{className:"af-h-4 af-w-20"}),(0,ne.jsx)(ae,{className:"af-h-4 af-w-16"})]},y))}),(0,ne.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):d?(0,ne.jsx)(Lt,{message:"Couldn't load this product's variants.",onRetry:()=>m(y=>y+1)}):T?(0,ne.jsx)(gr,{title:`Variants \xB7 ${P.length}`,children:(0,ne.jsx)("div",{className:"af-overflow-x-auto",children:(0,ne.jsxs)(et,{children:[(0,ne.jsx)(tt,{children:(0,ne.jsxs)(Ie,{children:[(0,ne.jsx)(j,{children:"Variant"}),(0,ne.jsx)(j,{children:"SKU"}),(0,ne.jsx)(j,{className:"af-text-right",children:"Price"}),(0,ne.jsx)(j,{children:"Stock"})]})}),(0,ne.jsx)(at,{children:P.map(y=>(0,ne.jsxs)(Ie,{children:[(0,ne.jsxs)(G,{className:"af-font-medium",children:[y.title||y.option_values.map(C=>C.value).join(" / ")||"\u2014",!y.active&&(0,ne.jsx)(oe,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,ne.jsx)(G,{className:"af-text-muted-foreground",children:y.sku?(0,ne.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:y.sku}):"\u2014"}),(0,ne.jsxs)(G,{className:"af-whitespace-nowrap af-text-right",children:[(0,ne.jsx)("div",{className:ui,children:Ul(y)}),y.compare_at_amount!==null&&y.unit_amount!==null&&y.compare_at_amount>y.unit_amount&&(0,ne.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:Z(y.compare_at_amount,y.currency)})]}),(0,ne.jsx)(G,{className:"af-text-sm",children:(0,ne.jsx)(Ml,{variant:y})})]},y.id))})]})})}):null,(0,ne.jsx)(gr,{title:"Details",children:(0,ne.jsxs)("dl",{className:"af-space-y-2",children:[(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Delivery"}),(0,ne.jsx)("dd",{className:"af-text-sm",children:b==="Digital download"?u.fulfillment.filename??"Digital download":b??"Nothing to deliver"})]}),u.fulfillment.type==="redirect"&&u.fulfillment.url&&(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Sends buyers to"}),(0,ne.jsx)("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Shipping address"}),(0,ne.jsx)("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Most one buyer can order"}),(0,ne.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),w&&(0,ne.jsx)(gr,{title:"Last 30 days",children:(0,ne.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Units sold"}),(0,ne.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:w.units_sold})]}),(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Orders"}),(0,ne.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:w.orders})]}),(0,ne.jsxs)("div",{children:[(0,ne.jsx)("dt",{className:Ys,children:"Gross"}),(0,ne.jsx)("dd",{className:ui,children:w.gross.length>0?pi(w.gross):"\u2014"})]})]})}),(0,ne.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var q=require("react/jsx-runtime"),od={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},ld=["all","active","draft","low_stock","out_of_stock"];function Hl(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t).getTime();return Number.isNaN(s)?0:s}function zl(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function cd(e){return e.inventory?.out_of_stock??!1}function ud(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return zl(e);case"out_of_stock":return cd(e);default:return!0}}function dd({product:e,showStats:t,onOpen:s}){let n=e.images[0],a=t?e.stats:void 0,r=mi(e),o=e.variant_count??0;return(0,q.jsxs)("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[n?(0,q.jsx)("img",{src:n,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,q.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:(0,q.jsx)(In.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,q.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,q.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,q.jsxs)("div",{className:"af-min-w-0",children:[(0,q.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,q.jsx)(di,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,q.jsx)(oe,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,q.jsx)(fi,{product:e}),o>1&&(0,q.jsxs)(oe,{variant:"outline",children:[o," variants"]}),r&&(0,q.jsx)(oe,{variant:"outline",children:r})]}),a&&(0,q.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[a.units_sold," sold",a.gross.length>0?` \xB7 ${pi(a.gross)}`:""," ",(0,q.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function fd(){return(0,q.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:[0,1,2,3,4,5].map(e=>(0,q.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,q.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,q.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,q.jsx)(ae,{className:"af-w-32"}),(0,q.jsx)(ae,{className:"af-w-16"}),(0,q.jsx)(ae,{className:"af-h-5 af-w-24"})]})]},e))})}function no({refreshKey:e,showStats:t=!1,onBackToWebsite:s,className:n}){let{products:a,isLoading:r,error:o,refetch:c}=fn({includeStats:t,refreshKey:e}),[d,l]=Qa.useState(!1),[i,m]=Qa.useState(null),[v,g]=Qa.useState("all"),{api:u}=W(),f=Qa.useCallback(()=>u.exportProductsCsv(),[u]),[p,b]=Qa.useState(""),[w,P]=Qa.useState("newest"),T=Qa.useMemo(()=>{if(!t)return null;let Q=null;for(let z of a)!z.stats||z.stats.units_sold===0||(!Q||z.stats.units_sold>(Q.stats?.units_sold??0))&&(Q=z);return Q},[a,t]),y=Qa.useMemo(()=>a.filter(zl).length,[a]),C=p.trim().toLowerCase(),k=Qa.useMemo(()=>{let z=[...a.filter(le=>ud(le,v)&&(!C||le.name.toLowerCase().includes(C)))];return w==="name"?z.sort((le,fe)=>le.name.localeCompare(fe.name)):w==="best_selling"?z.sort((le,fe)=>(fe.stats?.units_sold??0)-(le.stats?.units_sold??0)):z.sort((le,fe)=>Hl(fe.created_at)-Hl(le.created_at)),z},[a,v,C,w]),I=v!=="all"||!!C,N=()=>{g("all"),b("")},E=r||o!==null&&a.length===0,D=(0,q.jsx)("div",{className:"af-mb-6",children:(0,q.jsx)("div",{className:J("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:E?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(st,{label:"Products",children:(0,q.jsx)(ae,{className:"af-h-6 af-w-10"})}),t?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(st,{label:"Best seller",children:(0,q.jsx)(ae,{className:"af-h-6 af-w-28"})}),(0,q.jsx)(st,{label:"Low stock",children:(0,q.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,q.jsx)(st,{label:"Active",children:(0,q.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(st,{label:"Products",children:a.length}),t?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(st,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:T?`${T.stats?.units_sold??0} sold, last 30 days`:void 0,children:T?(0,q.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:T.name}):(0,q.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,q.jsx)(st,{label:"Low stock",children:y})]}):(0,q.jsx)(st,{label:"Active",children:a.filter(Q=>Q.active).length})]})})}),_=(0,q.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,q.jsx)("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:ld.map(Q=>(0,q.jsx)("button",{type:"button","aria-pressed":v===Q,onClick:()=>g(Q),className:J("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",v===Q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:od[Q]},Q))}),(0,q.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,q.jsx)(In.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,q.jsx)(re,{type:"text",value:p,onChange:Q=>b(Q.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,q.jsxs)(qa,{value:w,onValueChange:Q=>P(Q),children:[(0,q.jsx)(ka,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,q.jsx)(Wa,{})}),(0,q.jsxs)(Ta,{children:[(0,q.jsx)(dt,{value:"newest",children:"Newest"}),(0,q.jsx)(dt,{value:"name",children:"Name A\u2013Z"}),t&&(0,q.jsx)(dt,{value:"best_selling",children:"Best selling"})]})]}),I&&(0,q.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:N,children:"Clear filters"}),(0,q.jsx)(Zt,{fetchCsv:f,filename:"products",label:I?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&a.length===0?(0,q.jsx)(ae,{className:"af-h-4 af-w-28"}):(0,q.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:I?`${k.length} of ${a.length} products`:`${a.length} ${a.length===1?"product":"products"}${y>0?` \xB7 ${y} low stock`:""}`})]}),Y;return i?Y=(0,q.jsx)(Vl,{product:i,showStats:t,onBack:()=>{m(null),c()}},i.id):r&&a.length===0?Y=(0,q.jsxs)(q.Fragment,{children:[_,(0,q.jsx)(fd,{}),(0,q.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&a.length===0?Y=(0,q.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,q.jsx)(Lt,{message:"Couldn't load your products.",onRetry:()=>c()})}):a.length===0?Y=(0,q.jsxs)(aa,{icon:(0,q.jsx)(In.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,q.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):Y=(0,q.jsxs)(q.Fragment,{children:[_,o&&(0,q.jsx)("div",{className:"af-mb-4",children:(0,q.jsx)(Lt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>c()})}),k.length===0?(0,q.jsxs)(aa,{children:["No products match these filters.",(0,q.jsx)("br",{}),(0,q.jsx)(x,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:N,children:"Show all products"})]}):(0,q.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:k.map(Q=>(0,q.jsx)(dd,{product:Q,showStats:t,onOpen:()=>m(Q)},Q.id))})]}),(0,q.jsx)(St,{title:"Products",onBackToWebsite:s,hideBackButton:!!i,className:n,children:d?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(x,{variant:"ghost",onClick:()=>l(!1),children:"Back to products"}),(0,q.jsx)(nn,{})]}):(0,q.jsxs)(q.Fragment,{children:[!i&&(0,q.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,q.jsx)(x,{variant:"outline",onClick:()=>l(!0),children:"Promo codes"})}),!i&&D,Y]})})}var ha=ie(require("react"),1),Et=require("lucide-react");var ya=ie(require("react"),1);function vr({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=W(),[n,a]=ya.useState([]),[r,o]=ya.useState(!0),[c,d]=ya.useState(null),[l,i]=ya.useState(0),[m]=ya.useState(e),[v,g]=ya.useState(""),[u,f]=ya.useState(void 0),p=ya.useRef(0),b=ya.useCallback(async({afterRemoval:w=!1}={})=>{let P=++p.current;try{o(!0),d(null);let T={limit:m,offset:l*m};v.trim()&&(T.q=v.trim()),u&&(T.source=u);let y=await s.getPeople(T);if(P!==p.current)return;if(w&&y.people.length===0&&l>0){i(l-1);return}a(y.people)}catch(T){if(P!==p.current)return;d(T instanceof Error?T:new Error("Failed to fetch people"))}finally{P===p.current&&o(!1)}},[s,l,m,v,u,t]);return ya.useEffect(()=>{b()},[b]),{people:n,isLoading:r,error:c,page:l,pageSize:m,hasNextPage:n.length===m,hasPreviousPage:l>0,setPage:i,q:v,setQ:w=>{g(w),i(0)},source:u,setSource:w=>{f(w),i(0)},refetch:()=>b(),refetchAfterRemoval:()=>b({afterRemoval:!0})}}var ws=ie(require("react"),1);function br(e,{refreshKey:t}={}){let{api:s}=W(),[n,a]=ws.useState(null),[r,o]=ws.useState(e!==null),[c,d]=ws.useState(null),l=ws.useRef(0),i=ws.useCallback(async()=>{if(e===null){a(null),o(!1),d(null);return}let m=++l.current;try{o(!0),d(null);let v=await s.getPerson(e);if(m!==l.current)return;a(v)}catch(v){if(m!==l.current)return;d(v instanceof Error?v:new Error("Failed to fetch person"))}finally{m===l.current&&o(!1)}},[s,e,t]);return ws.useEffect(()=>{i()},[i]),{person:n,isLoading:r,error:c,refetch:i}}var R=require("react/jsx-runtime"),ro="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",md="af-text-xs af-text-muted-foreground";function Dn(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function io(e,t){let s=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function pd(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function gd({value:e,label:t}){let[s,n]=ha.useState(!1);return pd()?(0,R.jsxs)(x,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[s?(0,R.jsx)(Et.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,R.jsx)(Et.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function ql(e){return(0,R.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,R.jsxs)(oe,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,R.jsx)(oe,{variant:"secondary",children:"Contact form"})]})}function Wl(e){return e.name?e.name:e.email?e.email:(0,R.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var vd=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,bd=40;function yd(e){let t=Object.entries(e).filter(([a])=>!a.startsWith("_")),n=t.find(([a,r])=>vd.test(a)&&typeof r=="string"&&r.trim())??t.filter(([,a])=>typeof a=="string"&&a.trim().length>=bd).sort((a,r)=>String(r[1]).trim().length-String(a[1]).trim().length)[0];return n?{message:String(n[1]),rest:t.filter(([a])=>a!==n[0])}:{message:null,rest:t}}function hd(e){return e.replace(/_/g," ")}function xd(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Sd({data:e}){let{message:t,rest:s}=yd(e);return t===null&&s.length===0?(0,R.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,R.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,R.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),s.length>0&&(0,R.jsx)("dl",{className:"af-space-y-1",children:s.map(([n,a])=>(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,R.jsx)("dt",{className:J(md,"af-w-28 af-shrink-0 af-capitalize"),children:hd(n)}),(0,R.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:xd(a)})]},n))})]})}function Gl({formName:e,createdAt:t,data:s,onDelete:n}){return(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)(oe,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,R.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,R.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Dn(t)}),(0,R.jsx)(Nn,{iconOnly:!0,onDelete:n})]}),(0,R.jsx)(Sd,{data:s})]})}function wd(e){return e.charged_total??e.amount_total}function Nd({email:e,refreshKey:t,onBack:s,onRemoved:n}){let{api:a}=W(),{person:r,isLoading:o,error:c,refetch:d}=br(e,{refreshKey:t}),l=async m=>{await a.deleteSubmission(m),n(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?d():s()},i=io(e,r?.submissions[0]?.form_name);return(0,R.jsxs)("div",{children:[(0,R.jsxs)("div",{className:"af-mb-6",children:[(0,R.jsxs)(x,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,R.jsx)(Et.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,R.jsxs)("div",{className:"af-min-w-0",children:[o?(0,R.jsx)(ae,{className:"af-h-7 af-w-48"}):(0,R.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),(0,R.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,R.jsx)(gd,{value:e,label:"Copy email address"})]})]}),(0,R.jsx)(x,{asChild:!0,children:(0,R.jsxs)("a",{href:i,children:[(0,R.jsx)(Et.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),o?(0,R.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(m=>(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsx)(ae,{className:"af-w-40"}),(0,R.jsx)(ae,{className:"af-mt-2 af-w-64"})]},m)),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):c||!r?(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(Lt,{message:"Couldn't load this person.",onRetry:()=>d()})}):(0,R.jsxs)("div",{className:"af-space-y-6",children:[r.customer&&(0,R.jsxs)("div",{children:[(0,R.jsx)("h4",{className:J(ro,"af-mb-3"),children:"Customer"}),(0,R.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&(0,R.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,R.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,R.jsx)("dd",{children:r.customer.name})]}),r.customer.phone&&(0,R.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,R.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,R.jsx)("dd",{children:r.customer.phone})]}),(0,R.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,R.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,R.jsx)("dd",{children:Dn(r.customer.created_at)})]})]})]}),r.orders.length>0&&(0,R.jsxs)("div",{children:[(0,R.jsx)("h4",{className:J(ro,"af-mb-3"),children:"Purchases"}),(0,R.jsx)("div",{className:"af-overflow-x-auto",children:(0,R.jsxs)(et,{children:[(0,R.jsx)(tt,{children:(0,R.jsxs)(Ie,{children:[(0,R.jsx)(j,{children:"Order"}),(0,R.jsx)(j,{children:"Date"}),(0,R.jsx)(j,{className:"af-text-right",children:"Total"}),(0,R.jsx)(j,{children:"Status"})]})}),(0,R.jsx)(at,{children:r.orders.map(m=>(0,R.jsxs)(Ie,{children:[(0,R.jsx)(G,{className:"af-whitespace-nowrap af-font-medium",children:Is(m)}),(0,R.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Dn(m.created_at)}),(0,R.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:Z(wd(m),m.currency)}),(0,R.jsx)(G,{children:(0,R.jsx)(Gs,{status:m.status})})]},m.id))})]})}),(0,R.jsx)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),r.submissions.length>0&&(0,R.jsxs)("div",{children:[(0,R.jsx)("h4",{className:J(ro,"af-mb-3"),children:"Messages"}),(0,R.jsx)("div",{className:"af-space-y-3",children:r.submissions.map(m=>(0,R.jsx)(Gl,{formName:m.form_name,createdAt:m.created_at,data:m.data,onDelete:()=>l(m.id)},m.id))})]})]})]})}function Rd({submissionId:e,onBack:t,onRemoved:s}){let{api:n}=W(),[a,r]=ha.useState(null),[o,c]=ha.useState(!0),[d,l]=ha.useState(null),[i,m]=ha.useState(0);return ha.useEffect(()=>{let v=!1;return c(!0),l(null),n.getSubmission(e).then(g=>{v||r(g)}).catch(g=>{v||l(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{v||c(!1)}),()=>{v=!0}},[n,e,i]),(0,R.jsxs)("div",{children:[(0,R.jsxs)("div",{className:"af-mb-6",children:[(0,R.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,R.jsx)(Et.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,R.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),o?(0,R.jsx)(ae,{className:"af-mt-1 af-h-4 af-w-32"}):a&&(0,R.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Dn(a.metadata.submitted_at)})]}),o?(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,R.jsx)(ae,{className:"af-w-40"}),(0,R.jsx)(ae,{className:"af-mt-2 af-w-64"}),(0,R.jsx)(ae,{className:"af-mt-2 af-w-52"}),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):d||!a?(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(Lt,{message:"Couldn't load this submission.",onRetry:()=>m(v=>v+1)})}):(0,R.jsxs)("div",{className:"af-space-y-3",children:[(0,R.jsx)(Gl,{formName:null,createdAt:a.metadata.submitted_at,data:a.data,onDelete:async()=>{await n.deleteSubmission(e),s(),t()}}),(0,R.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"No email address came with this submission, so there is nobody to reply to."})]})]})}var _d={all:"All",customers:"Customers",leads:"Leads"},Pd=["all","customers","leads"],jl={all:void 0,customers:"customer",leads:"lead"};function Cd({refreshKey:e,onBackToWebsite:t,className:s,maxRows:n,onViewAll:a}){let r=typeof n=="number",{people:o,isLoading:c,error:d,page:l,pageSize:i,hasNextPage:m,hasPreviousPage:v,setPage:g,q:u,setQ:f,source:p,setSource:b,refetch:w,refetchAfterRemoval:P}=vr({refreshKey:e}),[T,y]=ha.useState({kind:"list"}),[C,k]=ha.useState(""),I=p==="customer"?"customers":p==="lead"?"leads":"all",N=ee=>{jl[ee]!==p&&b(jl[ee])},{api:E}=W(),D=ha.useCallback(()=>E.exportPeopleCsv({...u?{q:u}:{},...p?{source:p}:{}}),[E,u,p]),_=!r||!!a,Y=ee=>{if(r){a?.();return}ee.email?y({kind:"person",email:ee.email}):ee.submission_id&&y({kind:"submission",submissionId:ee.submission_id})},Q=ha.useRef(!1),z=()=>{Q.current=!0},le=()=>{y({kind:"list"}),Q.current?(Q.current=!1,P()):w()},fe=ee=>{let U=ee.trim();U!==u&&f(U)},he=r?o.slice(0,n):o,M;if(T.kind==="person")M=(0,R.jsx)(Nd,{email:T.email,refreshKey:e,onBack:le,onRemoved:z});else if(T.kind==="submission")M=(0,R.jsx)(Rd,{submissionId:T.submissionId,onBack:le,onRemoved:z});else{let ee=(0,R.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Pd.map(U=>(0,R.jsx)("button",{type:"button","aria-pressed":I===U,onClick:()=>N(U),className:J("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",I===U?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:_d[U]},U))}),(0,R.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,R.jsx)(Et.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,R.jsx)(re,{type:"text",value:C,onChange:U=>k(U.target.value),onBlur:()=>fe(C),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),fe(C))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),u&&(0,R.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>{k(""),f("")},children:"Clear search"}),(0,R.jsx)(Zt,{fetchCsv:D,filename:"people",className:"af-ml-auto"})]});if(c)M=(0,R.jsxs)("div",{children:[r?null:ee,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,R.jsx)(ae,{className:"af-h-4 af-w-32"}),(0,R.jsx)(ae,{className:"af-h-4 af-w-16"})]}),(0,R.jsx)(ae,{className:"af-mt-2 af-h-5 af-w-28"}),(0,R.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-56"})]},U))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(et,{children:[(0,R.jsx)(tt,{children:(0,R.jsxs)(Ie,{children:[(0,R.jsx)(j,{children:"Person"}),(0,R.jsx)(j,{children:"Came from"}),(0,R.jsx)(j,{children:"Latest message"}),(0,R.jsx)(j,{children:"Last activity"}),(0,R.jsx)(j,{className:"af-w-8"}),(0,R.jsx)(j,{className:"af-w-8"})]})}),(0,R.jsx)(at,{"aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,R.jsxs)(Ie,{children:[(0,R.jsx)(G,{children:(0,R.jsx)(ae,{className:"af-h-4 af-w-40"})}),(0,R.jsx)(G,{children:(0,R.jsx)(ae,{className:"af-h-5 af-w-24"})}),(0,R.jsx)(G,{children:(0,R.jsx)(ae,{className:"af-h-4 af-w-56"})}),(0,R.jsx)(G,{children:(0,R.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,R.jsx)(G,{}),(0,R.jsx)(G,{})]},U))})]})}),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(d)M=(0,R.jsxs)("div",{children:[r?null:ee,(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(Lt,{message:"Couldn't load your leads.",onRetry:()=>w()})})]});else if(he.length===0&&l===0){let U=!!u||I!=="all";M=(0,R.jsxs)("div",{children:[U&&ee,U?(0,R.jsx)(aa,{children:u?"Nobody matches that search.":I==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,R.jsx)(Ks,{icon:Et.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)M=(0,R.jsxs)("div",{children:[r?null:ee,(0,R.jsx)(aa,{children:"No more results."}),(0,R.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,R.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>g(l-1),children:[(0,R.jsx)(Et.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let U=l*i+1,ve=l*i+o.length;M=(0,R.jsxs)("div",{children:[r?null:ee,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:he.map((me,Qe)=>(0,R.jsxs)("div",{onClick:_?()=>Y(me):void 0,className:`af-rounded-md af-border af-p-3${_?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,R.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,R.jsxs)("div",{className:"af-min-w-0",children:[(0,R.jsx)("button",{type:"button",onClick:ke=>{ke.stopPropagation(),Y(me)},disabled:!_,"aria-label":`Open ${me.name||me.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${_?" hover:af-underline":""}`,children:Wl(me)}),me.name&&me.email&&(0,R.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:me.email})]}),(0,R.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,R.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:Dn(me.last_activity_at)}),me.email&&(0,R.jsx)(x,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,R.jsx)("a",{href:io(me.email),onClick:ke=>ke.stopPropagation(),"aria-label":`Email ${me.email}`,children:(0,R.jsx)(Et.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,R.jsx)("div",{className:"af-mt-2",children:ql(me)}),me.latest_message_excerpt&&(0,R.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:me.latest_message_excerpt})]},me.email??me.submission_id??Qe))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(et,{children:[(0,R.jsx)(tt,{children:(0,R.jsxs)(Ie,{children:[(0,R.jsx)(j,{children:"Person"}),(0,R.jsx)(j,{children:"Came from"}),(0,R.jsx)(j,{children:"Latest message"}),(0,R.jsx)(j,{children:"Last activity"}),(0,R.jsx)(j,{className:"af-w-8",children:(0,R.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,R.jsx)(j,{className:"af-w-8"})]})}),(0,R.jsx)(at,{children:he.map((me,Qe)=>(0,R.jsxs)(Ie,{onClick:_?()=>Y(me):void 0,className:_?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,R.jsxs)(G,{className:"af-max-w-[260px] af-font-medium",children:[(0,R.jsx)("button",{type:"button",onClick:ke=>{ke.stopPropagation(),Y(me)},disabled:!_,"aria-label":`Open ${me.name||me.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${_?" hover:af-underline":""}`,children:Wl(me)}),me.name&&me.email&&(0,R.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:me.email})]}),(0,R.jsx)(G,{children:ql(me)}),(0,R.jsx)(G,{className:"af-max-w-[320px]",children:me.latest_message_excerpt?(0,R.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:me.latest_message_excerpt}):(0,R.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,R.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Dn(me.last_activity_at)}),(0,R.jsx)(G,{className:"af-w-8",children:me.email&&(0,R.jsx)(x,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,R.jsx)("a",{href:io(me.email),onClick:ke=>ke.stopPropagation(),"aria-label":`Email ${me.email}`,children:(0,R.jsx)(Et.Mail,{className:"af-h-4 af-w-4"})})})}),(0,R.jsx)(G,{className:"af-w-8 af-text-right",children:(0,R.jsx)(Et.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},me.email??me.submission_id??Qe))})]})}),!r&&(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,R.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${U}-${ve}`}),(0,R.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,R.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>g(l-1),disabled:!v,children:[(0,R.jsx)(Et.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,R.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>g(l+1),disabled:!m,children:["Next",(0,R.jsx)(Et.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?(0,R.jsx)("div",{className:s,children:M}):(0,R.jsx)(St,{title:"Leads",onBackToWebsite:t,hideBackButton:T.kind!=="list",className:s,children:M})}function yr(e){return(0,R.jsx)(Cd,{...e},e.maxRows==null?"full":"compact")}var Xl=ie(require("react"),1),gn=require("lucide-react");var xa=ie(require("react"),1);function hr({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=W(),[n,a]=xa.useState([]),[r,o]=xa.useState(0),[c,d]=xa.useState(!0),[l,i]=xa.useState(null),[m,v]=xa.useState(0),[g,u]=xa.useState(e),[f,p]=xa.useState(void 0),b=xa.useRef(0),w=xa.useCallback(async()=>{let T=++b.current;try{d(!0),i(null);let y={limit:g,offset:m*g};f&&(y.status=f);let C=await s.getSubscriptions(y);if(T!==b.current)return;a(C.subscriptions),o(C.total)}catch(y){if(T!==b.current)return;i(y instanceof Error?y:new Error("Failed to fetch subscriptions"))}finally{T===b.current&&d(!1)}},[s,m,g,f,t]);xa.useEffect(()=>{w()},[w]);let P=Math.ceil(r/g);return{subscriptions:n,total:r,isLoading:c,error:l,page:m,pageSize:g,hasNextPage:m<P-1,hasPreviousPage:m>0,setPage:v,setPageSize:T=>{u(T),v(0)},status:f,setStatus:T=>{p(T),v(0)},refetch:w}}var V=require("react/jsx-runtime");function Kl(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Zl({sub:e}){return e.status==="canceled"?(0,V.jsx)(oe,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,V.jsx)(oe,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,V.jsx)(oe,{variant:"warning",children:"Scheduled to cancel"}):(0,V.jsx)(oe,{variant:"success",children:"Active"}):(0,V.jsx)(oe,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function kd(e,t){let s=Z(t,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function Yl({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-font-medium af-tabular-nums",children:kd(e,e.current_amount)}),t&&(0,V.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",Z(e.plan_amount,e.currency)]})]})}function Jl(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Kl(e.current_period_end)}`:"Ends at period end":e.current_period_end?Kl(e.current_period_end):"\u2014"}function oo({refreshKey:e,onBackToWebsite:t,className:s}){let{subscriptions:n,total:a,isLoading:r,error:o,page:c,pageSize:d,hasNextPage:l,hasPreviousPage:i,setPage:m,status:v,refetch:g}=hr({refreshKey:e}),{api:u}=W(),f=Xl.useCallback(()=>u.exportSubscriptionsCsv(v?{status:v}:{}),[u,v]),p;if(r)p=(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(b=>(0,V.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,V.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,V.jsx)(ae,{className:"af-h-4 af-w-40"}),(0,V.jsx)(ae,{className:"af-h-4 af-w-20"})]}),(0,V.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-32"}),(0,V.jsx)(ae,{className:"af-mt-2 af-h-5 af-w-24"})]},b))}),(0,V.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,V.jsxs)(et,{children:[(0,V.jsx)(tt,{children:(0,V.jsxs)(Ie,{children:[(0,V.jsx)(j,{children:"Subscriber"}),(0,V.jsx)(j,{children:"Plan"}),(0,V.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,V.jsx)(j,{children:"Renews"}),(0,V.jsx)(j,{children:"Status"})]})}),(0,V.jsx)(at,{"aria-hidden":"true",children:[0,1,2,3,4].map(b=>(0,V.jsxs)(Ie,{children:[(0,V.jsx)(G,{children:(0,V.jsx)(ae,{className:"af-h-4 af-w-44"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ae,{className:"af-h-4 af-w-32"})}),(0,V.jsx)(G,{className:"af-text-right",children:(0,V.jsx)(ae,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ae,{className:"af-h-5 af-w-20"})})]},b))})]})}),(0,V.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=(0,V.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,V.jsx)(Lt,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(n.length===0&&c===0)p=(0,V.jsx)(aa,{icon:(0,V.jsx)(gn.Repeat,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(n.length===0)p=(0,V.jsxs)("div",{children:[(0,V.jsx)(aa,{children:"No more results."}),(0,V.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,V.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>m(c-1),children:[(0,V.jsx)(gn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let b=c*d+1,w=c*d+n.length;p=(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,V.jsx)(Zt,{fetchCsv:f,filename:"subscriptions"})}),(0,V.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:n.map(P=>(0,V.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,V.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,V.jsxs)("div",{className:"af-min-w-0",children:[(0,V.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:P.customer_email||(0,V.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,V.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:P.plan_title||"Untitled plan"})]}),(0,V.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,V.jsx)(Yl,{sub:P})})]}),(0,V.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Zl,{sub:P}),P.is_test&&(0,V.jsx)(oe,{variant:"outline",children:"Test"}),(0,V.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Jl(P)})]}),(0,V.jsx)(ps,{deliveries:P.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},P.id))}),(0,V.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,V.jsxs)(et,{children:[(0,V.jsx)(tt,{children:(0,V.jsxs)(Ie,{children:[(0,V.jsx)(j,{children:"Subscriber"}),(0,V.jsx)(j,{children:"Plan"}),(0,V.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,V.jsx)(j,{children:"Renews"}),(0,V.jsx)(j,{children:"Status"})]})}),(0,V.jsx)(at,{children:n.map(P=>(0,V.jsxs)(Ie,{children:[(0,V.jsx)(G,{className:"af-max-w-[240px]",children:(0,V.jsx)("div",{className:"af-truncate af-font-medium",children:P.customer_email||(0,V.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,V.jsx)(G,{className:"af-max-w-[220px]",children:(0,V.jsx)("div",{className:"af-truncate",children:P.plan_title||(0,V.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,V.jsx)(G,{className:"af-whitespace-nowrap af-text-right",children:(0,V.jsx)(Yl,{sub:P})}),(0,V.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Jl(P)}),(0,V.jsxs)(G,{children:[(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Zl,{sub:P}),P.is_test&&(0,V.jsx)(oe,{variant:"outline",children:"Test"})]}),(0,V.jsx)(ps,{deliveries:P.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},P.id))})]})}),(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,V.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${b}-${w} of ${a}`}),(0,V.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,V.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>m(c-1),disabled:!i,children:[(0,V.jsx)(gn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,V.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>m(c+1),disabled:!l,children:["Next",(0,V.jsx)(gn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,V.jsx)(St,{title:"Subscriptions",onBackToWebsite:t,className:s,children:p})}var Rs=ie(require("react"),1),mc=require("lucide-react");var sa=ie(require("react"),1);var vi=ie(require("react"),1),vn=typeof window>"u"?vi.useEffect:vi.useLayoutEffect;var bi=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},Td=(e,t)=>e instanceof Error?e:new Error(t);function Ed(e){let t={};return e.due_days!==void 0&&(t.invoice_due_days=e.due_days),e.reminder_schedule!==void 0&&(t.invoice_reminder_schedule=e.reminder_schedule),e.footer!==void 0&&(t.invoice_footer=e.footer),t}function Ql(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function Os({siteId:e,refreshKey:t,onSaveInvoiceSettings:s}){let{api:n}=W(),[a,r]=sa.useState(null),[o,c]=sa.useState(!0),[d,l]=sa.useState(null),i=sa.useRef(null),[m,v]=sa.useState(()=>Ql(n,e)),g=m.api!==n||m.siteId!==e,u=m;g&&(u=Ql(n,e),v(u),r(null),c(!0),l(null));let f=sa.useRef(u);vn(()=>{f.current!==u&&(f.current=u,i.current=null)},[u]);let p=(N,E)=>f.current===N&&E>N.applied,b=(N,E,D)=>p(N,E)?(N.applied=E,i.current=D,r(D),c(!1),!0):!1,w=async N=>{for(;N.writing;)await N.idle;let E=++N.seq;try{let D=await N.api.getSite(N.siteId);return b(N,E,D)&&l(null),{seq:E,error:null}}catch(D){return{seq:E,error:Td(D,"Failed to load store settings")}}},P=(N,E)=>{let D=async()=>{if(f.current!==N)throw new Error("Not saved: the store switched to another site first.");N.writing=!0,N.idle=new Promise(Y=>{N.markIdle=Y});try{return await E(++N.seq)}finally{N.writing=!1,N.markIdle()}},_=N.queue.then(D,D);return N.queue=_.catch(()=>{}),_},T=sa.useCallback(async()=>{let N=await w(u);N.error&&p(u,N.seq)&&(l(N.error),c(!1))},[u]);sa.useEffect(()=>{T()},[T,t]);let y=sa.useCallback(N=>P(u,async E=>{let D=await u.api.updateSite(u.siteId,N),{currency_restatement:_,...Y}=D;return b(u,E,Y)&&l(Q=>Q instanceof bi?Q:null),D}),[u]),C=sa.useRef(s);vn(()=>{C.current=s});let k=sa.useCallback(async(N,E)=>{await P(u,()=>N());let D=await w(u);return D.error&&p(u,D.seq)&&i.current&&(b(u,D.seq,{...i.current,...E}),l(new bi(`Saved, but couldn't refresh settings: ${D.error.message}`))),f.current===u?i.current:null},[u]),I=sa.useCallback(N=>{let E=C.current;return k(()=>E(N),Ed(N))},[k]);return{site:g?null:a,isLoading:g||o,error:g?null:d,refetch:T,updateSite:y,saveInvoiceSettings:s?I:null}}var $t=ie(require("react"),1),uo=require("lucide-react");var vt=require("react/jsx-runtime");function yi(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var cs="af-grid af-gap-1 af-text-sm",ec="af-h-9 af-rounded-md af-border af-border-input af-bg-background af-px-3 af-text-sm disabled:af-cursor-not-allowed disabled:af-opacity-50",tc="af-min-h-[72px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50";function Sa({children:e}){return(0,vt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function xr({children:e}){return(0,vt.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var Ns=$t.forwardRef(function({id:t,title:s,description:n,children:a},r){let o=`af-store-${t}-title`;return(0,vt.jsxs)("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":o,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[(0,vt.jsxs)("div",{className:"af-space-y-1",children:[(0,vt.jsx)("h3",{id:o,className:"af-text-sm af-font-semibold",children:s}),n&&(0,vt.jsx)(Sa,{children:n})]}),a]})});function hi({label:e,description:t,checked:s,onSave:n,disabled:a=!1,disabledReason:r}){let[o,c]=$t.useState(null),[d,l]=$t.useState(null),i=o??s,m=async v=>{c(v),l(null);try{await n(v)}catch(g){l(yi(g))}finally{c(null)}};return(0,vt.jsxs)("div",{className:"af-space-y-1",children:[(0,vt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,vt.jsx)("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":i,checked:i,disabled:a||o!==null,onChange:v=>void m(v.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),(0,vt.jsxs)("span",{className:"af-space-y-0.5",children:[(0,vt.jsxs)("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,o!==null&&(0,vt.jsx)(uo.Loader2,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&(0,vt.jsx)(Sa,{children:t})]})]}),(a&&r||d)&&(0,vt.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[a&&r&&(0,vt.jsx)(Sa,{children:r}),d&&(0,vt.jsx)(xr,{children:d})]})]})}var co=(e,t)=>JSON.stringify(e)===JSON.stringify(t),lo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Id(e,t,s,n=[]){if(!lo(e)||!lo(t)||!lo(s))return{draft:co(e,t)?s:e,dropped:[]};let a=[],r={...s};for(let o of Object.keys(s))co(e[o],t[o])||(n.includes(o)?a.push(o):r[o]=e[o]);return{draft:r,dropped:a}}function An(e,t){let s=JSON.stringify(e),[n,a]=$t.useState(e),[r,o]=$t.useState([]),c=$t.useRef(e),d=$t.useRef(e),l=$t.useRef(n);vn(()=>{d.current=e,l.current=n});let i=$t.useRef(t?.when);$t.useEffect(()=>{let v=Object.is(i.current,t?.when)?[]:t?.fields??[];if(i.current=t?.when,co(c.current,d.current)&&v.length===0)return;let g=Id(l.current,c.current,d.current,v);c.current=d.current,a(g.draft),g.dropped.length&&o(g.dropped)},[s,t?.when]);let m=$t.useCallback(v=>{a(v??d.current),o([])},[]);return{draft:n,setDraft:a,dirty:JSON.stringify(n)!==s,reset:m,dropped:r}}function Ln({dirty:e,saving:t,error:s,onSave:n,onDiscard:a}){return e?(0,vt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,vt.jsxs)(x,{type:"button",size:"sm",disabled:t,onClick:n,children:[t&&(0,vt.jsx)(uo.Loader2,{className:"af-animate-spin"}),"Save"]}),(0,vt.jsx)(x,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:a,children:"Discard"}),s&&(0,vt.jsx)("p",{role:"alert",className:J("af-text-sm af-text-destructive"),children:s})]}):null}function On(){let[e,t]=$t.useState(!1),[s,n]=$t.useState(null),a=$t.useCallback(async r=>{t(!0),n(null);try{await r()}catch(o){n(yi(o))}finally{t(!1)}},[]);return{saving:e,error:s,setError:n,run:a}}function ac({what:e}){return(0,vt.jsxs)(Sa,{children:["Only the site owner can change ",e,"."]})}var es=ie(require("react"),1),bn=require("lucide-react");var H=require("react/jsx-runtime"),mo=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ic({site:e,updateSite:t}){return(0,H.jsxs)("div",{className:"af-space-y-4",children:[(0,H.jsx)(hi,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:s=>t({collect_phone_at_checkout:s})}),e.checkout_marketing_consent!==void 0&&(0,H.jsx)(hi,{label:"Ask buyers for marketing consent at checkout",description:"Adds Stripe's consent checkbox to your checkout. Buyers who tick it join your email list, and buyers who leave without paying can get your abandoned-cart recovery emails.",checked:e.checkout_marketing_consent&&e.stripe_account_country==="US",disabled:e.stripe_account_country!=="US",disabledReason:e.stripe_account_country?'Only available for US stores: Stripe offers its consent checkbox to US businesses only. Your checkout shows an "Email me" box instead.':"Available once your Stripe account is connected and its country has synced.",onSave:s=>t({checkout_marketing_consent:s})})]})}function sc(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(mt(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(mt(e.free_shipping_over,e.currency))}}function oc({site:e,updateSite:t,refetch:s,providerSlot:n,currencyChanging:a=!1}){let{draft:r,setDraft:o,dirty:c,reset:d,dropped:l}=An(sc(e),{when:e.currency,fields:["rates","threshold"]}),{saving:i,error:m,setError:v,run:g}=On(),u=e.currency.toUpperCase(),f=()=>g(async()=>{let b={},w=[...new Set(r.countries.split(/[\s,]+/).map(N=>N.trim().toUpperCase()).filter(Boolean))],P=w.find(N=>!/^[A-Z]{2}$/.test(N));if(P)throw new Error(`"${P}" isn't a two-letter country code (e.g. US, CA).`);let T=w.length?w:null;mo(T,e.shipping_countries)||(b.shipping_countries=T);let y=[];for(let N of r.rates){let E=N.label.trim(),D=zt(N.amount,e.currency);if(!E)throw new Error("Every rate needs a name.");if(N.amount.trim()===""||D===null)throw new Error(`Enter a price for "${E}" (0 for free).`);y.push({label:E,amount:D})}let C=y.length?y:null;mo(C,e.shipping_rates)||(b.shipping_rates=C);let k=null;if(r.threshold.trim()!==""&&(k=zt(r.threshold,e.currency),k===null||k===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(k!==e.free_shipping_over&&(b.free_shipping_over=k),Object.keys(b).length===0){d();return}("shipping_rates"in b||"free_shipping_over"in b)&&(b.expected_currency=e.currency);let I;try{I=await t(b)}catch(N){throw N instanceof Dt&&N.details?.code==="currency_changed"&&await s?.(),N}d(sc(I))}),p=(b,w)=>o({...r,rates:r.rates.map((P,T)=>T===b?{...P,...w}:P)});return(0,H.jsxs)("fieldset",{disabled:i||a,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:cs,children:["Countries you ship to",(0,H.jsx)(re,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:b=>o({...r,countries:b.target.value})}),(0,H.jsx)(Sa,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),(0,H.jsxs)("div",{className:"af-space-y-2",children:[(0,H.jsxs)("p",{className:"af-text-sm",children:["Flat shipping rates (",u,")"]}),r.rates.length===0&&(0,H.jsx)(Sa,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((b,w)=>(0,H.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,H.jsx)(re,{"aria-label":`Rate ${w+1} name`,value:b.label,placeholder:"Standard",onChange:P=>p(w,{label:P.target.value})}),(0,H.jsx)(re,{"aria-label":`Rate ${w+1} price`,type:"number",min:"0",step:"any",value:b.amount,placeholder:"0",className:"af-w-32",onChange:P=>p(w,{amount:P.target.value})}),(0,H.jsx)(x,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${w+1}`,onClick:()=>o({...r,rates:r.rates.filter((P,T)=>T!==w)}),children:(0,H.jsx)(bn.X,{})})]},w)),(0,H.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>o({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[(0,H.jsx)(bn.Plus,{})," Add rate"]}),(0,H.jsx)(Sa,{children:"Buyers pick one at checkout. The first is preselected."})]}),(0,H.jsxs)("label",{className:cs,children:["Free shipping over (",u,")",(0,H.jsx)(re,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:b=>o({...r,threshold:b.target.value})}),(0,H.jsx)(Sa,{children:"Orders at or above this get the cheapest rate free."})]}),l.length>0&&(0,H.jsxs)("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",u,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),(0,H.jsx)(Ln,{dirty:c,saving:i,error:m,onSave:()=>void f(),onDiscard:()=>{v(null),d()}}),n]})}var fo="exclusive",Dd=[{href:"https://docs.stripe.com/tax/set-up",label:"Set up Stripe Tax"},{href:"https://docs.stripe.com/tax/registering",label:"Add tax registrations"},{href:"https://docs.stripe.com/tax/zero-tax",label:"Why tax can be zero"},{href:"https://stripe.com/tax/pricing",label:"Stripe Tax pricing"}];function Ad({href:e,children:t}){return(0,H.jsxs)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"af-inline-flex af-items-center af-gap-1 af-font-medium af-underline af-underline-offset-2 hover:af-text-foreground",children:[t,(0,H.jsx)(bn.ExternalLink,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function lc({site:e,updateSite:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=An(e.tax_behavior??fo),{saving:o,error:c,setError:d,run:l}=On(),[i,m]=es.useState(!1),v=e.stripe_tax_enabled,g=v||i,u=()=>l(async()=>{let b=s;if(b===e.tax_behavior){r();return}let w={tax_behavior:b};b!=="inclusive"&&e.tax_rate_bps!=null&&(w.tax_rate_bps=null);let P=await t(w);r(P.tax_behavior??fo)}),f=()=>l(async()=>{let b={stripe_tax_enabled:!0,tax_behavior:s};s!=="inclusive"&&e.tax_rate_bps!=null&&(b.tax_rate_bps=null);let w=await t(b);r(w.tax_behavior??fo),m(!1)}),p=(a||i)&&s!=="inclusive"&&e.tax_rate_bps!=null;return(0,H.jsxs)("div",{className:"af-space-y-5",children:[(0,H.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[(0,H.jsx)("p",{children:"Tax at checkout is calculated by Stripe Tax, which you set up in your Stripe Dashboard (Settings \u2192 Tax): your business address, a default product tax code, and the places you're registered to collect tax."}),(0,H.jsx)("p",{children:"Stripe only collects tax where you've added a registration; anywhere else the tax comes out as zero. Stripe Tax has its own fees, and what it covers (such as filing) depends on your Stripe Tax plan."}),(0,H.jsx)("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:Dd.map(b=>(0,H.jsx)("li",{children:(0,H.jsx)(Ad,{href:b.href,children:b.label})},b.href))})]}),(0,H.jsx)(hi,{label:"Stripe automatic tax",description:v?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:g,onSave:async b=>{if(i){m(!1),d(null),r();return}if(b&&!e.tax_behavior){m(!0);return}return t({stripe_tax_enabled:b})}}),g&&(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4 af-pl-6",children:[(0,H.jsxs)("label",{className:cs,children:["Do your prices already include tax?",(0,H.jsxs)("select",{"aria-label":"Your prices",className:ec,value:s,onChange:b=>n(b.target.value),children:[(0,H.jsx)("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),(0,H.jsx)("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),(0,H.jsx)(Sa,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),p&&(0,H.jsxs)(Sa,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),i?(0,H.jsxs)("div",{className:"af-space-y-2",children:[(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(x,{type:"button",size:"sm",disabled:o,onClick:()=>void f(),children:"Turn on"}),(0,H.jsx)(x,{type:"button",size:"sm",variant:"outline",disabled:o,onClick:()=>{m(!1),d(null),r()},children:"Cancel"})]}),c&&(0,H.jsx)(xr,{children:c})]}):(0,H.jsx)(Ln,{dirty:a,saving:o,error:c,onSave:()=>void u(),onDiscard:()=>{d(null),r()}})]})]})}function nc(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function cc({site:e,updateSite:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=An(nc(e)),{saving:o,error:c,setError:d,run:l}=On(),i=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),m=()=>l(async()=>{let v={},g=null;if(i&&s.rate.trim()!==""){let b=Number(s.rate);if(!Number.isFinite(b)||b<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(b*100)}i&&g!==e.tax_rate_bps&&(v.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(v.tax_behavior="inclusive");let u=s.taxId.trim()||null;u!==e.tax_id&&(v.tax_id=u);let f=s.label.trim()||null;if(f!==e.tax_label&&(v.tax_label=f),Object.keys(v).length===0){r();return}let p=await t(v);r(nc(p))});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:cs,children:["Tax rate (%)",(0,H.jsx)(re,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!i,value:i?s.rate:"",onChange:v=>n({...s,rate:v.target.value})}),(0,H.jsx)(Sa,{children:i?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),(0,H.jsxs)("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[(0,H.jsxs)("label",{className:cs,children:["Tax ID",(0,H.jsx)(re,{"aria-label":"Tax ID",value:s.taxId,maxLength:64,placeholder:"DE123456789",onChange:v=>n({...s,taxId:v.target.value})})]}),(0,H.jsxs)("label",{className:cs,children:["Tax label",(0,H.jsx)(re,{"aria-label":"Tax label",value:s.label,maxLength:24,placeholder:"Tax",onChange:v=>n({...s,label:v.target.value})})]})]}),(0,H.jsx)(Ln,{dirty:a,saving:o,error:c,onSave:()=>void m(),onDiscard:()=>{d(null),r()}})]})}function uc({site:e,updateSite:t,onChangeStart:s}){let[n,a]=es.useState(e.currency.toUpperCase()),[r,o]=es.useState(!1),[c,d]=es.useState(!1),[l,i]=es.useState(null),m=e.currency.toUpperCase(),v=es.useRef(m);es.useEffect(()=>{v.current!==m&&(a(b=>b===v.current?m:b),v.current=m)},[m]);let g=n.trim().toUpperCase(),u=g!==m,f=/^[A-Z]{3}$/.test(g),p=async()=>{d(!0);let b=s?.(),w=!1;i(null);try{let P=await t({currency:g.toLowerCase()});w=!0;let T=P.currency_restatement;T&&!T.applied?i(T.reason?`Not changed: ${T.reason}.`:"The currency was not changed."):(a(P.currency.toUpperCase()),v.current=P.currency.toUpperCase()),o(!1)}catch(P){i(yi(P))}finally{d(!1),b?.(w)}};return(0,H.jsxs)("div",{className:"af-space-y-3",children:[(0,H.jsxs)("div",{className:"af-flex af-items-end af-gap-2",children:[(0,H.jsxs)("label",{className:cs,children:["Store currency",(0,H.jsx)(re,{"aria-label":"Store currency",value:n,maxLength:3,className:"af-w-24 af-uppercase",disabled:c||r,onChange:b=>{a(b.target.value),i(null)}})]}),u&&!r&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(x,{type:"button",size:"sm",disabled:!f,onClick:()=>o(!0),children:"Change currency"}),(0,H.jsx)(x,{type:"button",size:"sm",variant:"ghost",onClick:()=>{a(m),i(null)},children:"Discard"})]})]}),(0,H.jsx)(Sa,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&(0,H.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,H.jsxs)("p",{className:"af-text-sm",children:["Change the store currency from ",m," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",Z(2e3,m)," becomes ",Z(2e3,g),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(x,{type:"button",size:"sm",disabled:c,onClick:()=>void p(),children:"Confirm change"}),(0,H.jsx)(x,{type:"button",size:"sm",variant:"ghost",disabled:c,onClick:()=>o(!1),children:"Cancel"})]})]}),l&&(0,H.jsx)(xr,{children:l})]})}function rc(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function Ld(e){return e.length===0?"Off":e.map(t=>t===0?"on the due date":t<0?`${-t} day${t===-1?"":"s"} before`:`${t} day${t===1?"":"s"} after`).join(", ")}function dc({site:e,save:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=An(rc(e)),{saving:o,error:c,setError:d,run:l}=On();if(!t)return(0,H.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,H.jsxs)("p",{children:["Due ",e.invoice_due_days," days after sending"]}),(0,H.jsxs)("p",{children:["Reminders: ",Ld(e.invoice_reminder_schedule)]}),(0,H.jsxs)("p",{children:["Footer: ",e.invoice_footer||"None"]}),(0,H.jsx)(ac,{what:"invoice defaults"})]});let i=()=>l(async()=>{let m={},v=Number(s.dueDays);if(s.dueDays.trim()===""||!Number.isInteger(v)||v<0||v>90)throw new Error("Due days must be a whole number from 0 to 90.");v!==e.invoice_due_days&&(m.due_days=v);let u=s.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(u.some(w=>!Number.isInteger(w)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let f=[...new Set(u)].sort((w,P)=>w-P);mo(f,e.invoice_reminder_schedule)||(m.reminder_schedule=f);let p=s.footer.trim()||null;if(p!==e.invoice_footer&&(m.footer=p),Object.keys(m).length===0){r();return}let b=await t(m);r(b?rc(b):void 0)});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:cs,children:["Days until due",(0,H.jsx)(re,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:s.dueDays,onChange:m=>n({...s,dueDays:m.target.value})})]}),(0,H.jsxs)("label",{className:cs,children:["Reminder schedule",(0,H.jsx)(re,{"aria-label":"Reminder schedule",value:s.reminders,placeholder:"Off",onChange:m=>n({...s,reminders:m.target.value})}),(0,H.jsx)(Sa,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),(0,H.jsxs)("label",{className:cs,children:["Invoice footer",(0,H.jsx)("textarea",{"aria-label":"Invoice footer",className:tc,maxLength:300,value:s.footer,onChange:m=>n({...s,footer:m.target.value})})]}),(0,H.jsx)(Ln,{dirty:a,saving:o,error:c,onSave:()=>void i(),onDiscard:()=>{d(null),r()}})]})}function fc({site:e,updateSite:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=An(e.default_email_recipients),{saving:o,error:c,setError:d,run:l}=On(),[i,m]=es.useState(""),[v,g]=es.useState(null),u=()=>{let p=i.trim().toLowerCase();if(p){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p)){g("Enter a valid email address.");return}if(s.some(b=>b.toLowerCase()===p)){g("Already added.");return}n([...s,p]),m(""),g(null)}},f=()=>l(async()=>{let p=await t({default_email_recipients:s});r(p.default_email_recipients)});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-3",children:[(0,H.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[s.map(p=>(0,H.jsxs)(oe,{variant:"secondary",className:"af-gap-1",children:[p,(0,H.jsx)("button",{type:"button","aria-label":`Remove ${p}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>n(s.filter(b=>b!==p)),children:(0,H.jsx)(bn.X,{className:"af-h-3 af-w-3"})})]},p)),s.length===0&&(0,H.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(re,{"aria-label":"Add notification email",type:"email",value:i,placeholder:"Add email address",onChange:p=>{m(p.target.value),g(null)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),u())}}),(0,H.jsx)(x,{type:"button",variant:"outline",disabled:!i.trim(),onClick:u,children:"Add"})]}),v&&(0,H.jsx)(xr,{children:v}),(0,H.jsx)(Ln,{dirty:a,saving:o,error:c,onSave:()=>void f(),onDiscard:()=>{d(null),r()}})]})}var Yt=require("react/jsx-runtime");function po({siteId:e,refreshKey:t,section:s,shippingProviderSlot:n,onConnectStripe:a,onUpgradePlan:r,className:o}){let{site:c,isLoading:d,error:l,refetch:i,updateSite:m}=Os({siteId:e,refreshKey:t}),v=Rs.useRef(i),g=Rs.useRef(e);vn(()=>{v.current=i,g.current=e});let u=Rs.useRef({}),[f,p]=Rs.useState([]),b=f.some(C=>C.siteId===e),w=Rs.useCallback(()=>{let C={siteId:e},k=v.current;return p(I=>[...I,C]),I=>{let N=()=>p(D=>D.filter(_=>_!==C));!(g.current===C.siteId)||I&&v.current===k?N():v.current().finally(N)}},[e]),P=C=>k=>{u.current[C]=k},T=c!==null&&c.payments_active;if(Rs.useEffect(()=>{if(!T||!s)return;let C=u.current[s];C&&(C.scrollIntoView?.({behavior:"smooth",block:"start"}),C.focus({preventScroll:!0}))},[T,s]),d)return(0,Yt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Yt.jsx)(mc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!c)return(0,Yt.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l?.message??"Could not load store settings."});if(!c.payments_active)return(0,Yt.jsx)(dn,{className:o,onConnectStripe:a,onUpgradePlan:r,whenActive:(0,Yt.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let y={site:c,updateSite:m,refetch:i};return(0,Yt.jsxs)("div",{className:`af-space-y-6 ${o??""}`,children:[l&&(0,Yt.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l.message}),(0,Yt.jsx)(Ns,{ref:P("checkout"),id:"checkout",title:"Checkout",children:(0,Yt.jsx)(ic,{...y})}),(0,Yt.jsx)(Ns,{ref:P("shipping"),id:"shipping",title:"Shipping",children:(0,Yt.jsx)(oc,{...y,providerSlot:n,currencyChanging:b})}),(0,Yt.jsx)(Ns,{ref:P("tax"),id:"tax",title:"Tax",children:(0,Yt.jsx)(lc,{...y})}),(0,Yt.jsx)(Ns,{ref:P("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:(0,Yt.jsx)(uc,{...y,onChangeStart:w})})]},e)}var pc=require("lucide-react");var us=require("react/jsx-runtime");function Sr({siteId:e,refreshKey:t,onSaveInvoiceSettings:s,className:n}){let{site:a,isLoading:r,error:o,updateSite:c,refetch:d,saveInvoiceSettings:l}=Os({siteId:e,refreshKey:t,onSaveInvoiceSettings:s});return r?(0,us.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,us.jsx)(pc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):a?(0,us.jsxs)("div",{className:`af-space-y-6 ${n??""}`,children:[o&&(0,us.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o.message}),(0,us.jsx)(Ns,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:(0,us.jsx)(dc,{site:a,save:l})}),(0,us.jsx)(Ns,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:(0,us.jsx)(cc,{site:a,updateSite:c,refetch:d})})]},e):(0,us.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o?.message??"Could not load invoice settings."})}var gc=require("lucide-react");var Bs=require("react/jsx-runtime");function go({siteId:e,refreshKey:t,className:s}){let{site:n,isLoading:a,error:r,updateSite:o,refetch:c}=Os({siteId:e,refreshKey:t});return a?(0,Bs.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Bs.jsx)(gc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):n?(0,Bs.jsxs)("div",{className:`af-space-y-3 ${s??""}`,children:[r&&(0,Bs.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r.message}),(0,Bs.jsx)(Ns,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:(0,Bs.jsx)(fc,{site:n,updateSite:o,refetch:c})})]},e):(0,Bs.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r?.message??"Could not load notification settings."})}var Bn=ie(require("react"),1);var ot=require("react/jsx-runtime");function vo({refreshKey:e,initialInvoiceId:t,onBackToWebsite:s,onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:r,siteId:o,onSaveInvoiceSettings:c,className:d}){let{aggregates:l,isLoading:i,error:m,refetch:v}=cn({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=mn({refreshKey:e}),{api:u}=W(),f=g.filters,p=Bn.useCallback(()=>u.exportRetainersCsv(f),[u,f]),[b,w]=Bn.useState(!1),[P,T]=Bn.useState(null),[y,C]=Bn.useState(!1),k=(0,ot.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:m||!i&&!l?(0,ot.jsxs)("div",{role:"alert",className:"sm:af-col-span-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't load invoice totals. ",(0,ot.jsx)(x,{type:"button",variant:"link",size:"sm",onClick:()=>void v(),children:"Retry totals"})]}):i||!l?(0,ot.jsxs)(ot.Fragment,{children:[(0,ot.jsx)(st,{label:"Outstanding",children:(0,ot.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,ot.jsx)(st,{label:"Overdue",children:(0,ot.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,ot.jsx)(st,{label:"Paid this month",children:(0,ot.jsx)(ae,{className:"af-h-6 af-w-24"})})]}):(0,ot.jsxs)(ot.Fragment,{children:[(0,ot.jsx)(st,{label:"Outstanding",detail:`${l.outstanding.count} open`,children:Z(l.outstanding.amount,l.currency)}),(0,ot.jsx)(st,{label:"Overdue",detail:l.overdue.count===0?"Nothing overdue":`${l.overdue.count} overdue`,valueClassName:l.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:Z(l.overdue.amount,l.currency)}),(0,ot.jsx)(st,{label:"Paid this month",detail:`${l.paid_this_month.count} paid`,children:Z(l.paid_this_month.amount,l.currency)})]})});return(0,ot.jsxs)(St,{title:"Invoices",onBackToWebsite:s,hideBackButton:b,className:d,children:[k,o&&!b&&(0,ot.jsxs)("div",{className:"af-mb-6",children:[(0,ot.jsx)(x,{type:"button",variant:"outline",size:"sm","aria-expanded":y,"aria-controls":"af-invoice-settings",onClick:()=>C(I=>!I),children:"Invoice settings"}),y&&(0,ot.jsx)("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:(0,ot.jsx)(Sr,{siteId:o,refreshKey:e,onSaveInvoiceSettings:c})})]}),!b&&(0,ot.jsx)(un,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:P?.id??null,onShowCycles:I=>T(N=>N?.id===I.id?null:I),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded,exportCsv:p}),(0,ot.jsx)(Ls,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:w,onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:r,retainerFilter:P?{id:P.id,label:`${P.customer_name??P.customer_email??"Recurring invoices"} \u2014 ${P.description}`}:null,onClearRetainerFilter:()=>T(null)})]})}var Na=ie(require("react"),1),_c=require("lucide-react");var ts=ie(require("react"),1);function wa(e,t,s){let[n,a]=ts.useState(null),[r,o]=ts.useState(!0),[c,d]=ts.useState(null),l=ts.useRef(0),i=ts.useRef(e);i.current=e;let m=ts.useRef(s);m.current=s;let v=ts.useCallback(async()=>{let u=++l.current,f=m.current;o(!0),d(null);try{let p=await i.current();u===l.current&&a({scope:f,value:p})}catch(p){u===l.current&&d(p instanceof Error?p:new Error("Request failed"))}finally{u===l.current&&o(!1)}},[]);ts.useEffect(()=>{v()},[v,t]);let g=n!==null&&n.scope===s;return{data:g?n.value:null,isLoading:r||!g&&c===null,error:c,refetch:v}}var xi={commitBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts"},cancelBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts/{sendId}/cancel",params:["sendId"]},createDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts"},updateDraft:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},deleteDraft:{method:"DELETE",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},testSendDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/test",params:["draftId"]},importContacts:{method:"POST",path:"/sites/{siteId}/contacts/import"},exportContacts:{method:"GET",path:"/sites/{siteId}/contacts/export"},createTag:{method:"POST",path:"/sites/{siteId}/contact-tags"},updateTag:{method:"PATCH",path:"/sites/{siteId}/contact-tags/{tagId}",params:["tagId"]},bulkTagContacts:{method:"POST",path:"/sites/{siteId}/contacts/tags"},unsubscribeContact:{method:"POST",path:"/sites/{siteId}/contacts/{contactId}/unsubscribe",params:["contactId"]},updateSettings:{method:"PUT",path:"/sites/{siteId}/marketing"},setFormPurpose:{method:"PATCH",path:"/forms/{formId}",params:["formId"]},createWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps"},updateWelcomeStep:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},deleteWelcomeStep:{method:"DELETE",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},publishWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}/publish",params:["stepId"]},activateWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/activate"},pauseWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/pause"},updateWelcome:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome"},setRecoveryStep:{method:"PUT",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},publishRecoveryStep:{method:"POST",path:"/sites/{siteId}/marketing/recovery/steps/{step}/publish",params:["step"]},deleteRecoveryStep:{method:"DELETE",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},activateRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/activate"},pauseRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/pause"}};function vc(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(xi,e)}function bc(e,t,s){let n=xi[e],a="params"in n?n.params:[],r={...s};delete r.siteId;let o=n.path.replace("{siteId}",encodeURIComponent(t));for(let d of a){let l=r[d];if(typeof l!="string"&&typeof l!="number")throw new Error(`${e} needs ${d}`);o=o.replace(`{${d}}`,encodeURIComponent(String(l))),delete r[d]}let c=n.method==="GET"||n.method==="DELETE"?void 0:r;return{method:n.method,path:o,body:c}}var bo={marketing_disabled:"Email marketing is not available yet.",site_deleted:"This site has been deleted.",sending_not_enabled:"Email sending is not turned on for this site. It needs the Pro plan.",sending_paused:"Sending is paused while we review this site.",domain_not_verified:"Verify your sending domain before you can send.",dmarc_missing:"Your domain needs a DMARC record before you can send.",postal_address_missing:"Add your business postal address before you can send. Every email has to show it.",allowance_exhausted:"You've used this month's email allowance. Sending resumes next month or when you upgrade.",ramp_limit:"Today's sending limit for a new domain is used up. Sending continues tomorrow.",sample_failed:"Too many emails in the first batch bounced, so the rest of this send was stopped."},Si=new Set(["domain_not_verified","dmarc_missing","postal_address_missing"]);function yn(e){return e?bo[e]??"Sending is not available right now.":null}var _s=ie(require("react"),1);var hn=50;function wr({siteId:e,q:t="",offset:s=0,refreshKey:n=0}){let{api:a}=W(),r=wa(()=>a.getMarketingContacts(e,{q:t||void 0,limit:hn,offset:s}),`${e}|${t}|${s}|${n}`,e),o=wa(()=>a.getMarketingContactStats(e),`${e}|${n}`,e),c=wa(()=>a.getMarketingTags(e),`${e}|${n}`,e);return{contacts:r,stats:o,tags:c,refetchAll:async()=>{await Promise.all([r.refetch(),o.refetch(),c.refetch()])}}}var Mn=ie(require("react"),1);var Fs=ie(require("react"),1);var ds=require("react/jsx-runtime"),Nr=e=>`af-email-settings-${e}`,yo=Fs.createContext(null);function Wt(){let e=Fs.useContext(yo);if(!e)throw new Error("Email panels render inside EmailView");return e}function wi({onClick:e,children:t}){return(0,ds.jsx)("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function Ni({reason:e}){let{openSetup:t,onOpenStoreSettings:s}=Wt(),n=e&&Si.has(e)?(0,ds.jsx)(wi,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&s?(0,ds.jsx)(wi,{onClick:s,children:"Open Store settings"}):null;return n&&(0,ds.jsxs)(ds.Fragment,{children:[" ",n]})}function Od(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.code=="string"?t.code:typeof t.details?.code=="string"?t.details.code:null}function Fn(e,t){return Od(e)===t?!0:e instanceof Error&&e.message.includes(t)}function Un(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function na(){let{onOrgAction:e}=Wt(),[t,s]=Fs.useState(!1),[n,a]=Fs.useState(null),r=Fs.useCallback(async(o,c={})=>{s(!0),a(null);try{return{ok:!0,result:await e(o,c)}}catch(d){return a(Un(d)),{ok:!1,error:d}}finally{s(!1)}},[e]);return{busy:t,error:n,setError:a,run:r}}function Be({tone:e="info",children:t,className:s}){return(0,ds.jsx)("div",{role:e==="error"?"alert":"status",className:J("af-rounded-md af-border af-px-3 af-py-2 af-text-sm",e==="warning"&&"af-border-yellow-300 af-bg-yellow-50 af-text-yellow-900",e==="error"&&"af-border-destructive af-bg-destructive/10 af-text-destructive",e==="success"&&"af-border-green-300 af-bg-green-50 af-text-green-900",s),children:t})}function Va({children:e,action:t,id:s}){return(0,ds.jsxs)("div",{id:s,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[(0,ds.jsx)("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function Ue(e){return e.toLocaleString("en-US")}var wt=require("react/jsx-runtime"),Ri="I confirm that everyone in this file agreed to receive marketing email from my business.",Bd={invalid_email:"not a valid email address",duplicate:"listed more than once",inactive_in_source:"inactive or unsubscribed in the file",previously_unsubscribed:"unsubscribed before, so they stay unsubscribed",suppressed:"bounced or marked email as spam before",pending:"still confirming their signup"};function Rr({onImported:e}){let{canWrite:t}=Wt(),[s,n]=Mn.useState(""),[a,r]=Mn.useState(null),[o,c]=Mn.useState(""),[d,l]=Mn.useState(!1),[i,m]=Mn.useState(null),v=na(),g=async()=>{if(!d||!s.trim())return;let u=o.split(",").map(p=>p.trim()).filter(Boolean),f=await v.run("importContacts",{csv:s,attested:!0,...u.length?{tags:u}:{}});if(f.ok){let p=f.result;m(p),e?.(p)}};if(i){let u=new Map;for(let f of i.skipped_rows)u.set(f.reason,(u.get(f.reason)??0)+1);return(0,wt.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[(0,wt.jsx)("div",{className:"af-font-medium",children:"Import finished"}),(0,wt.jsxs)("p",{className:"af-text-sm",children:[Ue(i.rows)," rows: ",Ue(i.created)," new, ",Ue(i.updated)," updated, ",Ue(i.skipped)," skipped."]}),u.size>0&&(0,wt.jsx)("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...u].map(([f,p])=>(0,wt.jsxs)("li",{children:[Ue(p)," ",Bd[f]??f]},f))}),(0,wt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),(0,wt.jsx)(x,{type:"button",size:"sm",variant:"outline",onClick:()=>{m(null),n(""),r(null),l(!1)},children:"Import another file"})]})}return(0,wt.jsxs)("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:u=>{u.preventDefault(),g()},children:[(0,wt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,wt.jsx)("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),(0,wt.jsx)("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async u=>{let f=u.target.files?.[0];f&&(r(f.name),n(await f.text()))}}),(0,wt.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:'Needs an "email" column. Tags in a "tags" column are applied too.'}),a&&(0,wt.jsx)("span",{className:"af-block af-text-xs",children:a})]}),(0,wt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,wt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),(0,wt.jsx)(re,{"aria-label":"Tags for imported contacts",value:o,onChange:u=>c(u.target.value)})]}),(0,wt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,wt.jsx)("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:d,onChange:u=>l(u.target.checked)}),(0,wt.jsxs)("span",{children:[Ri," Importing people who didn't agree can get your sending paused."]})]}),v.error&&(0,wt.jsx)(Be,{tone:"error",children:v.error}),(0,wt.jsx)(x,{type:"submit",size:"sm",disabled:!t||!d||!s.trim()||v.busy,children:v.busy?"Importing\u2026":"Import contacts"})]})}var de=require("react/jsx-runtime"),Fd={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function yc(){let{siteId:e,canWrite:t,refreshKey:s}=Wt(),[n,a]=_s.useState(""),[r,o]=_s.useState(""),[c,d]=_s.useState(0),[l,i]=_s.useState(0),[m,v]=_s.useState(new Set),[g,u]=_s.useState(!1),f=wr({siteId:e,q:r,offset:c,refreshKey:l+s}),p=na(),b=()=>i(k=>k+1),w=f.stats.data,P=f.contacts.data,T=f.tags.data??[],y=w?w.growth.slice(-4).reduce((k,I)=>k+I.new_subscribers,0):null,C=async()=>{let k=await p.run("exportContacts",{});if(!k.ok||typeof k.result!="string"||typeof document>"u")return;let I=URL.createObjectURL(new Blob([k.result],{type:"text/csv;charset=utf-8"})),N=document.createElement("a");N.href=I,N.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(N),N.click(),document.body.removeChild(N),URL.revokeObjectURL(I)};return(0,de.jsxs)("div",{children:[(0,de.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[(0,de.jsx)(st,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:w?Ue(w.total):(0,de.jsx)(ae,{className:"af-h-6 af-w-16"})}),(0,de.jsx)(st,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:w?Ue(w.mailable):(0,de.jsx)(ae,{className:"af-h-6 af-w-16"})}),(0,de.jsx)(st,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:y!==null?Ue(y):(0,de.jsx)(ae,{className:"af-h-6 af-w-16"})})]}),(0,de.jsxs)("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,de.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:k=>{k.preventDefault(),d(0),o(n.trim())},children:[(0,de.jsx)(re,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:n,onChange:k=>a(k.target.value)}),(0,de.jsx)(x,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),(0,de.jsx)(x,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>u(k=>!k),children:g?"Close import":"Import"}),(0,de.jsx)(x,{type:"button",variant:"outline",size:"sm",disabled:!t||p.busy,onClick:()=>void C(),children:"Export"})]}),g&&(0,de.jsx)("div",{className:"af-mt-3",children:(0,de.jsx)(Rr,{onImported:b})}),p.error&&(0,de.jsx)(Be,{tone:"error",className:"af-mt-2",children:p.error}),t&&m.size>0&&(0,de.jsx)(Md,{tags:T.filter(k=>!k.system),count:m.size,busy:p.busy,onApply:async(k,I)=>{(await p.run("bulkTagContacts",{action:k,tag_id:I,contact_ids:[...m]})).ok&&(v(new Set),b())}}),(0,de.jsx)("div",{className:"af-mt-3",children:f.contacts.error?(0,de.jsx)(Lt,{message:"Couldn't load contacts.",onRetry:()=>void f.contacts.refetch()}):P?P.contacts.length===0?(0,de.jsx)(aa,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):(0,de.jsxs)(de.Fragment,{children:[(0,de.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:P.contacts.map(k=>(0,de.jsx)(Ud,{contact:k,canWrite:t,busy:p.busy,selected:m.has(k.id),onSelect:I=>v(N=>{let E=new Set(N);return I?E.add(k.id):E.delete(k.id),E}),onUnsubscribe:async()=>{(await p.run("unsubscribeContact",{contactId:k.id})).ok&&b()}},k.id))}),(0,de.jsxs)("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[(0,de.jsxs)("span",{children:[Ue(c+1),"\u2013",Ue(c+P.contacts.length)," of ",Ue(P.total)]}),(0,de.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,de.jsx)(x,{type:"button",variant:"ghost",size:"sm",disabled:c===0,onClick:()=>d(Math.max(0,c-hn)),children:"Previous"}),(0,de.jsx)(x,{type:"button",variant:"ghost",size:"sm",disabled:c+P.contacts.length>=P.total,onClick:()=>d(c+hn),children:"Next"})]})]})]}):(0,de.jsx)(ae,{className:"af-h-24 af-w-full"})}),(0,de.jsx)($d,{tags:T,canWrite:t,onChanged:b})]})}function Ud({contact:e,canWrite:t,busy:s,selected:n,onSelect:a,onUnsubscribe:r}){return(0,de.jsxs)("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&(0,de.jsx)("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:n,onChange:o=>a(o.target.checked)}),(0,de.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,de.jsxs)("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?(0,de.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),(0,de.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[(0,de.jsx)(oe,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":Fd[e.status]}),e.tags.map(o=>(0,de.jsx)(oe,{variant:"outline",children:o.label},o.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&(0,de.jsx)(x,{type:"button",variant:"ghost",size:"sm",disabled:s,onClick:r,children:"Unsubscribe"})]})}function Md({tags:e,count:t,busy:s,onApply:n}){let[a,r]=_s.useState("");return(0,de.jsxs)("div",{className:"af-mt-3 af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:[(0,de.jsxs)("span",{children:[Ue(t)," selected"]}),(0,de.jsxs)("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:a,onChange:o=>r(o.target.value),children:[(0,de.jsx)("option",{value:"",children:"Choose a tag\u2026"}),e.map(o=>(0,de.jsx)("option",{value:o.id,children:o.label},o.id))]}),(0,de.jsx)(x,{type:"button",size:"sm",variant:"outline",disabled:!a||s,onClick:()=>n("add",a),children:"Add tag"}),(0,de.jsx)(x,{type:"button",size:"sm",variant:"ghost",disabled:!a||s,onClick:()=>n("remove",a),children:"Remove tag"})]})}function $d({tags:e,canWrite:t,onChanged:s}){let[n,a]=_s.useState(""),[r,o]=_s.useState(null),c=na();return(0,de.jsxs)("div",{children:[(0,de.jsx)(Va,{children:"Tags"}),e.length===0?(0,de.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No tags yet. Contacts are tagged automatically with where they signed up and what they bought."}):(0,de.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(d=>(0,de.jsx)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:r?.id===d.id?(0,de.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async l=>{l.preventDefault(),(await c.run("updateTag",{tagId:d.id,label:r.label.trim()})).ok&&(o(null),s())},children:[(0,de.jsx)(re,{"aria-label":`New name for ${d.label}`,value:r.label,onChange:l=>o({id:d.id,label:l.target.value})}),(0,de.jsx)(x,{type:"submit",size:"sm",disabled:!r.label.trim()||c.busy,children:"Save"})]}):(0,de.jsxs)(de.Fragment,{children:[(0,de.jsxs)("span",{children:[d.label," ",(0,de.jsxs)("span",{className:"af-text-muted-foreground",children:["\xB7 ",Ue(d.total)," contacts, ",Ue(d.mailable)," can be emailed"]})]}),t&&!d.system&&(0,de.jsx)(x,{type:"button",size:"sm",variant:"ghost",onClick:()=>o({id:d.id,label:d.label}),children:"Rename"})]})},d.id))}),t&&(0,de.jsxs)("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async d=>{d.preventDefault(),(await c.run("createTag",{label:n.trim()})).ok&&(a(""),s())},children:[(0,de.jsx)(re,{"aria-label":"New tag",placeholder:"New tag",value:n,maxLength:100,onChange:d=>a(d.target.value)}),(0,de.jsx)(x,{type:"submit",size:"sm",variant:"outline",disabled:!n.trim()||c.busy,children:"Add tag"})]}),c.error&&(0,de.jsx)(Be,{tone:"error",className:"af-mt-2",children:c.error})]})}var lt=ie(require("react"),1),Sc=require("lucide-react");function _r({siteId:e,refreshKey:t=0}){let{api:s}=W();return wa(()=>s.getBroadcasts(e),`${e}|${t}`,e)}function Pr({siteId:e,kind:t,refreshKey:s=0}){let{api:n}=W();return wa(()=>n.getEmailDrafts(e,t),`${e}|${t??""}|${s}`,`${e}|${t??""}`)}var It=ie(require("react"),1);var Ne=require("react/jsx-runtime");function hc({draftId:e,renderCommit:t,onSaved:s}){let{api:n}=W(),{siteId:a,canWrite:r,refreshKey:o}=Wt(),[c,d]=It.useState(null),[l,i]=It.useState(null),[m,v]=It.useState(null),[g,u]=It.useState(null),[f,p]=It.useState(!1),[b,w]=It.useState(null),P=na(),T=na(),y=It.useRef(!1),C=It.useRef(!1),k=It.useCallback(E=>{y.current=E},[]),I=It.useCallback(async(E={})=>{u(null),v(null);let[D,_]=await Promise.allSettled([n.getEmailDraft(a,e),n.previewEmailDraft(a,e)]);if(E.unlessDirty&&y.current){C.current=!0;return}if(D.status==="rejected"){u(Un(D.reason));return}d(D.value),_.status==="fulfilled"?i(_.value):(i(null),v(Fn(_.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:Un(_.reason),code:null}))},[n,a,e]);It.useEffect(()=>{d(null),i(null),I()},[I]);let N=It.useRef(o);return It.useEffect(()=>{if(o!==N.current){if(N.current=o,y.current){C.current=!0;return}I({unlessDirty:!0})}},[o,I]),g?(0,Ne.jsxs)(Be,{tone:"error",children:["Couldn't load this email. ",g]}):c?(0,Ne.jsxs)("div",{className:"af-space-y-4",children:[(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:"Subject"}),(0,Ne.jsx)("div",{className:"af-font-medium",children:c.subject||"(no subject)"}),c.preheader&&(0,Ne.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:c.preheader})]}),f?(0,Ne.jsx)(Vd,{draft:c,onDirtyChange:k,busy:P.busy,error:P.error,onCancel:()=>{y.current=!1,p(!1),C.current&&(C.current=!1,I())},onSave:async E=>{let D=await P.run("updateDraft",{draftId:e,expected_version:c.version,...E});D.ok?(y.current=!1,C.current=!1,p(!1),await I(),s?.()):Fn(D.error,"version_conflict")&&(P.setError("This email changed while you were editing. We've loaded the latest version."),y.current=!1,C.current=!1,p(!1),await I())}},c.version):(0,Ne.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,Ne.jsx)(x,{type:"button",variant:"outline",size:"sm",disabled:!r,onClick:()=>p(!0),children:"Edit text"}),(0,Ne.jsx)(x,{type:"button",variant:"outline",size:"sm",disabled:!r||T.busy,onClick:async()=>{w(null);let E=await T.run("testSendDraft",{draftId:e});E.ok&&w(E.result?.sent_to??"your email")},children:"Send a test to me"})]}),P.error&&!f&&(0,Ne.jsx)(Be,{tone:"warning",children:P.error}),b&&(0,Ne.jsxs)(Be,{tone:"success",children:["Test sent to ",b,"."]}),T.error&&(0,Ne.jsx)(Be,{tone:"error",children:T.error}),l?(0,Ne.jsx)("iframe",{title:"Email preview",sandbox:"",srcDoc:l.html,className:"af-h-[480px] af-w-full af-rounded-md af-border af-bg-white"}):m?(0,Ne.jsxs)(Be,{tone:"warning",children:[m.text,(0,Ne.jsx)(Ni,{reason:m.code})]}):(0,Ne.jsx)(ae,{className:"af-h-40 af-w-full"}),l&&t?.({draft:c,preview:l,reload:I})]}):(0,Ne.jsx)(ae,{className:"af-h-40 af-w-full"})}function Vd({draft:e,busy:t,error:s,onSave:n,onCancel:a,onDirtyChange:r}){let[o,c]=It.useState(e.subject),[d,l]=It.useState(e.preheader??""),[i,m]=It.useState(e.blocks),v=o!==e.subject||d!==(e.preheader??"")||i!==e.blocks;It.useEffect(()=>r(v),[v,r]);let g=(u,f)=>m(p=>p.map((b,w)=>w===u?{...b,...f}:b));return(0,Ne.jsxs)("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:u=>{u.preventDefault(),n({subject:o,preheader:d.trim()||null,blocks:i})},children:[(0,Ne.jsx)(Us,{label:"Subject",children:(0,Ne.jsx)(re,{"aria-label":"Subject",value:o,maxLength:200,onChange:u=>c(u.target.value)})}),(0,Ne.jsx)(Us,{label:"Preview text",children:(0,Ne.jsx)(re,{"aria-label":"Preview text",value:d,maxLength:200,onChange:u=>l(u.target.value)})}),i.map((u,f)=>(0,Ne.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[u.type==="heading"&&(0,Ne.jsx)(Us,{label:"Heading",children:(0,Ne.jsx)(re,{"aria-label":`Heading ${f+1}`,value:u.text,onChange:p=>g(f,{text:p.target.value})})}),u.type==="text"&&(0,Ne.jsx)(Us,{label:"Text",children:(0,Ne.jsx)("textarea",{"aria-label":`Text ${f+1}`,className:"af-min-h-[96px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",value:u.text,onChange:p=>g(f,{text:p.target.value})})}),u.type==="image"&&(0,Ne.jsxs)(Ne.Fragment,{children:[(0,Ne.jsx)(Us,{label:"Image URL",children:(0,Ne.jsx)(re,{"aria-label":`Image URL ${f+1}`,value:u.url,onChange:p=>g(f,{url:p.target.value})})}),(0,Ne.jsx)(Us,{label:"Image description",children:(0,Ne.jsx)(re,{"aria-label":`Image description ${f+1}`,value:u.alt??"",onChange:p=>g(f,{alt:p.target.value})})})]}),u.type==="button"&&(0,Ne.jsxs)(Ne.Fragment,{children:[(0,Ne.jsx)(Us,{label:"Button label",children:(0,Ne.jsx)(re,{"aria-label":`Button label ${f+1}`,value:u.label,onChange:p=>g(f,{label:p.target.value})})}),(0,Ne.jsx)(Us,{label:"Button link",children:(0,Ne.jsx)(re,{"aria-label":`Button link ${f+1}`,value:u.url,onChange:p=>g(f,{url:p.target.value})})})]}),u.type==="cart"&&(0,Ne.jsx)(Us,{label:"Cart button label",children:(0,Ne.jsx)(re,{"aria-label":`Cart button label ${f+1}`,value:u.label,onChange:p=>g(f,{label:p.target.value})})})]},f)),s&&(0,Ne.jsx)(Be,{tone:"error",children:s}),(0,Ne.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ne.jsx)(x,{type:"submit",size:"sm",disabled:t,children:"Save changes"}),(0,Ne.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:a,children:"Cancel"})]})]})}function Us({label:e,children:t}){return(0,Ne.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Ne.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}var ue=require("react/jsx-runtime"),Hd={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function wc({initialDraftId:e}){let{siteId:t,canWrite:s,refreshKey:n}=Wt(),[a,r]=lt.useState(0),o=a+n,[c,d]=lt.useState(e??null),l=Pr({siteId:t,kind:"broadcast",refreshKey:o}),i=_r({siteId:t,refreshKey:o}),m=na();return c?(0,ue.jsxs)("div",{className:"af-space-y-4",children:[(0,ue.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(null),children:[(0,ue.jsx)(Sc.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),(0,ue.jsx)(hc,{draftId:c,onSaved:()=>r(v=>v+1),renderCommit:v=>(0,ue.jsx)(jd,{...v,onCommitted:()=>r(g=>g+1)})})]}):(0,ue.jsxs)("div",{children:[(0,ue.jsx)(Va,{children:"Drafts"}),l.error?(0,ue.jsx)(Lt,{message:"Couldn't load drafts.",onRetry:()=>void l.refetch()}):l.data?l.data.length===0?(0,ue.jsx)(aa,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):(0,ue.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:l.data.map(v=>(0,ue.jsxs)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[(0,ue.jsx)("span",{className:"af-truncate af-text-sm",children:v.subject||"(no subject)"}),(0,ue.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>d(v.id),children:"Review"})]},v.id))}):(0,ue.jsx)(ae,{className:"af-h-10 af-w-full"}),(0,ue.jsx)(Va,{children:"Sent and scheduled"}),m.error&&(0,ue.jsx)(Be,{tone:"error",children:m.error}),i.error?(0,ue.jsx)(Lt,{message:"Couldn't load broadcasts.",onRetry:()=>void i.refetch()}):i.data?i.data.length===0?(0,ue.jsx)(aa,{children:"Nothing sent yet."}):(0,ue.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:i.data.map(v=>(0,ue.jsx)(zd,{broadcast:v,canCancel:s&&(v.status==="scheduled"||v.status==="unscheduled"||v.status==="sending"),busy:m.busy,onCancel:async()=>{(await m.run("cancelBroadcast",{sendId:v.id})).ok&&r(u=>u+1)}},v.id))}):(0,ue.jsx)(ae,{className:"af-h-10 af-w-full"})]})}function zd({broadcast:e,canCancel:t,busy:s,onCancel:n}){return(0,ue.jsxs)("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[(0,ue.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,ue.jsx)("span",{className:"af-truncate af-text-sm af-font-medium",children:e.subject}),(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ue.jsx)(oe,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Hd[e.status]}),t&&(0,ue.jsx)(x,{type:"button",variant:"ghost",size:"sm",disabled:s,onClick:n,children:"Cancel"})]})]}),(0,ue.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",Ue(e.recipients.planned)," recipients \xB7 ",Ue(e.stats.delivered)," delivered \xB7 ",Ue(e.stats.opened)," opened \xB7"," ",Ue(e.stats.clicked)," clicked \xB7 ",Ue(e.stats.bounced)," bounced \xB7 ",Ue(e.stats.complained)," complaints \xB7"," ",Ue(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&(0,ue.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:yn(e.status_reason)})]})}var Nc=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function xc(e){let t=e.targeting??null,s=e.proposed_send_at?new Date(e.proposed_send_at):null,n=s!==null&&s.getTime()>Date.now();return{key:Nc(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:n?qd(s):"",suggested:t!==null||s!==null,timePassed:s!==null&&!n}}function qd(e){let t=s=>String(s).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}var Wd=(e,t)=>e.match===t.match&&e.scheduleAt===t.scheduleAt&&e.tagIds.length===t.tagIds.length&&e.tagIds.every(s=>t.tagIds.includes(s));function jd({draft:e,preview:t,reload:s,onCommitted:n}){let{api:a}=W(),{siteId:r,canWrite:o,settings:c,refreshKey:d}=Wt(),[l,i]=lt.useState(null),[m,v]=lt.useState(!1),[g,u]=lt.useState(null),[f,p]=lt.useState(()=>xc(e)),[b,w]=lt.useState(f.tagIds),[P,T]=lt.useState(f.match),[y,C]=lt.useState(f.scheduleAt),[k,I]=lt.useState(0),N=!Wd({tagIds:b,match:P,scheduleAt:y},f),E=Nc(e);lt.useEffect(()=>{if(E===f.key||e.id===f.draftId&&N)return;let te=xc(e);p(te),w(te.tagIds),T(te.match),C(te.scheduleAt),I(0)},[E,e,f,N]);let D=lt.useMemo(()=>l?new Set(l.map(te=>te.id)):null,[l]),_=D!==null&&b.every(te=>D.has(te));lt.useEffect(()=>{if(!D||b.every(we=>D.has(we)))return;let te=we=>we.filter(He=>D.has(He));I(we=>we+b.length-te(b).length),w(te(b)),p(we=>({...we,tagIds:te(we.tagIds)}))},[D,b]);let[Y,Q]=lt.useState(null),[z,le]=lt.useState(null),[fe,he]=lt.useState(null),M=na();lt.useEffect(()=>{a.getMarketingTags(r).then(te=>{i(te),v(!1)},()=>{i(null),v(!0)}),a.getMarketingContactStats(r).then(u,()=>u(null))},[a,r,d]);let ee=y?new Date(y).toISOString():null,U=JSON.stringify([b,P,ee]),ve=Y?.plan??null,me=Y!==null&&Y.key===U,Qe=lt.useRef(0),ke=lt.useCallback(async()=>{let te=++Qe.current;le(null);try{let we=await a.estimateBroadcast(r,{targeting:{tag_ids:b,match:P},scheduled_at:ee});te===Qe.current&&Q({key:U,plan:we})}catch(we){if(te!==Qe.current)return;Q(null),le(Un(we))}},[a,r,b,P,ee,U,d]),Ge=lt.useRef(!1);lt.useEffect(()=>{if(!_&&b.length>0)return;if(!Ge.current){Ge.current=!0,ke();return}let te=setTimeout(()=>void ke(),300);return()=>clearTimeout(te)},[ke,_,b.length]);let Je=c&&!c.readiness.can_send?yn(c.readiness.reason):null,Fe=ve!==null&&!ve.fits,_t=g?Math.max(0,g.by_status.subscribed-g.mailable):null,L=g&&ve&&_t!==null?Math.max(0,g.total-ve.recipients-_t):null,$=!o||M.busy||!ve||!me||Fe||ve.recipients===0||Je!==null||m&&b.length>0,F=async()=>{he(null);let te=await M.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:b,match:P},scheduled_at:ee});if(te.ok){he({tone:"success",text:ee?"Scheduled.":"Sending now."}),n();return}Fn(te.error,"version_conflict")?(M.setError(null),await s(),he({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):Fn(te.error,"over_allowance")&&await ke()},Re=te=>w(we=>we.includes(te)?we.filter(He=>He!==te):[...we,te]);return(0,ue.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[f.suggested&&!N&&(0,ue.jsx)(Be,{children:"Suggested by your assistant \u2014 review before sending."}),(0,ue.jsx)(Va,{children:"Who gets it"}),m&&(0,ue.jsx)(Be,{tone:"warning",children:b.length>0?"Couldn't load your tags, so this targeted send can't go out yet. Refresh to try again.":"Couldn't load your tags. Refresh to target by tag."}),k>0&&(0,ue.jsx)(Be,{tone:"warning",children:k===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),l&&l.length>0?(0,ue.jsxs)("div",{className:"af-space-y-2",children:[(0,ue.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map(te=>(0,ue.jsxs)("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[(0,ue.jsx)("input",{type:"checkbox",checked:b.includes(te.id),onChange:()=>Re(te.id)}),te.label]},te.id))}),b.length>1&&(0,ue.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",(0,ue.jsxs)("select",{"aria-label":"Tag match",value:P,onChange:te=>T(te.target.value),className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,ue.jsx)("option",{value:"any",children:"any of these tags"}),(0,ue.jsx)("option",{value:"all",children:"all of these tags"})]})]}),b.length===0&&(0,ue.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):(0,ue.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Everyone who can be emailed."}),(0,ue.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,ue.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),(0,ue.jsx)(re,{"aria-label":"Schedule time",type:"datetime-local",value:y,onChange:te=>C(te.target.value)})]}),f.timePassed&&!y&&(0,ue.jsx)(Be,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),z?(0,ue.jsxs)(Be,{tone:"error",children:["Couldn't work out the audience. ",z]}):ve?(0,ue.jsxs)("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[(0,ue.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,ue.jsx)(ho,{label:"Will receive it",value:ve.recipients}),(0,ue.jsx)(ho,{label:"Suppressed (bounced or complained)",value:_t}),(0,ue.jsx)(ho,{label:"Not included",value:L})]}),(0,ue.jsxs)("p",{className:"af-text-muted-foreground",children:[Ue(ve.allowance.remaining)," of ",Ue(ve.allowance.monthly)," emails left this month."]}),ve.sample_size!==null&&(0,ue.jsxs)(Be,{children:["We'll send to ",Ue(ve.sample_size)," people first and check for bounces before sending the rest."]}),ve.ramp_days.length>1&&(0,ue.jsxs)(Be,{children:["Your domain is new, so this goes out over ",ve.ramp_days.length," days:"," ",ve.ramp_days.map(te=>`${Ue(te.recipients)} on ${te.date}`).join(", "),"."]})]}):(0,ue.jsx)(ae,{className:"af-h-12 af-w-full"}),Fe&&ve&&(0,ue.jsxs)(Be,{tone:"warning",children:["This send needs ",Ue(ve.recipients)," emails, but only ",Ue(ve.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),Je&&(0,ue.jsxs)(Be,{tone:"warning",children:[Je,(0,ue.jsx)(Ni,{reason:c?.readiness.reason})]}),fe&&(0,ue.jsx)(Be,{tone:fe.tone,children:fe.text}),M.error&&(0,ue.jsx)(Be,{tone:"error",children:M.error}),(0,ue.jsx)(x,{type:"button",disabled:$,onClick:()=>void F(),children:ee?"Schedule":"Send now"})]})}function ho({label:e,value:t}){return(0,ue.jsxs)("div",{className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,ue.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,ue.jsx)("div",{className:"af-font-semibold",children:t===null?"\u2014":Ue(t)})]})}var ua=ie(require("react"),1);var ce=require("react/jsx-runtime"),kr="Subscribers confirm by email before they receive anything. Useful if many subscribers are in the EU (especially Germany), or if your forms attract fake or mistyped signups. Some signups need confirming even with this off: bursts of signups, and people re-subscribing after they unsubscribed.";function Gd(e){let{status:t,dmarc_status:s,sending_domain:n}=e.domain;return!n||t==="none"?"No sending domain yet.":t==="verified"?s==="ok"?`Verified. Emails send from ${n}.`:`${n} is verified, but your domain still needs a DMARC record.`:t==="failed"?`${n} couldn't be verified. Check the DNS records below.`:`Waiting for the DNS records on ${n} to take effect. This can take a few hours.`}function xo({onStartDomainSetup:e}){let{settings:t,refetchSettings:s,canWrite:n,settingsSection:a}=Wt(),r=t!==null;return ua.useEffect(()=>{r&&a&&document.getElementById(Nr(a))?.scrollIntoView?.({block:"start"})},[r,a]),t?(0,ce.jsxs)("div",{children:[(0,ce.jsx)(Va,{id:Nr("domain"),children:"Sending domain"}),(0,ce.jsx)(So,{settings:t,canWrite:n,onStartDomainSetup:e,onChanged:s}),(0,ce.jsx)(Zd,{settings:t}),(0,ce.jsx)(Jd,{settings:t,canWrite:n,onSaved:s},Yd(t)),(0,ce.jsx)(wo,{canWrite:n})]}):(0,ce.jsx)(ae,{className:"af-h-40 af-w-full"})}function So({settings:e,canWrite:t,onStartDomainSetup:s,onChanged:n}){let[a,r]=ua.useState(null),[o,c]=ua.useState(!1),[d,l]=ua.useState(null),i=e.domain.status==="verified"&&e.domain.dmarc_status==="ok";return(0,ce.jsxs)("div",{children:[(0,ce.jsx)("p",{className:"af-text-sm",children:Gd(e)}),!i&&s&&(0,ce.jsx)(x,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||o,onClick:async()=>{c(!0),l(null);try{r(await s()),await n()}catch(m){l(m instanceof Error?m.message:"Couldn't start domain setup.")}finally{c(!1)}},children:e.domain.sending_domain?"Check domain setup":"Set up sending domain"}),d&&(0,ce.jsx)(Be,{tone:"error",className:"af-mt-2",children:d}),a?.records&&a.records.length>0&&(0,ce.jsxs)("div",{className:"af-mt-3 af-space-y-1",children:[(0,ce.jsx)("p",{className:"af-text-sm",children:"Add these records at your domain provider:"}),(0,ce.jsxs)("table",{className:"af-w-full af-text-left af-text-xs",children:[(0,ce.jsx)("thead",{children:(0,ce.jsxs)("tr",{children:[(0,ce.jsx)("th",{className:"af-py-1 af-pr-2",children:"Type"}),(0,ce.jsx)("th",{className:"af-py-1 af-pr-2",children:"Name"}),(0,ce.jsx)("th",{className:"af-py-1 af-pr-2",children:"Value"}),(0,ce.jsx)("th",{className:"af-py-1",children:"Priority"})]})}),(0,ce.jsx)("tbody",{children:a.records.map((m,v)=>(0,ce.jsxs)("tr",{className:"af-border-t af-align-top",children:[(0,ce.jsx)("td",{className:"af-py-1 af-pr-2",children:m.type}),(0,ce.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:m.name}),(0,ce.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:m.value}),(0,ce.jsx)("td",{className:"af-py-1",children:m.priority??""})]},v))})]})]}),a&&(0,ce.jsx)(Kd,{result:a})]})}function Kd({result:e}){return e.status==="no_domain"?(0,ce.jsx)(Be,{tone:"warning",className:"af-mt-2",children:"Emails send from your own domain, so this site needs a custom domain first. Connect one, then come back to finish here."}):e.status==="not_available"?(0,ce.jsx)(Be,{tone:"warning",className:"af-mt-2",children:"Email sending isn't available for this site. It needs the Pro plan."}):e.records&&e.records.length>0?null:(0,ce.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",children:"We added the DNS records for you. Verification usually finishes within a few hours."})}function Zd({settings:e}){let{monthly:t,sent:s,reserved:n}=e.allowance,a=s+n;return(0,ce.jsxs)("div",{children:[(0,ce.jsx)(Va,{children:"Monthly allowance"}),(0,ce.jsxs)("p",{className:"af-text-sm",children:[Ue(a)," of ",Ue(t)," emails used this month (",Ue(Math.max(0,t-a))," left). Receipts and form notifications don't count."]})]})}function Yd(e){return JSON.stringify([e.business_name,e.postal_address,e.reply_to,e.brand,e.double_opt_in,e.checkout_marketing_consent,e.stripe_account_country])}function Jd({settings:e,canWrite:t,onSaved:s}){let[n,a]=ua.useState(e.business_name??""),[r,o]=ua.useState(e.postal_address??""),[c,d]=ua.useState(e.reply_to??""),[l,i]=ua.useState(e.brand.color),[m,v]=ua.useState(e.brand.logo_url??""),[g,u]=ua.useState(e.double_opt_in),[f,p]=ua.useState(!1),[b,w]=ua.useState(!1),P=na();return(0,ce.jsxs)("form",{onSubmit:async T=>{T.preventDefault(),w(!1),(await P.run("updateSettings",{business_name:n.trim()||null,postal_address:r.trim()||null,reply_to:c.trim()||null,double_opt_in:g,brand:{color:l,logo_url:m.trim()||null}})).ok&&(w(!0),await s())},children:[(0,ce.jsx)(Va,{id:Nr("sender"),children:"Sender details"}),(0,ce.jsxs)("div",{className:"af-space-y-3",children:[(0,ce.jsx)(Cr,{label:"Business name (shown as the sender)",children:(0,ce.jsx)(re,{"aria-label":"Business name",value:n,disabled:!t,onChange:T=>a(T.target.value)})}),(0,ce.jsx)(Cr,{label:"Postal address (required in every email)",children:(0,ce.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",value:r,disabled:!t,onChange:T=>o(T.target.value)})}),(0,ce.jsx)(Cr,{label:"Replies go to (your account email or an address on your domain)",children:(0,ce.jsx)(re,{"aria-label":"Reply-to email",type:"email",value:c,disabled:!t,onChange:T=>d(T.target.value)})})]}),(0,ce.jsx)(Va,{children:"Brand"}),(0,ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-3",children:[(0,ce.jsx)(Cr,{label:"Brand color",children:(0,ce.jsx)(re,{"aria-label":"Brand color",type:"color",className:"af-h-9 af-w-16 af-p-1",value:l,disabled:!t,onChange:T=>i(T.target.value)})}),(0,ce.jsx)(Cr,{label:"Logo URL (https)",children:(0,ce.jsx)(re,{"aria-label":"Logo URL",value:m,disabled:!t,onChange:T=>v(T.target.value)})})]}),(0,ce.jsx)(Va,{id:Nr("signups"),children:"Signups"}),(0,ce.jsx)("div",{className:"af-space-y-3 af-text-sm",children:(0,ce.jsxs)("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[(0,ce.jsxs)("label",{className:"af-flex af-items-center af-gap-2",children:[(0,ce.jsx)("input",{"aria-label":"Double opt-in",type:"checkbox",checked:g,disabled:!t,onChange:T=>u(T.target.checked)}),"Double opt-in"]}),(0,ce.jsx)("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:kr,className:"af-inline-flex af-h-4 af-w-4 af-cursor-help af-items-center af-justify-center af-rounded-full af-border af-text-[10px]",onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onFocus:()=>p(!0),onBlur:()=>p(!1),children:"?"}),(0,ce.jsx)("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!f,className:"af-absolute af-left-0 af-top-6 af-z-10 af-max-w-sm af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:kr})]})}),P.error&&(0,ce.jsx)(Be,{tone:"error",className:"af-mt-3",children:P.error}),b&&(0,ce.jsx)(Be,{tone:"success",className:"af-mt-3",children:"Saved."}),t&&(0,ce.jsx)(x,{type:"submit",size:"sm",className:"af-mt-3",disabled:P.busy,children:"Save settings"})]})}function wo({canWrite:e,heading:t=!0}){let{api:s}=W(),{siteId:n,refreshKey:a}=Wt(),r=wa(async()=>Promise.all((await s.getForms()).map(l=>s.getForm(l.id))),`${n}|${a}`,n),[o,c]=ua.useState({}),d=na();return!r.data||r.data.length===0?null:(0,ce.jsxs)("div",{children:[t&&(0,ce.jsx)(Va,{children:"Newsletter signup forms"}),(0,ce.jsx)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:"Submitting a newsletter signup form subscribes the visitor. Other forms need their own opt-in checkbox."}),(0,ce.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:r.data.map(l=>(0,ce.jsxs)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:[(0,ce.jsx)("span",{className:"af-truncate",children:l.name}),(0,ce.jsxs)("label",{className:"af-flex af-items-center af-gap-2",children:[(0,ce.jsx)("input",{type:"checkbox","aria-label":`${l.name} is a newsletter signup`,checked:(l.id in o?o[l.id]:l.purpose)==="newsletter",disabled:!e||d.busy,onChange:async i=>{let m=i.target.checked?"newsletter":"general";(await d.run("setFormPurpose",{formId:l.id,purpose:m})).ok&&c(g=>({...g,[l.id]:m}))}}),"Newsletter signup"]})]},l.id))}),d.error&&(0,ce.jsx)(Be,{tone:"error",className:"af-mt-2",children:d.error})]})}function Cr({label:e,children:t}){return(0,ce.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,ce.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}var _i=ie(require("react"),1),Tr=require("lucide-react");var Ae=require("react/jsx-runtime"),Xd=["Signups from your site's forms land here automatically.","The assistant drafts your newsletters. You review and press Send.","Every email carries the unsubscribe link, consent record and postal address the law asks for."];function Rc({onStartDomainSetup:e}){let{api:t}=W(),{siteId:s,settings:n,refetchSettings:a,canWrite:r,refreshKey:o}=Wt(),c=wa(()=>t.getMarketingContactStats(s),`${s}|${o}`,s);if(!n)return null;let d=n.domain.status==="verified"&&n.domain.dmarc_status==="ok",l=!!n.postal_address,i=c.data?.by_status.subscribed??0;return(0,Ae.jsxs)("div",{className:"af-mx-auto af-max-w-2xl",children:[(0,Ae.jsxs)("div",{className:"af-mb-6 af-rounded-lg af-border af-bg-muted/40 af-p-5",children:[(0,Ae.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-gap-2",children:[(0,Ae.jsx)(Tr.Mail,{className:"af-h-5 af-w-5","aria-hidden":!0}),(0,Ae.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Turn visitors into a list you own"})]}),(0,Ae.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Collect subscribers from your site, then send them newsletters from your own domain, branded with your logo and colors."}),(0,Ae.jsx)("ul",{className:"af-mt-3 af-space-y-1.5 af-text-sm",children:Xd.map(m=>(0,Ae.jsxs)("li",{className:"af-flex af-gap-2",children:[(0,Ae.jsx)(Tr.Check,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0 af-text-primary","aria-hidden":!0}),m]},m))}),i>0&&(0,Ae.jsxs)("p",{className:"af-mt-3 af-text-sm af-font-medium",children:[Ue(i)," ",i===1?"subscriber is":"subscribers are"," already waiting for your first email."]})]}),(0,Ae.jsx)("h3",{className:"af-mb-3 af-text-sm af-font-semibold",children:"Set up sending"}),!r&&(0,Ae.jsx)(Be,{className:"af-mb-3",children:"Only the site owner can finish setup."}),(0,Ae.jsxs)("ol",{className:"af-space-y-3",children:[(0,Ae.jsxs)(No,{n:1,title:"Send from your own domain",done:d,children:[(0,Ae.jsx)("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:"Emails go out from a subdomain of your site's domain, so they reach inboxes and are clearly from you."}),(0,Ae.jsx)(So,{settings:n,canWrite:r,onStartDomainSetup:e,onChanged:a})]}),(0,Ae.jsx)(No,{n:2,title:"Add your sender details",done:l,summary:l?n.business_name??void 0:void 0,children:(0,Ae.jsx)(Qd,{settings:n,canWrite:r,onSaved:a})}),(0,Ae.jsxs)(No,{n:3,title:"Collect subscribers",optional:!0,children:[(0,Ae.jsx)("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:'Mark a form as a newsletter signup, or ask the assistant to "add a newsletter signup to my footer".'}),(0,Ae.jsx)(wo,{canWrite:r,heading:!1})]})]})]})}function No({n:e,title:t,done:s=!1,optional:n=!1,summary:a,children:r}){return(0,Ae.jsxs)("li",{className:"af-rounded-lg af-border af-p-4","aria-label":`Step ${e}: ${t}${s?" (done)":""}`,children:[(0,Ae.jsxs)("div",{className:"af-flex af-items-center af-gap-3",children:[(0,Ae.jsx)("span",{className:J("af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-xs af-font-semibold",s?"af-bg-primary af-text-primary-foreground":"af-border"),children:s?(0,Ae.jsx)(Tr.Check,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0}):e}),(0,Ae.jsx)("span",{className:"af-text-sm af-font-medium",children:t}),n&&(0,Ae.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Optional"}),s&&a&&(0,Ae.jsx)("span",{className:"af-truncate af-text-xs af-text-muted-foreground",children:a})]}),!s&&(0,Ae.jsx)("div",{className:"af-mt-3 af-pl-9",children:r})]})}function Qd({settings:e,canWrite:t,onSaved:s}){let[n,a]=_i.useState(e.business_name??""),[r,o]=_i.useState(e.postal_address??""),[c,d]=_i.useState(e.reply_to??""),l=na();return(0,Ae.jsxs)("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),(await l.run("updateSettings",{business_name:n.trim()||null,postal_address:r.trim()||null,reply_to:c.trim()||null,double_opt_in:e.double_opt_in})).ok&&await s()},children:[(0,Ae.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Ae.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Business name (shown as the sender)"}),(0,Ae.jsx)(re,{"aria-label":"Business name",value:n,disabled:!t,onChange:i=>a(i.target.value)})]}),(0,Ae.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Ae.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Postal address (required in every email)"}),(0,Ae.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",value:r,disabled:!t,onChange:i=>o(i.target.value)})]}),(0,Ae.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Ae.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Replies go to (optional: your account email or an address on your domain)"}),(0,Ae.jsx)(re,{"aria-label":"Reply-to email",type:"email",value:c,disabled:!t,onChange:i=>d(i.target.value)})]}),l.error&&(0,Ae.jsx)(Be,{tone:"error",children:l.error}),t&&(0,Ae.jsx)(x,{type:"submit",size:"sm",disabled:l.busy||!r.trim(),children:"Save sender details"})]})}var We=require("react/jsx-runtime"),ef=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"settings",label:"Settings"}],tf={broadcast:"broadcasts",welcome:"broadcasts",recovery:"broadcasts"},af={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function Ro(e){return(0,We.jsx)(sf,{...e},e.siteId)}function sf({siteId:e,isOwnerSide:t,needsPaidPlan:s,initialDraftId:n,onOrgAction:a,onRequestReview:r,onStartDomainSetup:o,onBackToWebsite:c,onOpenStoreSettings:d,refreshKey:l=0,className:i}){let{api:m}=W(),v=wa(()=>m.getMarketingSettings(e),`${e}|${l}`,e),[g,u]=Na.useState(n?"broadcasts":"audience"),[f,p]=Na.useState(!n),[b,w]=Na.useState(null),P=_=>b===_?n:void 0,[T,y]=Na.useState(!!n),[C,k]=Na.useState(null),I=Na.useCallback(()=>y(!1),[]),N=Na.useCallback(_=>{u("settings"),k(_??null)},[]),E=!T&&v.data!==null&&Pc(v.data);Na.useEffect(()=>{if(!n||s)return;let _=!0;return m.getEmailDraft(e,n).then(Y=>{_&&(u(tf[Y.kind]),w(Y.kind),p(!0))},()=>_&&p(!0)),()=>{_=!1}},[m,e,n,s]);let D=Na.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:a,settings:v.data,refetchSettings:v.refetch,refreshKey:l,openSetup:I,openSettings:N,settingsSection:C,onOpenStoreSettings:d}),[e,t,a,v.data,v.refetch,l,I,N,C,d]);return s?(0,We.jsx)(St,{title:"Email Marketing",onBackToWebsite:c,className:i,children:(0,We.jsx)(Ks,{icon:_c.Mail,heading:"Email marketing is on the Pro plan.",body:"Upgrade to collect subscribers and send newsletters from your own domain."})}):(0,We.jsx)(St,{title:"Email Marketing",onBackToWebsite:c,className:i,children:(0,We.jsx)(yo.Provider,{value:D,children:E?(0,We.jsx)(Rc,{onStartDomainSetup:o}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(nf,{settingsError:v.error,onRetry:()=>void v.refetch(),onRequestReview:r}),!t&&(0,We.jsx)(Be,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),(0,We.jsx)("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:ef.map(_=>(0,We.jsx)("button",{type:"button",role:"tab","aria-selected":g===_.id,onClick:()=>{u(_.id),k(null)},className:J("af-border-b-2 af-px-3 af-py-2 af-text-sm",g===_.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:_.label},_.id))}),(0,We.jsx)("div",{role:"tabpanel",children:f?g==="audience"?(0,We.jsx)(yc,{}):g==="broadcasts"?(0,We.jsx)(wc,{initialDraftId:P("broadcast")}):(0,We.jsx)(xo,{onStartDomainSetup:o}):(0,We.jsx)(ae,{className:"af-h-24 af-w-full"})})]})})})}function Pc(e){return!e.paused.paused_at&&!e.readiness.can_send&&Si.has(e.readiness.reason??"")}function nf({settingsError:e,onRetry:t,onRequestReview:s}){let{settings:n,openSetup:a}=Wt(),[r,o]=Na.useState("idle");return e?(0,We.jsx)(Lt,{message:"Couldn't load email settings.",onRetry:t}):n?n.paused.paused_at?(0,We.jsxs)(Be,{tone:"warning",className:"af-mb-3",children:[(0,We.jsx)("div",{className:"af-font-medium",children:"Sending is paused."}),(0,We.jsxs)("p",{children:[af[n.paused.reason??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),s&&(r==="sent"?(0,We.jsx)("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):(0,We.jsx)(x,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{o("sending");try{await s(),o("sent")}catch{o("failed")}},children:"Request review"})),r==="failed"&&(0,We.jsx)("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]}):n.readiness.can_send?(0,We.jsxs)(Be,{tone:"success",className:"af-mb-3",children:["Ready to send from ",n.domain.sending_domain??"your domain","."]}):(0,We.jsxs)(Be,{tone:"warning",className:"af-mb-3",children:["You can collect and manage contacts now. ",yn(n.readiness.reason),Pc(n)&&(0,We.jsxs)(We.Fragment,{children:[" ",(0,We.jsx)(wi,{onClick:a,children:"Finish setup"})]})]}):(0,We.jsx)(ae,{className:"af-mb-3 af-h-10 af-w-full"})}var Vt=ie(require("react"),1);var rf=2e3,Jt=()=>({data:null,error:null,isLoading:!0});function xn(e,{refreshKey:t,breakdowns:s=[],filters:n=[]}={}){let{api:a}=W(),[r,o]=Vt.useState(Jt),[c,d]=Vt.useState(Jt),[l,i]=Vt.useState(Jt),[m,v]=Vt.useState(Jt),[g,u]=Vt.useState(Jt),f=M=>Object.fromEntries(M.map(ee=>[ee,Jt()])),[p,b]=Vt.useState(()=>f(s)),w=Vt.useRef(0),P=Vt.useRef(0),T=Vt.useRef("idle"),y=s.join(","),C=Vs()??"",k=JSON.stringify(n),I=`${e}:${y}:${k}:${C}`,[N,E]=Vt.useState({api:a,fetchIdentity:I});(N.api!==a||N.fetchIdentity!==I)&&(E({api:a,fetchIdentity:I}),w.current+=1,o(Jt),d(Jt),i(Jt),v(Jt),b(f(y?y.split(","):[])));let D=`${e}:${String(t??"")}:${C}`,[_,Y]=Vt.useState({api:a,conversionsIdentity:D});(_.api!==a||_.conversionsIdentity!==D)&&(Y({api:a,conversionsIdentity:D}),P.current+=1,T.current="idle",u(Jt));let Q=Vt.useCallback(async M=>{let ee=++w.current,U=y?y.split(","):[];o(Jt),d(Jt),i(Jt),v(Jt),b(Object.fromEntries(U.map(L=>[L,Jt()])));let ve=T.current!=="pending"&&(M?.force===!0||T.current==="idle"),me=(L,$)=>$.then(F=>{ee===w.current&&L({data:F,error:null,isLoading:!1})},F=>{ee===w.current&&L({data:null,error:F instanceof Error?F:new Error("Failed to fetch report"),isLoading:!1})}),Qe=a.getAnalyticsStatus(),ke=me(o,Qe),Ge=Symbol("status-timeout"),Je,Fe=await Promise.race([Qe.then(L=>L,()=>null),new Promise(L=>{Je=setTimeout(()=>L(Ge),rf)})]);if(clearTimeout(Je),ee!==w.current)return;if(Fe===Ge&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Fe!==null&&Fe!==Ge&&(Fe.collecting!==!0||Fe.first_seen===null&&!Fe.first_seen_unavailable||Fe.first_seen!==null&&Fe.first_seen_in_reports===!1)){let L={data:null,error:null,isLoading:!1};d(L),i(L),v(L),b(Object.fromEntries(U.map($=>[$,{...L}]))),ve&&(u(L),T.current="done"),await ke;return}await Promise.all([Fe===Ge?Promise.resolve():ke,me(d,a.getAnalyticsSummary(e,n)),me(i,a.getAnalyticsTimeseries(e,n)),me(v,a.getAnalyticsChannels(e,n)),ve?(()=>{T.current="pending";let L=++P.current;return u(Jt),a.getAnalyticsConversions(e).then($=>{L===P.current&&(u({data:$,error:null,isLoading:!1}),T.current="done")},$=>{L===P.current&&(u({data:null,error:$ instanceof Error?$:new Error("Failed to fetch report"),isLoading:!1}),T.current="done")})})():Promise.resolve(),...U.map(L=>a.getAnalyticsBreakdown(L,e,n).then($=>{ee===w.current&&b(F=>({...F,[L]:{data:$,error:null,isLoading:!1}}))},$=>{ee===w.current&&b(F=>({...F,[L]:{data:null,error:$ instanceof Error?$:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[a,e,y,k,D,C]),z=Vt.useCallback(async()=>{let M=w.current;try{let ee=await a.getAnalyticsStatus();if(M!==w.current)return;o({data:ee,error:null,isLoading:!1})}catch(ee){if(M!==w.current)return;o(U=>({data:U.data,error:ee instanceof Error?ee:new Error("Failed to fetch status"),isLoading:!1}))}},[a]),le=Vt.useCallback(()=>Q({force:!0}),[Q]);Vt.useEffect(()=>{Q()},[Q,t]);let fe=r.isLoading||c.isLoading||l.isLoading||m.isLoading||g.isLoading||Object.values(p).some(M=>M.isLoading),he=[l,c,m,g,...Object.values(p)].map(M=>M.data?.status==="ok"?M.data.timezone:void 0).find(M=>M!==void 0);return{status:r,summary:c,timeseries:l,channels:m,conversions:g,breakdowns:p,reportedZone:he,isLoading:fe,refetch:le,refetchStatus:z}}var Ht=ie(require("react"),1);var Pi=3e4,Ci=3;function Er(e={}){let t="collecting"in e,{collecting:s,statusFailed:n=!1,identity:a}=e,{api:r}=W(),[o,c]=Ht.useState(null),[d,l]=Ht.useState(null),[i,m]=Ht.useState(!1),[v,g]=Ht.useState(null),[u,f]=Ht.useState(!1),[p,b]=Ht.useState(!0),[w,P]=Ht.useState(0),T=Ht.useRef(0),y=Ht.useRef(0),C=Ht.useRef(void 0);s!==void 0&&(C.current=s);let k=t?C.current===!0||C.current===void 0&&n:!0,[I,N]=Ht.useState({api:r,identity:a}),E=a!==void 0&&a!==I.identity;(I.api!==r||E)&&(C.current=void 0,N({api:r,identity:a}),y.current+=1,T.current=0,c(null),l(null),m(!1),g(null),f(!1),b(!0),P(0));let D=Ht.useRef(()=>{}),_=Ht.useRef(null),Y=Ht.useCallback(async()=>{if(_.current!==null&&_.current===y.current)return;let Q=++y.current;_.current=Q;try{let z=await r.getAnalyticsRealtime();if(Q!==y.current)return;if(z.status==="unreachable"){f(!0),m(!0),b(!1),P(le=>le+1);return}T.current=0,f(!1),c(z.data.current_visitors),l(z.as_of),m(!1),g(null),b(!1),P(le=>le+1)}catch(z){if(Q!==y.current)return;T.current+=1,b(!1),P(le=>le+1),m(!0),T.current>=Ci&&g(z instanceof Error?z:new Error("Realtime unavailable"))}finally{_.current===Q&&(_.current=null)}},[r]);return D.current=()=>void Y(),Ht.useEffect(()=>{let Q,z=()=>{Q===void 0&&(Q=setInterval(()=>D.current(),Pi))},le=()=>{Q!==void 0&&(clearInterval(Q),Q=void 0)},fe=()=>{typeof document<"u"&&document.hidden?le():(D.current(),z())};return k?((typeof document>"u"||!document.hidden)&&(D.current(),z()),document?.addEventListener("visibilitychange",fe),()=>{le(),document?.removeEventListener("visibilitychange",fe),y.current+=1}):()=>{document?.removeEventListener("visibilitychange",fe)}},[I.api,I.identity,k]),{currentVisitors:o,asOf:d,isStale:i,error:v,isUnreachable:u,isInitialLoad:p,polls:w}}var Rt=ie(require("react"),1);var Cc=ie(require("react"),1);var Sn=require("react/jsx-runtime");function of(){try{let e=Intl.supportedValuesOf?.("timeZone");if(e&&e.length>0)return e.includes("UTC")?e:["UTC",...e]}catch{}return["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Madrid","Africa/Johannesburg","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Tokyo","Australia/Sydney"]}function _o({value:e,chosen:t,onChange:s}){let n=Hn(),a=t===null&&n!==null&&e===n,r=Cc.useMemo(()=>{let o=of();return o.includes(e)?o:[e,...o]},[e]);return(0,Sn.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,Sn.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,Sn.jsxs)("select",{value:a?"":e,onChange:o=>s(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[(0,Sn.jsx)("option",{value:"",children:n?`${n.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(o=>(0,Sn.jsx)("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var ki=(e,{published:t}={})=>{let s=t===!1,n=e!=null&&(!e.collecting||s&&e.first_seen===null&&!e.first_seen_unavailable),a=!n&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=a||r;return{notCollecting:n,awaitingFirstVisit:a,firstVisitTooRecent:r,holdingForFirstData:o,nothingToReport:n||o}};var Ir=ie(require("react"),1),lf=3e4;function Ti({status:e,holdingForFirstData:t,refetchStatus:s,refetch:n}){Ir.useEffect(()=>{if(!t)return;let r,o=()=>{r===void 0&&(r=setInterval(()=>void s(),lf))},c=()=>{r!==void 0&&(clearInterval(r),r=void 0)},d=()=>{typeof document<"u"&&document.hidden?c():(s(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",d),()=>{c(),document?.removeEventListener("visibilitychange",d)}},[t,s]);let a=Ir.useRef(void 0);Ir.useEffect(()=>{if(!e){a.current=void 0;return}let r=a.current;a.current=t,r===!0&&!t&&n()},[e,t,n])}var wn=ie(require("react"),1);var cf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function da(e){let t=Math.abs(e);if(t<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[n,a]of s)if(t>=n){let r=e/n,o=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(o)>=1e3&&n!==1e9?da(o*n):`${o}${a}`}return String(e)}function $n(e){return`${(e*100).toFixed(1)}%`}function Dr(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function Tc(e){let t=Math.max(0,Math.round(e));return t>=3600&&t%3600===0?`${t/3600}h`:t>=60&&t%60===0?`${t/60}m`:Dr(t)}function Ec(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Ic(e,t){if(!(!Number.isFinite(e)||e<=0))for(let s of t){let n=Math.ceil(e/s);if(n<=5)return Array.from({length:n+1},(a,r)=>Number((r*s).toPrecision(12)))}}function Ar(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Dc(e){let t=new Date(e);return Number.isNaN(t.getTime())?"as of an unknown time":`as of ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function Po(e){let t=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${cf[t-1]} ${s}`}function kc(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function uf(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Ac(e,t,s="UTC"){let n=new Map(t.map(o=>[o.date,o])),a=[],r=kc(e.to,s);for(let o=kc(e.from,s);o<r;o=uf(o))a.push(n.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return a}function Lc(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=new Date(`${e}T00:00:00Z`);if(Number.isNaN(n.getTime()))return e;let a=String(n.getUTCDate()).padStart(2,"0");return`${t[n.getUTCDay()]}, ${a} ${s[n.getUTCMonth()]}`}var Ha=require("react/jsx-runtime");function Oc({what:e="This report",onRetry:t,collecting:s}){return(0,Ha.jsxs)("div",{role:"status",className:"af-flex af-flex-col af-items-center af-gap-1 af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-8 af-text-center",children:[(0,Ha.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,Ha.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:s===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),t?(0,Ha.jsx)("button",{type:"button",onClick:t,className:"af-mt-2 af-rounded-md af-border af-border-border af-px-3 af-py-1 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Try again"}):null]})}function Ei({what:e="No data"}){return(0,Ha.jsx)("div",{className:"af-flex af-items-center af-justify-center af-rounded-md af-px-4 af-py-8 af-text-center af-text-xs af-text-muted-foreground",children:e})}function Ms({sourced:e,error:t,isLoading:s,what:n,onRetry:a,collecting:r,children:o}){return s?(0,Ha.jsx)("div",{role:"status","aria-label":`Loading ${n}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,Ha.jsx)(Oc,{what:n,onRetry:a,collecting:r}):!e||e.status==="unreachable"?(0,Ha.jsx)(Oc,{what:n,onRetry:a,collecting:r}):(0,Ha.jsx)(Ha.Fragment,{children:o(e.data)})}var ft=require("react/jsx-runtime");function Co({rows:e,dimension:t,metric:s,metricLabel:n,secondary:a,emptyCopy:r="No data for this period",onFilter:o,canFilter:c,maxRows:d=9}){let[l,i]=wn.useState(!1);if(e.length===0)return(0,ft.jsx)(Ei,{what:r});let m=e.reduce((u,f)=>Math.max(u,Number(f[s]??0)),0)||1,v=Math.max(0,e.length-d),g=l?e:e.slice(0,d);return(0,ft.jsxs)(ft.Fragment,{children:[(0,ft.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,ft.jsx)("thead",{children:(0,ft.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,ft.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,ft.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:n})]})}),(0,ft.jsx)("tbody",{children:g.map((u,f)=>{let p=Number(u[s]??0),b=u[t]??null,w=Ar(b),P=a?u[a]:null,T=b!==null&&(c?c(b,P):!0);return(0,ft.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,ft.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,ft.jsx)("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,p/m*100)}%`}}),b!==null&&o&&T?(0,ft.jsx)("button",{type:"button",onClick:()=>o(b,P),title:`Filter by ${w}`,"aria-label":`Filter by ${w}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:w}):(0,ft.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:w}),P?(0,ft.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:P}):null]}),(0,ft.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:da(p)})]},`${w}-${P??""}-${f}`)})})]}),v>0?(0,ft.jsx)("button",{type:"button",onClick:()=>i(u=>!u),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length}`}):null]})}function Lr({title:e,tabs:t,defaultTabId:s,headerRight:n}){let[a,r]=wn.useState(s),o=t.find(g=>g.id===a)??t[0],c=wn.useId(),d=g=>`${c}-tab-${g}`,l=g=>`${c}-panel-${g}`,i=wn.useRef(null),m=(g,u)=>{g.preventDefault();let f=(u+t.length)%t.length;r(t[f].id),i.current?.querySelectorAll('[role="tab"]')?.[f]?.focus()};return(0,ft.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,ft.jsxs)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:[(0,ft.jsx)("div",{ref:i,role:"tablist","aria-label":e,onKeyDown:g=>{let u=t.findIndex(f=>f.id===a);g.key==="ArrowRight"&&m(g,u+1),g.key==="ArrowLeft"&&m(g,u-1),g.key==="Home"&&m(g,0),g.key==="End"&&m(g,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(g=>(0,ft.jsx)("button",{id:d(g.id),role:"tab",type:"button","aria-selected":g.id===a,"aria-controls":l(g.id),tabIndex:g.id===a?0:-1,onClick:()=>r(g.id),className:g.id===a?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:g.label},g.id))}),n]}),o?(0,ft.jsx)("div",{id:l(o.id),role:"tabpanel","aria-labelledby":d(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var Ra=ie(require("react"),1),Qs=ie(require("@radix-ui/react-popover"),1);var Js=3,Xs=100;var je=require("react/jsx-runtime"),Or={channel:"Channel",source:"Source",campaign:"Campaign",utm_source:"UTM source",utm_medium:"UTM medium",utm_content:"UTM content",utm_term:"UTM term",page:"Page",entry_page:"Entry page",exit_page:"Exit page",country:"Country",region:"Region",city:"City",browser:"Browser",os:"Operating system",device:"Device"},df=Object.keys(Or);function Bc(e){let t=Or[e.dimension],s=e.operator==="is_not"?"is not":"is",n=e.values.map(a=>Ar(a)).join(" or ");return`${t} ${s} ${n}`}function ko(e,t){let s=e.findIndex(n=>n.dimension===t.dimension&&(n.operator??"is")===(t.operator??"is"));if(s>=0){let n=[...new Set([...e[s].values,...t.values])];return n.length>Xs||n.length===e[s].values.length?e:e.map((a,r)=>r===s?{...a,values:n}:a)}return t.values.length>Xs||e.length>=Js?e:[...e,t]}function ff(e,t){let s={};for(let[n,a]of Object.entries(t)){let r=e.get(n)??new Set;for(let o of a)r.add(o);e.set(n,r),s[n]=[...r]}return s}function Fc(e,t){let s=e.findIndex(n=>n.dimension===t.dimension&&(n.operator??"is")===(t.operator??"is"));return s>=0?e.map((n,a)=>a===s?t:n):t.values.length>Xs||e.length>=Js?e:[...e,t]}function mf(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Uc(e,t,s,n={}){if(e.api!==t.api||e.period!==t.period)return e.api=t.api,e.period=t.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let a=ff(e.byDimension,s);for(let[r,o]of Object.entries(n)){let c=e.foldsByLabel.get(r)??new Set;for(let d of o)c.add(d);e.foldsByLabel.set(r,c)}return{suggestions:a,folds:new Map([...e.foldsByLabel].map(([r,o])=>[r,[...o]]))}}function Mc(e){let{filters:t,onChange:s}=e,n=t.length>=Js;return Ra.useEffect(()=>{if(t.length===0)return;let a=r=>{let o=r.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||r.key==="Escape"&&s([])};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[t.length,s]),(0,je.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((a,r)=>(0,je.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-1 af-rounded-full af-border af-border-border af-bg-muted af-py-1 af-pl-3 af-pr-1 af-text-xs",children:[(0,je.jsx)("span",{className:"af-text-foreground",children:Bc(a)}),(0,je.jsx)("button",{type:"button","aria-label":`Remove filter ${Bc(a)}`,onClick:()=>s(t.filter((o,c)=>c!==r)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${a.dimension}-${a.operator??"is"}`)),(0,je.jsx)(pf,{...e,disabled:n}),t.length>0?(0,je.jsx)("button",{type:"button",onClick:()=>s([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function pf({filters:e,onChange:t,suggestions:s,resetKey:n,disabled:a,expandValues:r}){let[o,c]=Ra.useState(!1),d=Ra.useRef(null),[l,i]=Ra.useState(null);Ra.useEffect(()=>{i(d.current?.closest(".aifeatures-admin")??null)},[]);let[m,v]=Ra.useState(null),[g,u]=Ra.useState("is"),[f,p]=Ra.useState(""),[b,w]=Ra.useState([]);Ra.useEffect(()=>{o||(v(null),u("is"),p(""),w([]))},[o]);let P=Ra.useRef(n);P.current!==n&&(P.current=n,o&&c(!1),m!==null&&v(null),b.length>0&&w([]),f!==""&&p(""),g!=="is"&&u("is"));let T=E=>{let D=mf(E);v(D.dimension),w(D.picked),p(D.search),u(D.operator)},C=(m?s[m]??[]:[]).filter(E=>E.toLowerCase().includes(f.trim().toLowerCase())),k=m===null||b.length===0?null:ko(e,{dimension:m,operator:g,values:r?r(m,b):b}),I=k!==null&&k!==e,N=()=>{let E=k;!E||E===e||(t(E),c(!1))};return(0,je.jsxs)(Qs.Root,{open:o,onOpenChange:c,children:[(0,je.jsx)(Qs.Trigger,{asChild:!0,children:(0,je.jsx)("button",{ref:d,type:"button",disabled:!1,title:a?`At most ${Js} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),(0,je.jsx)(Qs.Portal,{container:l,children:(0,je.jsx)(Qs.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:m===null?(0,je.jsxs)("div",{children:[(0,je.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,je.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:df.filter(E=>s[E]!==void 0).map(E=>{let D=s[E]?.length??0,_=!e.some(Y=>Y.dimension===E)&&e.length>=Js;return(0,je.jsxs)("button",{type:"button",onClick:()=>T(E),disabled:D===0||_,className:"af-flex af-w-full af-items-center af-justify-between af-rounded-md af-px-2 af-py-1.5 af-text-left af-text-xs af-text-foreground hover:af-bg-muted disabled:af-text-muted-foreground disabled:hover:af-bg-transparent",children:[(0,je.jsx)("span",{children:Or[E]}),(0,je.jsx)("span",{className:"af-text-muted-foreground",children:D===0?"no data":_?"no room":D})]},E)})})]}):(0,je.jsxs)("div",{children:[(0,je.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,je.jsx)("button",{type:"button",onClick:()=>T(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,je.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Or[m]}),(0,je.jsxs)("select",{"aria-label":"Operator",value:g,onChange:E=>u(E.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,je.jsx)("option",{value:"is",children:"is"}),(0,je.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,je.jsx)("input",{type:"text",value:f,onChange:E=>p(E.target.value),placeholder:"Search\u2026","aria-label":`Search ${Or[m]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),(0,je.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:C.length===0?(0,je.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",f,"\u201D."]}):C.map(E=>(0,je.jsxs)("label",{className:"af-flex af-cursor-pointer af-items-center af-gap-2 af-rounded-md af-px-2 af-py-1.5 af-text-xs af-text-foreground hover:af-bg-muted",children:[(0,je.jsx)("input",{type:"checkbox",checked:b.includes(E),disabled:!b.includes(E)&&b.length>=Xs,onChange:D=>w(_=>D.target.checked?[..._,E]:_.filter(Y=>Y!==E))}),(0,je.jsx)("span",{className:"af-break-all",children:Ar(E)})]},E))}),(0,je.jsx)("button",{type:"button",onClick:N,disabled:!I,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:b.length<=1?"Apply filter":b.length>=Xs?`Apply filter (${b.length} values \u2014 the maximum)`:`Apply filter (${b.length} values)`})]})})})]})}var Nt=require("react/jsx-runtime"),gf=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:da,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:da,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:da,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:$n,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Dr,chart:"visit_duration_seconds"}];function vf({current:e,previous:t,downIsGood:s}){if(t===0)return null;let n=(e-t)/t;if(Math.abs(n)<5e-4)return null;let a=n>0,r=s?!a:a,o=`${a?"+":""}${(n*100).toFixed(1)}%`;return(0,Nt.jsx)("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:o})}function $c({summary:e,selected:t,onSelect:s}){return(0,Nt.jsx)("div",{className:"af-@container",children:(0,Nt.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:gf.map(n=>{let a=n.chart===t,r=s!==void 0,o=(0,Nt.jsxs)(Nt.Fragment,{children:[(0,Nt.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:n.label}),(0,Nt.jsxs)("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[(0,Nt.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:n.format(n.get(e.current))}),e.previous?(0,Nt.jsx)(vf,{current:n.get(e.current),previous:n.get(e.previous),downIsGood:n.downIsGood}):null]})]});return r?(0,Nt.jsx)("button",{type:"button","aria-pressed":a,onClick:()=>s(n.chart),className:a?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:o},n.key):(0,Nt.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},n.key)})})})}function To({currentVisitors:e,asOf:t,isStale:s,isUnreachable:n,isInitialLoad:a=!1,scopeIsSiteWide:r=!1}){if(a&&!n)return(0,Nt.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1","aria-hidden":"true",children:[(0,Nt.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,Nt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(n||e===null)return(0,Nt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?Dc(t):"freshness unknown",c=r?" across the whole site, not the current filter,":"",d=s?`${e} current visitors${c} ${o} (not updating)`:`${e} current visitors${c} ${o}`;return(0,Nt.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:d,children:[(0,Nt.jsx)("span",{"aria-hidden":"true",className:s?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),(0,Nt.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,Nt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),(0,Nt.jsx)("span",{className:"af-sr-only",children:d})]})}var Vc=ie(require("react"),1),Hc=require("lucide-react");var Ye=require("react/jsx-runtime");function Ii(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Di({rows:e,denominator:t,windowPrecedesCollection:s=!1,coverageUnknown:n=!1,emptyCopy:a="No conversions in this period",maxRows:r=9,primaryConversion:o}){let[c,d]=Vc.useState(!1),l=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||Ii(p,o)),i=s?(0,Ye.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This period starts before we began collecting for this site, so these counts cover less time than the dates suggest."}):n?(0,Ye.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null;if(l.length===0)return(0,Ye.jsxs)(Ye.Fragment,{children:[(0,Ye.jsx)(Ei,{what:a}),i]});let m=l.slice(0,r),v=o?l.find(p=>Ii(p,o)):void 0,g=v&&!m.includes(v)?l.filter(p=>m.includes(p)||p===v).slice(0,Math.max(0,r-1)).concat(v):m,u=c?e:g,f=Math.max(0,e.length-g.length);return(0,Ye.jsxs)(Ye.Fragment,{children:[(0,Ye.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Ye.jsx)("thead",{children:(0,Ye.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,Ye.jsx)("tbody",{children:u.map((p,b)=>(0,Ye.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":Ii(p,o)?"true":void 0,children:[(0,Ye.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Ii(p,o)?(0,Ye.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,Ye.jsx)(Hc.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,Ye.jsx)("span",{className:"af-font-medium af-text-foreground",children:p.goal}),(0,Ye.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):p.goal}),(0,Ye.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:da(p.visitors)}),(0,Ye.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:da(p.events)}),(0,Ye.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:p.conversion_rate===null?(0,Ye.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):$n(p.conversion_rate)})]},`${p.goal}-${b}`))})]}),f>0?(0,Ye.jsx)("button",{type:"button",onClick:()=>d(p=>!p),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:c?"Show fewer":`Show all ${e.length} goals`}):null,(0,Ye.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",da(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),i]})}var _a=require("recharts");var Pt=require("react/jsx-runtime"),Ai={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Io={visitors:da,visits:da,pageviews:da,views_per_visit:e=>e.toFixed(2),bounce_rate:$n,visit_duration_seconds:Dr},bf=31,yf=new Set(["visitors","visits","pageviews"]),hf={...Io,bounce_rate:Ec,visit_duration_seconds:Tc},Eo=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],xf=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Sf=[.01,.02,.05,.1,.2,.25,.5,1],wf=[.25,.5,1,2,5,10,25,50],Nf={visitors:Eo,visits:Eo,pageviews:Eo,views_per_visit:wf,bounce_rate:Sf,visit_duration_seconds:xf};function Rf({active:e,payload:t,label:s,metric:n}){if(!e||!t||t.length===0)return null;let a=t[0].payload;return(0,Pt.jsxs)("div",{className:"af-rounded-lg af-border af-border-border af-bg-popover af-px-3 af-py-2 af-text-popover-foreground af-shadow-md",children:[(0,Pt.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Ai[n]}),(0,Pt.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,Pt.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,Pt.jsx)("span",{className:"af-text-muted-foreground",children:Lc(String(s))}),(0,Pt.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Io[n](Number(a[n]??0))})]})]})}function Li({rows:e,window:t,metric:s,timeZone:n="UTC",height:a=260}){let r=Ac(t,e,n),o=Io[s],c=hf[s],d=Ic(r.reduce((i,m)=>Math.max(i,Number(m[s]??0)),0),Nf[s]),l=`${Ai[s]} by day: ${r.map(i=>`${Po(i.date)}: ${o(Number(i[s]??0))}`).join("; ")}.`;return(0,Pt.jsxs)("figure",{"aria-label":`${Ai[s]} over time`,className:"af-m-0",children:[(0,Pt.jsx)(_a.ResponsiveContainer,{width:"100%",height:a,children:(0,Pt.jsxs)(_a.AreaChart,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,Pt.jsx)("defs",{children:(0,Pt.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,Pt.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,Pt.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,Pt.jsx)(_a.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,Pt.jsx)(_a.XAxis,{dataKey:"date",tickFormatter:Po,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,Pt.jsx)(_a.YAxis,{allowDecimals:!yf.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...d?{ticks:d,domain:[0,d[d.length-1]]}:{},tickFormatter:i=>c(i),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,Pt.jsx)(_a.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,Pt.jsx)(Rf,{metric:s})}),(0,Pt.jsx)(_a.Area,{type:"linear",dataKey:s,name:Ai[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=bf?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,Pt.jsx)("figcaption",{className:"af-sr-only",children:l})]})}var pe=require("react/jsx-runtime"),_f="2026-08-13",Pf=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Cf=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function zc({filters:e,onFiltersChange:t,refreshKey:s,onBackToWebsite:n,primaryConversion:a,className:r,published:o,lastPublishedAt:c}){let[d,l]=Rt.useState(30),[i,m]=Rt.useState(()=>$i()),v=e!==void 0&&t!==void 0,[g,u]=Rt.useState(e??[]),{api:f}=W(),[p,b]=Rt.useState(f);p!==f&&(b(f),!v&&g.length>0&&u([]));let w=v?e:g,P=Rt.useCallback(F=>{t&&t(F),v||u(F)},[t,v]),T=Rt.useCallback((F,Re,te)=>{let we=Array.isArray(Re)?Re:[Re];if(we.length===0)return null;let He=ko(w,{dimension:F,operator:"is",values:we});if(te&&(!te.value||(He=Fc(He,{dimension:te.dimension,operator:"is",values:[te.value]}),!He.find(Ct=>Ct.dimension===te.dimension&&Ct.operator!=="is_not")?.values.includes(te.value))))return null;let bt=He.find(Ze=>Ze.dimension===F&&Ze.operator!=="is_not");return we.every(Ze=>bt?.values.includes(Ze))?JSON.stringify(He)===JSON.stringify(w)?null:He:null},[w]),y=Rt.useCallback((F,Re,te)=>T(F,Re,te)!==null,[T]),C=Rt.useCallback((F,Re,te)=>{let we=T(F,Re,te);we&&P(we)},[T,P]),[k,I]=Rt.useState("visitors"),N=xn(d,{refreshKey:s,breakdowns:Cf,filters:w}),E=N.status.data,D=N.reportedZone??E?.timezone,_=D??i??Hn()??"UTC",{notCollecting:Y,awaitingFirstVisit:Q,firstVisitTooRecent:z,holdingForFirstData:le}=ki(E,{published:o}),fe=o===!1,he=Er({collecting:Q||Y?!1:E?.collecting,statusFailed:N.status.error!=null,identity:E?.analytics_id}),M=Rt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),ee=Rt.useMemo(()=>{let F=N.breakdowns.sources?.data,Re={};if(!F||F.status!=="ok")return Re;for(let te of F.data){let we=te.source,He=te.sources;typeof we=="string"&&Array.isArray(He)&&He.length>0&&(Re[we]=He)}return Re},[N.breakdowns.sources?.data]),U=Rt.useMemo(()=>{let F=(we,He)=>{let bt=N.breakdowns[we]?.data;return!bt||bt.status!=="ok"?[]:[...new Set(bt.data.map(Ze=>Ze[He]).filter(Ze=>typeof Ze=="string"&&Ze!==""))]};return{channel:N.channels.data?.status==="ok"?[...new Set(N.channels.data.data.map(we=>we.channel))]:[],source:F("sources","source"),campaign:F("utm/campaign","campaign"),page:F("pages","pathname"),entry_page:F("entry-pages","pathname"),exit_page:F("exit-pages","pathname"),country:F("countries","country"),browser:F("browsers","browser"),os:F("operating-systems","os"),device:F("devices","device")}},[N.breakdowns,N.channels.data]),[ve,me]=Rt.useState({}),Qe=JSON.stringify(U),[ke,Ge]=Rt.useState(new Map),Je=JSON.stringify(ee);Rt.useEffect(()=>{let{suggestions:F,folds:Re}=Uc(M.current,{api:f,period:d},JSON.parse(Qe),JSON.parse(Je));me(F),Ge(Re)},[Qe,Je,f,d]);let Fe=Rt.useCallback((F,Re)=>F!=="source"?Re:[...new Set(Re.flatMap(te=>{let we=[...ke.get(te)??[],...ee[te]??[]];return we.length>0?we:[te]}))],[ke,ee]),_t=Rt.useMemo(()=>{let F=N.conversions.error;return F instanceof Dt&&F.details?.code==="goals_exceed_report_budget"?F.message:null},[N.conversions.error]),L=Rt.useMemo(()=>{let F=[N.summary,N.timeseries,N.channels,...Object.values(N.breakdowns)];for(let Re of F){let te=Re?.error;if(te instanceof Dt&&te.details?.code==="filter_unsupported")return te.message}return null},[N.summary,N.timeseries,N.channels,N.breakdowns]),$=(F,Re,te,we,He,bt,Ze,Ct,xe)=>()=>{let Me=N.breakdowns[F];return(0,pe.jsx)(Ms,{sourced:Me?.data??null,error:Me?.error,isLoading:Me?.isLoading,what:Re,collecting:E?.collecting,onRetry:N.refetch,children:yt=>{let Pa=Kt=>Ct?Fe(Ct,[Kt]):Kt;return(0,pe.jsx)(Co,{rows:yt,dimension:te,metric:we,metricLabel:He,secondary:bt,emptyCopy:w.length>0?"No data for this filter":Ze,canFilter:Ct?(Kt,fa)=>y(Ct,Pa(Kt),xe?{dimension:xe,value:fa}:void 0):()=>!1,onFilter:Ct?(Kt,fa)=>C(Ct,Pa(Kt),xe?{dimension:xe,value:fa}:void 0):void 0})}})};if(Ti({status:E,holdingForFirstData:le,refetchStatus:N.refetchStatus,refetch:N.refetch}),Y){let F=!!c&&String(c).slice(0,10)<_f;return(0,pe.jsx)(St,{title:"Analytics",onBackToWebsite:n,className:r,children:(0,pe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,pe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:fe?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":F?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return Q?(0,pe.jsx)(St,{title:"Analytics",onBackToWebsite:n,className:r,children:(0,pe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,pe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:"Your site is set up and analytics is running. The first visit shows up here shortly after someone lands on a published page."})]})}):z?(0,pe.jsxs)(St,{title:"Analytics",onBackToWebsite:n,className:r,children:[(0,pe.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,pe.jsx)(_o,{value:_,chosen:i,onChange:F=>{Vi(F),m(F)}})}),(0,pe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,pe.jsxs)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",E?.timezone?` ${E.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,pe.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,pe.jsx)(To,{currentVisitors:he.currentVisitors,asOf:he.asOf,isStale:he.isStale,isUnreachable:he.isUnreachable||he.error!==null,isInitialLoad:he.isInitialLoad})})]})]}):(0,pe.jsx)(St,{title:"Analytics",onBackToWebsite:n,className:r,children:(0,pe.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,pe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,pe.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Pf.map(F=>(0,pe.jsx)("button",{type:"button","aria-pressed":F.value===d,onClick:()=>l(F.value),className:F.value===d?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:F.label},F.value))}),(0,pe.jsx)(_o,{value:_,chosen:i,onChange:F=>{Vi(F),m(F)}}),(0,pe.jsx)(To,{currentVisitors:he.currentVisitors,asOf:he.asOf,isStale:he.isStale,isUnreachable:he.isUnreachable||he.error!==null,isInitialLoad:he.isInitialLoad,scopeIsSiteWide:w.length>0})]}),(0,pe.jsx)(Mc,{filters:w,onChange:P,suggestions:ve,expandValues:Fe,resetKey:f}),L?(0,pe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,pe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:L}),(0,pe.jsx)("button",{type:"button",onClick:()=>P([]),className:"af-mt-4 af-rounded-md af-border af-border-border af-px-3 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Clear filters"})]}):null,!L&&E?.timezone_defaulted?(0,pe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,L?null:(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)(Ms,{sourced:N.summary.data,error:N.summary.error,isLoading:N.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:N.refetch,children:F=>(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)($c,{summary:F,selected:k,onSelect:I}),F.previous_unavailable?(0,pe.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[F.previous_unavailable_reason==="filter"?"No comparison for this filter \u2014 the previous period has too many distinct traffic sources to resolve it. Try a shorter period, or filter by source instead.":"No comparison available right now \u2014 we couldn\u2019t check how far back this site\u2019s history goes. It should return on its own."," ","The numbers above are still for the period you selected."]}):null]})}),(0,pe.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,pe.jsx)(Ms,{sourced:N.timeseries.data,error:N.timeseries.error,isLoading:N.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:N.refetch,children:F=>{let Re=N.timeseries.data?.status==="ok"?N.timeseries.data.window:{from:"",to:""};return(0,pe.jsx)(Li,{rows:F,window:Re,metric:k,timeZone:D??"UTC"})}})}),(0,pe.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,pe.jsx)(Lr,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,pe.jsx)(Ms,{sourced:N.channels.data,error:N.channels.error,isLoading:N.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:N.refetch,children:F=>(0,pe.jsx)(Co,{rows:F,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:w.length>0?"No data for this filter":"No data for this period",canFilter:Re=>y("channel",Re),onFilter:Re=>C("channel",Re)})})},{id:"sources",label:"Sources",render:$("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:$("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,pe.jsx)(Lr,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:$("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:$("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:$("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,pe.jsx)(Lr,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:$("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:$("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:$("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,pe.jsx)(Lr,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:$("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:$("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:$("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,pe.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,pe.jsx)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:(0,pe.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,pe.jsxs)("div",{className:"af-px-3 af-py-2",children:[w.length>0?(0,pe.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",w.length===1?"filter":"filters"," above."]}):null,_t!==null?(0,pe.jsxs)("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[(0,pe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,pe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:_t})]}):(0,pe.jsx)(Ms,{sourced:N.conversions.data,error:N.conversions.error,isLoading:N.conversions.isLoading,what:"Conversions",collecting:E?.collecting,onRetry:N.refetch,children:F=>{let Re=N.conversions.data?.status==="ok"?N.conversions.data:null;return(0,pe.jsx)(pe.Fragment,{children:(0,pe.jsx)(Di,{rows:F,primaryConversion:a,denominator:Re?.denominator??0,windowPrecedesCollection:Re?.window_precedes_collection??!1,coverageUnknown:Re?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var Zc=ie(require("react"),1),jt=require("lucide-react");var as=ie(require("react"),1),$s=require("lucide-react");var Ce=require("react/jsx-runtime"),qc=90,Wc=100;function kf(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function jc(e){return!!e.label&&e.label!==e.target}function Tf(e,t,s){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:n,with_a_value:a}=t;return n===0?e===0?"Nothing specific has converted here yet.":null:a===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":a<n?s?`These cover ${a.toLocaleString()} of ${n.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${a.toLocaleString()} of ${n.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function Br(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Gc({current:e,onChange:t,onClose:s}){let{api:n}=W(),[a,r]=as.useState(null),[o,c]=as.useState(!1),[d,l]=as.useState({at:"goals"}),[i,m]=as.useState(null),[v,g]=as.useState(null),[u,f]=as.useState(!1),[p,b]=as.useState(null),w=as.useRef(0);as.useEffect(()=>{let C=!0;return r(null),c(!1),l({at:"goals"}),m(null),g(null),f(!1),b(null),w.current+=1,n.getAnalyticsConversions(qc).then(k=>{if(C){if(k.status!=="ok"){c(!0);return}r(k.data)}}).catch(()=>{C&&c(!0)}),()=>{C=!1}},[n]);let P=C=>{l({at:"targets",row:C}),m(null),g(null),f(!1),b(null);let k=++w.current;n.getAnalyticsGoalTargets(C.goal,qc,Wc).then(I=>{if(k===w.current){if(I.status!=="ok"){g("failed");return}m(I.data),f(I.truncated===!0),b(I.coverage??null)}}).catch(I=>{if(k!==w.current)return;let N=I instanceof Dt?I.details?.code:void 0;g(N==="goal_has_no_targets"?"no-values":"failed")})},T=C=>{t(C),s()};if(o)return(0,Ce.jsx)("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!a)return(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,Ce.jsx)($s.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Ce.jsx)("span",{children:"Loading your conversions\u2026"})]});if(d.at==="targets"){let C=d.row,k=new Map;for(let I of i??[])k.set(I.label,(k.get(I.label)??0)+1);return(0,Ce.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[(0,Ce.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,Ce.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>l({at:"goals"}),children:[(0,Ce.jsx)($s.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,Ce.jsx)("span",{children:"All conversions"})]})}),(0,Ce.jsxs)("button",{type:"button","aria-current":e&&Br(C,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:C.goal,implicit:C.implicit}),children:[e&&Br(C,e)&&!e.target&&(0,Ce.jsx)($s.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ce.jsxs)("span",{children:["Any ",C.goal.toLowerCase()]})]}),v==="no-values"&&(0,Ce.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),v==="failed"&&(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,Ce.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>P(C),children:"Try again"})]}),!i&&v===null&&(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,Ce.jsx)($s.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Ce.jsx)("span",{children:"Loading\u2026"})]}),i&&(0,Ce.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Tf(i.length,p,u)}),u&&(0,Ce.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Wc,". If what you want isn\u2019t here, pick the conversion itself instead."]}),i?.some(jc)&&(0,Ce.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),i?.map(I=>{let N=!!(e&&Br(C,e)&&e.target===I.target),E=k.get(I.label)>1;return jc(I)?(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-3 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,Ce.jsxs)("span",{className:"af-min-w-0",children:[(0,Ce.jsx)("span",{className:"af-block af-truncate",children:I.label}),E&&(0,Ce.jsx)("span",{className:"af-block af-truncate af-text-xs",children:I.target})]}),(0,Ce.jsx)("span",{className:"af-shrink-0 af-text-xs",children:I.visitors.toLocaleString()})]},I.target):(0,Ce.jsxs)("button",{type:"button","aria-current":N?"true":void 0,className:"af-flex af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:C.goal,implicit:C.implicit,target:I.target,...I.label&&I.label!==I.target?{label:I.label}:{}}),children:[(0,Ce.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[N&&(0,Ce.jsx)($s.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ce.jsxs)("span",{className:"af-min-w-0",children:[(0,Ce.jsx)("span",{className:"af-block af-truncate",children:I.label}),E&&(0,Ce.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:I.target})]})]}),(0,Ce.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:I.visitors.toLocaleString()})]},I.target)})]})}let y=e?.goal&&!a.some(C=>Br(C,e));return(0,Ce.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[y&&(0,Ce.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),a.length===0&&(0,Ce.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),a.map(C=>{let k=e?Br(C,e):!1;return(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,Ce.jsxs)("button",{type:"button","aria-current":k?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:C.goal,implicit:C.implicit}),children:[(0,Ce.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[k&&(0,Ce.jsx)($s.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ce.jsx)("span",{className:"af-truncate",children:C.goal})]}),(0,Ce.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:C.visitors.toLocaleString()})]}),kf(C)&&(0,Ce.jsx)(x,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${C.goal}`,onClick:()=>P(C),children:"Narrow"})]},C.goal)}),e?.goal&&(0,Ce.jsx)("button",{type:"button",className:"af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm af-text-muted-foreground hover:af-bg-accent",onClick:()=>T(null),children:"No main conversion"})]})}var za=require("react/jsx-runtime");function Ef(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let s of t)try{let{hostname:n}=new URL(s);if(n)return n.toLowerCase().replace(/^www\./,"")}catch{}return null}function If(e){if(Do(e,"whatsapp"))return!0;let t=Ef(e);return t===null?!1:["wa.me","whatsapp.com"].some(s=>t===s||t.endsWith(`.${s}`))}function Do(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var Kc=[{goal:"Contact",target:e=>Do(e,"tel"),icon:jt.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Do(e,"mailto"),icon:jt.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:jt.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>If(e),icon:jt.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:jt.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:jt.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:jt.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:jt.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:jt.Download,line:"This site is set up to get your file downloaded."}];function Yc(e){let{goal:t,target:s}=e;return e.implicit!==!0?null:(s?Kc.find(a=>a.goal===t&&a.target?.(s)):void 0)??Kc.find(a=>a.goal===t&&!a.target)??null}function Df(e){return Yc(e)?.icon??jt.Target}function Jc({primaryConversion:e,onChange:t}){let[s,n]=Zc.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?Yc(e):null,o=e?.label?.trim(),c=e?Df(e):jt.Target,d=e?.goal?o?`Your main conversion is ${o}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",l=(0,za.jsxs)(za.Fragment,{children:[(0,za.jsx)(c,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,za.jsx)("span",{children:d})]});return t?(0,za.jsxs)(Jr,{open:s,onOpenChange:n,children:[(0,za.jsx)(Xr,{asChild:!0,children:(0,za.jsx)("button",{type:"button",className:"af-flex af-items-center af-gap-2 af-rounded af-text-left af-text-sm af-text-muted-foreground hover:af-text-foreground focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:l})}),(0,za.jsx)(cr,{align:"start",className:"af-w-80 af-p-1",children:s&&(0,za.jsx)(Gc,{current:e,onChange:t,onClose:()=>n(!1)})})]}):(0,za.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:l})}var ra=require("react/jsx-runtime");function Xc({refreshKey:e,onViewAll:t,primaryConversion:s}){let n=xn(7,{refreshKey:e,breakdowns:[]}),a=n.status.data??void 0,{nothingToReport:r,notCollecting:o,holdingForFirstData:c}=ki(a);return Ti({status:a,holdingForFirstData:c,refetchStatus:n.refetchStatus,refetch:n.refetch}),(0,ra.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ra.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,ra.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,ra.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?(0,ra.jsx)("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:o?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):(0,ra.jsxs)(ra.Fragment,{children:[(0,ra.jsx)(Ms,{sourced:n.timeseries.data,error:n.timeseries.error,isLoading:n.timeseries.isLoading,what:"The visitors chart",collecting:a?.collecting,onRetry:n.refetch,children:d=>{let l=n.timeseries.data?.status==="ok"?n.timeseries.data:null;return(0,ra.jsx)(Li,{rows:d,window:l?.window??{from:"",to:""},metric:"visitors",timeZone:l?.timezone,height:140})}}),(0,ra.jsxs)("div",{className:"af-mt-3",children:[(0,ra.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,ra.jsx)(Ms,{sourced:n.conversions.data,error:n.conversions.error,isLoading:n.conversions.isLoading,what:"Conversions",collecting:a?.collecting,onRetry:n.refetch,children:d=>{let l=n.conversions.data?.status==="ok"?n.conversions.data:null;return(0,ra.jsx)(Di,{rows:d,primaryConversion:s,denominator:l?.denominator??0,windowPrecedesCollection:l?.window_precedes_collection??!1,coverageUnknown:l?.first_seen_unavailable??!1})}})]})]})]})}var Gt=require("react/jsx-runtime"),Ao=5;function Lo({title:e,viewAllLabel:t,onViewAll:s}){return(0,Gt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Gt.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),s&&(0,Gt.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:s,children:t})]})}function Qc({refreshKey:e,onBackToWebsite:t,primaryConversion:s,onChangePrimaryConversion:n,onOpenSurface:a,needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:c}){let d=pn({refreshKey:e}),l=(d.summary?.products.count??0)>0||(d.summary?.commerce?.storefront_orders??!1),i=l||(d.summary?.commerce?.invoicing??!1);return(0,Gt.jsx)(St,{title:"Dashboard",onBackToWebsite:t,children:(0,Gt.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,Gt.jsx)(Jc,{primaryConversion:s,onChange:n}),(0,Gt.jsx)(Xc,{refreshKey:e,onViewAll:a&&(()=>a("analytics")),primaryConversion:s}),(0,Gt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Gt.jsx)(Lo,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:a&&(()=>a("leads"))}),(0,Gt.jsx)(yr,{refreshKey:e,maxRows:Ao,onViewAll:a&&(()=>a("leads"))})]}),l&&(0,Gt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Gt.jsx)(Lo,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:a&&(()=>a("orders"))}),(0,Gt.jsx)(Ds,{refreshKey:e,maxRows:Ao,onViewAll:a&&(()=>a("orders"))})]}),i&&(0,Gt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Gt.jsx)(Lo,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:a&&(()=>a("invoices"))}),(0,Gt.jsx)(Ls,{refreshKey:e,maxRows:Ao,onViewAll:a&&(()=>a("invoices")),needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:c})]})]})})}0&&(module.exports={AUDIENCE_PAGE_SIZE,AifeaturesApiError,AifeaturesProvider,AnalyticsView,ContactImport,CustomerDetail,CustomersList,DOUBLE_OPT_IN_HELP,DashboardView,EMAIL_ORG_ACTIONS,EMAIL_READINESS_TEXT,EmailView,ExportCsvButton,FormSettings,FormSubmissions,FormsDashboard,FormsList,IMPORT_ATTESTATION,InvoiceDetail,InvoiceLabelBadge,InvoiceSettingsPanel,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,NotificationRecipientsSettings,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,PromosPanel,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,StoreSettings,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,buildEmailOrgRequest,chargedTotal,createApiClient,emailReadinessText,formatPrice,isEmailOrgAction,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useAudience,useBroadcasts,useBusinessSummary,useCsvExport,useCustomers,useEmailDrafts,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSiteSettings,useSubmissions,useSubscriptions});
|
|
2
|
+
"use strict";var Jd=Object.create;var ti=Object.defineProperty;var Xd=Object.getOwnPropertyDescriptor;var Qd=Object.getOwnPropertyNames;var eu=Object.getPrototypeOf,tu=Object.prototype.hasOwnProperty;var au=(e,t)=>{for(var a in t)ti(e,a,{get:t[a],enumerable:!0})},wl=(e,t,a,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Qd(t))!tu.call(e,n)&&n!==a&&ti(e,n,{get:()=>t[n],enumerable:!(s=Xd(t,n))||s.enumerable});return e};var ce=(e,t,a)=>(a=e!=null?Jd(eu(e)):{},wl(t||!e||!e.__esModule?ti(a,"default",{value:e,enumerable:!0}):a,e)),nu=e=>wl(ti({},"__esModule",{value:!0}),e);var Zm={};au(Zm,{AUDIENCE_PAGE_SIZE:()=>Cs,AifeaturesApiError:()=>jt,AifeaturesProvider:()=>Pl,AnalyticsView:()=>Ud,ContactImport:()=>Hr,CustomerDetail:()=>Er,CustomersList:()=>Ir,DOUBLE_OPT_IN_HELP:()=>Gr,DashboardView:()=>Zd,EMAIL_ORG_ACTIONS:()=>Mi,EMAIL_READINESS_TEXT:()=>Fo,EmailView:()=>rl,ExportCsvButton:()=>da,FormSettings:()=>xr,FormSubmissions:()=>gr,FormsDashboard:()=>co,FormsList:()=>cr,IMPORT_ATTESTATION:()=>Vi,InvoiceDetail:()=>_i,InvoiceLabelBadge:()=>Ws,InvoiceSettingsPanel:()=>Mr,InvoicesList:()=>Gn,InvoicesView:()=>Bo,LeadsView:()=>Or,MAX_ANALYTICS_FILTERS:()=>ls,MAX_ANALYTICS_FILTER_VALUES:()=>cs,NotificationRecipientsSettings:()=>Oo,OrderDetail:()=>Cr,OrderStatusBadge:()=>ss,OrdersList:()=>jn,OrdersView:()=>Ro,PaymentsDashboard:()=>No,PaymentsSetup:()=>xs,ProductSettings:()=>Rr,ProductsList:()=>Sr,ProductsView:()=>_o,PromosPanel:()=>ps,REALTIME_FAILURES_BEFORE_ERROR:()=>Zi,REALTIME_POLL_MS:()=>Ki,RetainerStatusBadge:()=>ki,RetainersPanel:()=>ys,StoreSettings:()=>Lo,SubmissionDetail:()=>mr,SubscriptionsView:()=>Co,VariantsEditor:()=>Nr,ViewShell:()=>Lt,WebhookDeliveries:()=>hr,WebhookSettings:()=>yr,buildEmailOrgRequest:()=>Xc,chargedTotal:()=>Cn,createApiClient:()=>si,emailReadinessText:()=>ks,formatPrice:()=>ee,isEmailOrgAction:()=>Jc,isZeroDecimalCurrency:()=>Wa,toMajorUnits:()=>kt,toMinorUnits:()=>ia,useAifeatures:()=>W,useAifeaturesContext:()=>W,useAnalytics:()=>Os,useAudience:()=>$r,useBroadcasts:()=>Es,useBusinessSummary:()=>Ns,useCsvExport:()=>pr,useCustomers:()=>Tr,useEmailDrafts:()=>Is,useEventDestinations:()=>vr,useForms:()=>us,useInvoices:()=>hs,useOrders:()=>_r,usePaymentsStatus:()=>Hn,usePeople:()=>Ar,usePerson:()=>Lr,useProducts:()=>ws,useRealtimeVisitors:()=>Kr,useRetainers:()=>Ss,useSiteSettings:()=>Kn,useSubmissions:()=>ur,useSubscriptions:()=>Br});module.exports=nu(Zm);var es=ce(require("react"),1);var so="aifeatures:analytics:timezone",ro;function rr(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function Sl(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function Xn(){return io()??rr()}function io(){if(ro!==void 0)return ro;try{let e=window.localStorage.getItem(so);return Sl(e)?e:null}catch{return null}}function oo(e){if(!(e!==null&&!Sl(e))){ro=e;try{e===null?window.localStorage.removeItem(so):window.localStorage.setItem(so,e)}catch{}}}function ai(e,t){let a=new URLSearchParams({period:String(e)}),s=Xn();return s&&a.set("timezone",s),t&&t.length>0&&a.set("filters",JSON.stringify(t)),a.toString()}var jt=class extends Error{constructor(a,s,n){super(a);this.status=s;this.details=n;this.name="AifeaturesApiError"}};function ni(e,t){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${t}`}function ir(e,t){let a=t.toString();return a?`${e}?${a}`:e}function Nl(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 Rl(e){let t=new URLSearchParams;return e.statuses?.length&&t.set("status",e.statuses.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),t}function si(e,t="https://aifeatures.dev"){async function a(n,r={}){let i=`${t}${n}`,l=await fetch(i,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!l.ok){let f;try{f=await l.json()}catch{}throw new jt(ni(f?.error,l.status),l.status,f)}if(l.status!==204)return l.json()}async function s(n){let r=await fetch(`${t}${n}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let i;try{i=await r.json()}catch{}throw new jt(ni(i?.error,r.status),r.status,i)}return r.blob()}return{async getForms(){return(await a("/api/v1/forms")).forms},async getForm(n){return a(`/api/v1/forms/${n}`)},async createForm(n){return a("/api/v1/forms",{method:"POST",body:JSON.stringify(n)})},async updateForm(n,r){return a(`/api/v1/forms/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(n){await a(`/api/v1/forms/${n}`,{method:"DELETE"})},async getSubmissions(n,r={}){let i=new URLSearchParams;r.limit!==void 0&&i.set("limit",String(r.limit)),r.offset!==void 0&&i.set("offset",String(r.offset));let l=i.toString(),f=`/api/v1/forms/${n}/submissions${l?`?${l}`:""}`;return a(f)},async getSubmission(n){return a(`/api/v1/submissions/${n}`)},async exportSubmissionsCsv(n,r={}){let i=new URLSearchParams;return r.includeSpam&&i.set("include_spam","true"),s(ir(`/api/v1/forms/${encodeURIComponent(n)}/submissions/export`,i))},async deleteSubmission(n){await a(`/api/v1/submissions/${n}`,{method:"DELETE"})},async downloadAttachment(n,r){let i=typeof r=="string"?{name:r}:r,l=i.name,f=i.id??i.name,d=`${t}/api/v1/submissions/${n}/attachments/${encodeURIComponent(f)}`,o=await fetch(d,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let m;try{m=await o.json()}catch{}throw new jt(ni(m?.error,o.status),o.status,m)}let c=await o.blob(),b=URL.createObjectURL(c),g=document.createElement("a");g.href=b,g.download=l,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(b)},async getSite(n){return a(`/api/v1/sites/${encodeURIComponent(n)}`)},async updateSite(n,r){return a(`/api/v1/sites/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return a("/api/v1/payments/status")},getPromos(n){let r=new URLSearchParams({limit:"10"});return n&&r.set("cursor",n),a(`/api/v1/promos?${r}`)},getPromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}`)},createPromo(n){return a("/api/v1/promos",{method:"POST",body:JSON.stringify(n)})},disablePromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}/disable`,{method:"POST"})},replacePromo(n,r){return a(`/api/v1/promos/${encodeURIComponent(n)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(n={}){let r=new URLSearchParams;n.include&&r.set("include",n.include);let i=r.toString();return(await a(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(n){return a(`/api/v1/products/${n}`)},async createProduct(n){return a("/api/v1/products",{method:"POST",body:JSON.stringify(n)})},async updateProduct(n,r){return a(`/api/v1/products/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(n){await a(`/api/v1/products/${n}`,{method:"DELETE"})},async attachProductFile(n,r){let i=new FormData;i.append("file",r);let l=await fetch(`${t}/api/v1/products/${n}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!l.ok){let f;try{f=await l.json()}catch{}throw new jt(ni(f?.error,l.status),l.status,f)}return l.json()},async attachProductFileFromUrl(n,r){return a(`/api/v1/products/${n}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(n,r){return a(`/api/v1/products/${n}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(n,r){return a(`/api/v1/options/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(n){await a(`/api/v1/options/${n}`,{method:"DELETE"})},async createVariant(n,r){return a(`/api/v1/products/${n}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(n,r){return a(`/api/v1/variants/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(n){await a(`/api/v1/variants/${n}`,{method:"DELETE"})},async setVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(n={}){let r=new URLSearchParams;n.email?r.set("email",n.email):n.q&&r.set("q",n.q),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(n){return a(`/api/v1/customers/${n}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(n={}){let r=Nl(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/orders${i?`?${i}`:""}`)},async exportOrdersCsv(n={}){return s(ir("/api/v1/orders/export",Nl(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=Rl(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/retainers${i?`?${i}`:""}`)},async exportRetainersCsv(n={}){return s(ir("/api/v1/retainers/export",Rl(n)))},async getRetainer(n){return a(`/api/v1/retainers/${n}`)},async resendOrderReceipt(n){await a(`/api/v1/orders/${n}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(n){return a(`/api/v1/orders/${n}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(n,r){return a(`/api/v1/orders/${n}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(n={}){let r=new URLSearchParams;n.status&&r.set("status",n.status),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/subscriptions${i?`?${i}`:""}`)},async exportSubscriptionsCsv(n={}){let r=new URLSearchParams;return n.status&&r.set("status",n.status),s(ir("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let n=new URLSearchParams,r=Xn();r&&n.set("timezone",r);let i=n.toString();return a(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(n,r){return a(`/api/v1/analytics/summary?${ai(n,r)}`)},async getAnalyticsTimeseries(n,r){return a(`/api/v1/analytics/timeseries?${ai(n,r)}`)},async getAnalyticsRealtime(){return a("/api/v1/analytics/realtime")},async getAnalyticsChannels(n,r){return a(`/api/v1/analytics/channels?${ai(n,r)}`)},async getAnalyticsConversions(n){return a((()=>{let r=new URLSearchParams({period:String(n)}),i=Xn();return i&&r.set("timezone",i),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(n,r,i){let l=new URLSearchParams({goal:n,period:String(r)}),f=Xn();return f&&l.set("timezone",f),i!==void 0&&l.set("limit",String(i)),a(`/api/v1/analytics/conversions/targets?${l.toString()}`)},async getAnalyticsBreakdown(n,r,i){let l=n.split("/").map(encodeURIComponent).join("/");return a(`/api/v1/analytics/${l}?${ai(r,i)}`)},async getBusinessSummary(n){let r=new URLSearchParams;r.set("tz_offset_minutes",String(n.tzOffsetMinutes));let i=Xn();return i&&r.set("timezone",i),a(`/api/v1/summary?${r.toString()}`)},async getPeople(n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/people${i?`?${i}`:""}`)},async exportPeopleCsv(n={}){let r=new URLSearchParams;return n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),s(ir("/api/v1/people/export",r))},async getPerson(n){return a(`/api/v1/people/${encodeURIComponent(n)}`)},async getEventDestinations(){return(await a("/api/v1/event-destinations")).destinations},async createEventDestination(n){return a("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(n)})},async updateEventDestination(n,r){return a(`/api/v1/event-destinations/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(n){await a(`/api/v1/event-destinations/${n}`,{method:"DELETE"})},async rotateEventDestinationSecret(n){return a(`/api/v1/event-destinations/${n}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(n){return(await a(`/api/v1/event-destinations/${n}/secret`)).secret},async getEventDeliveries(n,r){let i=r===void 0?"":`?limit=${r}`;return(await a(`/api/v1/event-destinations/${n}/deliveries${i}`)).deliveries},async retryEventDelivery(n,r){return a(`/api/v1/event-destinations/${n}/deliveries/${r}/retry`,{method:"POST"})},async getMarketingSettings(n){return a(`${Oa(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(`${Oa(n)}/contacts${l?`?${l}`:""}`)},async getMarketingContactStats(n){return a(`${Oa(n)}/contacts/stats`)},async getMarketingTags(n){return(await a(`${Oa(n)}/contact-tags`)).tags},async getEmailDrafts(n,r){let i=r?`?kind=${r}`:"";return(await a(`${Oa(n)}/marketing/drafts${i}`)).drafts},async getEmailDraft(n,r){return a(`${Oa(n)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(n,r,i){let l=i?.editable?"?mode=editable":"";return a(`${Oa(n)}/marketing/drafts/${encodeURIComponent(r)}/preview${l}`)},async getEmailTemplates(n){return(await a(`${Oa(n)}/marketing/templates`)).templates},async previewEmailTemplate(n,r,i){let l=i?`?draft_id=${encodeURIComponent(i)}`:"";return a(`${Oa(n)}/marketing/templates/${encodeURIComponent(r)}/preview${l}`)},async getBroadcasts(n){return(await a(`${Oa(n)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(n,r){return a(`${Oa(n)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getWelcomeSequence(n){return a(`${Oa(n)}/marketing/welcome`)},async getRecoveryFlow(n){return a(`${Oa(n)}/marketing/recovery`)}}}function Oa(e){return`/api/v1/sites/${encodeURIComponent(e)}`}var Qn=require("react/jsx-runtime"),_l=es.createContext(null);function su(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 Pl({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:n}){let r=es.useMemo(()=>su(e),[e]),i=es.useMemo(()=>si(e,t),[e,t]),l=es.useMemo(()=>({siteToken:e,apiUrl:t,api:i}),[e,t,i]);return r?(0,Qn.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:(0,Qn.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Qn.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Qn.jsx)("p",{className:"af-text-sm af-text-destructive",children:r})]})}):(0,Qn.jsx)(_l.Provider,{value:l,children:(0,Qn.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:n})})}function W(){let e=es.useContext(_l);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var Vn=ce(require("react"),1),Vs=require("lucide-react");var ri=ce(require("react"),1),gn=ce(require("@radix-ui/react-tabs"),1);var kl=require("clsx"),Cl=require("tailwind-merge"),ru=(0,Cl.extendTailwindMerge)({prefix:"af-"});function X(...e){return ru((0,kl.clsx)(e))}var oi=require("react/jsx-runtime"),ii=gn.Root,or=ri.forwardRef(({className:e,...t},a)=>(0,oi.jsx)(gn.List,{ref:a,className:X("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));or.displayName=gn.List.displayName;var vn=ri.forwardRef(({className:e,...t},a)=>(0,oi.jsx)(gn.Trigger,{ref:a,className:X("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));vn.displayName=gn.Trigger.displayName;var bn=ri.forwardRef(({className:e,...t},a)=>(0,oi.jsx)(gn.Content,{ref:a,className:X("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));bn.displayName=gn.Content.displayName;var Tl=ce(require("react"),1),El=require("@radix-ui/react-slot"),Il=require("class-variance-authority");var Dl=require("react/jsx-runtime"),iu=(0,Il.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=Tl.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...n},r)=>(0,Dl.jsx)(s?El.Slot:"button",{className:X(iu({variant:t,size:a,className:e})),ref:r,...n}));y.displayName="Button";var lr=require("lucide-react");var Un=ce(require("react"),1);var _n=require("react/jsx-runtime"),ft=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,_n.jsx)("table",{ref:a,className:X("af-w-full af-caption-bottom af-text-sm",e),...t})}));ft.displayName="Table";var mt=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("thead",{ref:a,className:X("[&_tr]:af-border-b",e),...t}));mt.displayName="TableHeader";var pt=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("tbody",{ref:a,className:X("[&_tr:last-child]:af-border-0",e),...t}));pt.displayName="TableBody";var ou=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("tfoot",{ref:a,className:X("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));ou.displayName="TableFooter";var Fe=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("tr",{ref:a,className:X("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Fe.displayName="TableRow";var Z=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("th",{ref:a,className:X("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));Z.displayName="TableHead";var Y=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("td",{ref:a,className:X("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));Y.displayName="TableCell";var lu=Un.forwardRef(({className:e,...t},a)=>(0,_n.jsx)("caption",{ref:a,className:X("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));lu.displayName="TableCaption";var hn=ce(require("react"),1);function us(){let{api:e}=W(),[t,a]=hn.useState([]),[s,n]=hn.useState(!0),[r,i]=hn.useState(null),l=hn.useCallback(async()=>{try{n(!0),i(null);let c=await e.getForms();a(c)}catch(c){i(c instanceof Error?c:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);hn.useEffect(()=>{l()},[l]);let f=hn.useCallback(async c=>{let b=await e.createForm(c);return a(g=>[...g,b]),b},[e]),d=hn.useCallback(async(c,b)=>{let g=await e.updateForm(c,b);return a(m=>m.map(p=>p.id===c?g:p)),g},[e]),o=hn.useCallback(async c=>{await e.deleteForm(c),a(b=>b.filter(g=>g.id!==c))},[e]);return{forms:t,isLoading:s,error:r,refetch:l,createForm:f,updateForm:d,deleteForm:o}}var Nt=require("react/jsx-runtime");function cr({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:n}=us();return s?(0,Nt.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Nt.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,Nt.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Nt.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):a.length===0?(0,Nt.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,Nt.jsx)(lr.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Nt.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Nt.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Nt.jsx)("div",{className:t,children:(0,Nt.jsxs)(ft,{children:[(0,Nt.jsx)(mt,{children:(0,Nt.jsxs)(Fe,{children:[(0,Nt.jsx)(Z,{children:"Name"}),(0,Nt.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,Nt.jsx)(pt,{children:a.map(r=>(0,Nt.jsxs)(Fe,{children:[(0,Nt.jsx)(Y,{className:"af-font-medium",children:r.name}),(0,Nt.jsx)(Y,{className:"af-text-right",children:(0,Nt.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Nt.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[(0,Nt.jsx)(lr.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Nt.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[(0,Nt.jsx)(lr.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}var Ol=require("lucide-react");var Al=require("class-variance-authority");var Ll=require("react/jsx-runtime"),cu=(0,Al.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,Ll.jsx)("div",{className:X(cu({variant:t}),e),...a})}var Ba=require("react/jsx-runtime"),du={form_notification:"Form notification",purchase_receipt:"Buyer receipt",merchant_sale:"Sale notification",subscription_payment_failed:"Payment reminder",subscription_cancellation:"Cancellation confirmation",subscription_address_change:"Address change confirmation",merchant_subscription_canceled:"Subscription cancellation notice",account_login:"Sign-in email",oversell_refund:"Refund notification",merchant_oversell:"Stock issue notification",dispute_opened:"Dispute notification"};function li(e){switch(e.state){case"sending":return{label:"Sending",variant:"secondary",detail:null};case"sent":return{label:"Sent",variant:"secondary",detail:"Accepted for sending. Delivery has not been confirmed yet."};case"delivered":return{label:"Delivered",variant:"success",detail:"Accepted by the recipient\u2019s email server. This does not confirm it was read."};case"delivery_delayed":return{label:"Delayed",variant:"warning",detail:"Delivery is delayed. The email provider is still trying."};case"bounced":return{label:"Bounced",variant:"destructive",detail:"A receiving email server rejected this message."};case"complained":return{label:"Marked as spam",variant:"destructive",detail:"A recipient marked this email as spam. Do not resend it to that recipient."};case"suppressed":return{label:"Delivery blocked",variant:"destructive",detail:"The email provider blocked delivery to a recipient after a previous delivery problem or spam complaint."};case"failed":return{label:"Send failed",variant:"destructive",detail:"The email provider reported a sending failure."};case"unknown":return{label:"Delivery unconfirmed",variant:"warning",detail:"We could not confirm whether the email was sent. Check with the recipient before sending it again."}}}function lo(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function uu(e){return["sending","sent","delivered","delivery_delayed","unknown","complained"].includes(e.state)?null:e.kind==="form_notification"?"Check this form\u2019s notification email addresses in its settings. The submission is saved here.":e.kind==="merchant_sale"||e.kind==="merchant_oversell"?"Check your notification email addresses. You can view and fulfill this order here.":e.kind==="dispute_opened"?"Check your notification email addresses and review this dispute in Stripe.":e.kind==="merchant_subscription_canceled"?"Check your notification email addresses. The subscription status is still shown here.":e.kind==="account_login"?"Ask the customer to confirm their email address and request a new sign-in link once the delivery problem is resolved.":e.kind==="purchase_receipt"?"Contact the buyer another way to confirm their email address. Payment and download details are still available on this order.":"Contact the customer another way to confirm their email address. Email delivery does not change their subscription or payment status."}function dr({deliveries:e,label:t="Email needs attention"}){return lo(e)?(0,Ba.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,Ba.jsx)(Ol.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Pn({deliveries:e,problemsOnly:t=!1,className:a=""}){let s=(e??[]).filter(n=>!t||lo([n]));return s.length?(0,Ba.jsx)("div",{className:`af-space-y-3 ${a}`,"aria-label":"Email delivery",children:s.map(n=>{let r=li(n),i=uu(n);return(0,Ba.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Ba.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Ba.jsx)("span",{className:"af-font-medium",children:du[n.kind]??"Email notification"}),(0,Ba.jsx)(ie,{variant:r.variant,children:r.label})]}),(0,Ba.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&lo([n])&&(0,Ba.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,Ba.jsx)("p",{className:"af-mt-1",children:r.detail}),i&&(0,Ba.jsx)("p",{className:"af-mt-1",children:i})]},n.id)})}):null}var as=ce(require("react"),1),nn=require("lucide-react");var ts=ce(require("react"),1),We=ce(require("@radix-ui/react-select"),1),fs=require("lucide-react");var Vt=require("react/jsx-runtime"),en=We.Root;var tn=We.Value,Fa=ts.forwardRef(({className:e,children:t,...a},s)=>(0,Vt.jsxs)(We.Trigger,{ref:s,className:X("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...a,children:[t,(0,Vt.jsx)(We.Icon,{asChild:!0,children:(0,Vt.jsx)(fs.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Fa.displayName=We.Trigger.displayName;var Bl=ts.forwardRef(({className:e,...t},a)=>(0,Vt.jsx)(We.ScrollUpButton,{ref:a,className:X("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,Vt.jsx)(fs.ChevronUp,{className:"af-h-4 af-w-4"})}));Bl.displayName=We.ScrollUpButton.displayName;var Fl=ts.forwardRef(({className:e,...t},a)=>(0,Vt.jsx)(We.ScrollDownButton,{ref:a,className:X("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,Vt.jsx)(fs.ChevronDown,{className:"af-h-4 af-w-4"})}));Fl.displayName=We.ScrollDownButton.displayName;var Ma=ts.forwardRef(({className:e,children:t,position:a="popper",...s},n)=>(0,Vt.jsx)(We.Portal,{children:(0,Vt.jsxs)(We.Content,{ref:n,className:X("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:a,...s,children:[(0,Vt.jsx)(Bl,{}),(0,Vt.jsx)(We.Viewport,{className:X("af-p-1",a==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,Vt.jsx)(Fl,{})]})}));Ma.displayName=We.Content.displayName;var fu=ts.forwardRef(({className:e,...t},a)=>(0,Vt.jsx)(We.Label,{ref:a,className:X("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));fu.displayName=We.Label.displayName;var Rt=ts.forwardRef(({className:e,children:t,...a},s)=>(0,Vt.jsxs)(We.Item,{ref:s,className:X("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...a,children:[(0,Vt.jsx)("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:(0,Vt.jsx)(We.ItemIndicator,{children:(0,Vt.jsx)(fs.Check,{className:"af-h-4 af-w-4"})})}),(0,Vt.jsx)(We.ItemText,{children:t})]}));Rt.displayName=We.Item.displayName;var mu=ts.forwardRef(({className:e,...t},a)=>(0,Vt.jsx)(We.Separator,{ref:a,className:X("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));mu.displayName=We.Separator.displayName;var xa=ce(require("react"),1);function ur({formId:e,initialPageSize:t=25}){let{api:a}=W(),[s,n]=xa.useState([]),[r,i]=xa.useState(0),[l,f]=xa.useState(!0),[d,o]=xa.useState(null),[c,b]=xa.useState(0),[g,m]=xa.useState(t),p=xa.useRef(0),u=xa.useCallback(async()=>{if(!e)return;let T=++p.current;try{f(!0),o(null);let h={limit:g,offset:c*g},R=await a.getSubmissions(e,h);if(T!==p.current)return;if(R.submissions.length===0&&c>0){b(Math.max(0,Math.ceil(R.total/g)-1));return}n(R.submissions),i(R.total)}catch(h){if(T!==p.current)return;o(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{T===p.current&&f(!1)}},[a,e,c,g]);xa.useEffect(()=>{u()},[u]);let v=xa.useRef(u);v.current=u;let x=xa.useCallback(async T=>{await a.deleteSubmission(T),v.current()},[a]),k=Math.ceil(r/g);return{submissions:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<k-1,hasPreviousPage:c>0,setPage:b,setPageSize:T=>{m(T),b(0)},refetch:u,deleteSubmission:x}}var ci=ce(require("react"),1),$l=require("lucide-react");var fr=ce(require("react"),1),Jt=ce(require("@radix-ui/react-dialog"),1),Ml=require("lucide-react");var Pa=require("react/jsx-runtime"),an=Jt.Root;var pu=Jt.Portal;var Ul=fr.forwardRef(({className:e,...t},a)=>(0,Pa.jsx)(Jt.Overlay,{ref:a,className:X("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Ul.displayName=Jt.Overlay.displayName;var Ua=fr.forwardRef(({className:e,children:t,...a},s)=>(0,Pa.jsx)(pu,{children:(0,Pa.jsxs)("div",{className:"aifeatures-admin",children:[(0,Pa.jsx)(Ul,{}),(0,Pa.jsxs)(Jt.Content,{ref:s,className:X("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...a,children:[t,(0,Pa.jsxs)(Jt.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[(0,Pa.jsx)(Ml.X,{className:"af-h-4 af-w-4"}),(0,Pa.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Ua.displayName=Jt.Content.displayName;var $a=({className:e,...t})=>(0,Pa.jsx)("div",{className:X("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});$a.displayName="DialogHeader";var Va=({className:e,...t})=>(0,Pa.jsx)("div",{className:X("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Va.displayName="DialogFooter";var Ha=fr.forwardRef(({className:e,...t},a)=>(0,Pa.jsx)(Jt.Title,{ref:a,className:X("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Ha.displayName=Jt.Title.displayName;var za=fr.forwardRef(({className:e,...t},a)=>(0,Pa.jsx)(Jt.Description,{ref:a,className:X("af-text-sm af-text-muted-foreground",e),...t}));za.displayName=Jt.Description.displayName;var ma=require("react/jsx-runtime");function Us({onDelete:e,iconOnly:t}){let[a,s]=ci.useState(!1),[n,r]=ci.useState(!1),[i,l]=ci.useState(null);return(0,ma.jsxs)(ma.Fragment,{children:[(0,ma.jsxs)(y,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{l(null),s(!0)},children:[(0,ma.jsx)($l.Trash2,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),(0,ma.jsx)(an,{open:a,onOpenChange:d=>{!d&&!n&&s(!1)},children:(0,ma.jsxs)(Ua,{children:[(0,ma.jsxs)($a,{children:[(0,ma.jsx)(Ha,{children:"Delete this submission?"}),(0,ma.jsx)(za,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),i&&(0,ma.jsx)("p",{className:"af-text-sm af-text-destructive",children:i}),(0,ma.jsxs)(Va,{children:[(0,ma.jsx)(y,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),(0,ma.jsx)(y,{variant:"destructive",onClick:async()=>{r(!0),l(null);try{await e(),s(!1)}catch(d){l(d instanceof Error?d.message:"Failed to delete submission")}finally{r(!1)}},disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}var Hl=ce(require("react"),1),pa=require("lucide-react");var De=require("react/jsx-runtime");function Vl(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function gu(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function mr({submission:e,onBack:t,onDelete:a}){let{api:s}=W(),[n,r]=Hl.useState(null),i=d=>d.id??d.name,l=async d=>{r(i(d));try{await s.downloadAttachment(e.id,d)}catch(o){console.error("Download failed:",o)}finally{r(null)}},f=Object.entries(e.data).filter(([d])=>!d.startsWith("_"));return(0,De.jsxs)("div",{children:[(0,De.jsxs)("div",{className:"af-mb-6",children:[(0,De.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,De.jsx)(pa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,De.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,De.jsxs)("div",{children:[(0,De.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,De.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Vl(e.metadata.submitted_at)]})]}),a&&(0,De.jsx)(Us,{onDelete:a})]})]}),(0,De.jsxs)("div",{className:"af-space-y-6",children:[(0,De.jsx)(Pn,{deliveries:e.email_deliveries}),(0,De.jsxs)("div",{children:[(0,De.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,De.jsxs)("div",{className:"af-space-y-3",children:[f.map(([d,o])=>(0,De.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,De.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:d.replace(/_/g," ")}),(0,De.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof o=="string"&&o.includes(`
|
|
3
|
+
`)?(0,De.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:o}):String(o)})]},d)),f.length===0&&(0,De.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,De.jsxs)("div",{children:[(0,De.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,De.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((d,o)=>(0,De.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,De.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,De.jsx)(pa.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,De.jsx)("span",{className:"af-text-sm",children:d.name}),(0,De.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",gu(d.size),")"]})]}),(0,De.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>l(d),disabled:n===i(d),children:[n===i(d)?(0,De.jsx)(pa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,De.jsx)(pa.Download,{className:"af-h-4 af-w-4 af-mr-1"}),n===i(d)?"Downloading...":"Download"]})]},o))})]}),(0,De.jsxs)("div",{children:[(0,De.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,De.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,De.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,De.jsx)(pa.Clock,{className:"af-h-4 af-w-4"}),(0,De.jsx)("span",{children:Vl(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,De.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,De.jsx)(pa.Globe,{className:"af-h-4 af-w-4"}),(0,De.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,De.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,De.jsx)(pa.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,De.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,De.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,De.jsx)(pa.Mail,{className:"af-h-4 af-w-4"}),(0,De.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var ql=require("lucide-react");var ms=ce(require("react"),1);var vu=/^\+[1-9]\d{1,14}$/;function zl(e){let t=e==null?"":String(e),a=!vu.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),s=a?`'${t}`:t;return a||/[",;\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function di(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function ui(e,t){if(typeof document>"u")return;let a=URL.createObjectURL(e),s=document.createElement("a");s.href=a,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(a)}function pr({fetchCsv:e,filename:t}){let[a,s]=ms.useState(!1),[n,r]=ms.useState(null),i=ms.useRef(!1);return{exportCsv:ms.useCallback(async()=>{if(!i.current){i.current=!0,s(!0),r(null);try{let f=await e();ui(f,di(t))}catch(f){r(f instanceof Error?f:new Error("Export failed"))}finally{i.current=!1,s(!1)}}},[e,t]),exporting:a,error:n}}var $s=require("react/jsx-runtime");function da({fetchCsv:e,filename:t,label:a="Export CSV",disabled:s,className:n}){let{exportCsv:r,exporting:i,error:l}=pr({fetchCsv:e,filename:t});return(0,$s.jsxs)("span",{className:n,children:[(0,$s.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||i,"aria-busy":i,children:[(0,$s.jsx)(ql.Download,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Exporting\u2026":a]}),l&&(0,$s.jsx)("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}var xe=require("react/jsx-runtime");function bu(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function hu(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 yu=["message","comments","comment","inquiry","question","details","body","notes"];function xu(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=(yu.map(r=>a.get(r)).find(Boolean)??t.reduce((r,[,i])=>i.length>r.length?i:r,"")).trim().replace(/\s+/g," ");return n.length>80?n.slice(0,80)+"\u2026":n}function gr({formId:e,className:t,defaultSubmissionId:a,submissionId:s,onSelectSubmission:n}){let{api:r}=W(),{submissions:i,total:l,isLoading:f,error:d,page:o,pageSize:c,hasNextPage:b,hasPreviousPage:g,setPage:m,setPageSize:p,deleteSubmission:u}=ur({formId:e}),v=as.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[x,k]=as.useState(a??null),T=n?s??null:x,h=n??k,R=H=>!!H&&H.id===T&&H.form_id===e,P=i.find(R),[D,N]=as.useState(null),E=R(D)?D:null,[A,C]=as.useState(null);if(as.useEffect(()=>{if(C(null),!T||P||E)return;let H=!1;return r.getSubmission(T).then(de=>{if(!H){if(de.form_id!==e){C("This submission could not be found.");return}N(de)}}).catch(()=>{H||C("This submission could not be found.")}),()=>{H=!0}},[r,e,T,P,E]),T){let H=P??E;return H?(0,xe.jsx)("div",{className:t,children:(0,xe.jsx)(mr,{submission:H,onBack:()=>h(null),onDelete:async()=>{await u(H.id),h(null)}})}):A?(0,xe.jsxs)("div",{className:t,children:[(0,xe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>h(null),className:"af-mb-2 af--ml-2",children:[(0,xe.jsx)(nn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,xe.jsx)("p",{className:"af-text-sm af-text-destructive",children:A})]}):(0,xe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,xe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(f)return(0,xe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,xe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(d)return(0,xe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,xe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",d.message]})});if(i.length===0&&o===0)return(0,xe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,xe.jsx)(nn.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,xe.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,xe.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let K=o*c+1,Q=Math.min((o+1)*c,l);return(0,xe.jsxs)("div",{className:t,children:[(0,xe.jsx)("div",{className:"af-mb-2 af-flex af-justify-end",children:(0,xe.jsx)(da,{fetchCsv:v,filename:"submissions"})}),(0,xe.jsxs)(ft,{children:[(0,xe.jsx)(mt,{children:(0,xe.jsxs)(Fe,{children:[(0,xe.jsx)(Z,{children:"Email"}),(0,xe.jsx)(Z,{children:"Preview"}),(0,xe.jsx)(Z,{children:"Date"}),(0,xe.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,xe.jsx)(pt,{children:i.map(H=>{let de=hu(H.data),me=xu(H.data);return(0,xe.jsxs)(Fe,{children:[(0,xe.jsxs)(Y,{className:"af-font-medium",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[de||(0,xe.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),H.attachments.length>0&&(0,xe.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${H.attachments.length} attachment(s)`,children:[(0,xe.jsx)(nn.Paperclip,{className:"af-h-3 af-w-3"}),(0,xe.jsx)("span",{className:"af-text-xs",children:H.attachments.length})]})]}),(0,xe.jsx)(dr,{deliveries:H.email_deliveries,label:"Notification email needs attention"})]}),(0,xe.jsx)(Y,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:me||(0,xe.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,xe.jsx)(Y,{className:"af-text-muted-foreground",children:bu(H.metadata.submitted_at)}),(0,xe.jsxs)(Y,{className:"af-text-right",children:[(0,xe.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>h(H.id),title:"View details",children:(0,xe.jsx)(nn.Eye,{className:"af-h-4 af-w-4"})}),(0,xe.jsx)(Us,{iconOnly:!0,onDelete:()=>u(H.id)})]})]},H.id)})})]}),(0,xe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,xe.jsxs)("span",{children:["Showing ",K,"-",Q," of ",l]}),(0,xe.jsxs)(en,{value:String(c),onValueChange:H=>p(Number(H)),children:[(0,xe.jsx)(Fa,{className:"af-w-[70px] af-h-8",children:(0,xe.jsx)(tn,{})}),(0,xe.jsxs)(Ma,{children:[(0,xe.jsx)(Rt,{value:"10",children:"10"}),(0,xe.jsx)(Rt,{value:"25",children:"25"}),(0,xe.jsx)(Rt,{value:"50",children:"50"}),(0,xe.jsx)(Rt,{value:"100",children:"100"})]})]}),(0,xe.jsx)("span",{children:"per page"})]}),(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,xe.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>m(o-1),disabled:!g,children:[(0,xe.jsx)(nn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,xe.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>m(o+1),disabled:!b,children:["Next",(0,xe.jsx)(nn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var ja=ce(require("react"),1),ns=require("lucide-react");var jl=ce(require("react"),1);var Wl=require("react/jsx-runtime"),oe=jl.forwardRef(({className:e,type:t,...a},s)=>(0,Wl.jsx)("input",{type:t,className:X("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...a}));oe.displayName="Input";var Gl=ce(require("react"),1),Kl=require("class-variance-authority");var Zl=require("react/jsx-runtime"),wu=(0,Kl.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Ve=Gl.forwardRef(({className:e,...t},a)=>(0,Zl.jsx)("label",{ref:a,className:X(wu(),e),...t}));Ve.displayName="Label";var sn=ce(require("react"),1),ga=require("lucide-react");var qa=ce(require("react"),1);function vr(){let{api:e}=W(),[t,a]=qa.useState([]),[s,n]=qa.useState(!0),[r,i]=qa.useState(null),l=qa.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]);qa.useEffect(()=>{l()},[l]);let f=qa.useCallback(async g=>{let m=await e.createEventDestination(g);return a(p=>[m,...p]),m},[e]),d=qa.useCallback(async(g,m)=>{let p=await e.updateEventDestination(g,m);return a(u=>u.map(v=>v.id===g?p:v)),p},[e]),o=qa.useCallback(async g=>{await e.deleteEventDestination(g),a(m=>m.filter(p=>p.id!==g))},[e]),c=qa.useCallback(async g=>{let m=await e.rotateEventDestinationSecret(g);return a(p=>p.map(u=>u.id===g?m:u)),m},[e]),b=qa.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:s,error:r,refetch:l,createDestination:f,updateDestination:d,deleteDestination:o,rotateSecret:c,getSecret:b}}var $n=ce(require("react"),1),br=require("lucide-react");var Xt=require("react/jsx-runtime");function hr({destinationId:e,limit:t=25,className:a}){let{api:s}=W(),[n,r]=$n.useState([]),[i,l]=$n.useState(!0),[f,d]=$n.useState(null),[o,c]=$n.useState(null),b=$n.useCallback(async()=>{try{l(!0),d(null),r(await s.getEventDeliveries(e,t))}catch(m){d(m instanceof Error?m.message:"Failed to load deliveries")}finally{l(!1)}},[s,e,t]);$n.useEffect(()=>{b()},[b]);let g=async m=>{try{c(m.id),d(null);let p=await s.retryEventDelivery(e,m.id);r(u=>u.map(v=>v.id===m.id?p:v))}catch(p){d(p instanceof Error?p.message:"Retry failed")}finally{c(null)}};return i?(0,Xt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,Xt.jsx)(br.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):f?(0,Xt.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:f}):n.length===0?(0,Xt.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):(0,Xt.jsx)("div",{className:a,children:(0,Xt.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(m=>{let p=m.delivered_at!==null;return(0,Xt.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,Xt.jsxs)("div",{className:"af-min-w-0",children:[(0,Xt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[p?(0,Xt.jsx)(ie,{variant:"secondary",children:m.last_status??200}):(0,Xt.jsx)(ie,{variant:"destructive",children:m.last_status??"failed"}),(0,Xt.jsx)("span",{className:"af-text-sm af-truncate",children:m.type})]}),(0,Xt.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[m.event_id," \xB7 ",m.created_at,m.attempts>0&&` \xB7 ${m.attempts} failed ${m.attempts===1?"attempt":"attempts"}`]}),!p&&m.last_error&&(0,Xt.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:m.last_error})]}),(0,Xt.jsx)(y,{variant:"ghost",size:"sm",title:"Send this event again",disabled:o===m.id,onClick:()=>g(m),children:o===m.id?(0,Xt.jsx)(br.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Xt.jsx)(br.RotateCw,{className:"af-h-4 af-w-4"})})]},m.id)})})})}var Ce=require("react/jsx-runtime");function yr({formId:e,topics:t,description:a,className:s}){let{destinations:n,isLoading:r,error:i,createDestination:l,updateDestination:f,deleteDestination:d,rotateSecret:o,getSecret:c}=vr(),[b,g]=sn.useState(""),[m,p]=sn.useState(!1),[u,v]=sn.useState(null),[x,k]=sn.useState(null),[T,h]=sn.useState(null),[R,P]=sn.useState(!1),[D,N]=sn.useState(null),[E,A]=sn.useState(null),[C,K]=sn.useState(null),Q=sn.useMemo(()=>n.filter(F=>F.form_id===e),[n,e]),H=async()=>{let F=b.trim();if(F){if(!F.startsWith("https://")){v("Webhook URLs must start with https://");return}try{p(!0),v(null),await l({url:F,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(ge){v(ge instanceof Error?ge.message:"Failed to add webhook")}finally{p(!1)}}},de=async F=>{try{A(F.id),v(null),await o(F.id),P(!1),h(await c(F.id))}catch(ge){v(ge instanceof Error?ge.message:"Failed to rotate secret")}finally{A(null)}},me=async F=>{try{A(F.id),v(null),await f(F.id,{status:"active"})}catch(ge){v(ge instanceof Error?ge.message:"Failed to re-enable")}finally{A(null)}},be=async()=>{if(D)try{A(D.id),await d(D.id),N(null)}catch(F){v(F instanceof Error?F.message:"Failed to delete")}finally{A(null)}},V=async F=>{if(x===F.id){k(null),h(null);return}try{A(F.id),v(null),P(!1),k(F.id),h(await c(F.id))}catch(ge){k(null),v(ge instanceof Error?ge.message:"Failed to read secret")}finally{A(null)}},J=async()=>{if(T)try{await navigator.clipboard.writeText(T),P(!0)}catch{}};return(0,Ce.jsxs)("div",{className:s,children:[(0,Ce.jsxs)("div",{className:"af-space-y-1",children:[(0,Ce.jsx)(Ve,{children:"Webhooks"}),(0,Ce.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:a??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),(0,Ce.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,Ce.jsx)(oe,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:F=>g(F.target.value),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),H())},disabled:m}),(0,Ce.jsxs)(y,{onClick:H,disabled:m||!b.trim(),children:[m?(0,Ce.jsx)(ga.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ce.jsx)(ga.Plus,{className:"af-h-4 af-w-4"}),(0,Ce.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(u||i)&&(0,Ce.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:u||i?.message}),(0,Ce.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[r&&(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Ce.jsx)(ga.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&Q.length===0&&(0,Ce.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),Q.map(F=>(0,Ce.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,Ce.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,Ce.jsxs)("div",{className:"af-min-w-0",children:[(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Ce.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:F.url}),F.status==="disabled"?(0,Ce.jsx)(ie,{variant:"destructive",children:"Disabled"}):(0,Ce.jsx)(ie,{variant:"secondary",children:"Active"})]}),(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:F.topics.includes("*")?"All events":F.topics.join(", ")})]}),(0,Ce.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,Ce.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>K(C===F.id?null:F.id),children:C===F.id?"Hide log":"Deliveries"}),(0,Ce.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>V(F),disabled:E===F.id,children:x===F.id?"Hide secret":"Show secret"}),(0,Ce.jsx)(y,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:E===F.id,onClick:()=>N(F),children:(0,Ce.jsx)(ga.Trash2,{className:"af-h-4 af-w-4"})})]})]}),F.status==="disabled"&&(0,Ce.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[(0,Ce.jsx)(ga.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,Ce.jsxs)("div",{className:"af-text-sm",children:[(0,Ce.jsxs)("p",{children:["We stopped sending after repeated failures."," ",F.disabled_reason]}),(0,Ce.jsx)(y,{variant:"outline",size:"sm",className:"af-mt-2",disabled:E===F.id,onClick:()=>me(F),children:"Re-enable"})]})]}),x===F.id&&T&&(0,Ce.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Optional. Use this if you want your endpoint to check that a delivery really came from us. Rotating replaces it."}),(0,Ce.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ce.jsx)(oe,{readOnly:!0,value:T,className:"af-font-mono"}),(0,Ce.jsx)(y,{variant:"outline",title:"Copy signing secret",onClick:J,children:R?(0,Ce.jsx)(ga.Check,{className:"af-h-4 af-w-4"}):(0,Ce.jsx)(ga.Copy,{className:"af-h-4 af-w-4"})}),(0,Ce.jsx)(y,{variant:"outline",title:"Rotate signing secret",disabled:E===F.id,onClick:()=>de(F),children:E===F.id?(0,Ce.jsx)(ga.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,Ce.jsx)(ga.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),C===F.id&&(0,Ce.jsx)(hr,{destinationId:F.id})]},F.id))]}),(0,Ce.jsx)(an,{open:!!D,onOpenChange:F=>{!F&&!E&&N(null)},children:(0,Ce.jsxs)(Ua,{children:[(0,Ce.jsxs)($a,{children:[(0,Ce.jsx)(Ha,{children:"Delete this webhook?"}),(0,Ce.jsxs)(za,{children:["New submissions will stop being sent to ",D?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),(0,Ce.jsxs)(Va,{children:[(0,Ce.jsx)(y,{variant:"outline",onClick:()=>N(null),disabled:!!E,children:"Cancel"}),(0,Ce.jsx)(y,{variant:"destructive",onClick:be,disabled:!!E,children:E?"Deleting...":"Delete"})]})]})})]})}var $e=require("react/jsx-runtime");function xr({form:e,onSaved:t,className:a}){let{updateForm:s}=us(),[n,r]=ja.useState(!1),[i,l]=ja.useState(null),[f,d]=ja.useState(null),[o,c]=ja.useState(e.name),[b,g]=ja.useState(e.redirect_url||""),[m,p]=ja.useState(e.email_recipients),[u,v]=ja.useState("");ja.useEffect(()=>{c(e.name),g(e.redirect_url||""),p(e.email_recipients),d(null)},[e]);let x=ja.useCallback(async P=>{try{r(!0),d(null);let D=await s(e.id,P);l(new Date),t?.(D)}catch(D){d(D instanceof Error?D.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);ja.useEffect(()=>{if(i){let P=setTimeout(()=>l(null),2e3);return()=>clearTimeout(P)}},[i]);let k=async()=>{let P=u.trim().toLowerCase();if(!P)return;if(!P.includes("@")){d("Please enter a valid email address");return}if(m.includes(P)){d("This email is already added");return}let D=[...m,P];p(D),v(""),d(null),await x({email_recipients:D})},T=async P=>{let D=m.filter(N=>N!==P);p(D),await x({email_recipients:D})},h=async()=>{o!==e.name&&await x({name:o})},R=async()=>{let P=b||null;P!==e.redirect_url&&await x({redirect_url:P})};return(0,$e.jsxs)("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(n||i)&&(0,$e.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,$e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-background af-border af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,$e.jsx)(ns.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,$e.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,$e.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-bg-green-50 af-border af-border-green-200 af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[(0,$e.jsx)(ns.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,$e.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{htmlFor:"form-name",children:"Form Name"}),(0,$e.jsx)(oe,{id:"form-name",value:o,onChange:P=>c(P.target.value),onBlur:h,placeholder:"Contact Form"}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{children:"Email Recipients"}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,$e.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[m.map(P=>(0,$e.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[P,(0,$e.jsx)("button",{type:"button",onClick:()=>T(P),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,$e.jsx)(ns.X,{className:"af-h-3 af-w-3"})})]},P)),m.length===0&&(0,$e.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,$e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,$e.jsx)(oe,{type:"email",value:u,onChange:P=>v(P.target.value),placeholder:"Add email address",onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),k())},disabled:n}),(0,$e.jsx)(y,{type:"button",variant:"outline",onClick:k,disabled:!u.trim()||n,children:(0,$e.jsx)(ns.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,$e.jsx)(oe,{id:"redirect-url",value:b,onChange:P=>g(P.target.value),onBlur:R,placeholder:"/thank-you"}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Where to send visitors after a successful submission. Use a site path (/thank-you) or a full URL (https://example.com/thank-you). Leave empty for a default success page."})]}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{children:"Form Endpoint"}),(0,$e.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,$e.jsx)("code",{className:"af-flex-1 af-text-xs af-bg-muted af-px-3 af-py-2 af-rounded af-border",children:e.endpoint_url})}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,$e.jsxs)("div",{className:"af-space-y-2",children:[(0,$e.jsx)(Ve,{children:"Captcha Protection"}),(0,$e.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,$e.jsx)(ie,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,$e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,$e.jsx)(yr,{formId:e.id}),f&&(0,$e.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f})]})}var yt=require("react/jsx-runtime");function co({className:e,location:t,onNavigate:a,submissionId:s}){let{api:n}=W(),[r,i]=Vn.useState({submissionId:s});Vn.useEffect(()=>{s&&i({submissionId:s})},[s]);let l=a?t??{}:r,f=a??i,[d,o]=Vn.useState(null),c=`${l.formId??""}|${l.submissionId??""}`,[b,g]=Vn.useState(null),m=b?.key===c?b.message:null,p=l.formId??(d&&d.submissionId===l.submissionId?d.formId:void 0);Vn.useEffect(()=>{let P=l.submissionId;if(!P||l.formId)return;let D=!1;return n.getSubmission(P).then(N=>{D||(g(null),o({submissionId:P,formId:N.form_id}))}).catch(()=>{D||g({key:c,message:"This submission could not be found."})}),()=>{D=!0}},[n,l.submissionId,l.formId,c]);let[u,v]=Vn.useState(null);Vn.useEffect(()=>{if(!p||u?.id===p)return;let P=!1;return n.getForm(p).then(D=>{P||(g(null),v(D))}).catch(()=>{P||g({key:c,message:"This form could not be found."})}),()=>{P=!0}},[n,p,u?.id,c]);let x=(P,D)=>{v(P),f({formId:P.id,tab:D})},k=()=>f({});if(!l.formId&&!l.submissionId)return(0,yt.jsxs)("div",{className:e,children:[(0,yt.jsxs)("div",{className:"af-mb-6",children:[(0,yt.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,yt.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,yt.jsx)(cr,{onSelectForm:x})]});let h=(0,yt.jsxs)(y,{variant:"ghost",size:"sm",onClick:k,className:"af-mb-2 af--ml-2",children:[(0,yt.jsx)(Vs.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(m)return(0,yt.jsxs)("div",{className:e,children:[h,(0,yt.jsx)("p",{className:"af-text-sm af-text-destructive",children:m})]});if(!p||u?.id!==p)return(0,yt.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,yt.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let R=l.submissionId?"submissions":l.tab??"submissions";return(0,yt.jsxs)("div",{className:e,children:[(0,yt.jsxs)("div",{className:"af-mb-6",children:[h,(0,yt.jsx)("h2",{className:"af-text-lg af-font-semibold",children:u.name})]}),(0,yt.jsxs)(ii,{value:R,onValueChange:P=>f({formId:p,tab:P}),children:[(0,yt.jsxs)(or,{className:"af-mb-4",children:[(0,yt.jsxs)(vn,{value:"submissions",className:"af-gap-2",children:[(0,yt.jsx)(Vs.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,yt.jsxs)(vn,{value:"settings",className:"af-gap-2",children:[(0,yt.jsx)(Vs.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,yt.jsx)(bn,{value:"submissions",children:(0,yt.jsx)(gr,{formId:p,submissionId:l.submissionId,onSelectSubmission:P=>f({formId:p,tab:"submissions",submissionId:P??void 0})})}),(0,yt.jsx)(bn,{value:"settings",children:(0,yt.jsx)(xr,{form:u,onSaved:v})})]})]})}var rt=ce(require("react"),1);var kn=ce(require("react"),1);function Hn(){let{api:e}=W(),[t,a]=kn.useState(null),[s,n]=kn.useState(!0),[r,i]=kn.useState(null),l=kn.useRef(0),f=kn.useCallback(async()=>{let d=++l.current;try{n(!0),i(null);let o=await e.getPaymentsStatus();if(d!==l.current)return;a(o)}catch(o){if(d!==l.current)return;i(o instanceof Error?o:new Error("Failed to fetch payments status"))}finally{d===l.current&&n(!1)}},[e]);return kn.useEffect(()=>{f()},[f]),{status:t,isLoading:s,error:r,refetch:f}}var Su=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Wa(e){return Su.has(e.toLowerCase())}function ee(e,t,a){let s=Wa(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Cn(e){let t=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+t}function ia(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=Wa(t)?a:a*100;return Math.round(s)}function kt(e,t){return Wa(t)?e:e/100}function fi(e){return e.amount_paid??Math.max(0,Cn(e)-(e.credit_applied??0))}var ye=require("react/jsx-runtime");function wr(e){return e instanceof jt&&e.status===404?"Promo management is not available yet. Try again after the service is updated.":e instanceof Error?e.message:"Could not complete the request."}function Yl(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${ee(e.amount_off,e.currency)} off`:"Discount unavailable"}function ps(){let{api:e,siteToken:t}=W();return(0,ye.jsx)(Nu,{api:e},t)}function Nu({api:e}){let{status:t,error:a}=Hn(),[s,n]=rt.useState([]),[r,i]=rt.useState(null),[l,f]=rt.useState(null),[d,o]=rt.useState(!1),[c,b]=rt.useState(!1),[g,m]=rt.useState(""),[p,u]=rt.useState(null),[v,x]=rt.useState(null),[k,T]=rt.useState(!1),h=rt.useRef(0),R=rt.useCallback(async N=>{let E=++h.current;o(!0),m("");try{let A=await e.getPromos(N);if(E!==h.current)return;n(C=>N?[...C,...A.promos.filter(K=>!C.some(Q=>Q.id===K.id))]:A.promos),i(A.next_cursor),f(A.checkout_enabled)}catch(A){E===h.current&&m(wr(A))}finally{E===h.current&&o(!1)}},[e]);rt.useEffect(()=>(R(),()=>{h.current++}),[R]);async function P(N){let E=++h.current;o(!0),m(""),T(!1);try{let A=await e.getPromo(N);E===h.current&&u(A)}catch(A){E===h.current&&m(wr(A))}finally{E===h.current&&o(!1)}}async function D(){if(p){b(!0),o(!0),m("");try{let N=await e.disablePromo(p.id);if(u(N),!["inactive","expired","exhausted"].includes(N.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");T(!1),await R()}catch(N){m(wr(N))}finally{b(!1),o(!1)}}}return v?(0,ye.jsx)(Ru,{currency:t?.currency??void 0,replaces:v.replaces,onCancel:()=>x(null),onSave:async N=>{let E=v.replaces?await e.replacePromo(v.replaces.id,N):await e.createPromo(N),A=await e.getPromo(E.id);if(A.status==="pending"||A.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");u(A),x(null),await R()}}):(0,ye.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,ye.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,ye.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,ye.jsx)(y,{disabled:d||!t?.currency,onClick:()=>{m(""),x({})},children:"Create promo code"})]}),(0,ye.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),l===!1&&(0,ye.jsx)("p",{role:"status",className:"af-rounded-md af-border af-p-3 af-text-sm",children:"Checkout code entry is not enabled yet. You can prepare codes, but buyers cannot enter them in our checkout until it is enabled."}),!t?.currency&&(0,ye.jsx)("p",{className:"af-text-sm",children:a?wr(a):"Connect Stripe and set the payment currency before creating codes."}),g&&(0,ye.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",(0,ye.jsx)(y,{variant:"outline",disabled:d,onClick:()=>p?void P(p.id):void R(),children:"Refresh"})]}),p?(0,ye.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,ye.jsx)(y,{variant:"ghost",disabled:c,onClick:()=>{u(null),T(!1),R()},children:"Back to codes"}),(0,ye.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[p.code," \xB7 ",p.name]}),(0,ye.jsxs)("p",{children:[Yl(p)," \xB7 ",p.status]}),(0,ye.jsxs)("p",{className:"af-text-sm",children:[p.times_redeemed==null?"Usage unavailable":`${p.times_redeemed} redemptions`,p.max_redemptions!=null?` / ${p.max_redemptions} maximum`:""]}),(0,ye.jsxs)("p",{className:"af-text-sm",children:[p.minimum_amount!=null&&p.currency?`Minimum order: ${ee(p.minimum_amount,p.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,ye.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",p.duration==="repeating"?`${p.duration_in_months} months`:p.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,ye.jsx)("p",{className:"af-text-sm",children:p.expires_at?`Expires ${new Date(p.expires_at).toLocaleString()}`:"No expiry"}),(0,ye.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ye.jsx)(y,{variant:"outline",disabled:d,onClick:()=>void P(p.id),children:"Refresh details"}),(0,ye.jsx)(y,{variant:"outline",disabled:d||p.status==="pending"||p.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:p}),children:"Replace with new code"}),(0,ye.jsx)(y,{variant:"outline",disabled:d||!["active","pending","unavailable"].includes(p.status),onClick:()=>T(!0),children:p.status==="pending"?"Cancel pending offer":"Disable code"})]}),k&&(0,ye.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,ye.jsxs)("p",{className:"af-text-sm",children:[p.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${p.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,ye.jsx)(y,{disabled:d,onClick:()=>void D(),children:p.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,ye.jsx)(y,{variant:"ghost",disabled:d,onClick:()=>T(!1),children:"Cancel"})]})]}):(0,ye.jsxs)(ye.Fragment,{children:[s.map(N=>(0,ye.jsxs)("button",{type:"button",disabled:d,onClick:()=>void P(N.id),className:"af-w-full af-rounded-lg af-border af-p-4 af-text-left hover:af-bg-muted focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[(0,ye.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,ye.jsx)("span",{className:"af-font-semibold af-break-all",children:N.code}),(0,ye.jsx)("span",{className:"af-text-sm",children:N.status})]}),(0,ye.jsxs)("div",{className:"af-text-sm",children:[Yl(N)," \xB7"," ",N.times_redeemed==null?"Usage unavailable":`${N.times_redeemed} redemptions`]})]},N.id)),!d&&!g&&s.length===0&&(0,ye.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),d&&(0,ye.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),r&&(0,ye.jsx)(y,{variant:"outline",disabled:d,onClick:()=>void R(r),children:"Load more"})]})]})}function Ru({currency:e,replaces:t,onCancel:a,onSave:s}){let[n,r]=rt.useState(""),[i,l]=rt.useState(t?.name??""),[f,d]=rt.useState(t?.amount_off!=null?"fixed":"percent"),[o,c]=rt.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(kt(t.amount_off,e)):"")),[b,g]=rt.useState(t?.minimum_amount!=null&&e?String(kt(t.minimum_amount,e)):""),[m,p]=rt.useState(()=>{if(!t?.expires_at)return"";let me=new Date(t.expires_at);return Number.isFinite(me.getTime())?new Date(me.getTime()-me.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[u,v]=rt.useState(t?.max_redemptions?.toString()??""),[x,k]=rt.useState(t?.duration??"once"),[T,h]=rt.useState(t?.duration_in_months?.toString()??"3"),[R,P]=rt.useState(null),[D,N]=rt.useState(!1),[E,A]=rt.useState(""),C=rt.useRef(!1),K=e&&Wa(e)?"1":"0.01";async function Q(me){if(me.preventDefault(),C.current)return;A("");let be=R;if(!be){if(!e){A("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){A("Choose a different code for the replacement.");return}let V=ia(o,e),J=b?ia(b,e):null;if(f==="fixed"&&(!V||V>999999999999)||b&&(!J||J>999999999999)){A("Enter a positive amount within the supported range.");return}if(m&&new Date(m).getTime()<=Date.now()){A("Choose a future expiry.");return}be={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:i.trim(),duration:x,...f==="percent"?{percent_off:Number(o)}:{amount_off:V,currency:e},...b?{minimum_amount:J,currency:e}:{},...m?{expires_at:new Date(m).toISOString()}:{},...u?{max_redemptions:Number(u)}:{},...x==="repeating"?{duration_in_months:Number(T)}:{}},P(be)}C.current=!0,N(!0);try{await s(be)}catch(V){A(wr(V)),V instanceof jt&&V.status>=400&&V.status<500&&V.details?.retryable!==!0&&P(null)}finally{C.current=!1,N(!1)}}let H=(me,be,V,J={})=>(0,ye.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[me,(0,ye.jsx)(oe,{"aria-label":me,value:be,onChange:F=>V(F.target.value),...J})]}),de="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,ye.jsxs)("form",{onSubmit:Q,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,ye.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,ye.jsx)("p",{className:"af-text-sm",children:"Use a different code. The old code will be disabled only after the replacement is created. Existing subscription discounts continue."}),(0,ye.jsxs)("fieldset",{disabled:D||!!R,className:"af-grid af-gap-4",children:[H("Code",n,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),H("Name",i,l,{required:!0,maxLength:40}),(0,ye.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,ye.jsxs)("select",{"aria-label":"Discount type",className:de,value:f,onChange:me=>d(me.target.value),children:[(0,ye.jsx)("option",{value:"percent",children:"Percentage"}),(0,ye.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),H("Discount",o,c,{type:"number",required:!0,min:f==="percent"?"0.01":K,max:f==="percent"?"100":void 0,step:f==="percent"?"0.01":K}),H("Minimum order amount",b,g,{type:"number",min:K,step:K,placeholder:e?.toUpperCase()}),(0,ye.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),H("Expires at (local time)",m,p,{type:"datetime-local",step:1}),H("Maximum redemptions",u,v,{type:"number",min:1,max:1e6,step:1}),(0,ye.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,ye.jsxs)("select",{"aria-label":"Subscription duration",className:de,value:x,onChange:me=>k(me.target.value),children:[(0,ye.jsx)("option",{value:"once",children:"First invoice only"}),(0,ye.jsx)("option",{value:"forever",children:"Every invoice"}),(0,ye.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&H("Months",T,h,{type:"number",required:!0,min:1,max:36,step:1})]}),E&&(0,ye.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:E}),R&&!D&&(0,ye.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,ye.jsx)("span",{className:"af-break-all",children:R.request_id})]}),(0,ye.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ye.jsx)(y,{type:"submit",disabled:D,children:D?"Saving\u2026":R?"Retry same request":t?"Create replacement":"Create code"}),(0,ye.jsx)(y,{type:"button",variant:"ghost",disabled:D||!!R,onClick:a,children:"Cancel"})]})]})}var Gs=ce(require("react"),1),cn=require("lucide-react");var mi=ce(require("react"),1),zn=require("lucide-react");var Oe=require("react/jsx-runtime");function _u(e){if(e.allow_custom_amount){let t=e.min_amount!==null?ee(e.min_amount,e.currency):"?",a=e.max_amount!==null?ee(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":ee(e.unit_amount,e.currency)}function Pu(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Sr({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:n,isLoading:r,error:i,deleteProduct:l}=e,[f,d]=mi.useState(null),[o,c]=mi.useState(!1),[b,g]=mi.useState(null),m=async()=>{if(f)try{c(!0),g(null),await l(f.id),d(null)}catch(p){g(p instanceof Error?p.message:"Failed to delete product")}finally{c(!1)}};return r?(0,Oe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Oe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):i?(0,Oe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Oe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i.message]})}):n.length===0?(0,Oe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[(0,Oe.jsx)(zn.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Oe.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,Oe.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,Oe.jsxs)(y,{variant:"outline",onClick:()=>a?.(),children:[(0,Oe.jsx)(zn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,Oe.jsxs)("div",{className:s,children:[(0,Oe.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,Oe.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[(0,Oe.jsx)(zn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,Oe.jsxs)(ft,{children:[(0,Oe.jsx)(mt,{children:(0,Oe.jsxs)(Fe,{children:[(0,Oe.jsx)(Z,{children:"Name"}),(0,Oe.jsx)(Z,{children:"Price"}),(0,Oe.jsx)(Z,{children:"Fulfillment"}),(0,Oe.jsx)(Z,{children:"Status"}),(0,Oe.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,Oe.jsx)(pt,{children:n.map(p=>(0,Oe.jsxs)(Fe,{children:[(0,Oe.jsx)(Y,{className:"af-font-medium",children:p.name}),(0,Oe.jsx)(Y,{children:_u(p)}),(0,Oe.jsx)(Y,{className:"af-text-muted-foreground",children:Pu(p)}),(0,Oe.jsx)(Y,{children:(0,Oe.jsx)(ie,{variant:p.active?"success":"secondary",children:p.active?"Active":"Inactive"})}),(0,Oe.jsx)(Y,{className:"af-text-right",children:(0,Oe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Oe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>t?.(p),children:[(0,Oe.jsx)(zn.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,Oe.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>{g(null),d(p)},children:[(0,Oe.jsx)(zn.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},p.id))})]}),(0,Oe.jsx)(an,{open:!!f,onOpenChange:p=>{!p&&!o&&d(null)},children:(0,Oe.jsxs)(Ua,{children:[(0,Oe.jsxs)($a,{children:[(0,Oe.jsx)(Ha,{children:"Delete product?"}),(0,Oe.jsxs)(za,{children:['"',f?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&(0,Oe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),(0,Oe.jsxs)(Va,{children:[(0,Oe.jsx)(y,{variant:"outline",onClick:()=>d(null),disabled:o,children:"Cancel"}),(0,Oe.jsx)(y,{variant:"destructive",onClick:m,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})}var Ct=ce(require("react"),1),Ga=require("lucide-react");var Wt=ce(require("react"),1),rn=require("lucide-react");var B=require("react/jsx-runtime");function uo(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Nr({productId:e,currency:t,className:a}){let{api:s}=W(),n=Wa(t)?"1":"0.01",[r,i]=Wt.useState(null),[l,f]=Wt.useState(!0),[d,o]=Wt.useState(null),[c,b]=Wt.useState(null),[g,m]=Wt.useState(!1),p=Wt.useRef(!0);Wt.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);let u=Wt.useCallback(async()=>{try{let L=await s.getProduct(e);if(!p.current)return;i(L)}catch(L){if(!p.current)return;o(L instanceof Error?L.message:"Failed to load product")}finally{p.current&&f(!1)}},[s,e]);Wt.useEffect(()=>{u()},[u]);let v=async L=>{b(null),m(!0);try{await L(),await u()}catch(M){p.current&&b(M instanceof Error?M.message:"Something went wrong")}finally{p.current&&m(!1)}},[x,k]=Wt.useState(""),[T,h]=Wt.useState(""),[R,P]=Wt.useState({}),D=()=>v(async()=>{let L=x.trim(),M=T.split(",").map(U=>U.trim()).filter(Boolean);if(!L)throw new Error("Option name is required");if(M.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:L,values:M}),p.current&&(k(""),h(""))}),N=L=>v(async()=>{let M=(R[L.id]??"").trim();if(!M)throw new Error("Enter a value");await s.updateOption(L.id,{add_values:[M]}),p.current&&P(U=>({...U,[L.id]:""}))}),E=(L,M)=>v(()=>s.updateOption(L.id,{remove_values:[M]})),A=L=>v(()=>s.deleteOption(L.id)),[C,K]=Wt.useState(null),[Q,H]=Wt.useState(null),[de,me]=Wt.useState(!1),[be,V]=Wt.useState(null),J=r?.options??[],F=r?.variants??[],ge=()=>{H(null),K({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(J.map(L=>[L.id,L.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},pe=L=>{H(null);let M=L.inventory?.on_hand??0,U=M<0?"":String(M);K({variant:L,title:L.title??"",sku:L.sku??"",unitAmount:L.unit_amount!=null?String(kt(L.unit_amount,t)):"",compareAt:L.compare_at_amount!=null?String(kt(L.compare_at_amount,t)):"",active:L.active,optionValues:{},tracked:L.inventory?.tracked??!1,onHand:U,initialOnHand:U,allowBackorder:L.inventory?.allow_backorder??!1})},He=async()=>{if(!C)return;H(null);let L=C.variant?.allow_custom_amount??!1,M=null,U=null;if(!L){if(M=ia(C.unitAmount,t),M===null||M<=0){H("Enter a valid price");return}if(C.compareAt.trim()&&(U=ia(C.compareAt,t),U===null||U<=M)){H("Compare-at price must be greater than the price");return}}let Te=C.onHand.trim()!==C.initialOnHand.trim(),ne=parseInt(C.onHand,10);if(C.tracked&&Te&&(!Number.isFinite(ne)||ne<0)){H("On-hand quantity must be zero or more");return}try{if(me(!0),C.variant)await s.updateVariant(C.variant.id,{title:C.title.trim()||null,sku:C.sku.trim()||null,...L?{}:{unit_amount:M,compare_at_amount:U},active:C.active}),await s.setVariantInventory(C.variant.id,{tracked:C.tracked,on_hand:C.tracked&&Te?ne:void 0,allow_backorder:C.allowBackorder});else{let Re={};for(let je of J){let wt=C.optionValues[je.id];if(!wt){H(`Choose a ${je.title}`),me(!1);return}Re[je.title]=wt}await s.createVariant(e,{title:C.title.trim()||null,sku:C.sku.trim()||null,unit_amount:M,compare_at_amount:U,active:C.active,option_values:J.length>0?Re:void 0,inventory:C.tracked?{tracked:!0,on_hand:ne,allow_backorder:C.allowBackorder}:{tracked:!1,allow_backorder:C.allowBackorder}})}await u(),p.current&&K(null)}catch(Re){if(p.current&&H(Re instanceof Error?Re.message:"Failed to save variant"),C.variant)try{let je=await s.getProduct(e);p.current&&i(je)}catch{}}finally{p.current&&me(!1)}},Pe=()=>v(async()=>{be&&(await s.deleteVariant(be.id),p.current&&V(null))}),Ue=C?.variant?.allow_custom_amount??!1,ze=C?.variant!=null&&C.variant.option_values.length===0&&J.length>0&&!C.variant.active,fe=C?.variant?.inventory!=null&&C.variant.inventory.on_hand<0?-C.variant.inventory.on_hand:null;function lt(L){let M=L.inventory;if(!M||!M.tracked)return(0,B.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let U=M.available??M.on_hand;return U<0?(0,B.jsxs)("span",{children:[-U," backordered"]}):(0,B.jsxs)("span",{children:[U," in stock",M.allow_backorder&&(0,B.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return l?(0,B.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:(0,B.jsx)(rn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):d?(0,B.jsx)("div",{className:a,children:(0,B.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})}):(0,B.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,B.jsxs)("div",{className:"af-space-y-3",children:[(0,B.jsxs)("div",{children:[(0,B.jsx)(Ve,{children:"Options"}),(0,B.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),J.length>0&&(0,B.jsx)("div",{className:"af-space-y-3",children:J.map(L=>(0,B.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,B.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,B.jsx)("span",{className:"af-text-sm af-font-medium",children:L.title}),(0,B.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>A(L),disabled:g,children:(0,B.jsx)(rn.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,B.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:L.values.map(M=>(0,B.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[M.value,(0,B.jsx)("button",{type:"button",onClick:()=>E(L,M.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:(0,B.jsx)(rn.X,{className:"af-h-3 af-w-3"})})]},M.id))}),(0,B.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,B.jsx)(oe,{value:R[L.id]??"",onChange:M=>P(U=>({...U,[L.id]:M.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),N(L))},disabled:g}),(0,B.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>N(L),disabled:g||!(R[L.id]??"").trim(),children:(0,B.jsx)(rn.Plus,{className:"af-h-4 af-w-4"})})]})]},L.id))}),(0,B.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,B.jsx)(oe,{id:"new-option-title",value:x,onChange:L=>k(L.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),(0,B.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,B.jsx)(Ve,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,B.jsx)(oe,{id:"new-option-values",value:T,onChange:L=>h(L.target.value),placeholder:"S, M, L",disabled:g})]}),(0,B.jsxs)(y,{type:"button",variant:"outline",onClick:D,disabled:g||!x.trim()||!T.trim(),children:[(0,B.jsx)(rn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,B.jsxs)("div",{className:"af-space-y-3",children:[(0,B.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,B.jsx)(Ve,{children:"Variants"}),(0,B.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:ge,disabled:g||J.length===0,children:[(0,B.jsx)(rn.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),J.length===0&&(0,B.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),F.length===0?(0,B.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,B.jsxs)(ft,{children:[(0,B.jsx)(mt,{children:(0,B.jsxs)(Fe,{children:[(0,B.jsx)(Z,{children:"Variant"}),(0,B.jsx)(Z,{children:"SKU"}),(0,B.jsx)(Z,{children:"Price"}),(0,B.jsx)(Z,{children:"Stock"}),(0,B.jsx)(Z,{children:"Status"}),(0,B.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,B.jsx)(pt,{children:F.map(L=>(0,B.jsxs)(Fe,{children:[(0,B.jsx)(Y,{className:"af-font-medium",children:uo(L)}),(0,B.jsx)(Y,{className:"af-text-muted-foreground",children:L.sku||"-"}),(0,B.jsx)(Y,{children:L.unit_amount!=null?(0,B.jsxs)("span",{children:[L.compare_at_amount!=null&&(0,B.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:ee(L.compare_at_amount,L.currency)}),ee(L.unit_amount,L.currency)]}):L.allow_custom_amount?(0,B.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,B.jsx)(Y,{children:lt(L)}),(0,B.jsx)(Y,{children:(0,B.jsx)(ie,{variant:L.active?"success":"secondary",children:L.active?"Active":"Inactive"})}),(0,B.jsx)(Y,{className:"af-text-right",children:(0,B.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,B.jsx)(y,{variant:"ghost",size:"sm",onClick:()=>pe(L),disabled:g,children:"Edit"}),(0,B.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>V(L),disabled:g,title:"Delete variant",children:(0,B.jsx)(rn.Trash2,{className:"af-h-4 af-w-4"})})]})})]},L.id))})]})]}),c&&(0,B.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c}),(0,B.jsx)(an,{open:C!==null,onOpenChange:L=>{!L&&!de&&K(null)},children:(0,B.jsxs)(Ua,{children:[(0,B.jsxs)($a,{children:[(0,B.jsx)(Ha,{children:C?.variant?"Edit variant":"Add variant"}),(0,B.jsx)(za,{children:"Price, markdown, and stock live on the variant."})]}),C&&(0,B.jsxs)("div",{className:"af-space-y-3",children:[C.variant?C.variant.option_values.length>0&&(0,B.jsxs)("div",{className:"af-text-sm",children:[(0,B.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),uo(C.variant)]}):J.map(L=>(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{className:"af-text-xs af-text-muted-foreground",children:L.title}),(0,B.jsxs)(en,{value:C.optionValues[L.id]??"",onValueChange:M=>K(U=>U&&{...U,optionValues:{...U.optionValues,[L.id]:M}}),children:[(0,B.jsx)(Fa,{children:(0,B.jsx)(tn,{placeholder:`Choose ${L.title}`})}),(0,B.jsx)(Ma,{children:L.values.map(M=>(0,B.jsx)(Rt,{value:M.value,children:M.value},M.id))})]})]},L.id)),Ue?(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,B.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,B.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsxs)(Ve,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,B.jsx)(oe,{id:"variant-price",type:"number",min:"0",step:n,value:C.unitAmount,onChange:L=>K(M=>M&&{...M,unitAmount:L.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,B.jsx)(oe,{id:"variant-compare",type:"number",min:"0",step:n,value:C.compareAt,onChange:L=>K(M=>M&&{...M,compareAt:L.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,B.jsx)(oe,{id:"variant-sku",value:C.sku,onChange:L=>K(M=>M&&{...M,sku:L.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,B.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,B.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,B.jsx)("input",{type:"checkbox",checked:C.tracked,onChange:L=>K(M=>M&&{...M,tracked:L.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),C.tracked&&(0,B.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,B.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsx)(Ve,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,B.jsx)(oe,{id:"variant-onhand",type:"number",min:"0",step:"1",value:C.onHand,onChange:L=>K(M=>M&&{...M,onHand:L.target.value}),placeholder:fe!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,B.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,B.jsx)("input",{type:"checkbox",checked:C.allowBackorder,onChange:L=>K(M=>M&&{...M,allowBackorder:L.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),fe!=null&&(0,B.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",fe," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,B.jsxs)("div",{className:"af-space-y-1",children:[(0,B.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,B.jsx)("input",{type:"checkbox",checked:C.active,onChange:L=>K(M=>M&&{...M,active:L.target.checked}),className:"af-h-4 af-w-4",disabled:ze}),"Active (buyers can purchase this variant)"]}),ze&&(0,B.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),Q&&(0,B.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Q})]}),(0,B.jsxs)(Va,{children:[(0,B.jsx)(y,{variant:"outline",onClick:()=>K(null),disabled:de,children:"Cancel"}),(0,B.jsxs)(y,{onClick:He,disabled:de,children:[de?(0,B.jsx)(rn.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,C?.variant?"Save":"Add variant"]})]})]})}),(0,B.jsx)(an,{open:be!==null,onOpenChange:L=>{!L&&!g&&V(null)},children:(0,B.jsxs)(Ua,{children:[(0,B.jsxs)($a,{children:[(0,B.jsx)(Ha,{children:"Delete variant?"}),(0,B.jsx)(za,{children:be&&`"${uo(be)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,B.jsxs)(Va,{children:[(0,B.jsx)(y,{variant:"outline",onClick:()=>V(null),disabled:g,children:"Cancel"}),(0,B.jsx)(y,{variant:"destructive",onClick:Pe,disabled:g,children:"Delete"})]})]})})]})}var se=require("react/jsx-runtime");function ku(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function Rr({productsState:e,product:t,currency:a,onSaved:s,className:n}){let{createProduct:r,updateProduct:i,attachProductFile:l,attachProductFileFromUrl:f}=e,d=!!t,o=t?.currency??a,c=Wa(o)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,m]=Ct.useState(!1),[p,u]=Ct.useState(null),v=Ct.useRef(!0);Ct.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);let[x,k]=Ct.useState(t?.name??""),[T,h]=Ct.useState(t?.description??""),[R,P]=Ct.useState(t?.allow_custom_amount?"custom":"fixed"),[D,N]=Ct.useState(t?.unit_amount!=null?String(kt(t.unit_amount,o)):""),[E,A]=Ct.useState(t?.min_amount!=null?String(kt(t.min_amount,o)):""),[C,K]=Ct.useState(t?.max_amount!=null?String(kt(t.max_amount,o)):""),[Q,H]=Ct.useState(String(t?.max_quantity??10)),de=Ct.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(kt(t.unit_amount,o)):"",minAmount:t?.min_amount!=null?String(kt(t.min_amount,o)):"",maxAmount:t?.max_amount!=null?String(kt(t.max_amount,o)):"",maxQuantity:String(t?.max_quantity??10)}).current,[me,be]=Ct.useState(t?.collect_shipping_address??!1),[V,J]=Ct.useState(t?.active??!0),[F,ge]=Ct.useState(t?.images??[]),[pe,He]=Ct.useState(""),[Pe,Ue]=Ct.useState(t?.fulfillment??null),[ze,fe]=Ct.useState(!1),[lt,L]=Ct.useState(""),[M,U]=Ct.useState(null),Te=Ct.useRef(null),ne=g||ze,Re=()=>{let Ne=pe.trim();if(Ne){if(F.includes(Ne)){u("This image URL is already added");return}ge(Le=>[...Le,Ne]),He(""),u(null)}},je=Ne=>{ge(Le=>Le.filter(ct=>ct!==Ne))},wt=async()=>{if(u(null),!x.trim()){u("Product name is required");return}let Ne=null,Le=null,ct=null,at=!d||R!==de.pricingMode||(R==="fixed"?D!==de.unitAmount:E!==de.minAmount||C!==de.maxAmount),qt=!d||Q!==de.maxQuantity,Ut=b||R==="fixed";if(!(b||!at))if(R==="fixed"){if(Ne=ia(D,o),Ne===null||Ne<=0){u("Enter a valid price");return}}else{if(Le=ia(E,o),ct=ia(C,o),Le===null||ct===null){u("Enter valid minimum and maximum amounts");return}if(ct<Le){u("Maximum amount must be at least the minimum amount");return}}let sa=parseInt(Q,10);if(Ut&&qt&&(!Number.isFinite(sa)||sa<1)){u("Max quantity must be at least 1");return}try{m(!0);let dt;if(d&&t){let ht={name:x.trim(),description:T.trim()||null,images:F,collect_shipping_address:me,active:V};!b&&at&&(ht.allow_custom_amount=R==="custom",R==="fixed"?ht.unit_amount=Ne:(ht.min_amount=Le,ht.max_amount=ct)),Ut&&qt&&(ht.max_quantity=sa),dt=await i(t.id,ht),de.pricingMode=dt.allow_custom_amount?"custom":"fixed",de.unitAmount=dt.unit_amount!=null?String(kt(dt.unit_amount,o)):"",de.minAmount=dt.min_amount!=null?String(kt(dt.min_amount,o)):"",de.maxAmount=dt.max_amount!=null?String(kt(dt.max_amount,o)):"",de.maxQuantity=String(dt.max_quantity)}else{let ht={name:x.trim(),allow_custom_amount:R==="custom",collect_shipping_address:me,active:V};T.trim()&&(ht.description=T.trim()),F.length>0&&(ht.images=F),R==="fixed"?(ht.unit_amount=Ne,ht.max_quantity=sa):(ht.min_amount=Le,ht.max_amount=ct),dt=await r(ht)}if(!v.current)return;Ue(dt.fulfillment),s?.(dt)}catch(dt){if(!v.current)return;u(dt instanceof Error?dt.message:"Failed to save product")}finally{v.current&&m(!1)}},et=async Ne=>{let Le=Ne.target.files?.[0];if(!(!Le||!t))try{fe(!0),U(null);let ct=await l(t.id,Le);if(!v.current)return;Ue(ct.fulfillment),s?.(ct)}catch(ct){if(!v.current)return;U(ct instanceof Error?ct.message:"Failed to upload file")}finally{v.current&&(fe(!1),Te.current&&(Te.current.value=""))}},Dt=async()=>{let Ne=lt.trim();if(!(!Ne||!t))try{fe(!0),U(null);let Le=await f(t.id,Ne);if(!v.current)return;Ue(Le.fulfillment),L(""),s?.(Le)}catch(Le){if(!v.current)return;U(Le instanceof Error?Le.message:"Failed to fetch file")}finally{v.current&&fe(!1)}};return(0,se.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{htmlFor:"product-name",children:"Name"}),(0,se.jsx)(oe,{id:"product-name",value:x,onChange:Ne=>k(Ne.target.value),placeholder:"My product"})]}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{htmlFor:"product-description",children:"Description"}),(0,se.jsx)("textarea",{id:"product-description",value:T,onChange:Ne=>h(Ne.target.value),rows:3,placeholder:"Shown on the Stripe checkout page.",className:"af-flex af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring"})]}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{children:"Pricing"}),b?(0,se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):(0,se.jsxs)(se.Fragment,{children:[(0,se.jsxs)(en,{value:R,onValueChange:Ne=>P(Ne),children:[(0,se.jsx)(Fa,{className:"af-w-[260px]",children:(0,se.jsx)(tn,{})}),(0,se.jsxs)(Ma,{children:[(0,se.jsx)(Rt,{value:"fixed",children:"Fixed price"}),(0,se.jsx)(Rt,{value:"custom",children:"Buyer chooses the amount"})]})]}),R==="fixed"?(0,se.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsxs)(Ve,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",o.toUpperCase(),")"]}),(0,se.jsx)(oe,{id:"product-price",type:"number",min:"0",step:c,value:D,onChange:Ne=>N(Ne.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsxs)(Ve,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",o.toUpperCase(),")"]}),(0,se.jsx)(oe,{id:"product-min-amount",type:"number",min:"0",step:c,value:E,onChange:Ne=>A(Ne.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsxs)(Ve,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",o.toUpperCase(),")"]}),(0,se.jsx)(oe,{id:"product-max-amount",type:"number",min:"0",step:c,value:C,onChange:Ne=>K(Ne.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Buyers pick their own amount within these bounds (tip jar, pay-what-you-want). Quantity is always 1."})]}),(0,se.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",o.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||R==="fixed")&&(0,se.jsxs)("div",{className:"af-space-y-1",children:[(0,se.jsx)(Ve,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,se.jsx)(oe,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:Q,onChange:Ne=>H(Ne.target.value),className:"af-w-[140px]"})]})]}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{children:"Images"}),(0,se.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,se.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[F.map(Ne=>(0,se.jsxs)(ie,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,se.jsx)("span",{className:"af-truncate",children:Ne}),(0,se.jsx)("button",{type:"button",onClick:()=>je(Ne),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:(0,se.jsx)(Ga.X,{className:"af-h-3 af-w-3"})})]},Ne)),F.length===0&&(0,se.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,se.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,se.jsx)(oe,{type:"url",value:pe,onChange:Ne=>He(Ne.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:Ne=>{Ne.key==="Enter"&&(Ne.preventDefault(),Re())},disabled:g}),(0,se.jsx)(y,{type:"button",variant:"outline",onClick:Re,disabled:!pe.trim()||g,children:(0,se.jsx)(Ga.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{children:"Digital File"}),(0,se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, Word, Excel, PowerPoint, CSV, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),d?(0,se.jsxs)("div",{className:"af-space-y-3",children:[Pe?.type==="download"&&(0,se.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,se.jsx)(Ga.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,se.jsx)("span",{className:"af-text-sm",children:Pe.filename}),Pe.size!=null&&(0,se.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",ku(Pe.size),")"]})]}),Pe?.type==="redirect"&&Pe.url&&(0,se.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,se.jsx)(Ga.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,se.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Pe.url]})]}),(0,se.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,se.jsx)("input",{ref:Te,type:"file",onChange:et,className:"af-hidden",disabled:ne}),(0,se.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>Te.current?.click(),disabled:ne,children:[ze?(0,se.jsx)(Ga.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,se.jsx)(Ga.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Pe?.type==="download"?"Replace file":"Upload file"]}),(0,se.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,se.jsx)(oe,{type:"url",value:lt,onChange:Ne=>L(Ne.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:ze}),(0,se.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:Dt,disabled:!lt.trim()||ne,children:"Fetch from URL"})]}),M&&(0,se.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:M})]}):(0,se.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsx)(Ve,{children:"Settings"}),(0,se.jsxs)("div",{className:"af-space-y-2",children:[(0,se.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,se.jsx)("input",{type:"checkbox",checked:me,onChange:Ne=>be(Ne.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,se.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,se.jsx)("input",{type:"checkbox",checked:V,onChange:Ne=>J(Ne.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),d&&t&&(0,se.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,se.jsx)(Ve,{children:"Options & Variants"}),(0,se.jsx)(Nr,{productId:t.id,currency:o})]}),p&&(0,se.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:p}),(0,se.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,se.jsxs)(y,{type:"button",onClick:wt,disabled:ne,children:[g?(0,se.jsx)(Ga.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?"Save changes":"Create product"]})})]})}var Qt=ce(require("react"),1),Ka=require("lucide-react");var At=ce(require("react"),1);var Cu=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function _r({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=W(),[s,n]=At.useState([]),[r,i]=At.useState(0),[l,f]=At.useState(!0),[d,o]=At.useState(null),[c,b]=At.useState(0),[g,m]=At.useState(e),[p,u]=At.useState(void 0),[v,x]=At.useState(""),[k,T]=At.useState(""),[h,R]=At.useState(""),[P,D]=At.useState(!1),[N,E]=At.useState(!1),[A,C]=At.useState(void 0),K=A?A.join(","):"",Q=At.useMemo(()=>{if(!K)return;let V=new Set(K.split(","));return Cu.filter(J=>!V.has(J))},[K]),H=At.useMemo(()=>{let V={};return p?V.status=p:Q?V.excludeStatus=Q:P||(V.excludeStatus=["pending","expired"]),v.trim()&&(V.customerEmail=v.trim()),k.trim()&&(V.from=k.trim()),h.trim()&&(V.to=h.trim()),N&&(V.unfulfilledOnly=!0),V},[p,Q,P,v,k,h,N]),de=At.useRef(0),me=At.useCallback(async()=>{let V=++de.current;try{f(!0),o(null);let J={...H,limit:g,offset:c*g},F=await a.getOrders(J);if(V!==de.current)return;n(F.orders),i(F.total)}catch(J){if(V!==de.current)return;o(J instanceof Error?J:new Error("Failed to fetch orders"))}finally{V===de.current&&f(!1)}},[a,c,g,H,t]);At.useEffect(()=>{me()},[me]);let be=Math.ceil(r/g);return{orders:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<be-1,hasPreviousPage:c>0,setPage:b,setPageSize:V=>{m(V),b(0)},status:p,setStatus:V=>{u(V),b(0)},statusIn:A,setStatusIn:V=>{C(V&&V.length>0?V:void 0),b(0)},customerEmail:v,setCustomerEmail:V=>{x(V),b(0)},from:k,setFrom:V=>{T(V),b(0)},to:h,setTo:V=>{R(V),b(0)},showAbandoned:P,setShowAbandoned:V=>{D(V),b(0)},unfulfilledOnly:N,setUnfulfilledOnly:V=>{E(V),b(0)},clearFilters:()=>{u(void 0),C(void 0),D(!1),E(!1),x(""),T(""),R(""),b(0)},filters:H,refetch:me}}var Ht=ce(require("react"),1),Ye=require("lucide-react");var Jl=ce(require("react"),1),Tn=ce(require("@radix-ui/react-popover"),1);var pi=require("react/jsx-runtime"),gi=Tn.Root,vi=Tn.Trigger;var Pr=Jl.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},n)=>(0,pi.jsx)(Tn.Portal,{children:(0,pi.jsx)("div",{className:"aifeatures-admin",children:(0,pi.jsx)(Tn.Content,{ref:n,align:t,sideOffset:a,className:X("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...s})})}));Pr.displayName=Tn.Content.displayName;var kr=require("react/jsx-runtime"),Tu={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Eu(e){return Tu[e]??e}function Xl(e){switch(e){case"paid":return"success";case"pending":return"secondary";case"refunded":case"partially_refunded":return"warning";case"disputed":return"destructive";default:return"outline"}}function gs({status:e,className:t}){return(0,kr.jsx)(ie,{variant:Xl(e),className:t,children:Eu(e)})}function ss({status:e}){return(0,kr.jsx)(gs,{status:e})}function Hs({order:e,className:t}){return e.line_items.some(a=>a.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,kr.jsx)(ie,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,kr.jsx)(ie,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function qn(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var w=require("react/jsx-runtime"),ac="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",vs="af-text-xs af-text-muted-foreground";function fo(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Iu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nc(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var bi=24,Du=["paid","partially_refunded"],Au=["paid","partially_refunded","disputed"],Lu=/^[A-Za-z0-9 _-]*$/,Ql=100;function go(e,t,a,s,n){let r=Du.includes(s);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${a} of ${bi} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${bi} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?a<bi&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:a<bi&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${a} attempt${a===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${s==="refunded"?"because the order was refunded":s==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function ec({title:e,recipient:t,status:a,attempts:s,side:n,orderStatus:r,action:i,delivery:l}){if(l)return(0,w.jsxs)("div",{children:[(0,w.jsx)(Pn,{deliveries:[l]}),i&&(0,w.jsx)("div",{className:"af-mt-2",children:i})]});let f=go(n,a,s,r,t);return(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,w.jsxs)("div",{className:"af-min-w-0",children:[(0,w.jsx)("div",{className:"af-text-sm",children:e}),t&&(0,w.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,w.jsx)(ie,{variant:f.variant,className:"af-shrink-0",children:f.label})]}),f.detail&&(0,w.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:f.detail}),i&&(0,w.jsx)("div",{className:"af-mt-2",children:i})]})}function tc(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=Iu(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}: ${nc(n)}`)}function Ou(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function vo({value:e,label:t,children:a,className:s,size:n="icon"}){let[r,i]=Ht.useState(!1);if(!Ou())return null;let l=async()=>{try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},f=r?(0,w.jsx)(Ye.Check,{className:"af-h-3 af-w-3"}):(0,w.jsx)(Ye.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,w.jsx)(y,{variant:"ghost",size:"icon",className:X("af-h-6 af-w-6 af-shrink-0",s),onClick:l,title:t,"aria-label":t,children:f}):(0,w.jsxs)(y,{variant:"outline",size:"sm",className:s,onClick:l,"aria-label":t,children:[r?(0,w.jsx)(Ye.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,w.jsx)(Ye.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":a]})}function mo({label:e,value:t}){return(0,w.jsxs)("div",{children:[(0,w.jsx)("div",{className:vs,children:e}),(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,w.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,w.jsx)(vo,{value:t,label:`Copy ${e}`})]})]})}function Bu({src:e}){let[t,a]=Ht.useState(!1);return!e||t?(0,w.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-10 af-w-10 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-muted",children:(0,w.jsx)(Ye.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,w.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>a(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function En({title:e,action:t,children:a,className:s}){return(0,w.jsxs)("section",{className:X("af-rounded-lg af-border af-p-4",s),children:[(0,w.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,w.jsx)("h4",{className:ac,children:e}),t]}),(0,w.jsx)("div",{className:"af-mt-3",children:a})]})}function ka({label:e,emphasis:t,divider:a,children:s}){return(0,w.jsxs)("div",{className:X("af-flex af-items-baseline af-justify-between af-gap-6",a&&"af-mt-2 af-border-t af-pt-2"),children:[(0,w.jsx)("span",{className:t?"af-text-base af-font-semibold":vs,children:e}),(0,w.jsx)("span",{className:X("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function po({onSelect:e,disabled:t,icon:a,children:s}){return(0,w.jsxs)(y,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,w.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function Fu(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?t.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${ee(fi(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),s=a?li(a):go("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),s=a?li(a):go("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${ee(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function Cr({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:n=!1,onPrevOrder:r,onNextOrder:i,hasPrevOrder:l=!1,hasNextOrder:f=!1}){let{api:d}=W(),[o,c]=Ht.useState(e),[b,g]=Ht.useState(null),[m,p]=Ht.useState(null),[u,v]=Ht.useState(!1),[x,k]=Ht.useState(!1),[T,h]=Ht.useState(!1),[R,P]=Ht.useState(!1),[D,N]=Ht.useState(""),[E,A]=Ht.useState(!1),[C,K]=Ht.useState(null),[Q,H]=Ht.useState(!1),[de,me]=Ht.useState(""),[be,V]=Ht.useState([]),[J,F]=Ht.useState(!1),[ge,pe]=Ht.useState(!1),[He,Pe]=Ht.useState(null);Ht.useEffect(()=>{c(e)},[e]);let Ue=$=>{let nt=$.id===o.id&&$.email_deliveries===void 0?{...$,email_deliveries:o.email_deliveries}:$;c(nt),s?.(nt)},ze=Object.entries(o.metadata??{}),fe=Math.max(0,fi(o)-o.amount_refunded),lt=(o.status==="paid"||o.status==="partially_refunded")&&fe>0,L=o.exclusive_tax_total!=null,M=$=>typeof $.amountNet=="number"?$.amountNet+($.exclusiveTax??0):(typeof $.unitAmount=="number"?$.unitAmount:0)*(typeof $.quantity=="number"&&$.quantity>0?$.quantity:1),U=Math.max(0,(o.shipping_total??0)-(o.shipping_refunded??0)),Te=be.reduce(($,nt)=>$+M(o.line_items[nt]??{}),0)+(J?U:0),ne=o.tax_total??0,Re=Math.max(0,(o.exclusive_tax_total??0)-o.line_items.reduce(($,nt)=>$+(nt.exclusiveTax??0),0)),je=L?J&&U>0?Re:0:o.automatic_tax&&o.tax_behavior==="exclusive"&&ne>0&&o.amount_total+(o.shipping_total??0)>0?Math.min(Math.max(0,ne-(o.tax_refunded??0)),Math.round(ne*Te/(o.amount_total+(o.shipping_total??0)))):0,wt=o.source==="subscription"&&(o.credit_applied??0)>0&&o.line_items.length===1?Math.min(Te+je,fe):Te+je,et=be.length>0||J,Dt=et?wt:ia(de,o.currency),Ne=Wa(o.currency)?"1":"0.01",Le=async()=>{try{v(!0),g(null),p(null),await d.resendOrderReceipt(o.id);let $=await d.getOrder(o.id);Ue($),p("Receipt email queued.")}catch($){g($ instanceof Error?$.message:"Failed to resend receipt")}finally{v(!1)}},ct=async()=>{try{k(!0),g(null),p(null);let $=await d.resetOrderDownloads(o.id);Ue($),h(!1),p("Download count reset.")}catch($){g($ instanceof Error?$.message:"Failed to reset downloads")}finally{k(!1)}},at=o.line_items.some($=>$.collectShippingAddress===!0&&!$.refunded&&!$.unavailableReason),qt=typeof o.merchant_fulfilled_at=="string",Ut=Au.includes(o.status)||o.status==="refunded"&&o.line_items.some($=>$.collectShippingAddress===!0&&$.amountNet===0&&!$.refunded&&!$.unavailableReason),sa=D.trim(),dt=Lu.test(sa)&&sa.length<=Ql,ht=async $=>{try{A(!0),K(null),p(null);let nt=await d.setOrderFulfillment(o.id,{fulfilled:$,...$&&sa?{trackingNumber:sa}:{}});Ue(nt),N(""),p($?"Marked as shipped.":"Marked as not shipped.")}catch(nt){nt instanceof jt&&nt.status===409?K(`This order is ${o.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):K(nt instanceof Error?nt.message:"Failed to update the order")}finally{A(!1)}},ke=()=>{Pe(null),me(String(kt(fe,o.currency))),V([]),F(!1),H(!0)},ut=$=>V(nt=>nt.includes($)?nt.filter(_a=>_a!==$):[...nt,$]),tt=async($,nt)=>{if(a)try{pe(!0),Pe(null),await a(o,$,nt);let _a=await d.getOrder(o.id);Ue(_a),H(!1),p("Refund issued.")}catch(_a){Pe(_a instanceof Error?_a.message:"Refund failed")}finally{pe(!1)}},St=async()=>{if(et){if(wt<=0){Pe("The lines you picked were charged nothing");return}if(wt>fe){Pe(`That selection exceeds the refundable remainder (${ee(fe,o.currency)})`);return}await tt(wt,{...be.length>0?{line_items:[...be].sort((nt,_a)=>nt-_a)}:{},...J?{shipping:!0}:{}});return}let $=ia(de,o.currency);if($===null||$<=0){Pe("Enter a valid refund amount");return}if($>fe){Pe(`Amount exceeds the refundable remainder (${ee(fe,o.currency)})`);return}await tt($,{amount:$})},z=()=>tt(fe,{full:!0}),Xe=!o.subscription_history_only&&o.fulfillment_type==="download",ra=!o.subscription_history_only&&n&&at,Ms=Fu(o),re=o.shipping_address?tc(o.shipping_address).join(`
|
|
4
|
+
`):"",ya=o.shipping_total!=null,no=o.exclusive_tax_total??(o.automatic_tax&&o.tax_behavior==="exclusive"?o.tax_total??0:0),vl=o.exclusive_tax_total!=null?Math.max(0,(o.tax_total??0)-no):o.automatic_tax&&o.tax_behavior==="exclusive"?0:o.tax_total??0,bl=no>0,Yd=vl>0,hl=o.amount_subtotal!=null||ya||bl||(o.discount_total??0)>0,sr=[];return o.subscription_history_only||sr.push((0,w.jsx)(po,{icon:u?(0,w.jsx)(Ye.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,w.jsx)(Ye.Mail,{className:"af-h-4 af-w-4"}),disabled:u||o.fulfillment_status!=="fulfilled",onSelect:()=>{P(!1),Le()},children:"Resend receipt"},"resend")),Xe&&sr.push((0,w.jsx)(po,{icon:(0,w.jsx)(Ye.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{P(!1),h(!0)},children:"Reset download count"},"reset")),lt&&sr.push((0,w.jsxs)("div",{children:[(0,w.jsx)(po,{icon:(0,w.jsx)(Ye.Undo2,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{P(!1),ke()},children:"Refund\u2026"}),!a&&(0,w.jsx)("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"af-mb-6",children:[(0,w.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,w.jsx)(Ye.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,w.jsxs)("div",{className:"af-min-w-0",children:[(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)("h3",{className:"af-text-xl af-font-semibold",children:qn(o)}),(0,w.jsx)(gs,{status:o.status}),n&&!o.subscription_history_only&&(0,w.jsx)(Hs,{order:o}),o.is_test&&(0,w.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,w.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",fo(o.created_at)]}),o.is_test&&(0,w.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||i)&&(0,w.jsxs)("div",{className:"af-flex af-items-center",children:[(0,w.jsx)(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!l,"aria-label":"Previous order",children:(0,w.jsx)(Ye.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,w.jsx)(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:i,disabled:!f,"aria-label":"Next order",children:(0,w.jsx)(Ye.ChevronRight,{className:"af-h-4 af-w-4"})})]}),ra&&(qt?(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,w.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",o.merchant_fulfilled_at?` \xB7 ${fo(o.merchant_fulfilled_at)}`:""]}),Ut&&(0,w.jsxs)(y,{variant:"ghost",size:"sm",onClick:()=>ht(!1),disabled:E,children:[E?(0,w.jsx)(Ye.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,w.jsx)(Ye.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Ut?(0,w.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,w.jsx)(oe,{value:D,onChange:$=>N($.target.value),placeholder:"Tracking number (optional)",maxLength:Ql,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:E}),(0,w.jsxs)(y,{variant:"default",className:"af-shrink-0",onClick:()=>ht(!0),disabled:E||!dt,children:[E?(0,w.jsx)(Ye.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,w.jsx)(Ye.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),sr.length>0&&(0,w.jsxs)(gi,{open:R,onOpenChange:P,children:[(0,w.jsx)(vi,{asChild:!0,children:(0,w.jsx)(y,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,w.jsx)(Ye.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,w.jsx)(Pr,{children:(0,w.jsx)("div",{className:"af-space-y-0.5",children:sr})})]})]})]}),ra&&!qt&&!dt&&(0,w.jsx)("p",{className:"af-mt-2 af-text-xs af-text-destructive",children:"Tracking numbers can use letters, numbers, spaces, dashes and underscores \u2014 up to 100 characters."}),C&&(0,w.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:C}),m&&(0,w.jsx)("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:m}),b&&(0,w.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:b})]}),(0,w.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,w.jsxs)("div",{className:"af-space-y-6",children:[o.line_items.length>0&&(0,w.jsx)(En,{title:"Items",children:(0,w.jsx)("ul",{className:"af-space-y-3",children:o.line_items.map(($,nt)=>{let _a=typeof $.name=="string"&&$.name?$.name:"Item",yl=typeof $.quantity=="number"&&$.quantity>0?$.quantity:1,xl=typeof $.unitAmount=="number";return(0,w.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,w.jsx)(Bu,{src:typeof $.imageUrl=="string"&&$.imageUrl?$.imageUrl:void 0}),(0,w.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,w.jsxs)("div",{className:"af-text-sm af-font-medium",children:[_a,typeof $.variantTitle=="string"&&$.variantTitle&&(0,w.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",$.variantTitle]})]}),(0,w.jsxs)("div",{className:vs,children:[yl," \xD7"," ",xl?ee($.unitAmount,o.currency):"\u2014"]}),$.unavailableReason==="oversold"&&!$.refunded&&(0,w.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:$.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),$.refunded===!0&&(0,w.jsx)(ie,{variant:"secondary",className:"af-mt-1",children:$.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,w.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof $.amountNet=="number"||xl?ee($.amountNet??$.unitAmount*yl,o.currency):"\u2014"})]},nt)})})}),ze.length>0&&(0,w.jsx)(En,{title:"Order details",children:(0,w.jsx)("dl",{className:"af-space-y-2",children:ze.map(([$,nt])=>(0,w.jsxs)("div",{children:[(0,w.jsx)("dt",{className:X(vs,"af-capitalize"),children:$.replace(/_/g," ")}),(0,w.jsx)("dd",{className:"af-text-sm af-break-words",children:nc(nt)})]},$))})}),(0,w.jsx)(En,{title:"Totals",children:(0,w.jsxs)("div",{className:"af-w-full",children:[hl&&(0,w.jsx)(ka,{label:"Subtotal",children:ee(o.amount_subtotal??o.amount_total+(o.discount_total??0),o.currency)}),(o.discount_total??0)>0&&(0,w.jsxs)(ka,{label:"Discount",children:["\u2212",ee(o.discount_total,o.currency)]}),ya&&(0,w.jsx)(ka,{label:"Shipping",children:o.shipping_total===0?"Free":ee(o.shipping_total??0,o.currency)}),bl&&(0,w.jsx)(ka,{label:"Tax",children:ee(no,o.currency)}),(0,w.jsx)(ka,{label:"Total",emphasis:!0,divider:hl,children:ee(Cn(o),o.currency)}),(o.credit_applied??0)>0&&(0,w.jsxs)(ka,{label:"Credit applied",children:["\u2212",ee(o.credit_applied,o.currency)]}),o.amount_paid!=null&&(0,w.jsx)(ka,{label:"Amount paid",children:ee(o.amount_paid,o.currency)}),Yd&&(0,w.jsx)(ka,{label:"incl. tax",children:ee(vl,o.currency)}),o.base_currency!=null&&o.base_amount_total!=null&&(0,w.jsxs)(ka,{label:"Your price",children:[ee(o.base_amount_total,o.base_currency),(0,w.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",o.currency.toUpperCase()]})]}),o.amount_refunded>0&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(ka,{label:"Refunded",children:["\u2212",ee(o.amount_refunded,o.currency),(o.shipping_refunded??0)>0&&(0,w.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",ee(o.shipping_refunded??0,o.currency)," ","shipping"]})]}),(0,w.jsx)(ka,{label:"Net",children:(0,w.jsx)("span",{className:"af-font-medium",children:ee(Math.max(0,fi(o)-o.amount_refunded),o.currency)})})]})]})}),o.application_fee_state&&(0,w.jsxs)(En,{title:"Platform fee",children:[o.application_fee_original!=null&&(0,w.jsx)(ka,{label:"Collected",children:ee(o.application_fee_original,o.application_fee_currency??o.currency)}),o.application_fee_returned!=null&&(0,w.jsx)(ka,{label:"Returned",children:ee(o.application_fee_returned,o.application_fee_currency??o.currency)}),o.application_fee_retained!=null&&(0,w.jsx)(ka,{label:"Retained",children:ee(o.application_fee_retained,o.application_fee_currency??o.currency)}),o.application_fee_state!=="complete"&&(0,w.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:o.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,w.jsx)(En,{title:"Timeline",children:(0,w.jsx)("ol",{className:"af-space-y-3",children:Ms.map($=>(0,w.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,w.jsx)("span",{"aria-hidden":"true",className:X("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",$.tone==="destructive"?"af-bg-destructive":$.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,w.jsxs)("div",{className:"af-min-w-0",children:[(0,w.jsx)("div",{className:"af-text-sm af-break-words",children:$.text}),$.at&&(0,w.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:fo($.at)})]})]},$.key))})})]}),(0,w.jsxs)("div",{className:"af-space-y-6",children:[(0,w.jsx)(En,{title:"Customer",children:(0,w.jsxs)("div",{className:"af-space-y-2",children:[(0,w.jsxs)("div",{children:[(0,w.jsx)("div",{className:vs,children:"Email"}),(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,w.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:o.customer_email||(0,w.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),o.customer_email&&(0,w.jsx)(vo,{value:o.customer_email,label:"Copy email"})]})]}),o.customer_name&&(0,w.jsxs)("div",{children:[(0,w.jsx)("div",{className:vs,children:"Name"}),(0,w.jsx)("div",{className:"af-text-sm",children:o.customer_name})]}),o.customer&&(0,w.jsxs)("div",{children:[(0,w.jsx)("div",{className:vs,children:"Customer record"}),(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)("span",{className:"af-break-all af-text-sm",children:o.customer.name||o.customer.email}),(0,w.jsx)(ie,{variant:"secondary",children:"Linked"})]})]})]})}),o.shipping_address&&(0,w.jsx)(En,{title:"Ship to",action:(0,w.jsx)(vo,{value:re,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,w.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:tc(o.shipping_address).map(($,nt)=>(0,w.jsx)("div",{children:$},nt))})}),o.subscription_history_only?(0,w.jsx)(En,{title:"Subscription history",children:(0,w.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This renewal had no payment due. No items were fulfilled and no purchase receipt was sent."})}):(0,w.jsxs)(En,{title:"Emails",children:[(0,w.jsx)(Pn,{deliveries:o.email_deliveries?.filter($=>!["purchase_receipt","merchant_sale"].includes($.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,w.jsxs)("div",{className:"af-space-y-4",children:[(0,w.jsx)(ec,{side:"buyer",title:"Receipt to buyer",delivery:o.email_deliveries?.find($=>$.kind==="purchase_receipt"),recipient:o.customer_email,status:o.buyer_email_status,attempts:o.buyer_email_attempts,orderStatus:o.status,action:(0,w.jsxs)(y,{variant:"outline",size:"sm",onClick:Le,disabled:u||o.fulfillment_status!=="fulfilled",children:[u?(0,w.jsx)(Ye.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,w.jsx)(Ye.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,w.jsx)(ec,{side:"merchant",title:"Sale alert to you",delivery:o.email_deliveries?.find($=>$.kind==="merchant_sale"),recipient:null,status:o.merchant_email_status,attempts:o.merchant_email_attempts,orderStatus:o.status})]})]}),Xe&&(0,w.jsx)(En,{title:"Download",children:(0,w.jsxs)("div",{className:"af-space-y-2",children:[(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,w.jsx)(Ye.Download,{className:"af-h-4 af-w-4"}),(0,w.jsxs)("span",{children:["Downloaded ",o.download_count," time",o.download_count===1?"":"s"]})]}),o.download_url&&(0,w.jsx)("a",{href:o.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,w.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,w.jsx)("summary",{className:X(ac,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,w.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,w.jsx)(mo,{label:"Order ID",value:o.id}),o.stripe_checkout_session_id&&(0,w.jsx)(mo,{label:"Checkout session",value:o.stripe_checkout_session_id}),o.stripe_payment_intent_id&&(0,w.jsx)(mo,{label:"Payment",value:o.stripe_payment_intent_id})]})]})]})]}),(0,w.jsx)(an,{open:T,onOpenChange:$=>{!$&&!x&&h(!1)},children:(0,w.jsxs)(Ua,{children:[(0,w.jsxs)($a,{children:[(0,w.jsx)(Ha,{children:"Reset download count?"}),(0,w.jsx)(za,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,w.jsxs)(Va,{children:[(0,w.jsx)(y,{variant:"outline",onClick:()=>h(!1),disabled:x,children:"Cancel"}),(0,w.jsx)(y,{onClick:ct,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),(0,w.jsx)(an,{open:Q,onOpenChange:$=>{!$&&!ge&&H(!1)},children:(0,w.jsxs)(Ua,{children:[(0,w.jsxs)($a,{children:[(0,w.jsx)(Ha,{children:"Refund order"}),(0,w.jsxs)(za,{children:["Refund up to ",ee(fe,o.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,w.jsxs)("div",{className:"af-space-y-4",children:[(o.line_items.length>0||U>0)&&(0,w.jsxs)("div",{className:"af-space-y-2",children:[(0,w.jsx)(Ve,{children:"Items"}),(0,w.jsxs)("div",{className:"af-space-y-2",children:[o.line_items.map(($,nt)=>{let _a=$.refunded===!0;return(0,w.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,w.jsx)("input",{type:"checkbox",checked:be.includes(nt),onChange:()=>ut(nt),disabled:ge||_a||!!$.unavailableReason||M($)<=0,className:"af-h-4 af-w-4"}),(0,w.jsxs)("span",{className:_a?"af-text-muted-foreground af-line-through":void 0,children:[typeof $.name=="string"&&$.name?$.name:"Item",typeof $.variantTitle=="string"&&$.variantTitle?` \u2014 ${$.variantTitle}`:"",typeof $.quantity=="number"&&$.quantity>1?` \xD7 ${$.quantity}`:""]}),(0,w.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:_a?"Refunded":ee(M($),o.currency)})]},nt)}),U>0&&(0,w.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,w.jsx)("input",{type:"checkbox",checked:J,onChange:$=>F($.target.checked),disabled:ge,className:"af-h-4 af-w-4"}),(0,w.jsx)("span",{children:"Shipping"}),(0,w.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:ee(U,o.currency)})]})]})]}),(0,w.jsxs)("div",{className:"af-space-y-2",children:[(0,w.jsxs)(Ve,{htmlFor:"refund-amount",children:["Amount (",o.currency.toUpperCase(),")"]}),(0,w.jsx)(oe,{id:"refund-amount",type:"number",min:"0",step:Ne,value:et?String(kt(wt,o.currency)):de,onChange:$=>me($.target.value),disabled:ge||et}),et&&(0,w.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),He&&(0,w.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:He}),(0,w.jsxs)(Va,{children:[(0,w.jsx)(y,{variant:"outline",onClick:()=>H(!1),disabled:ge,children:"Cancel"}),(0,w.jsx)(y,{variant:"outline",onClick:z,disabled:ge,children:"Refund everything"}),(0,w.jsx)(y,{variant:"destructive",onClick:St,disabled:ge,children:ge?"Refunding...":Dt!==null&&Dt>0?`Refund ${ee(Dt,o.currency)}`:"Refund"})]})]})})]})}var hi=ce(require("react"),1),yi=require("lucide-react");var Tt=require("react/jsx-runtime");function Lt({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:n}){let r=hi.useRef(null);return hi.useEffect(()=>{r.current?.focus()},[]),(0,Tt.jsxs)("div",{className:X("af-bg-background",n),children:[(0,Tt.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,Tt.jsx)("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!a&&(0,Tt.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,Tt.jsx)(yi.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,Tt.jsx)("div",{className:"af-p-4",children:s})]})}function ae({className:e}){return(0,Tt.jsx)("div",{"aria-hidden":"true",className:X("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function gt({label:e,children:t,detail:a,valueClassName:s}){return(0,Tt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,Tt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,Tt.jsx)("div",{className:X("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&(0,Tt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function Et({message:e,onRetry:t}){return(0,Tt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Tt.jsx)("span",{children:e}),(0,Tt.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,Tt.jsx)(yi.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function va({icon:e,children:t}){return(0,Tt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,Tt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function zs({icon:e,heading:t,body:a,action:s,className:n,children:r}){return(0,Tt.jsxs)("div",{className:X("af-px-6 af-py-10 af-text-center",n),children:[(0,Tt.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,Tt.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,Tt.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&(0,Tt.jsx)(y,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}var O=require("react/jsx-runtime"),Mu={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},sc={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 ic(e){let t=Array.isArray(e.line_items)?e.line_items:[],a=t[0];if(!a)return"\u2014";let s=typeof a.name=="string"&&a.name?a.name:"Item",n=typeof a.quantity=="number"&&a.quantity>0?a.quantity:1,r=n>1?`${s} \xD7${n}`:s;return t.length>1?`${r} +${t.length-1} more`:r}function xi(e){return e.customer?.name||e.customer_name||null}function Uu({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:n=!1,emptyMessage:r,onDetailOpenChange:i,maxRows:l,onViewAll:f}){let d=typeof l=="number",{api:o}=W(),c=_r({refreshKey:a}),{orders:b,total:g,isLoading:m,error:p,page:u,pageSize:v,hasNextPage:x,hasPreviousPage:k,setPage:T,setPageSize:h,customerEmail:R,setCustomerEmail:P,setStatusIn:D,from:N,setFrom:E,to:A,setTo:C,showAbandoned:K,setShowAbandoned:Q,setUnfulfilledOnly:H,filters:de,refetch:me}=c,be=Qt.useCallback(()=>o.exportOrdersCsv(de),[o,de]),[V,J]=Qt.useState("list"),[F,ge]=Qt.useState(null),[pe,He]=Qt.useState(""),[Pe,Ue]=Qt.useState(""),[ze,fe]=Qt.useState(!d&&n?"needs_shipping":"all"),[lt,L]=Qt.useState(!1),[M,U]=Qt.useState(!!s&&!d),[Te,ne]=Qt.useState(null);Qt.useEffect(()=>{if(!s||d)return;let re=!1;return U(!0),ne(null),o.getOrder(s).then(ya=>{re||(ge(ya),J("detail"))}).catch(()=>{re||ne("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{re||U(!1)}),()=>{re=!0}},[o,s,d]);let Re=Qt.useCallback(re=>{fe(re);let ya=sc[re];D(ya.statusIn),H(ya.unfulfilledOnly)},[D,H]);Qt.useEffect(()=>{n&&!d&&H(!0)},[]);let je=Qt.useRef(!n);Qt.useEffect(()=>{je.current||m||(je.current=!0,b.length===0&&Re("all"))},[m,b.length,Re]);let wt=V==="detail"&&!!F;Qt.useEffect(()=>{i?.(wt)},[wt,i]);let et=(N?1:0)+(A?1:0)+(K?1:0),Dt=et>0||!!R||!!Pe,Ne=!!N&&!!A&&N>A,Le=!d||!!f,ct=re=>{if(d){f?.();return}ge(re),J("detail")},at=()=>{J("list"),ge(null),me()},qt=re=>{let ya=re.trim();if(!ya){Ue(""),R&&P("");return}if(ya.startsWith("#")||/^\d+$/.test(ya)){Ue(ya),R&&P("");return}Ue(""),P(ya)},Ut=()=>{He(""),Ue(""),P(""),E(""),C(""),Q(!1),L(!1)},sa=Pe.replace(/^#/,"").toLowerCase(),dt=sa?b.filter(re=>String(re.order_number??"")===sa||re.id.toLowerCase().startsWith(sa)):b,ht=d?dt.slice(0,l):dt,ke=F?b.findIndex(re=>re.id===F.id):-1,ut=ke>0,tt=ke>=0&&ke<b.length-1;if(M)return(0,O.jsx)("div",{className:t,children:(0,O.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,O.jsx)(Ka.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(V==="detail"&&F)return(0,O.jsx)("div",{className:t,children:(0,O.jsx)(Cr,{order:F,onBack:at,onRefund:e,onOrderUpdated:re=>ge(re),allowFulfillment:n,onPrevOrder:ut?()=>ge(b[ke-1]):void 0,onNextOrder:tt?()=>ge(b[ke+1]):void 0,hasPrevOrder:ut,hasNextOrder:tt},F.id)});let z=(0,O.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[Te&&(0,O.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:Te}),(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,O.jsx)("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(re=>(0,O.jsx)("button",{type:"button","aria-pressed":ze===re,onClick:()=>Re(re),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",ze===re?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Mu[re]},re))}),(0,O.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,O.jsx)(Ka.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,O.jsx)(oe,{type:"text",value:pe,onChange:re=>He(re.target.value),onBlur:()=>qt(pe),onKeyDown:re=>{re.key==="Enter"&&(re.preventDefault(),qt(pe))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,O.jsxs)(y,{type:"button",variant:et>0?"secondary":"ghost",size:"sm",onClick:()=>L(re=>!re),"aria-expanded":lt,children:[(0,O.jsx)(Ka.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",et>0&&(0,O.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:et})]}),Dt&&(0,O.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:Ut,children:"Clear filters"}),(0,O.jsx)(da,{fetchCsv:be,filename:"orders",disabled:!!Pe,className:"af-ml-auto"})]}),(lt||!!N||!!A)&&(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2",children:[(0,O.jsx)(Ve,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,O.jsx)(oe,{id:"orders-from",type:"date",value:N,max:A||void 0,onChange:re=>E(re.target.value),className:"af-w-[170px]"}),(0,O.jsx)(Ve,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,O.jsx)(oe,{id:"orders-to",type:"date",value:A,min:N||void 0,onChange:re=>C(re.target.value),className:"af-w-[170px]"}),!sc[ze].statusIn&&(0,O.jsx)(y,{type:"button",variant:K?"secondary":"ghost",size:"sm",onClick:()=>Q(!K),"aria-pressed":K,children:K?"Hide abandoned":"Show abandoned"})]}),Ne&&(0,O.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(m)return(0,O.jsxs)("div",{className:t,children:[d?null:z,(0,O.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(re=>(0,O.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)(ae,{className:"af-h-4 af-w-16"}),(0,O.jsx)(ae,{className:"af-h-4 af-w-14"})]}),(0,O.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-40"}),(0,O.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-24"})]},re))}),(0,O.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,O.jsxs)(ft,{children:[(0,O.jsx)(mt,{children:(0,O.jsxs)(Fe,{children:[(0,O.jsx)(Z,{children:"Order"}),(0,O.jsx)(Z,{children:"Date"}),(0,O.jsx)(Z,{children:"Customer"}),(0,O.jsx)(Z,{children:"Items"}),(0,O.jsx)(Z,{className:"af-text-right",children:"Total"}),(0,O.jsx)(Z,{children:"Status"}),(0,O.jsx)(Z,{className:"af-w-8"})]})}),(0,O.jsx)(pt,{"aria-hidden":"true",children:[0,1,2,3,4].map(re=>(0,O.jsxs)(Fe,{children:[(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-4 af-w-14"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-4 af-w-40"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-4 af-w-32"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,O.jsx)(Y,{children:(0,O.jsx)(ae,{className:"af-h-5 af-w-16"})}),(0,O.jsx)(Y,{})]},re))})]})}),(0,O.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(p)return(0,O.jsxs)("div",{className:t,children:[d?null:z,(0,O.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,O.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,O.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>me(),children:"Try again"})]})]});let Xe=ze!=="all";if(dt.length===0&&u===0)return Dt||Xe?(0,O.jsxs)("div",{className:t,children:[!d&&z,(0,O.jsx)(va,{children:"No orders match these filters."})]}):(0,O.jsx)("div",{className:t,children:(0,O.jsx)(zs,{icon:Ka.Receipt,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!d&&(0,O.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>Q(!0),children:"Show abandoned checkouts"})})});let ra=u*v+1,Ms=Math.min((u+1)*v,g);return(0,O.jsxs)("div",{className:t,children:[d?null:z,(0,O.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ht.map(re=>(0,O.jsxs)("button",{type:"button",onClick:()=>ct(re),disabled:!Le,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Le?" hover:af-bg-muted/50":""}`,children:[(0,O.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,O.jsx)("span",{className:"af-font-medium",children:qn(re)}),(0,O.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:ee(Cn(re),re.currency)})]}),(0,O.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,O.jsxs)("div",{className:"af-truncate af-text-sm",children:[re.customer_email||(0,O.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),xi(re)&&(0,O.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",xi(re)]})]}),(0,O.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ic(re)}),re.amount_refunded>0&&(0,O.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",ee(re.amount_refunded,re.currency)," refunded"]})]}),(0,O.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,O.jsx)(gs,{status:re.status}),(0,O.jsx)(dr,{deliveries:re.email_deliveries}),re.is_test&&(0,O.jsx)(ie,{variant:"outline",children:"Test"}),n&&(0,O.jsx)(Hs,{order:re}),(0,O.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:rc(re.created_at)})]})]},re.id))}),(0,O.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,O.jsxs)(ft,{children:[(0,O.jsx)(mt,{children:(0,O.jsxs)(Fe,{children:[(0,O.jsx)(Z,{children:"Order"}),(0,O.jsx)(Z,{children:"Date"}),(0,O.jsx)(Z,{children:"Customer"}),(0,O.jsx)(Z,{children:"Items"}),(0,O.jsx)(Z,{className:"af-text-right",children:"Total"}),(0,O.jsx)(Z,{children:"Status"}),(0,O.jsx)(Z,{className:"af-w-8"})]})}),(0,O.jsx)(pt,{children:ht.map(re=>(0,O.jsxs)(Fe,{onClick:Le?()=>ct(re):void 0,className:Le?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,O.jsxs)(Y,{className:"af-whitespace-nowrap af-font-medium",children:[(0,O.jsx)("button",{type:"button",onClick:ya=>{ya.stopPropagation(),ct(re)},disabled:!Le,"aria-label":`Open order ${qn(re)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Le?" hover:af-underline":""}`,children:qn(re)}),re.is_test&&(0,O.jsx)(ie,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,O.jsx)(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rc(re.created_at)}),(0,O.jsxs)(Y,{className:"af-max-w-[220px]",children:[(0,O.jsx)("div",{className:"af-truncate",children:re.customer_email||(0,O.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),xi(re)&&(0,O.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:xi(re)})]}),(0,O.jsx)(Y,{className:"af-max-w-[220px]",children:(0,O.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:ic(re)})}),(0,O.jsxs)(Y,{className:"af-whitespace-nowrap af-text-right",children:[(0,O.jsx)("div",{className:"af-font-medium af-tabular-nums",children:ee(Cn(re),re.currency)}),re.amount_refunded>0&&(0,O.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",ee(re.amount_refunded,re.currency)," ","refunded"]})]}),(0,O.jsx)(Y,{children:(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,O.jsx)(gs,{status:re.status}),(0,O.jsx)(dr,{deliveries:re.email_deliveries}),n&&(0,O.jsx)(Hs,{order:re})]})}),(0,O.jsx)(Y,{className:"af-w-8 af-text-right",children:(0,O.jsx)(Ka.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},re.id))})]})}),d?null:(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,O.jsx)("span",{children:sa?`${dt.length} matching this page`:`Showing ${ra}-${Ms} of ${g}`}),(0,O.jsxs)(en,{value:String(v),onValueChange:re=>h(Number(re)),children:[(0,O.jsx)(Fa,{className:"af-w-[70px] af-h-8",children:(0,O.jsx)(tn,{})}),(0,O.jsxs)(Ma,{children:[(0,O.jsx)(Rt,{value:"10",children:"10"}),(0,O.jsx)(Rt,{value:"25",children:"25"}),(0,O.jsx)(Rt,{value:"50",children:"50"}),(0,O.jsx)(Rt,{value:"100",children:"100"})]})]}),(0,O.jsx)("span",{children:"per page"})]}),(0,O.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,O.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>T(u-1),disabled:!k,children:[(0,O.jsx)(Ka.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,O.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>T(u+1),disabled:!x,children:["Next",(0,O.jsx)(Ka.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function jn(e){return(0,O.jsx)(Uu,{...e},e.maxRows==null?"full":"compact")}var qs=ce(require("react"),1),In=require("lucide-react");var Ca=ce(require("react"),1);function Tr({initialPageSize:e=25}={}){let{api:t}=W(),[a,s]=Ca.useState([]),[n,r]=Ca.useState(0),[i,l]=Ca.useState(!0),[f,d]=Ca.useState(null),[o,c]=Ca.useState(0),[b,g]=Ca.useState(e),[m,p]=Ca.useState(""),u=Ca.useRef(0),v=Ca.useCallback(async()=>{let k=++u.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!==u.current)return;s(h.customers),r(h.total)}catch(T){if(k!==u.current)return;d(T instanceof Error?T:new Error("Failed to fetch customers"))}finally{k===u.current&&l(!1)}},[t,o,b,m]);Ca.useEffect(()=>{v()},[v]);let x=Math.ceil(n/b);return{customers:a,total:n,isLoading:i,error:f,page:o,pageSize:b,hasNextPage:o<x-1,hasPreviousPage:o>0,setPage:c,setPageSize:k=>{g(k),c(0)},email:m,setEmail:k=>{p(k),c(0)},refetch:v}}var bs=ce(require("react"),1),wi=require("lucide-react");var Ie=require("react/jsx-runtime");function oc(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 $u(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let a=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return a&&t.push(a),e.country&&t.push(e.country),t}function Er({customer:e,onBack:t,className:a}){let{api:s}=W(),[n,r]=bs.useState(null),[i,l]=bs.useState([]),[f,d]=bs.useState(!0),[o,c]=bs.useState(null);bs.useEffect(()=>{let m=!1;return d(!0),c(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([p,u])=>{m||(r(p),l(u.orders))}).catch(p=>{m||c(p instanceof Error?p.message:"Failed to load customer")}).finally(()=>{m||d(!1)}),()=>{m=!0}},[s,e.id,e.email]);let b=n?.addresses??[],g=n?.order_count??i.length;return(0,Ie.jsxs)("div",{className:a,children:[(0,Ie.jsxs)("div",{className:"af-mb-6",children:[(0,Ie.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,Ie.jsx)(wi.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,Ie.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,Ie.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",oc(e.created_at)]})]}),f?(0,Ie.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,Ie.jsx)(wi.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):o?(0,Ie.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o}):(0,Ie.jsxs)("div",{className:"af-space-y-6",children:[(0,Ie.jsx)(Pn,{deliveries:n?.email_deliveries}),(0,Ie.jsxs)("div",{children:[(0,Ie.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,Ie.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,Ie.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ie.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,Ie.jsx)("span",{children:e.email})]}),e.name&&(0,Ie.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ie.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,Ie.jsx)("span",{children:e.name})]}),e.phone&&(0,Ie.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ie.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,Ie.jsx)("span",{children:e.phone})]}),(0,Ie.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ie.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,Ie.jsx)("span",{children:g})]})]})]}),b.length>0&&(0,Ie.jsxs)("div",{children:[(0,Ie.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,Ie.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(m=>(0,Ie.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[m.is_default&&(0,Ie.jsx)(ie,{variant:"secondary",className:"af-mb-1",children:"Default"}),$u(m).map((p,u)=>(0,Ie.jsx)("div",{children:p},u))]},m.id))})]}),(0,Ie.jsxs)("div",{children:[(0,Ie.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),i.length===0?(0,Ie.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,Ie.jsxs)(ft,{children:[(0,Ie.jsx)(mt,{children:(0,Ie.jsxs)(Fe,{children:[(0,Ie.jsx)(Z,{children:"Date"}),(0,Ie.jsx)(Z,{children:"Amount"}),(0,Ie.jsx)(Z,{children:"Status"})]})}),(0,Ie.jsx)(pt,{children:i.map(m=>(0,Ie.jsxs)(Fe,{children:[(0,Ie.jsx)(Y,{className:"af-text-muted-foreground",children:oc(m.created_at)}),(0,Ie.jsx)(Y,{children:ee(Cn(m),m.currency)}),(0,Ie.jsx)(Y,{children:(0,Ie.jsx)(ss,{status:m.status})})]},m.id))})]})]})]})]})}var we=require("react/jsx-runtime");function Vu(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Ir({className:e}){let{customers:t,total:a,isLoading:s,error:n,page:r,pageSize:i,hasNextPage:l,hasPreviousPage:f,setPage:d,setPageSize:o,email:c,setEmail:b,refetch:g}=Tr(),{api:m}=W(),p=qs.useCallback(()=>m.exportCustomersCsv(),[m]),[u,v]=qs.useState("list"),[x,k]=qs.useState(null),[T,h]=qs.useState(""),R=A=>{k(A),v("detail")},P=()=>{v("list"),k(null),g()};if(u==="detail"&&x)return(0,we.jsx)("div",{className:e,children:(0,we.jsx)(Er,{customer:x,onBack:P})});let D=(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,we.jsx)(oe,{type:"email",value:T,onChange:A=>h(A.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),b(T.trim()))}}),(0,we.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>b(T.trim()),children:[(0,we.jsx)(In.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),c&&(0,we.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),b("")},children:"Clear"}),(0,we.jsx)(da,{fetchCsv:p,filename:"customers",className:"af-ml-auto"})]});if(s)return(0,we.jsxs)("div",{className:e,children:[D,(0,we.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,we.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,we.jsxs)("div",{className:e,children:[D,(0,we.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,we.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&r===0)return(0,we.jsxs)("div",{className:e,children:[c&&D,(0,we.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,we.jsx)(In.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,we.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:c?"No customers match that email.":(0,we.jsxs)(we.Fragment,{children:["No customers yet.",(0,we.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let N=r*i+1,E=Math.min((r+1)*i,a);return(0,we.jsxs)("div",{className:e,children:[D,(0,we.jsxs)(ft,{children:[(0,we.jsx)(mt,{children:(0,we.jsxs)(Fe,{children:[(0,we.jsx)(Z,{children:"Email"}),(0,we.jsx)(Z,{children:"Name"}),(0,we.jsx)(Z,{children:"Phone"}),(0,we.jsx)(Z,{children:"Customer since"}),(0,we.jsx)(Z,{className:"af-text-right",children:"Actions"})]})}),(0,we.jsx)(pt,{children:t.map(A=>(0,we.jsxs)(Fe,{children:[(0,we.jsx)(Y,{className:"af-font-medium",children:A.email}),(0,we.jsx)(Y,{children:A.name||(0,we.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,we.jsx)(Y,{children:A.phone||(0,we.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,we.jsx)(Y,{className:"af-text-muted-foreground",children:Vu(A.created_at)}),(0,we.jsx)(Y,{className:"af-text-right",children:(0,we.jsx)(y,{variant:"ghost",size:"icon",onClick:()=>R(A),title:"View customer",children:(0,we.jsx)(In.Eye,{className:"af-h-4 af-w-4"})})})]},A.id))})]}),(0,we.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,we.jsxs)("span",{children:["Showing ",N,"-",E," of ",a]}),(0,we.jsxs)(en,{value:String(i),onValueChange:A=>o(Number(A)),children:[(0,we.jsx)(Fa,{className:"af-w-[70px] af-h-8",children:(0,we.jsx)(tn,{})}),(0,we.jsxs)(Ma,{children:[(0,we.jsx)(Rt,{value:"10",children:"10"}),(0,we.jsx)(Rt,{value:"25",children:"25"}),(0,we.jsx)(Rt,{value:"50",children:"50"}),(0,we.jsx)(Rt,{value:"100",children:"100"})]})]}),(0,we.jsx)("span",{children:"per page"})]}),(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,we.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>d(r-1),disabled:!f,children:[(0,we.jsx)(In.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,we.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>d(r+1),disabled:!l,children:["Next",(0,we.jsx)(In.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Ge=ce(require("react"),1),Kt=require("lucide-react");var Gt=ce(require("react"),1);function hs({initialPageSize:e=25,refreshKey:t,includeAggregates:a=!1}={}){let{api:s}=W(),[n,r]=Gt.useState([]),[i,l]=Gt.useState(0),[f,d]=Gt.useState(null),[o,c]=Gt.useState(!0),[b,g]=Gt.useState(null),[m,p]=Gt.useState(0),[u,v]=Gt.useState(e),[x,k]=Gt.useState(void 0),[T,h]=Gt.useState(""),[R,P]=Gt.useState(""),[D,N]=Gt.useState(""),[E,A]=Gt.useState(""),[C,K]=Gt.useState(""),Q=x?x.join(","):"",H=Gt.useRef(0),de=Gt.useCallback(async()=>{let be=++H.current;c(!0),g(null);try{let V={labels:Q?Q.split(","):void 0,customerEmail:T||void 0,q:R||void 0,from:D||void 0,to:E||void 0,retainerId:C||void 0,includeAggregates:a,limit:u,offset:m*u},J=await s.getInvoices(V);if(be!==H.current)return;if(m>0&&m*u>=J.total){p(Math.max(0,Math.ceil(J.total/u)-1));return}r(J.invoices),l(J.total),a&&d(J.aggregates??null)}catch(V){if(be!==H.current)return;g(V instanceof Error?V:new Error("Failed to fetch invoices"))}finally{be===H.current&&c(!1)}},[s,Q,T,R,D,E,C,m,u,a]);Gt.useEffect(()=>{de()},[de,t]);let me=be=>V=>{p(0),be(V)};return{invoices:n,total:i,aggregates:f,isLoading:o,error:b,page:m,pageSize:u,hasNextPage:(m+1)*u<i,hasPreviousPage:m>0,setPage:p,setPageSize:me(v),labels:x,setLabels:me(k),customerEmail:T,setCustomerEmail:me(h),q:R,setQ:me(P),from:D,setFrom:me(N),to:E,setTo:me(A),retainerId:C,setRetainerId:me(K),clearFilters:()=>{p(0),k(void 0),h(""),P(""),N(""),A(""),K("")},refetch:de}}var S=require("react/jsx-runtime"),Hu={creating:"Creating",failed:"Failed",awaiting_payment:"Awaiting payment",overdue:"Overdue",payment_processing:"Payment processing",awaiting_authentication:"Awaiting authentication",paid:"Paid",paid_outside_stripe:"Paid outside Stripe",paid_by_credit:"Paid by credit",partially_refunded:"Partially refunded",refunded:"Refunded",disputed:"Disputed",voided:"Voided",uncollectible:"Marked uncollectible"};function xo(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Hu[e.label]??e.label}function zu(e){switch(e){case"paid":case"paid_outside_stripe":case"paid_by_credit":return"success";case"overdue":case"disputed":case"failed":return"destructive";case"partially_refunded":case"refunded":case"payment_processing":case"awaiting_authentication":return"warning";case"awaiting_payment":return"secondary";default:return"outline"}}var yo={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},qu={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Ws({invoice:e,className:t}){return(0,S.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,S.jsx)(ie,{variant:zu(e.label),className:t,children:xo(e)}),e.collection_method==="charge_automatically"&&(0,S.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"})]})}function Ri({delivery:e,className:t}){if(!e)return null;let a=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,S.jsx)(ie,{variant:a,className:t,children:yo[e.state]??e.state})}function js(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ln(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 lc={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Si={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},bo=100,ho=5e3;async function ju(e,t){let a=[],s=0;for(let n=0;n<ho;n+=bo){let r=await e.getInvoices({...t,limit:bo,offset:n});if(s=r.total,a.push(...r.invoices),r.invoices.length<bo||a.length>=s)break}return{invoices:a.slice(0,ho),total:s,truncated:s>a.length||s>ho}}function dc(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],a=e.map(s=>[s.id,js(s),xo(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),ee(s.amount_subtotal,s.currency),ee(s.tax_total,s.currency),ee(s.amount_total,s.currency),s.amount_due===null?"":ee(s.amount_due,s.currency),s.amount_paid===null?"":ee(s.amount_paid,s.currency),ee(s.amount_refunded,s.currency),s.payment_method??"",s.pay_url??"",s.retainer_id??"",s.replaces_order_id??"",s.replaced_by_order_id??"",s.tax_behavior??"",s.discount_total===void 0?"":ee(s.discount_total,s.currency),s.collection_method??""]);return[t,...a].map(s=>s.map(zl).join(",")).join(`
|
|
5
|
+
`)}function Wu(e){ui(new Blob([dc(e)],{type:"text/csv;charset=utf-8"}),di("invoices"))}function Gu({className:e,refreshKey:t,initialInvoiceId:a,onDetailOpenChange:s,onConnectStripe:n,onUpgradePlan:r,needsPaidPlan:i=!1,retainerFilter:l=null,onClearRetainerFilter:f,maxRows:d,onViewAll:o}){let c=typeof d=="number",{api:b}=W(),{invoices:g,total:m,isLoading:p,error:u,page:v,pageSize:x,hasNextPage:k,hasPreviousPage:T,setPage:h,labels:R,setLabels:P,customerEmail:D,setCustomerEmail:N,q:E,setQ:A,from:C,setFrom:K,to:Q,setTo:H,retainerId:de,setRetainerId:me,refetch:be}=hs({refreshKey:t}),[V,J]=Ge.useState(typeof d=="number"?"all":"open"),[F,ge]=Ge.useState(""),[pe,He]=Ge.useState(null),Pe=Ge.useRef(0),Ue=!c||!!o,ze=Ge.useCallback(z=>{if(c){o?.();return}Pe.current++,lt(!1),He(z)},[c,o]),[fe,lt]=Ge.useState(!1),[L,M]=Ge.useState(0),[U,Te]=Ge.useState(null),[ne,Re]=Ge.useState(!1),[je,wt]=Ge.useState(0);Ge.useEffect(()=>{He(z=>{if(!z)return z;let Xe=g.find(ra=>ra.id===z.id);return Xe&&Xe!==z?Xe:z})},[g]);let[et,Dt]=Ge.useState(!1),[Ne,Le]=Ge.useState(null),ct=async()=>{if(!et){Dt(!0),Le(null);try{let{invoices:z,total:Xe,truncated:ra}=await ju(b,{labels:R,customerEmail:D,q:E,from:C,to:Q,retainerId:de});Wu(z),Le(ra?`Exported the first ${z.length.toLocaleString()} of ${Xe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Le("Couldn't export \u2014 try again.")}finally{Dt(!1)}}},at=!D&&!E&&!C&&!Q&&!de,[qt,Ut]=Ge.useState(null);Ge.useEffect(()=>{if(p||m>0||!at||V!=="open")return;let z=!1;return b.getInvoices({limit:1}).then(Xe=>{z||Ut(Xe.total>0)}).catch(()=>{z||Ut(!0)}),()=>{z=!0}},[b,p,m,at,V,t]),Ge.useEffect(()=>{P(c?Si.all:Si.open)},[]),Ge.useEffect(()=>{let z=l?.id??"";z!==de&&(me(z),z&&(J("all"),P(Si.all),N(""),A(""),ge(""),K(""),H("")))},[l?.id]),Ge.useEffect(()=>{let z=!1;return Re(!1),b.getInvoiceSettings().then(Xe=>{z||Te({payments_active:Xe.payments_active,blocked:Xe.blocked})}).catch(()=>{z||Re(!0)}),()=>{z=!0}},[b,t,je]),Ge.useEffect(()=>{if(!a||c)return;let z=!1,Xe=Pe.current;return lt(!1),b.getInvoice(a).then(ra=>{!z&&Xe===Pe.current&&He(ra)}).catch(()=>{!z&&Xe===Pe.current&<(!0)}),()=>{z=!0}},[b,a,L,c]),Ge.useEffect(()=>{s?.(pe!==null)},[pe,s]);let sa=z=>{J(z),P(Si[z])},dt=z=>{let Xe=z.trim();if(!Xe){E&&A(""),D&&N("");return}if(Xe.includes("@")){E&&A(""),N(Xe);return}D&&N(""),A(Xe.replace(/^#/,""))},ht=g,ke=c?ht.slice(0,d):ht,ut=fe&&(0,S.jsxs)("div",{role:"alert",className:"af-mb-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't open the requested invoice. ",(0,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>M(z=>z+1),children:"Retry opening invoice"})]});if(pe)return(0,S.jsxs)("div",{className:e,children:[ut,(0,S.jsx)(_i,{invoice:pe,refreshKey:t,onBack:()=>{ze(null),be()}},pe.id)]});let tt=(0,S.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[ne&&(0,S.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>wt(z=>z+1),children:"Retry setup check"})]}),ut,U?.blocked&&(0,S.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",U.blocked.reason?`: ${U.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),l&&(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,S.jsxs)(ie,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",l.label]}),f&&(0,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:f,children:"Clear schedule filter"})]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.jsx)("div",{role:"group","aria-label":"Invoice views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Object.keys(lc).map(z=>(0,S.jsx)("button",{type:"button","aria-pressed":V===z,onClick:()=>sa(z),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",V===z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:lc[z]},z))}),(0,S.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,S.jsx)(Kt.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,S.jsx)(oe,{type:"text",value:F,onChange:z=>ge(z.target.value),onBlur:()=>dt(F),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),dt(F))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,S.jsx)(Ve,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,S.jsx)(oe,{id:"invoices-from",type:"date",value:C,max:Q||void 0,onChange:z=>K(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,S.jsx)(Ve,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,S.jsx)(oe,{id:"invoices-to",type:"date",value:Q,min:C||void 0,onChange:z=>H(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,S.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void ct(),disabled:et||p||!!u||m===0,"aria-busy":et,children:[(0,S.jsx)(Kt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),et?"Exporting\u2026":"Export CSV (all matching)"]})]}),Ne&&(0,S.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:Ne})]});return p?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(z=>(0,S.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,S.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,S.jsx)(ae,{className:"af-h-4 af-w-20"}),(0,S.jsx)(ae,{className:"af-h-4 af-w-16"})]}),(0,S.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-40"})]},z))})]}):u?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>void be(),children:"Retry"})]})]}):m===0&&at&&(V==="all"||qt===!1)&&(V==="open"||V==="all")?U?.blocked?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)(Ni,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):i?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)(Ni,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):U&&!U.payments_active?(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)(Ni,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):(0,S.jsxs)("div",{className:e,children:[c?null:tt,(0,S.jsx)(Ni,{heading:"No invoices yet",body:!U||ne?"Once invoice setup is ready, you can send invoices from the chat.":"Ask in the chat to send an invoice to a client for your services."})]}):(0,S.jsxs)("div",{className:e,children:[c?null:tt,ke.length===0?(0,S.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:"No invoices match."}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ke.map(z=>(0,S.jsxs)("button",{type:"button",onClick:()=>ze(z),disabled:!Ue,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ue?" hover:af-bg-muted/50":""}`,children:[(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,S.jsx)("span",{className:"af-font-medium",children:js(z)}),(0,S.jsx)(Ws,{invoice:z})]}),(0,S.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:z.customer_name??z.customer_email??"\u2014"}),z.delivery&&(0,S.jsx)("div",{className:"af-mt-1",children:(0,S.jsx)(Ri,{delivery:z.delivery})}),(0,S.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[(0,S.jsx)("span",{children:z.collection_method==="charge_automatically"?"Automatic collection":z.due_at?`Due ${ln(z.due_at)}`:"Due on receipt"}),(0,S.jsx)("span",{className:"af-font-medium af-tabular-nums",children:ee(z.amount_due??z.amount_total,z.currency)})]})]},z.id))}),(0,S.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,S.jsxs)(ft,{children:[(0,S.jsx)(mt,{children:(0,S.jsxs)(Fe,{children:[(0,S.jsx)(Z,{children:"Invoice"}),(0,S.jsx)(Z,{children:"Created"}),(0,S.jsx)(Z,{children:"Customer"}),(0,S.jsx)(Z,{children:"Due"}),(0,S.jsx)(Z,{className:"af-text-right",children:"Amount"}),(0,S.jsx)(Z,{children:"Status"}),(0,S.jsx)(Z,{children:"Delivery"}),(0,S.jsx)(Z,{className:"af-w-8"})]})}),(0,S.jsx)(pt,{children:ke.map(z=>(0,S.jsxs)(Fe,{className:Ue?"af-cursor-pointer":void 0,onClick:Ue?()=>ze(z):void 0,children:[(0,S.jsx)(Y,{className:"af-font-medium",children:(0,S.jsx)("button",{type:"button",disabled:!Ue,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ue?" hover:af-underline":""}`,onClick:Xe=>{Xe.stopPropagation(),ze(z)},"aria-label":`Open invoice ${js(z)}`,children:js(z)})}),(0,S.jsx)(Y,{children:ln(z.created_at)}),(0,S.jsxs)(Y,{children:[(0,S.jsx)("div",{children:z.customer_name??"\u2014"}),(0,S.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:z.customer_email})]}),(0,S.jsx)(Y,{children:z.collection_method==="charge_automatically"?"Automatic":z.due_at?ln(z.due_at):"On receipt"}),(0,S.jsx)(Y,{className:"af-text-right af-tabular-nums",children:ee(z.amount_due??z.amount_total,z.currency)}),(0,S.jsx)(Y,{children:(0,S.jsx)(Ws,{invoice:z})}),(0,S.jsx)(Y,{children:(0,S.jsx)(Ri,{delivery:z.delivery})}),(0,S.jsx)(Y,{children:(0,S.jsx)(Kt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},z.id))})]})}),c?null:(0,S.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,S.jsxs)("span",{children:[m," invoice",m===1?"":"s"]}),(0,S.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,S.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(v-1),disabled:!T,"aria-label":"Previous page",children:(0,S.jsx)(Kt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,S.jsxs)("span",{className:"af-tabular-nums",children:[v*x+1,"\u2013",Math.min((v+1)*x,m)]}),(0,S.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(v+1),disabled:!k,"aria-label":"Next page",children:(0,S.jsx)(Kt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Ni({heading:e,body:t,action:a}){return(0,S.jsx)(zs,{icon:Kt.FileText,heading:e,body:t,action:a})}function Gn(e){return(0,S.jsx)(Gu,{...e},e.maxRows==null?"full":"compact")}var Wn="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=Ge.useRef(null);Ge.useEffect(()=>{r.current?.focus()},[e.id]);let[i,l]=Ge.useState(!1),[f,d]=Ge.useState(null),[o,c]=Ge.useState(!1),[b,g]=Ge.useState(!1),m=Ge.useRef(0),[p,u]=Ge.useState(null),[v,x]=Ge.useState(!1),[k,T]=Ge.useState(0);Ge.useEffect(()=>{let C=!1;return x(!1),n.getInvoice(e.id).then(K=>{C||u({source:e,value:K})}).catch(()=>{C||x(!0)}),()=>{C=!0}},[n,e,a,k]);let h=p?.source===e?p.value:e,R=h.collection_method==="charge_automatically";Ge.useEffect(()=>(m.current++,d(null),c(!1),g(!1),l(!1),()=>{m.current++}),[n,h,a]);let P=C=>C==null?"\u2014":ee(C,h.currency),D=async()=>{if(!(!h.pay_url||!cc()))try{await navigator.clipboard.writeText(h.pay_url),l(!0),setTimeout(()=>l(!1),1500)}catch{}},N=async()=>{if(f){d(null);return}let C=++m.current;g(!1),c(!0);try{let K=await n.getInvoicePreview(h.id);C===m.current&&d(K)}catch{C===m.current&&g(!0)}finally{C===m.current&&c(!1)}},E=h.bill_to,A=E?[E.company,E.name,E.address?.line1,E.address?.line2,[E.address?.city,E.address?.state,E.address?.postal_code].filter(Boolean).join(", "),E.address?.country,E.tax_id?`${E.tax_id.value}`:null,E.po_number?`PO ${E.po_number}`:null,E.service_period?`Service period: ${E.service_period}`:null].filter(C=>!!C&&C.length>0):[];return(0,S.jsxs)("div",{className:s,children:[(0,S.jsxs)("div",{className:"af-mb-4",children:[(0,S.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,S.jsx)(Kt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,S.jsxs)("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",js(h)]}),(0,S.jsx)(Ws,{invoice:h}),(0,S.jsx)(Ri,{delivery:h.delivery})]}),(0,S.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[h.customer_name??h.customer_email,h.customer_name&&h.customer_email?` \xB7 ${h.customer_email}`:""]})]}),v&&(0,S.jsxs)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't refresh this invoice. These details may be out of date. ",(0,S.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>T(C=>C+1),children:"Retry details"})]}),h.label==="failed"&&(0,S.jsx)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),h.label==="creating"&&(0,S.jsx)("p",{role:"status",className:"af-mb-4 af-text-sm af-text-muted-foreground",children:"This invoice is still being created. Its final details will appear when it is ready."}),(0,S.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,S.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,S.jsxs)(ft,{children:[(0,S.jsx)(mt,{children:(0,S.jsxs)(Fe,{children:[(0,S.jsx)(Z,{children:"Description"}),(0,S.jsx)(Z,{className:"af-text-right",children:"Qty"}),(0,S.jsx)(Z,{className:"af-text-right",children:"Amount"})]})}),(0,S.jsx)(pt,{children:h.line_items.map((C,K)=>(0,S.jsxs)(Fe,{children:[(0,S.jsx)(Y,{style:{overflowWrap:"anywhere"},children:C.description}),(0,S.jsx)(Y,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:C.quantity}),(0,S.jsx)(Y,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:P(C.amount)})]},K))})]}),(0,S.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,S.jsx)(rs,{label:"Subtotal",value:P(h.amount_subtotal)}),(h.discount_total??0)>0&&(0,S.jsx)(rs,{label:"Discount",value:`-${P(h.discount_total)}`}),h.tax_total>0&&(0,S.jsx)(rs,{label:h.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:P(h.tax_total)}),(0,S.jsx)(rs,{label:"Total",value:P(h.amount_total),strong:!0}),h.credit_applied>0&&(0,S.jsx)(rs,{label:"Credit applied",value:`-${P(h.credit_applied)}`}),h.amount_due!==null&&h.amount_due!==h.amount_total&&(0,S.jsx)(rs,{label:"Amount due",value:P(h.amount_due),strong:!0}),h.amount_paid!==null&&h.amount_paid>0&&(0,S.jsx)(rs,{label:"Amount paid",value:P(h.amount_paid)}),h.amount_refunded>0&&(0,S.jsx)(rs,{label:"Refunded",value:P(h.amount_refunded)})]}),h.credit_notes?.length>0&&(0,S.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,S.jsx)("div",{className:Wn,children:"Credit notes"}),h.credit_notes.map(C=>(0,S.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,S.jsxs)("span",{className:"af-text-muted-foreground",children:[ln(C.created_at)," \xB7 ",C.origin==="dashboard"?"issued in Stripe":"refund",C.stripe_credit_note_id?"":" \xB7 being created"]}),(0,S.jsxs)("span",{className:"af-tabular-nums",children:["-",ee(C.amount,C.currency)]})]},C.id))]})]}),(h.note||h.footer)&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[h.note&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Wn,children:"Note"}),(0,S.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:h.note})]}),h.footer&&(0,S.jsxs)("div",{children:[(0,S.jsx)("div",{className:Wn,children:"Footer"}),(0,S.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:h.footer})]})]}),f&&!R&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,S.jsxs)("div",{className:X(Wn,"af-break-words"),children:["Email preview \u2014 ",f.subject]}),(0,S.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,S.jsx)("iframe",{title:"Invoice email preview",srcDoc:f.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,S.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,S.jsx)(on,{label:"Created",value:ln(h.created_at)}),(0,S.jsx)(on,{label:"Due",value:h.collection_method==="charge_automatically"?"Managed in Stripe":h.due_at?ln(h.due_at):"On receipt"}),h.paid_at&&(0,S.jsx)(on,{label:"Paid",value:ln(h.paid_at)}),h.payment_method&&(0,S.jsx)(on,{label:"Paid by",value:h.paid_out_of_band?`${h.payment_method} (recorded outside Stripe)`:h.payment_method}),h.payment_state!=="none"&&(0,S.jsx)(on,{label:"Payment",value:h.payment_state==="processing"?"Processing":h.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),h.delivery&&(0,S.jsx)(on,{label:"Delivery",value:`${yo[h.delivery.state]} \xB7 ${h.delivery.recipient}`}),h.marked_uncollectible_at&&(0,S.jsx)(on,{label:"Written off",value:ln(h.marked_uncollectible_at)}),h.correction_reason&&(0,S.jsx)(on,{label:"Correction",value:h.correction_reason}),h.replaced_by_order_id&&(0,S.jsx)(on,{label:"Replaced by",value:h.replaced_by_order_id}),h.collection_method==="charge_automatically"?(0,S.jsx)(on,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):h.retainer_id&&(0,S.jsx)(on,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),h.replaces_order_id&&(0,S.jsx)(on,{label:"Replaces",value:h.replaces_order_id})]}),(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,S.jsx)("div",{className:Wn,children:"Reminders"}),R?(0,S.jsx)("div",{children:"View automatic payment reminders in Stripe."}):h.reminders.disabled?(0,S.jsx)("div",{children:"Off for this invoice."}):h.reminders.paused_until?(0,S.jsxs)("div",{children:["Paused until ",ln(h.reminders.paused_until),"."]}):h.reminders.next_at?(0,S.jsxs)("div",{children:["Next on ",ln(h.reminders.next_at),"."]}):h.reminders.final_sent_at?(0,S.jsxs)("div",{children:["Final reminder sent ",ln(h.reminders.final_sent_at),"."]}):(0,S.jsx)("div",{children:"None scheduled."}),!R&&(0,S.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",h.reminders.schedule.length===0?"none":h.reminders.schedule.map(C=>C<0?`${-C}d before`:C===0?"due day":`${C}d after`).join(", ")]})]}),h.communications&&h.communications.length>0&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,S.jsx)("div",{className:Wn,children:"Email delivery history"}),h.communications.map(C=>(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,S.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[qu[C.kind]??C.kind,C.kind==="reminder"&&C.slot!==null?` #${C.slot}`:"",(0,S.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",C.recipient]})]}),(0,S.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[yo[C.state]??C.state," \xB7 ",ln(C.state_at??C.created_at)]})]},C.id))]}),A.length>0&&(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,S.jsx)("div",{className:Wn,children:"Bill to"}),A.map((C,K)=>(0,S.jsx)("div",{className:"af-break-words",children:C},K))]}),(0,S.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[h.pay_url&&(0,S.jsxs)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void D(),disabled:!cc(),children:[(0,S.jsx)(Kt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Copied":R?"Copy invoice link":"Copy pay link"]}),h.pdf_url&&(0,S.jsx)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,S.jsxs)("a",{href:h.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,S.jsx)(Kt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!R&&(0,S.jsxs)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void N(),disabled:o,children:[o?(0,S.jsx)(Kt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,S.jsx)(Kt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),f?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!R&&(0,S.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),h.pay_url&&(0,S.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:h.pay_url}),(0,S.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:R?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function on({label:e,value:t}){return(0,S.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,S.jsx)("span",{className:X(Wn,"af-shrink-0"),children:e}),(0,S.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function rs({label:e,value:t,strong:a}){return(0,S.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,S.jsx)("dt",{className:X(Wn,a&&"af-font-medium af-text-foreground"),children:e}),(0,S.jsx)("dd",{className:X("af-tabular-nums",a&&"af-font-semibold"),children:t})]})}var fc=require("lucide-react");var Je=require("react/jsx-runtime"),Ku={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},uc={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Zu(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 mc(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>uc[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>uc[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Ku[e.status]}function pc(e){let t=e.interval==="year"?"every year":"every month";return`${ee(e.amount,e.currency)} ${t}`}function Yu(e){return e.status==="canceled"?`Ended ${Pi(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Pi(e.next_cycle_at)}`:"Ends this period":e.collection_method==="charge_automatically"?"Billing schedule managed in Stripe":e.status==="paused"?"Future invoices paused":e.status==="failed"||e.status==="creating"?"Next invoice not scheduled yet":e.skip_next_cycle?e.next_cycle_at?`Skipping ${Pi(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Pi(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Pi(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),a=new Date(t);return Number.isNaN(a.getTime())?e.slice(0,10):a.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ki({retainer:e,className:t}){return(0,Je.jsx)(ie,{variant:Zu(e.status),className:X("af-max-w-full af-whitespace-normal af-break-words",t),children:mc(e)})}function ys({retainers:e,isLoading:t,error:a,onRetry:s,onShowCycles:n,activeRetainerId:r,total:i,endedTotal:l=0,isLoadingMore:f=!1,onLoadMore:d,includeEnded:o=!1,onIncludeEndedChange:c,exportCsv:b,className:g}){let m=!!c;if(!t&&!a&&e.length===0&&!(m&&(o||l>0)))return null;let p=i!==void 0?Math.max(0,i-e.length):0;return(0,Je.jsxs)("section",{className:X("af-mb-6",g),"aria-label":"Recurring invoices",children:[(0,Je.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Je.jsx)(fc.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,Je.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,Je.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),m&&(0,Je.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":o,onClick:()=>c?.(!o),children:o?"Hide ended recurring invoices":l>0&&e.length===0?`Show ended recurring invoices (${l})`:"Show ended recurring invoices"}),b&&(0,Je.jsx)(da,{fetchCsv:b,filename:"retainers",className:m?void 0:"af-ml-auto"})]}),a?(0,Je.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",(0,Je.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?(0,Je.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(u=>(0,Je.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,Je.jsx)(ae,{className:"af-h-4 af-w-48"}),(0,Je.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-32"})]},u))}):e.length===0?(0,Je.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:o?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,Je.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(u=>{let v=r===u.id;return(0,Je.jsxs)("li",{className:X("af-rounded-md af-border af-p-3",v&&"af-border-primary af-bg-muted/40"),children:[(0,Je.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,Je.jsxs)("div",{className:"af-min-w-0",children:[(0,Je.jsx)("div",{className:"af-truncate af-font-medium",children:u.customer_name??u.customer_email??"\u2014"}),(0,Je.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:u.description})]}),(0,Je.jsx)(ki,{retainer:u})]}),u.collection_method==="charge_automatically"?(0,Je.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,Je.jsx)(ie,{variant:"secondary",children:"Managed in Stripe"}),(0,Je.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Automatic charging is enabled in Stripe. View or change the billing terms there. To edit this schedule from the chat, switch it back to sending invoices in Stripe."})]}):(0,Je.jsx)("div",{className:"af-mt-2 af-text-sm",children:pc(u)}),(0,Je.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-text-xs af-text-muted-foreground",children:[(0,Je.jsxs)("span",{children:[Yu(u)," \xB7 ",u.cycles.count===0?"no invoices yet":`${u.cycles.paid} paid${u.cycles.open>0?`, ${u.cycles.open} open`:""}`]}),u.cycles.count>0&&(0,Je.jsx)(y,{type:"button",variant:v?"secondary":"ghost",size:"sm",onClick:()=>n(u),"aria-pressed":v,children:v?"Showing invoices":"View invoices"})]}),u.status==="failed"&&u.operation?.last_error&&(0,Je.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",u.operation.last_error,". Ask in the chat to try again."]})]},u.id)})}),!t&&!a&&p>0&&d&&(0,Je.jsx)("div",{className:"af-mt-2",children:(0,Je.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:d,disabled:f,children:f?"Loading\u2026":`Load more (${p} more)`})})]})}var gc=ce(require("react"),1),Za=require("lucide-react");var Me=require("react/jsx-runtime");function xs({onConnectStripe:e,onUpgradePlan:t,whenActive:a,className:s}){let{status:n,isLoading:r,error:i,refetch:l}=Hn(),[f,d]=gc.useState(!1),o=async()=>{d(!0);try{await l()}finally{d(!1)}};return r&&!n?(0,Me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Me.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!n?(0,Me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Me.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):n.status==="active"?a!==void 0?(0,Me.jsx)("div",{className:s,children:a}):(0,Me.jsx)("div",{className:s,children:(0,Me.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-green-50 af-border af-border-green-200 af-rounded-lg af-p-4",children:[(0,Me.jsx)(Za.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Me.jsxs)("div",{children:[(0,Me.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Me.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",n.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,Me.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[n.reason==="needs_stripe"&&(0,Me.jsxs)("div",{className:"af-space-y-3",children:[(0,Me.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Me.jsx)(Za.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Me.jsxs)("div",{children:[(0,Me.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"It only takes a few minutes. You'll enter your details with Stripe, who handle the payments, and money from sales goes straight to your own bank."})]})]}),e?(0,Me.jsxs)(y,{onClick:e,children:[(0,Me.jsx)(Za.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),n.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),n.reason==="needs_paid_plan"&&(0,Me.jsxs)("div",{className:"af-space-y-3",children:[(0,Me.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Me.jsx)(Za.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Me.jsxs)("div",{children:[(0,Me.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your products are saved as drafts. Upgrade to a paid plan to start accepting payments on your site."})]})]}),t?(0,Me.jsx)(y,{onClick:t,children:"Upgrade plan"}):(0,Me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),n.reason==="account_disabled"&&(0,Me.jsxs)("div",{className:"af-space-y-3",children:[(0,Me.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-yellow-50 af-border af-border-yellow-200 af-rounded-lg af-p-4",children:[(0,Me.jsx)(Za.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Me.jsxs)("div",{children:[(0,Me.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),n.stripe_account_connected?(0,Me.jsx)("p",{className:"af-text-sm af-text-yellow-800",children:"Your Stripe account can't currently accept charges. Check your Stripe account for outstanding requirements or notifications \u2014 once Stripe re-enables charges, payments resume here automatically."}):(0,Me.jsx)("p",{className:"af-text-sm af-text-yellow-800",children:"Payments are currently paused for this site. If you think this is a mistake, get in touch with support and we'll look into it with you."})]})]}),(0,Me.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&n.stripe_account_connected&&(0,Me.jsxs)(y,{onClick:e,children:[(0,Me.jsx)(Za.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Me.jsxs)(y,{variant:"outline",onClick:o,disabled:f,children:[f?(0,Me.jsx)(Za.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Me.jsx)(Za.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var wa=ce(require("react"),1);function wo(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function ws({includeStats:e=!1,refreshKey:t}={}){let{api:a}=W(),[s,n]=wa.useState([]),[r,i]=wa.useState(!0),[l,f]=wa.useState(null),d=wa.useRef(0),o=wa.useCallback(async()=>{let u=++d.current;try{i(!0),f(null);let v=await a.getProducts(e?{include:"stats"}:{});if(u!==d.current)return;n(v)}catch(v){if(u!==d.current)return;f(v instanceof Error?v:new Error("Failed to fetch products"))}finally{u===d.current&&i(!1)}},[a,e,t]);wa.useEffect(()=>{o()},[o]);let c=wa.useCallback(async u=>{let v=await a.createProduct(u);return n(x=>[v,...x]),v},[a]),b=wa.useCallback(async(u,v)=>{let x=await a.updateProduct(u,v);return n(k=>wo(k,u,x)),x},[a]),g=wa.useCallback(async u=>{await a.deleteProduct(u),n(v=>v.filter(x=>x.id!==u))},[a]),m=wa.useCallback(async(u,v)=>{let x=await a.attachProductFile(u,v);return n(k=>wo(k,u,x)),x},[a]),p=wa.useCallback(async(u,v)=>{let x=await a.attachProductFileFromUrl(u,v);return n(k=>wo(k,u,x)),x},[a]);return{products:s,isLoading:r,error:l,refetch:o,createProduct:c,updateProduct:b,deleteProduct:g,attachProductFile:m,attachProductFileFromUrl:p}}var Sa=ce(require("react"),1);var So=["creating","active","paused","canceling"],Ju=["canceled","failed"],Xu={statuses:So},Qu={};function Ss({refreshKey:e,includeEnded:t=!1,limit:a=50}={}){let{api:s}=W(),[n,r]=Sa.useState([]),[i,l]=Sa.useState(0),[f,d]=Sa.useState(0),[o,c]=Sa.useState(!0),[b,g]=Sa.useState(!1),[m,p]=Sa.useState(null),[u,v]=Sa.useState(t),x=Sa.useRef(0),k=Sa.useCallback(async()=>{let h=++x.current;c(!0),g(!1),p(null);try{let R=await s.getRetainers({statuses:u?void 0:So,limit:a,offset:0});if(h!==x.current)return;if(r(R.retainers),l(R.total),!u&&R.total===0){let P=await s.getRetainers({statuses:Ju,limit:1,offset:0});if(h!==x.current)return;d(P.total)}else d(0)}catch(R){if(h!==x.current)return;p(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{h===x.current&&c(!1)}},[s,u,a]);Sa.useEffect(()=>{k()},[k,e]);let T=Sa.useCallback(async()=>{if(o||b||n.length>=i)return;let h=x.current;g(!0);try{let R=await s.getRetainers({statuses:u?void 0:So,limit:a,offset:n.length});if(h!==x.current)return;r(P=>{let D=new Set(P.map(N=>N.id));return[...P,...R.retainers.filter(N=>!D.has(N.id))]}),l(R.total)}catch(R){if(h!==x.current)return;p(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{h===x.current&&g(!1)}},[s,u,a,o,b,n.length,i]);return{retainers:n,total:i,endedTotal:f,hasMore:n.length<i,isLoading:o,isLoadingMore:b,error:m,includeEnded:u,setIncludeEnded:v,loadMore:T,refetch:k,filters:u?Qu:Xu}}var Be=require("react/jsx-runtime");function No({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:n}){let[r,i]=Gs.useState(t),[l,f]=Gs.useState("list"),[d,o]=Gs.useState(null),c=ws(),{status:b,error:g}=Hn(),m=b?.currency,p=k=>{o(k),f("edit")},u=()=>{o(null),f("create")},v=()=>{f("list"),o(null)},x=k=>{o(k),f("edit")};return(0,Be.jsxs)("div",{className:e,children:[(0,Be.jsxs)("div",{className:"af-mb-6",children:[(0,Be.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Be.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Be.jsxs)(ii,{value:r,onValueChange:k=>i(k),children:[(0,Be.jsxs)(or,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Be.jsxs)(vn,{value:"products",className:"af-gap-2",children:[(0,Be.jsx)(cn.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Be.jsxs)(vn,{value:"orders",className:"af-gap-2",children:[(0,Be.jsx)(cn.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Be.jsxs)(vn,{value:"invoices",className:"af-gap-2",children:[(0,Be.jsx)(cn.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Be.jsxs)(vn,{value:"customers",className:"af-gap-2",children:[(0,Be.jsx)(cn.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Be.jsx)(vn,{value:"promos",children:"Promo codes"}),(0,Be.jsxs)(vn,{value:"setup",className:"af-gap-2",children:[(0,Be.jsx)(cn.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Be.jsx)(bn,{value:"products",children:l==="list"?(0,Be.jsx)(Sr,{productsState:c,onSelectProduct:p,onCreateProduct:u}):(0,Be.jsxs)("div",{children:[(0,Be.jsxs)("div",{className:"af-mb-6",children:[(0,Be.jsxs)(y,{variant:"ghost",size:"sm",onClick:v,className:"af-mb-2 af--ml-2",children:[(0,Be.jsx)(cn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Be.jsx)("h3",{className:"af-text-lg af-font-semibold",children:l==="create"?"New Product":d?.name})]}),l==="create"&&!m?(0,Be.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?(0,Be.jsxs)("div",{className:"af-text-destructive",children:["Error: ",g.message]}):(0,Be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Be.jsx)(Rr,{productsState:c,product:l==="edit"?d:null,currency:m??"usd",onSaved:x},l==="edit"?d?.id??"edit":"new")]})}),(0,Be.jsx)(bn,{value:"orders",children:(0,Be.jsx)(jn,{onRefund:s})}),(0,Be.jsx)(bn,{value:"invoices",children:(0,Be.jsx)(ef,{onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),(0,Be.jsx)(bn,{value:"customers",children:(0,Be.jsx)(Ir,{})}),(0,Be.jsx)(bn,{value:"promos",children:(0,Be.jsx)(ps,{})}),(0,Be.jsx)(bn,{value:"setup",children:(0,Be.jsx)(xs,{onConnectStripe:a,onUpgradePlan:n})})]})]})}function ef({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a}){let s=Ss(),[n,r]=Gs.useState(null),[i,l]=Gs.useState(!1);return(0,Be.jsxs)(Be.Fragment,{children:[!i&&(0,Be.jsx)(ys,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:n?.id??null,onShowCycles:f=>r(d=>d?.id===f.id?null:f),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),(0,Be.jsx)(Gn,{onDetailOpenChange:l,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}var bc=ce(require("react"),1);var Dn=ce(require("react"),1);function Ns({refreshKey:e}={}){let{api:t}=W(),[a,s]=Dn.useState(null),[n,r]=Dn.useState(!0),[i,l]=Dn.useState(null),f=Dn.useRef(0),d=Dn.useCallback(async()=>{let o=++f.current;try{r(!0),l(null);let c=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(o!==f.current)return;s(c)}catch(c){if(o!==f.current)return;l(c instanceof Error?c:new Error("Failed to fetch summary"))}finally{o===f.current&&r(!1)}},[t,e]);return Dn.useEffect(()=>{d()},[d]),{summary:a,isLoading:n,error:i,refetch:d}}var vt=require("react/jsx-runtime");function vc(e,t){if(e.settled.complete)return{headline:ee(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:ee(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${ee(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:ee(0,t),extra:[]}}function Ro({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:n,className:r}){let{summary:i,isLoading:l,error:f,refetch:d}=Ns({refreshKey:e}),[o,c]=bc.useState(!1),b=(0,vt.jsx)("div",{className:"af-mb-6",children:f&&!i?(0,vt.jsx)(Et,{message:"Couldn't load your revenue summary.",onRetry:()=>d()}):(0,vt.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:l||!i?(0,vt.jsxs)(vt.Fragment,{children:[(0,vt.jsx)(gt,{label:"This week",children:(0,vt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,vt.jsx)(gt,{label:"Today",children:(0,vt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,vt.jsx)(gt,{label:"Needs attention",children:(0,vt.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,vt.jsx)(vt.Fragment,{children:(()=>{let g=vc(i.revenue.d7,i.currency),m=vc(i.revenue.today,i.currency);return(0,vt.jsxs)(vt.Fragment,{children:[(0,vt.jsx)(gt,{label:"This week",detail:g.extra.length>0?(0,vt.jsx)("div",{children:g.extra.map(p=>(0,vt.jsx)("div",{children:p},p))}):void 0,children:g.headline}),(0,vt.jsx)(gt,{label:"Today",detail:m.extra.length>0?(0,vt.jsx)("div",{children:m.extra.map(p=>(0,vt.jsx)("div",{children:p},p))}):void 0,children:m.headline}),(0,vt.jsx)(gt,{label:"Needs attention",valueClassName:i.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:i.needs_attention.count===0?"All clear":i.needs_attention.items[0]?.title??void 0,children:i.needs_attention.count})]})})()})})});return(0,vt.jsxs)(Lt,{title:"Orders",onBackToWebsite:n,hideBackButton:o,className:r,children:[b,(0,vt.jsx)(jn,{refreshKey:e,initialOrderId:t,onDetailOpenChange:c,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var dn=ce(require("react"),1),Ks=require("lucide-react");var An=ce(require("react"),1),Ai=require("lucide-react");var oa=require("react/jsx-runtime"),hc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",is="af-text-xs af-text-muted-foreground",Ci="af-text-sm af-font-medium af-tabular-nums",tf=3;function af(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let f=e.min_amount??t?.min_amount??null,d=e.max_amount??t?.max_amount??null;return f!==null&&d!==null?{text:`Buyer chooses (${ee(f,a)} \u2013 ${ee(d,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(n===null||r===null)return{text:"Varies by variant",compareAt:null};let i=n===r?ee(n,a):`${ee(n,a)} \u2013 ${ee(r,a)}`,l=t?.compare_at_amount??null;return{text:i,compareAt:l!==null&&l>r?ee(l,a):null}}function Ti({product:e,className:t}){let a=af(e);return(0,oa.jsxs)("div",{className:t,children:[(0,oa.jsx)("span",{className:Ci,children:a.text}),a.compareAt&&(0,oa.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function Ei({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,oa.jsx)(ie,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,oa.jsxs)(ie,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,oa.jsx)(ie,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,oa.jsxs)(ie,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,oa.jsx)(ie,{variant:"warning",children:"Low stock"}):null}function Ii(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Di(e){return e.map(t=>ee(t.amount,t.currency)).join(" + ")}function yc(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${ee(e.min_amount,e.currency)} \u2013 ${ee(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":ee(e.unit_amount,e.currency)}function xc({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,oa.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?(0,oa.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,oa.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,a)}),(0,oa.jsx)(ie,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?(0,oa.jsx)(ie,{variant:"destructive",children:"Out of stock"}):(0,oa.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,oa.jsx)("span",{className:"af-tabular-nums",children:a}),a<=tf&&(0,oa.jsx)(ie,{variant:"warning",children:"Low"})]})}var le=require("react/jsx-runtime");function Dr({title:e,children:t,className:a}){return(0,le.jsxs)("section",{className:X("af-rounded-lg af-border af-p-4",a),children:[(0,le.jsx)("h4",{className:hc,children:e}),(0,le.jsx)("div",{className:"af-mt-3",children:t})]})}function wc({src:e,className:t}){let[a,s]=An.useState(!1);return An.useEffect(()=>s(!1),[e]),!e||a?(0,le.jsx)("div",{"aria-hidden":"true",className:X("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,le.jsx)(Ai.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,le.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:X("af-object-cover",t)})}function Sc({product:e,showStats:t=!1,onBack:a}){let{api:s}=W(),[n,r]=An.useState(null),[i,l]=An.useState(!0),[f,d]=An.useState(null),[o,c]=An.useState(0),[b,g]=An.useState(0);An.useEffect(()=>{let h=!1;return l(!0),d(null),s.getProduct(e.id).then(R=>{h||r(R)}).catch(R=>{h||d(R instanceof Error?R:new Error("Failed to load product"))}).finally(()=>{h||l(!1)}),()=>{h=!0}},[s,e.id,o]);let m=n?{...e,...n}:e,p=m.images.length>0?m.images:e.images,u=p[b]??p[0],v=Ii(m),x=t?m.stats:void 0,k=n?.variants??[],T=k.length>1;return(0,le.jsxs)("div",{children:[(0,le.jsxs)("div",{className:"af-mb-6",children:[(0,le.jsxs)(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,le.jsx)(Ai.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,le.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,le.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:m.name}),(0,le.jsx)(ie,{variant:m.active?"success":"secondary",children:m.active?"Active":"Draft"}),(0,le.jsx)(Ei,{product:m})]}),(0,le.jsx)(Ti,{product:m,className:"af-mt-1"}),!m.active&&(0,le.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),(0,le.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,le.jsxs)("div",{className:"af-space-y-2",children:[(0,le.jsx)(wc,{src:u,className:"af-h-48 af-w-full af-rounded-md af-border"}),p.length>1&&(0,le.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:p.map((h,R)=>(0,le.jsx)("button",{type:"button",onClick:()=>g(R),"aria-label":`Show photo ${R+1} of ${p.length}`,"aria-pressed":R===b,className:X("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",R===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,le.jsx)(wc,{src:h,className:"af-h-12 af-w-12 af-rounded-md"})},`${h}-${R}`))})]}),(0,le.jsxs)("div",{className:"af-space-y-6",children:[m.description&&(0,le.jsx)(Dr,{title:"Description",children:(0,le.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:m.description})}),i?(0,le.jsxs)(Dr,{title:"Variants",children:[(0,le.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(h=>(0,le.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,le.jsx)(ae,{className:"af-h-4 af-w-28"}),(0,le.jsx)(ae,{className:"af-h-4 af-w-20"}),(0,le.jsx)(ae,{className:"af-h-4 af-w-16"})]},h))}),(0,le.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):f?(0,le.jsx)(Et,{message:"Couldn't load this product's variants.",onRetry:()=>c(h=>h+1)}):T?(0,le.jsx)(Dr,{title:`Variants \xB7 ${k.length}`,children:(0,le.jsx)("div",{className:"af-overflow-x-auto",children:(0,le.jsxs)(ft,{children:[(0,le.jsx)(mt,{children:(0,le.jsxs)(Fe,{children:[(0,le.jsx)(Z,{children:"Variant"}),(0,le.jsx)(Z,{children:"SKU"}),(0,le.jsx)(Z,{className:"af-text-right",children:"Price"}),(0,le.jsx)(Z,{children:"Stock"})]})}),(0,le.jsx)(pt,{children:k.map(h=>(0,le.jsxs)(Fe,{children:[(0,le.jsxs)(Y,{className:"af-font-medium",children:[h.title||h.option_values.map(R=>R.value).join(" / ")||"\u2014",!h.active&&(0,le.jsx)(ie,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,le.jsx)(Y,{className:"af-text-muted-foreground",children:h.sku?(0,le.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:h.sku}):"\u2014"}),(0,le.jsxs)(Y,{className:"af-whitespace-nowrap af-text-right",children:[(0,le.jsx)("div",{className:Ci,children:yc(h)}),h.compare_at_amount!==null&&h.unit_amount!==null&&h.compare_at_amount>h.unit_amount&&(0,le.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:ee(h.compare_at_amount,h.currency)})]}),(0,le.jsx)(Y,{className:"af-text-sm",children:(0,le.jsx)(xc,{variant:h})})]},h.id))})]})})}):null,(0,le.jsx)(Dr,{title:"Details",children:(0,le.jsxs)("dl",{className:"af-space-y-2",children:[(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Delivery"}),(0,le.jsx)("dd",{className:"af-text-sm",children:v==="Digital download"?m.fulfillment.filename??"Digital download":v??"Nothing to deliver"})]}),m.fulfillment.type==="redirect"&&m.fulfillment.url&&(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Sends buyers to"}),(0,le.jsx)("dd",{className:"af-break-all af-text-sm",children:m.fulfillment.url})]}),(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Shipping address"}),(0,le.jsx)("dd",{className:"af-text-sm",children:m.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Most one buyer can order"}),(0,le.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:m.max_quantity})]})]})}),x&&(0,le.jsx)(Dr,{title:"Last 30 days",children:(0,le.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Units sold"}),(0,le.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Orders"}),(0,le.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),(0,le.jsxs)("div",{children:[(0,le.jsx)("dt",{className:is,children:"Gross"}),(0,le.jsx)("dd",{className:Ci,children:x.gross.length>0?Di(x.gross):"\u2014"})]})]})}),(0,le.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var G=require("react/jsx-runtime"),nf={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},sf=["all","active","draft","low_stock","out_of_stock"];function Nc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function Rc(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function rf(e){return e.inventory?.out_of_stock??!1}function of(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Rc(e);case"out_of_stock":return rf(e);default:return!0}}function lf({product:e,showStats:t,onOpen:a}){let s=e.images[0],n=t?e.stats:void 0,r=Ii(e),i=e.variant_count??0;return(0,G.jsxs)("button",{type:"button",onClick:a,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?(0,G.jsx)("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,G.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:(0,G.jsx)(Ks.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,G.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,G.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,G.jsxs)("div",{className:"af-min-w-0",children:[(0,G.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,G.jsx)(Ti,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,G.jsx)(ie,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,G.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,G.jsx)(Ei,{product:e}),i>1&&(0,G.jsxs)(ie,{variant:"outline",children:[i," variants"]}),r&&(0,G.jsx)(ie,{variant:"outline",children:r})]}),n&&(0,G.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Di(n.gross)}`:""," ",(0,G.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function cf(){return(0,G.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:[0,1,2,3,4,5].map(e=>(0,G.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,G.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,G.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,G.jsx)(ae,{className:"af-w-32"}),(0,G.jsx)(ae,{className:"af-w-16"}),(0,G.jsx)(ae,{className:"af-h-5 af-w-24"})]})]},e))})}function _o({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:n,isLoading:r,error:i,refetch:l}=ws({includeStats:t,refreshKey:e}),[f,d]=dn.useState(!1),[o,c]=dn.useState(null),[b,g]=dn.useState("all"),{api:m}=W(),p=dn.useCallback(()=>m.exportProductsCsv(),[m]),[u,v]=dn.useState(""),[x,k]=dn.useState("newest"),T=dn.useMemo(()=>{if(!t)return null;let Q=null;for(let H of n)!H.stats||H.stats.units_sold===0||(!Q||H.stats.units_sold>(Q.stats?.units_sold??0))&&(Q=H);return Q},[n,t]),h=dn.useMemo(()=>n.filter(Rc).length,[n]),R=u.trim().toLowerCase(),P=dn.useMemo(()=>{let H=[...n.filter(de=>of(de,b)&&(!R||de.name.toLowerCase().includes(R)))];return x==="name"?H.sort((de,me)=>de.name.localeCompare(me.name)):x==="best_selling"?H.sort((de,me)=>(me.stats?.units_sold??0)-(de.stats?.units_sold??0)):H.sort((de,me)=>Nc(me.created_at)-Nc(de.created_at)),H},[n,b,R,x]),D=b!=="all"||!!R,N=()=>{g("all"),v("")},E=r||i!==null&&n.length===0,A=(0,G.jsx)("div",{className:"af-mb-6",children:(0,G.jsx)("div",{className:X("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:E?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(gt,{label:"Products",children:(0,G.jsx)(ae,{className:"af-h-6 af-w-10"})}),t?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(gt,{label:"Best seller",children:(0,G.jsx)(ae,{className:"af-h-6 af-w-28"})}),(0,G.jsx)(gt,{label:"Low stock",children:(0,G.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,G.jsx)(gt,{label:"Active",children:(0,G.jsx)(ae,{className:"af-h-6 af-w-10"})})]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(gt,{label:"Products",children:n.length}),t?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(gt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:T?`${T.stats?.units_sold??0} sold, last 30 days`:void 0,children:T?(0,G.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:T.name}):(0,G.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,G.jsx)(gt,{label:"Low stock",children:h})]}):(0,G.jsx)(gt,{label:"Active",children:n.filter(Q=>Q.active).length})]})})}),C=(0,G.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,G.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,G.jsx)("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:sf.map(Q=>(0,G.jsx)("button",{type:"button","aria-pressed":b===Q,onClick:()=>g(Q),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",b===Q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:nf[Q]},Q))}),(0,G.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,G.jsx)(Ks.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,G.jsx)(oe,{type:"text",value:u,onChange:Q=>v(Q.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,G.jsxs)(en,{value:x,onValueChange:Q=>k(Q),children:[(0,G.jsx)(Fa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,G.jsx)(tn,{})}),(0,G.jsxs)(Ma,{children:[(0,G.jsx)(Rt,{value:"newest",children:"Newest"}),(0,G.jsx)(Rt,{value:"name",children:"Name A\u2013Z"}),t&&(0,G.jsx)(Rt,{value:"best_selling",children:"Best selling"})]})]}),D&&(0,G.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:N,children:"Clear filters"}),(0,G.jsx)(da,{fetchCsv:p,filename:"products",label:D?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&n.length===0?(0,G.jsx)(ae,{className:"af-h-4 af-w-28"}):(0,G.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:D?`${P.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),K;return o?K=(0,G.jsx)(Sc,{product:o,showStats:t,onBack:()=>{c(null),l()}},o.id):r&&n.length===0?K=(0,G.jsxs)(G.Fragment,{children:[C,(0,G.jsx)(cf,{}),(0,G.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):i&&n.length===0?K=(0,G.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,G.jsx)(Et,{message:"Couldn't load your products.",onRetry:()=>l()})}):n.length===0?K=(0,G.jsxs)(va,{icon:(0,G.jsx)(Ks.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,G.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):K=(0,G.jsxs)(G.Fragment,{children:[C,i&&(0,G.jsx)("div",{className:"af-mb-4",children:(0,G.jsx)(Et,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>l()})}),P.length===0?(0,G.jsxs)(va,{children:["No products match these filters.",(0,G.jsx)("br",{}),(0,G.jsx)(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:N,children:"Show all products"})]}):(0,G.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:P.map(Q=>(0,G.jsx)(lf,{product:Q,showStats:t,onOpen:()=>c(Q)},Q.id))})]}),(0,G.jsx)(Lt,{title:"Products",onBackToWebsite:a,hideBackButton:!!o,className:s,children:f?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(y,{variant:"ghost",onClick:()=>d(!1),children:"Back to products"}),(0,G.jsx)(ps,{})]}):(0,G.jsxs)(G.Fragment,{children:[!o&&(0,G.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,G.jsx)(y,{variant:"outline",onClick:()=>d(!0),children:"Promo codes"})}),!o&&A,K]})})}var Ea=ce(require("react"),1),zt=require("lucide-react");var Ta=ce(require("react"),1);function Ar({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=W(),[s,n]=Ta.useState([]),[r,i]=Ta.useState(!0),[l,f]=Ta.useState(null),[d,o]=Ta.useState(0),[c]=Ta.useState(e),[b,g]=Ta.useState(""),[m,p]=Ta.useState(void 0),u=Ta.useRef(0),v=Ta.useCallback(async({afterRemoval:x=!1}={})=>{let k=++u.current;try{i(!0),f(null);let T={limit:c,offset:d*c};b.trim()&&(T.q=b.trim()),m&&(T.source=m);let h=await a.getPeople(T);if(k!==u.current)return;if(x&&h.people.length===0&&d>0){o(d-1);return}n(h.people)}catch(T){if(k!==u.current)return;f(T instanceof Error?T:new Error("Failed to fetch people"))}finally{k===u.current&&i(!1)}},[a,d,c,b,m,t]);return Ta.useEffect(()=>{v()},[v]),{people:s,isLoading:r,error:l,page:d,pageSize:c,hasNextPage:s.length===c,hasPreviousPage:d>0,setPage:o,q:b,setQ:x=>{g(x),o(0)},source:m,setSource:x=>{p(x),o(0)},refetch:()=>v(),refetchAfterRemoval:()=>v({afterRemoval:!0})}}var Ln=ce(require("react"),1);function Lr(e,{refreshKey:t}={}){let{api:a}=W(),[s,n]=Ln.useState(null),[r,i]=Ln.useState(e!==null),[l,f]=Ln.useState(null),d=Ln.useRef(0),o=Ln.useCallback(async()=>{if(e===null){n(null),i(!1),f(null);return}let c=++d.current;try{i(!0),f(null);let b=await a.getPerson(e);if(c!==d.current)return;n(b)}catch(b){if(c!==d.current)return;f(b instanceof Error?b:new Error("Failed to fetch person"))}finally{c===d.current&&i(!1)}},[a,e,t]);return Ln.useEffect(()=>{o()},[o]),{person:s,isLoading:r,error:l,refetch:o}}var _=require("react/jsx-runtime"),Po="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",df="af-text-xs af-text-muted-foreground";function Zs(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function ko(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function uf(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function ff({value:e,label:t}){let[a,s]=Ea.useState(!1);return uf()?(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[a?(0,_.jsx)(zt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,_.jsx)(zt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function _c(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 Pc(e){return e.name?e.name:e.email?e.email:(0,_.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var mf=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,pf=40;function gf(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),s=t.find(([n,r])=>mf.test(n)&&typeof r=="string"&&r.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=pf).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 vf(e){return e.replace(/_/g," ")}function bf(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function hf({data:e}){let{message:t,rest:a}=gf(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(df,"af-w-28 af-shrink-0 af-capitalize"),children:vf(s)}),(0,_.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:bf(n)})]},s))})]})}function Cc({formName:e,createdAt:t,data:a,onDelete:s}){return(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)(ie,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,_.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,_.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Zs(t)}),(0,_.jsx)(Us,{iconOnly:!0,onDelete:s})]}),(0,_.jsx)(hf,{data:a})]})}function yf(e){return e.charged_total??e.amount_total}function xf({email:e,refreshKey:t,onBack:a,onRemoved:s}){let{api:n}=W(),{person:r,isLoading:i,error:l,refetch:f}=Lr(e,{refreshKey:t}),d=async c=>{await n.deleteSubmission(c),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?f():a()},o=ko(e,r?.submissions[0]?.form_name);return(0,_.jsxs)("div",{children:[(0,_.jsxs)("div",{className:"af-mb-6",children:[(0,_.jsxs)(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,_.jsx)(zt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,_.jsxs)("div",{className:"af-min-w-0",children:[i?(0,_.jsx)(ae,{className:"af-h-7 af-w-48"}):(0,_.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),(0,_.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,_.jsx)(ff,{value:e,label:"Copy email address"})]})]}),(0,_.jsx)(y,{asChild:!0,children:(0,_.jsxs)("a",{href:o,children:[(0,_.jsx)(zt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),i?(0,_.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(c=>(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsx)(ae,{className:"af-w-40"}),(0,_.jsx)(ae,{className:"af-mt-2 af-w-64"})]},c)),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):l||!r?(0,_.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,_.jsx)(Et,{message:"Couldn't load this person.",onRetry:()=>f()})}):(0,_.jsxs)("div",{className:"af-space-y-6",children:[r.customer&&(0,_.jsxs)("div",{children:[(0,_.jsx)("h4",{className:X(Po,"af-mb-3"),children:"Customer"}),(0,_.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&(0,_.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,_.jsx)("dd",{children:r.customer.name})]}),r.customer.phone&&(0,_.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,_.jsx)("dd",{children:r.customer.phone})]}),(0,_.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,_.jsx)("dd",{children:Zs(r.customer.created_at)})]})]})]}),r.orders.length>0&&(0,_.jsxs)("div",{children:[(0,_.jsx)("h4",{className:X(Po,"af-mb-3"),children:"Purchases"}),(0,_.jsx)("div",{className:"af-overflow-x-auto",children:(0,_.jsxs)(ft,{children:[(0,_.jsx)(mt,{children:(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Z,{children:"Order"}),(0,_.jsx)(Z,{children:"Date"}),(0,_.jsx)(Z,{className:"af-text-right",children:"Total"}),(0,_.jsx)(Z,{children:"Status"})]})}),(0,_.jsx)(pt,{children:r.orders.map(c=>(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Y,{className:"af-whitespace-nowrap af-font-medium",children:qn(c)}),(0,_.jsx)(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Zs(c.created_at)}),(0,_.jsx)(Y,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:ee(yf(c),c.currency)}),(0,_.jsx)(Y,{children:(0,_.jsx)(ss,{status:c.status})})]},c.id))})]})}),(0,_.jsx)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),r.submissions.length>0&&(0,_.jsxs)("div",{children:[(0,_.jsx)("h4",{className:X(Po,"af-mb-3"),children:"Messages"}),(0,_.jsx)("div",{className:"af-space-y-3",children:r.submissions.map(c=>(0,_.jsx)(Cc,{formName:c.form_name,createdAt:c.created_at,data:c.data,onDelete:()=>d(c.id)},c.id))})]})]})]})}function wf({submissionId:e,onBack:t,onRemoved:a}){let{api:s}=W(),[n,r]=Ea.useState(null),[i,l]=Ea.useState(!0),[f,d]=Ea.useState(null),[o,c]=Ea.useState(0);return Ea.useEffect(()=>{let b=!1;return l(!0),d(null),s.getSubmission(e).then(g=>{b||r(g)}).catch(g=>{b||d(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{b||l(!1)}),()=>{b=!0}},[s,e,o]),(0,_.jsxs)("div",{children:[(0,_.jsxs)("div",{className:"af-mb-6",children:[(0,_.jsxs)(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,_.jsx)(zt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,_.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,_.jsx)(ae,{className:"af-mt-1 af-h-4 af-w-32"}):n&&(0,_.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Zs(n.metadata.submitted_at)})]}),i?(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,_.jsx)(ae,{className:"af-w-40"}),(0,_.jsx)(ae,{className:"af-mt-2 af-w-64"}),(0,_.jsx)(ae,{className:"af-mt-2 af-w-52"}),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):f||!n?(0,_.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,_.jsx)(Et,{message:"Couldn't load this submission.",onRetry:()=>c(b=>b+1)})}):(0,_.jsxs)("div",{className:"af-space-y-3",children:[(0,_.jsx)(Cc,{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 Sf={all:"All",customers:"Customers",leads:"Leads"},Nf=["all","customers","leads"],kc={all:void 0,customers:"customer",leads:"lead"};function Rf({refreshKey:e,onBackToWebsite:t,className:a,maxRows:s,onViewAll:n}){let r=typeof s=="number",{people:i,isLoading:l,error:f,page:d,pageSize:o,hasNextPage:c,hasPreviousPage:b,setPage:g,q:m,setQ:p,source:u,setSource:v,refetch:x,refetchAfterRemoval:k}=Ar({refreshKey:e}),[T,h]=Ea.useState({kind:"list"}),[R,P]=Ea.useState(""),D=u==="customer"?"customers":u==="lead"?"leads":"all",N=J=>{kc[J]!==u&&v(kc[J])},{api:E}=W(),A=Ea.useCallback(()=>E.exportPeopleCsv({...m?{q:m}:{},...u?{source:u}:{}}),[E,m,u]),C=!r||!!n,K=J=>{if(r){n?.();return}J.email?h({kind:"person",email:J.email}):J.submission_id&&h({kind:"submission",submissionId:J.submission_id})},Q=Ea.useRef(!1),H=()=>{Q.current=!0},de=()=>{h({kind:"list"}),Q.current?(Q.current=!1,k()):x()},me=J=>{let F=J.trim();F!==m&&p(F)},be=r?i.slice(0,s):i,V;if(T.kind==="person")V=(0,_.jsx)(xf,{email:T.email,refreshKey:e,onBack:de,onRemoved:H});else if(T.kind==="submission")V=(0,_.jsx)(wf,{submissionId:T.submissionId,onBack:de,onRemoved:H});else{let J=(0,_.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,_.jsx)("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Nf.map(F=>(0,_.jsx)("button",{type:"button","aria-pressed":D===F,onClick:()=>N(F),className:X("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",D===F?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Sf[F]},F))}),(0,_.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,_.jsx)(zt.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,_.jsx)(oe,{type:"text",value:R,onChange:F=>P(F.target.value),onBlur:()=>me(R),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),me(R))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),m&&(0,_.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{P(""),p("")},children:"Clear search"}),(0,_.jsx)(da,{fetchCsv:A,filename:"people",className:"af-ml-auto"})]});if(l)V=(0,_.jsxs)("div",{children:[r?null:J,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(F=>(0,_.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,_.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,_.jsx)(ae,{className:"af-h-4 af-w-32"}),(0,_.jsx)(ae,{className:"af-h-4 af-w-16"})]}),(0,_.jsx)(ae,{className:"af-mt-2 af-h-5 af-w-28"}),(0,_.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-56"})]},F))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(ft,{children:[(0,_.jsx)(mt,{children:(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Z,{children:"Person"}),(0,_.jsx)(Z,{children:"Came from"}),(0,_.jsx)(Z,{children:"Latest message"}),(0,_.jsx)(Z,{children:"Last activity"}),(0,_.jsx)(Z,{className:"af-w-8"}),(0,_.jsx)(Z,{className:"af-w-8"})]})}),(0,_.jsx)(pt,{"aria-hidden":"true",children:[0,1,2,3,4].map(F=>(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Y,{children:(0,_.jsx)(ae,{className:"af-h-4 af-w-40"})}),(0,_.jsx)(Y,{children:(0,_.jsx)(ae,{className:"af-h-5 af-w-24"})}),(0,_.jsx)(Y,{children:(0,_.jsx)(ae,{className:"af-h-4 af-w-56"})}),(0,_.jsx)(Y,{children:(0,_.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,_.jsx)(Y,{}),(0,_.jsx)(Y,{})]},F))})]})}),(0,_.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(f)V=(0,_.jsxs)("div",{children:[r?null:J,(0,_.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,_.jsx)(Et,{message:"Couldn't load your leads.",onRetry:()=>x()})})]});else if(be.length===0&&d===0){let F=!!m||D!=="all";V=(0,_.jsxs)("div",{children:[F&&J,F?(0,_.jsx)(va,{children:m?"Nobody matches that search.":D==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,_.jsx)(zs,{icon:zt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(i.length===0)V=(0,_.jsxs)("div",{children:[r?null:J,(0,_.jsx)(va,{children:"No more results."}),(0,_.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>g(d-1),children:[(0,_.jsx)(zt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let F=d*o+1,ge=d*o+i.length;V=(0,_.jsxs)("div",{children:[r?null:J,(0,_.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:be.map((pe,He)=>(0,_.jsxs)("div",{onClick:C?()=>K(pe):void 0,className:`af-rounded-md af-border af-p-3${C?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,_.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,_.jsxs)("div",{className:"af-min-w-0",children:[(0,_.jsx)("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),K(pe)},disabled:!C,"aria-label":`Open ${pe.name||pe.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${C?" hover:af-underline":""}`,children:Pc(pe)}),pe.name&&pe.email&&(0,_.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:pe.email})]}),(0,_.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,_.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:Zs(pe.last_activity_at)}),pe.email&&(0,_.jsx)(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,_.jsx)("a",{href:ko(pe.email),onClick:Pe=>Pe.stopPropagation(),"aria-label":`Email ${pe.email}`,children:(0,_.jsx)(zt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,_.jsx)("div",{className:"af-mt-2",children:_c(pe)}),pe.latest_message_excerpt&&(0,_.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:pe.latest_message_excerpt})]},pe.email??pe.submission_id??He))}),(0,_.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,_.jsxs)(ft,{children:[(0,_.jsx)(mt,{children:(0,_.jsxs)(Fe,{children:[(0,_.jsx)(Z,{children:"Person"}),(0,_.jsx)(Z,{children:"Came from"}),(0,_.jsx)(Z,{children:"Latest message"}),(0,_.jsx)(Z,{children:"Last activity"}),(0,_.jsx)(Z,{className:"af-w-8",children:(0,_.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,_.jsx)(Z,{className:"af-w-8"})]})}),(0,_.jsx)(pt,{children:be.map((pe,He)=>(0,_.jsxs)(Fe,{onClick:C?()=>K(pe):void 0,className:C?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,_.jsxs)(Y,{className:"af-max-w-[260px] af-font-medium",children:[(0,_.jsx)("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),K(pe)},disabled:!C,"aria-label":`Open ${pe.name||pe.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${C?" hover:af-underline":""}`,children:Pc(pe)}),pe.name&&pe.email&&(0,_.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:pe.email})]}),(0,_.jsx)(Y,{children:_c(pe)}),(0,_.jsx)(Y,{className:"af-max-w-[320px]",children:pe.latest_message_excerpt?(0,_.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:pe.latest_message_excerpt}):(0,_.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,_.jsx)(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Zs(pe.last_activity_at)}),(0,_.jsx)(Y,{className:"af-w-8",children:pe.email&&(0,_.jsx)(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,_.jsx)("a",{href:ko(pe.email),onClick:Pe=>Pe.stopPropagation(),"aria-label":`Email ${pe.email}`,children:(0,_.jsx)(zt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,_.jsx)(Y,{className:"af-w-8 af-text-right",children:(0,_.jsx)(zt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},pe.email??pe.submission_id??He))})]})}),!r&&(0,_.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,_.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${F}-${ge}`}),(0,_.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>g(d-1),disabled:!b,children:[(0,_.jsx)(zt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,_.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>g(d+1),disabled:!c,children:["Next",(0,_.jsx)(zt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?(0,_.jsx)("div",{className:a,children:V}):(0,_.jsx)(Lt,{title:"Leads",onBackToWebsite:t,hideBackButton:T.kind!=="list",className:a,children:V})}function Or(e){return(0,_.jsx)(Rf,{...e},e.maxRows==null?"full":"compact")}var Ac=ce(require("react"),1),Rs=require("lucide-react");var Ia=ce(require("react"),1);function Br({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=W(),[s,n]=Ia.useState([]),[r,i]=Ia.useState(0),[l,f]=Ia.useState(!0),[d,o]=Ia.useState(null),[c,b]=Ia.useState(0),[g,m]=Ia.useState(e),[p,u]=Ia.useState(void 0),v=Ia.useRef(0),x=Ia.useCallback(async()=>{let T=++v.current;try{f(!0),o(null);let h={limit:g,offset:c*g};p&&(h.status=p);let R=await a.getSubscriptions(h);if(T!==v.current)return;n(R.subscriptions),i(R.total)}catch(h){if(T!==v.current)return;o(h instanceof Error?h:new Error("Failed to fetch subscriptions"))}finally{T===v.current&&f(!1)}},[a,c,g,p,t]);Ia.useEffect(()=>{x()},[x]);let k=Math.ceil(r/g);return{subscriptions:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<k-1,hasPreviousPage:c>0,setPage:b,setPageSize:T=>{m(T),b(0)},status:p,setStatus:T=>{u(T),b(0)},refetch:x}}var q=require("react/jsx-runtime");function Tc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Ec({sub:e}){return e.status==="canceled"?(0,q.jsx)(ie,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,q.jsx)(ie,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,q.jsx)(ie,{variant:"warning",children:"Scheduled to cancel"}):(0,q.jsx)(ie,{variant:"success",children:"Active"}):(0,q.jsx)(ie,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function _f(e,t){let a=ee(t,e.currency);return e.plan_interval_count===1?`${a} / ${e.plan_interval}`:`${a} every ${e.plan_interval_count} ${e.plan_interval}s`}function Ic({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,q.jsxs)("div",{children:[(0,q.jsx)("div",{className:"af-font-medium af-tabular-nums",children:_f(e,e.current_amount)}),t&&(0,q.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",ee(e.plan_amount,e.currency)]})]})}function Dc(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Tc(e.current_period_end)}`:"Ends at period end":e.current_period_end?Tc(e.current_period_end):"\u2014"}function Co({refreshKey:e,onBackToWebsite:t,className:a}){let{subscriptions:s,total:n,isLoading:r,error:i,page:l,pageSize:f,hasNextPage:d,hasPreviousPage:o,setPage:c,status:b,refetch:g}=Br({refreshKey:e}),{api:m}=W(),p=Ac.useCallback(()=>m.exportSubscriptionsCsv(b?{status:b}:{}),[m,b]),u;if(r)u=(0,q.jsxs)("div",{children:[(0,q.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(v=>(0,q.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,q.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,q.jsx)(ae,{className:"af-h-4 af-w-40"}),(0,q.jsx)(ae,{className:"af-h-4 af-w-20"})]}),(0,q.jsx)(ae,{className:"af-mt-2 af-h-3 af-w-32"}),(0,q.jsx)(ae,{className:"af-mt-2 af-h-5 af-w-24"})]},v))}),(0,q.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,q.jsxs)(ft,{children:[(0,q.jsx)(mt,{children:(0,q.jsxs)(Fe,{children:[(0,q.jsx)(Z,{children:"Subscriber"}),(0,q.jsx)(Z,{children:"Plan"}),(0,q.jsx)(Z,{className:"af-text-right",children:"Amount"}),(0,q.jsx)(Z,{children:"Renews"}),(0,q.jsx)(Z,{children:"Status"})]})}),(0,q.jsx)(pt,{"aria-hidden":"true",children:[0,1,2,3,4].map(v=>(0,q.jsxs)(Fe,{children:[(0,q.jsx)(Y,{children:(0,q.jsx)(ae,{className:"af-h-4 af-w-44"})}),(0,q.jsx)(Y,{children:(0,q.jsx)(ae,{className:"af-h-4 af-w-32"})}),(0,q.jsx)(Y,{className:"af-text-right",children:(0,q.jsx)(ae,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,q.jsx)(Y,{children:(0,q.jsx)(ae,{className:"af-h-4 af-w-24"})}),(0,q.jsx)(Y,{children:(0,q.jsx)(ae,{className:"af-h-5 af-w-20"})})]},v))})]})}),(0,q.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(i)u=(0,q.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,q.jsx)(Et,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(s.length===0&&l===0)u=(0,q.jsx)(va,{icon:(0,q.jsx)(Rs.Repeat,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(s.length===0)u=(0,q.jsxs)("div",{children:[(0,q.jsx)(va,{children:"No more results."}),(0,q.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,q.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>c(l-1),children:[(0,q.jsx)(Rs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let v=l*f+1,x=l*f+s.length;u=(0,q.jsxs)("div",{children:[(0,q.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,q.jsx)(da,{fetchCsv:p,filename:"subscriptions"})}),(0,q.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(k=>(0,q.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,q.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,q.jsxs)("div",{className:"af-min-w-0",children:[(0,q.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:k.customer_email||(0,q.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,q.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:k.plan_title||"Untitled plan"})]}),(0,q.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,q.jsx)(Ic,{sub:k})})]}),(0,q.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,q.jsx)(Ec,{sub:k}),k.is_test&&(0,q.jsx)(ie,{variant:"outline",children:"Test"}),(0,q.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Dc(k)})]}),(0,q.jsx)(Pn,{deliveries:k.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},k.id))}),(0,q.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,q.jsxs)(ft,{children:[(0,q.jsx)(mt,{children:(0,q.jsxs)(Fe,{children:[(0,q.jsx)(Z,{children:"Subscriber"}),(0,q.jsx)(Z,{children:"Plan"}),(0,q.jsx)(Z,{className:"af-text-right",children:"Amount"}),(0,q.jsx)(Z,{children:"Renews"}),(0,q.jsx)(Z,{children:"Status"})]})}),(0,q.jsx)(pt,{children:s.map(k=>(0,q.jsxs)(Fe,{children:[(0,q.jsx)(Y,{className:"af-max-w-[240px]",children:(0,q.jsx)("div",{className:"af-truncate af-font-medium",children:k.customer_email||(0,q.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,q.jsx)(Y,{className:"af-max-w-[220px]",children:(0,q.jsx)("div",{className:"af-truncate",children:k.plan_title||(0,q.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,q.jsx)(Y,{className:"af-whitespace-nowrap af-text-right",children:(0,q.jsx)(Ic,{sub:k})}),(0,q.jsx)(Y,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Dc(k)}),(0,q.jsxs)(Y,{children:[(0,q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,q.jsx)(Ec,{sub:k}),k.is_test&&(0,q.jsx)(ie,{variant:"outline",children:"Test"})]}),(0,q.jsx)(Pn,{deliveries:k.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},k.id))})]})}),(0,q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,q.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${v}-${x} of ${n}`}),(0,q.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,q.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>c(l-1),disabled:!o,children:[(0,q.jsx)(Rs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,q.jsxs)(y,{variant:"outline",size:"sm",onClick:()=>c(l+1),disabled:!d,children:["Next",(0,q.jsx)(Rs.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,q.jsx)(Lt,{title:"Subscriptions",onBackToWebsite:t,className:a,children:u})}var Bn=ce(require("react"),1),Kc=require("lucide-react");var ba=ce(require("react"),1);var Li=ce(require("react"),1),_s=typeof window>"u"?Li.useEffect:Li.useLayoutEffect;var Oi=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},Pf=(e,t)=>e instanceof Error?e:new Error(t);function kf(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 Lc(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function Kn({siteId:e,refreshKey:t,onSaveInvoiceSettings:a}){let{api:s}=W(),[n,r]=ba.useState(null),[i,l]=ba.useState(!0),[f,d]=ba.useState(null),o=ba.useRef(null),[c,b]=ba.useState(()=>Lc(s,e)),g=c.api!==s||c.siteId!==e,m=c;g&&(m=Lc(s,e),b(m),r(null),l(!0),d(null));let p=ba.useRef(m);_s(()=>{p.current!==m&&(p.current=m,o.current=null)},[m]);let u=(N,E)=>p.current===N&&E>N.applied,v=(N,E,A)=>u(N,E)?(N.applied=E,o.current=A,r(A),l(!1),!0):!1,x=async N=>{for(;N.writing;)await N.idle;let E=++N.seq;try{let A=await N.api.getSite(N.siteId);return v(N,E,A)&&d(null),{seq:E,error:null}}catch(A){return{seq:E,error:Pf(A,"Failed to load store settings")}}},k=(N,E)=>{let A=async()=>{if(p.current!==N)throw new Error("Not saved: the store switched to another site first.");N.writing=!0,N.idle=new Promise(K=>{N.markIdle=K});try{return await E(++N.seq)}finally{N.writing=!1,N.markIdle()}},C=N.queue.then(A,A);return N.queue=C.catch(()=>{}),C},T=ba.useCallback(async()=>{let N=await x(m);N.error&&u(m,N.seq)&&(d(N.error),l(!1))},[m]);ba.useEffect(()=>{T()},[T,t]);let h=ba.useCallback(N=>k(m,async E=>{let A=await m.api.updateSite(m.siteId,N),{currency_restatement:C,...K}=A;return v(m,E,K)&&d(Q=>Q instanceof Oi?Q:null),A}),[m]),R=ba.useRef(a);_s(()=>{R.current=a});let P=ba.useCallback(async(N,E)=>{await k(m,()=>N());let A=await x(m);return A.error&&u(m,A.seq)&&o.current&&(v(m,A.seq,{...o.current,...E}),d(new Oi(`Saved, but couldn't refresh settings: ${A.error.message}`))),p.current===m?o.current:null},[m]),D=ba.useCallback(N=>{let E=R.current;return P(()=>E(N),kf(N))},[P]);return{site:g?null:n,isLoading:g||i,error:g?null:f,refetch:T,updateSite:h,saveInvoiceSettings:a?D:null}}var ea=ce(require("react"),1),Io=require("lucide-react");var It=require("react/jsx-runtime");function Bi(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var yn="af-grid af-gap-1 af-text-sm",Oc="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",Bc="af-min-h-[72px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50";function Da({children:e}){return(0,It.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Fr({children:e}){return(0,It.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var On=ea.forwardRef(function({id:t,title:a,description:s,children:n},r){let i=`af-store-${t}-title`;return(0,It.jsxs)("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":i,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[(0,It.jsxs)("div",{className:"af-space-y-1",children:[(0,It.jsx)("h3",{id:i,className:"af-text-sm af-font-semibold",children:a}),s&&(0,It.jsx)(Da,{children:s})]}),n]})});function Fi({label:e,description:t,checked:a,onSave:s,disabled:n=!1,disabledReason:r}){let[i,l]=ea.useState(null),[f,d]=ea.useState(null),o=i??a,c=async b=>{l(b),d(null);try{await s(b)}catch(g){d(Bi(g))}finally{l(null)}};return(0,It.jsxs)("div",{className:"af-space-y-1",children:[(0,It.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,It.jsx)("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":o,checked:o,disabled:n||i!==null,onChange:b=>void c(b.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),(0,It.jsxs)("span",{className:"af-space-y-0.5",children:[(0,It.jsxs)("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,i!==null&&(0,It.jsx)(Io.Loader2,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&(0,It.jsx)(Da,{children:t})]})]}),(n&&r||f)&&(0,It.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[n&&r&&(0,It.jsx)(Da,{children:r}),f&&(0,It.jsx)(Fr,{children:f})]})]})}var Eo=(e,t)=>JSON.stringify(e)===JSON.stringify(t),To=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Cf(e,t,a,s=[]){if(!To(e)||!To(t)||!To(a))return{draft:Eo(e,t)?a:e,dropped:[]};let n=[],r={...a};for(let i of Object.keys(a))Eo(e[i],t[i])||(s.includes(i)?n.push(i):r[i]=e[i]);return{draft:r,dropped:n}}function Ys(e,t){let a=JSON.stringify(e),[s,n]=ea.useState(e),[r,i]=ea.useState([]),l=ea.useRef(e),f=ea.useRef(e),d=ea.useRef(s);_s(()=>{f.current=e,d.current=s});let o=ea.useRef(t?.when);ea.useEffect(()=>{let b=Object.is(o.current,t?.when)?[]:t?.fields??[];if(o.current=t?.when,Eo(l.current,f.current)&&b.length===0)return;let g=Cf(d.current,l.current,f.current,b);l.current=f.current,n(g.draft),g.dropped.length&&i(g.dropped)},[a,t?.when]);let c=ea.useCallback(b=>{n(b??f.current),i([])},[]);return{draft:s,setDraft:n,dirty:JSON.stringify(s)!==a,reset:c,dropped:r}}function Js({dirty:e,saving:t,error:a,onSave:s,onDiscard:n}){return e?(0,It.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,It.jsxs)(y,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&(0,It.jsx)(Io.Loader2,{className:"af-animate-spin"}),"Save"]}),(0,It.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:n,children:"Discard"}),a&&(0,It.jsx)("p",{role:"alert",className:X("af-text-sm af-text-destructive"),children:a})]}):null}function Xs(){let[e,t]=ea.useState(!1),[a,s]=ea.useState(null),n=ea.useCallback(async r=>{t(!0),s(null);try{await r()}catch(i){s(Bi(i))}finally{t(!1)}},[]);return{saving:e,error:a,setError:s,run:n}}function Fc({what:e}){return(0,It.jsxs)(Da,{children:["Only the site owner can change ",e,"."]})}var un=ce(require("react"),1),Ps=require("lucide-react");var j=require("react/jsx-runtime"),Ao=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Vc({site:e,updateSite:t}){return(0,j.jsxs)("div",{className:"af-space-y-4",children:[(0,j.jsx)(Fi,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:a=>t({collect_phone_at_checkout:a})}),e.checkout_marketing_consent!==void 0&&(0,j.jsx)(Fi,{label:"Ask buyers for marketing consent at checkout",description:"Adds Stripe's consent checkbox to your checkout. Buyers who tick it join your email list, and buyers who leave without paying can get your abandoned-cart recovery emails.",checked:e.checkout_marketing_consent&&e.stripe_account_country==="US",disabled:e.stripe_account_country!=="US",disabledReason:e.stripe_account_country?'Only available for US stores: Stripe offers its consent checkbox to US businesses only. Your checkout shows an "Email me" box instead.':"Available once your Stripe account is connected and its country has synced.",onSave:a=>t({checkout_marketing_consent:a})})]})}function Mc(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(kt(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(kt(e.free_shipping_over,e.currency))}}function Hc({site:e,updateSite:t,refetch:a,providerSlot:s,currencyChanging:n=!1}){let{draft:r,setDraft:i,dirty:l,reset:f,dropped:d}=Ys(Mc(e),{when:e.currency,fields:["rates","threshold"]}),{saving:o,error:c,setError:b,run:g}=Xs(),m=e.currency.toUpperCase(),p=()=>g(async()=>{let v={},x=[...new Set(r.countries.split(/[\s,]+/).map(N=>N.trim().toUpperCase()).filter(Boolean))],k=x.find(N=>!/^[A-Z]{2}$/.test(N));if(k)throw new Error(`"${k}" isn't a two-letter country code (e.g. US, CA).`);let T=x.length?x:null;Ao(T,e.shipping_countries)||(v.shipping_countries=T);let h=[];for(let N of r.rates){let E=N.label.trim(),A=ia(N.amount,e.currency);if(!E)throw new Error("Every rate needs a name.");if(N.amount.trim()===""||A===null)throw new Error(`Enter a price for "${E}" (0 for free).`);h.push({label:E,amount:A})}let R=h.length?h:null;Ao(R,e.shipping_rates)||(v.shipping_rates=R);let P=null;if(r.threshold.trim()!==""&&(P=ia(r.threshold,e.currency),P===null||P===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(P!==e.free_shipping_over&&(v.free_shipping_over=P),Object.keys(v).length===0){f();return}("shipping_rates"in v||"free_shipping_over"in v)&&(v.expected_currency=e.currency);let D;try{D=await t(v)}catch(N){throw N instanceof jt&&N.details?.code==="currency_changed"&&await a?.(),N}f(Mc(D))}),u=(v,x)=>i({...r,rates:r.rates.map((k,T)=>T===v?{...k,...x}:k)});return(0,j.jsxs)("fieldset",{disabled:o||n,className:"af-space-y-4",children:[(0,j.jsxs)("label",{className:yn,children:["Countries you ship to",(0,j.jsx)(oe,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:v=>i({...r,countries:v.target.value})}),(0,j.jsx)(Da,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsxs)("p",{className:"af-text-sm",children:["Flat shipping rates (",m,")"]}),r.rates.length===0&&(0,j.jsx)(Da,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((v,x)=>(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,j.jsx)(oe,{"aria-label":`Rate ${x+1} name`,value:v.label,placeholder:"Standard",onChange:k=>u(x,{label:k.target.value})}),(0,j.jsx)(oe,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:v.amount,placeholder:"0",className:"af-w-32",onChange:k=>u(x,{amount:k.target.value})}),(0,j.jsx)(y,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${x+1}`,onClick:()=>i({...r,rates:r.rates.filter((k,T)=>T!==x)}),children:(0,j.jsx)(Ps.X,{})})]},x)),(0,j.jsxs)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[(0,j.jsx)(Ps.Plus,{})," Add rate"]}),(0,j.jsx)(Da,{children:"Buyers pick one at checkout. The first is preselected."})]}),(0,j.jsxs)("label",{className:yn,children:["Free shipping over (",m,")",(0,j.jsx)(oe,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:v=>i({...r,threshold:v.target.value})}),(0,j.jsx)(Da,{children:"Orders at or above this get the cheapest rate free."})]}),d.length>0&&(0,j.jsxs)("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",m,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),(0,j.jsx)(Js,{dirty:l,saving:o,error:c,onSave:()=>void p(),onDiscard:()=>{b(null),f()}}),s]})}var Do="exclusive",Tf=[{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 Ef({href:e,children:t}){return(0,j.jsxs)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"af-inline-flex af-items-center af-gap-1 af-font-medium af-underline af-underline-offset-2 hover:af-text-foreground",children:[t,(0,j.jsx)(Ps.ExternalLink,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function zc({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=Ys(e.tax_behavior??Do),{saving:i,error:l,setError:f,run:d}=Xs(),[o,c]=un.useState(!1),b=e.stripe_tax_enabled,g=b||o,m=()=>d(async()=>{let v=a;if(v===e.tax_behavior){r();return}let x={tax_behavior:v};v!=="inclusive"&&e.tax_rate_bps!=null&&(x.tax_rate_bps=null);let k=await t(x);r(k.tax_behavior??Do)}),p=()=>d(async()=>{let v={stripe_tax_enabled:!0,tax_behavior:a};a!=="inclusive"&&e.tax_rate_bps!=null&&(v.tax_rate_bps=null);let x=await t(v);r(x.tax_behavior??Do),c(!1)}),u=(n||o)&&a!=="inclusive"&&e.tax_rate_bps!=null;return(0,j.jsxs)("div",{className:"af-space-y-5",children:[(0,j.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[(0,j.jsx)("p",{children:"Tax at checkout is calculated by Stripe Tax, which you set up in your Stripe Dashboard (Settings \u2192 Tax): your business address, a default product tax code, and the places you're registered to collect tax."}),(0,j.jsx)("p",{children:"Stripe only collects tax where you've added a registration; anywhere else the tax comes out as zero. Stripe Tax has its own fees, and what it covers (such as filing) depends on your Stripe Tax plan."}),(0,j.jsx)("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:Tf.map(v=>(0,j.jsx)("li",{children:(0,j.jsx)(Ef,{href:v.href,children:v.label})},v.href))})]}),(0,j.jsx)(Fi,{label:"Stripe automatic tax",description:b?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:g,onSave:async v=>{if(o){c(!1),f(null),r();return}if(v&&!e.tax_behavior){c(!0);return}return t({stripe_tax_enabled:v})}}),g&&(0,j.jsxs)("fieldset",{disabled:i,className:"af-space-y-4 af-pl-6",children:[(0,j.jsxs)("label",{className:yn,children:["Do your prices already include tax?",(0,j.jsxs)("select",{"aria-label":"Your prices",className:Oc,value:a,onChange:v=>s(v.target.value),children:[(0,j.jsx)("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),(0,j.jsx)("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),(0,j.jsx)(Da,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),u&&(0,j.jsxs)(Da,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),o?(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(y,{type:"button",size:"sm",disabled:i,onClick:()=>void p(),children:"Turn on"}),(0,j.jsx)(y,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>{c(!1),f(null),r()},children:"Cancel"})]}),l&&(0,j.jsx)(Fr,{children:l})]}):(0,j.jsx)(Js,{dirty:n,saving:i,error:l,onSave:()=>void m(),onDiscard:()=>{f(null),r()}})]})]})}function Uc(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function qc({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=Ys(Uc(e)),{saving:i,error:l,setError:f,run:d}=Xs(),o=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),c=()=>d(async()=>{let b={},g=null;if(o&&a.rate.trim()!==""){let v=Number(a.rate);if(!Number.isFinite(v)||v<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(v*100)}o&&g!==e.tax_rate_bps&&(b.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let m=a.taxId.trim()||null;m!==e.tax_id&&(b.tax_id=m);let p=a.label.trim()||null;if(p!==e.tax_label&&(b.tax_label=p),Object.keys(b).length===0){r();return}let u=await t(b);r(Uc(u))});return(0,j.jsxs)("fieldset",{disabled:i,className:"af-space-y-4",children:[(0,j.jsxs)("label",{className:yn,children:["Tax rate (%)",(0,j.jsx)(oe,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!o,value:o?a.rate:"",onChange:b=>s({...a,rate:b.target.value})}),(0,j.jsx)(Da,{children:o?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),(0,j.jsxs)("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[(0,j.jsxs)("label",{className:yn,children:["Tax ID",(0,j.jsx)(oe,{"aria-label":"Tax ID",value:a.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...a,taxId:b.target.value})})]}),(0,j.jsxs)("label",{className:yn,children:["Tax label",(0,j.jsx)(oe,{"aria-label":"Tax label",value:a.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...a,label:b.target.value})})]})]}),(0,j.jsx)(Js,{dirty:n,saving:i,error:l,onSave:()=>void c(),onDiscard:()=>{f(null),r()}})]})}function jc({site:e,updateSite:t,onChangeStart:a}){let[s,n]=un.useState(e.currency.toUpperCase()),[r,i]=un.useState(!1),[l,f]=un.useState(!1),[d,o]=un.useState(null),c=e.currency.toUpperCase(),b=un.useRef(c);un.useEffect(()=>{b.current!==c&&(n(v=>v===b.current?c:v),b.current=c)},[c]);let g=s.trim().toUpperCase(),m=g!==c,p=/^[A-Z]{3}$/.test(g),u=async()=>{f(!0);let v=a?.(),x=!1;o(null);try{let k=await t({currency:g.toLowerCase()});x=!0;let T=k.currency_restatement;T&&!T.applied?o(T.reason?`Not changed: ${T.reason}.`:"The currency was not changed."):(n(k.currency.toUpperCase()),b.current=k.currency.toUpperCase()),i(!1)}catch(k){o(Bi(k))}finally{f(!1),v?.(x)}};return(0,j.jsxs)("div",{className:"af-space-y-3",children:[(0,j.jsxs)("div",{className:"af-flex af-items-end af-gap-2",children:[(0,j.jsxs)("label",{className:yn,children:["Store currency",(0,j.jsx)(oe,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:l||r,onChange:v=>{n(v.target.value),o(null)}})]}),m&&!r&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(y,{type:"button",size:"sm",disabled:!p,onClick:()=>i(!0),children:"Change currency"}),(0,j.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>{n(c),o(null)},children:"Discard"})]})]}),(0,j.jsx)(Da,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&(0,j.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,j.jsxs)("p",{className:"af-text-sm",children:["Change the store currency from ",c," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",ee(2e3,c)," becomes ",ee(2e3,g),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(y,{type:"button",size:"sm",disabled:l,onClick:()=>void u(),children:"Confirm change"}),(0,j.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:l,onClick:()=>i(!1),children:"Cancel"})]})]}),d&&(0,j.jsx)(Fr,{children:d})]})}function $c(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function If(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 Wc({site:e,save:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=Ys($c(e)),{saving:i,error:l,setError:f,run:d}=Xs();if(!t)return(0,j.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,j.jsxs)("p",{children:["Due ",e.invoice_due_days," days after sending"]}),(0,j.jsxs)("p",{children:["Reminders: ",If(e.invoice_reminder_schedule)]}),(0,j.jsxs)("p",{children:["Footer: ",e.invoice_footer||"None"]}),(0,j.jsx)(Fc,{what:"invoice defaults"})]});let o=()=>d(async()=>{let c={},b=Number(a.dueDays);if(a.dueDays.trim()===""||!Number.isInteger(b)||b<0||b>90)throw new Error("Due days must be a whole number from 0 to 90.");b!==e.invoice_due_days&&(c.due_days=b);let m=a.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(m.some(x=>!Number.isInteger(x)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let p=[...new Set(m)].sort((x,k)=>x-k);Ao(p,e.invoice_reminder_schedule)||(c.reminder_schedule=p);let u=a.footer.trim()||null;if(u!==e.invoice_footer&&(c.footer=u),Object.keys(c).length===0){r();return}let v=await t(c);r(v?$c(v):void 0)});return(0,j.jsxs)("fieldset",{disabled:i,className:"af-space-y-4",children:[(0,j.jsxs)("label",{className:yn,children:["Days until due",(0,j.jsx)(oe,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:a.dueDays,onChange:c=>s({...a,dueDays:c.target.value})})]}),(0,j.jsxs)("label",{className:yn,children:["Reminder schedule",(0,j.jsx)(oe,{"aria-label":"Reminder schedule",value:a.reminders,placeholder:"Off",onChange:c=>s({...a,reminders:c.target.value})}),(0,j.jsx)(Da,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),(0,j.jsxs)("label",{className:yn,children:["Invoice footer",(0,j.jsx)("textarea",{"aria-label":"Invoice footer",className:Bc,maxLength:300,value:a.footer,onChange:c=>s({...a,footer:c.target.value})})]}),(0,j.jsx)(Js,{dirty:n,saving:i,error:l,onSave:()=>void o(),onDiscard:()=>{f(null),r()}})]})}function Gc({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=Ys(e.default_email_recipients),{saving:i,error:l,setError:f,run:d}=Xs(),[o,c]=un.useState(""),[b,g]=un.useState(null),m=()=>{let u=o.trim().toLowerCase();if(u){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u)){g("Enter a valid email address.");return}if(a.some(v=>v.toLowerCase()===u)){g("Already added.");return}s([...a,u]),c(""),g(null)}},p=()=>d(async()=>{let u=await t({default_email_recipients:a});r(u.default_email_recipients)});return(0,j.jsxs)("fieldset",{disabled:i,className:"af-space-y-3",children:[(0,j.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[a.map(u=>(0,j.jsxs)(ie,{variant:"secondary",className:"af-gap-1",children:[u,(0,j.jsx)("button",{type:"button","aria-label":`Remove ${u}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(a.filter(v=>v!==u)),children:(0,j.jsx)(Ps.X,{className:"af-h-3 af-w-3"})})]},u)),a.length===0&&(0,j.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(oe,{"aria-label":"Add notification email",type:"email",value:o,placeholder:"Add email address",onChange:u=>{c(u.target.value),g(null)},onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),m())}}),(0,j.jsx)(y,{type:"button",variant:"outline",disabled:!o.trim(),onClick:m,children:"Add"})]}),b&&(0,j.jsx)(Fr,{children:b}),(0,j.jsx)(Js,{dirty:n,saving:i,error:l,onSave:()=>void p(),onDiscard:()=>{f(null),r()}})]})}var ua=require("react/jsx-runtime");function Lo({siteId:e,refreshKey:t,section:a,shippingProviderSlot:s,onConnectStripe:n,onUpgradePlan:r,className:i}){let{site:l,isLoading:f,error:d,refetch:o,updateSite:c}=Kn({siteId:e,refreshKey:t}),b=Bn.useRef(o),g=Bn.useRef(e);_s(()=>{b.current=o,g.current=e});let m=Bn.useRef({}),[p,u]=Bn.useState([]),v=p.some(R=>R.siteId===e),x=Bn.useCallback(()=>{let R={siteId:e},P=b.current;return u(D=>[...D,R]),D=>{let N=()=>u(A=>A.filter(C=>C!==R));!(g.current===R.siteId)||D&&b.current===P?N():b.current().finally(N)}},[e]),k=R=>P=>{m.current[R]=P},T=l!==null&&l.payments_active;if(Bn.useEffect(()=>{if(!T||!a)return;let R=m.current[a];R&&(R.scrollIntoView?.({behavior:"smooth",block:"start"}),R.focus({preventScroll:!0}))},[T,a]),f)return(0,ua.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ua.jsx)(Kc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!l)return(0,ua.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d?.message??"Could not load store settings."});if(!l.payments_active)return(0,ua.jsx)(xs,{className:i,onConnectStripe:n,onUpgradePlan:r,whenActive:(0,ua.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let h={site:l,updateSite:c,refetch:o};return(0,ua.jsxs)("div",{className:`af-space-y-6 ${i??""}`,children:[d&&(0,ua.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d.message}),(0,ua.jsx)(On,{ref:k("checkout"),id:"checkout",title:"Checkout",children:(0,ua.jsx)(Vc,{...h})}),(0,ua.jsx)(On,{ref:k("shipping"),id:"shipping",title:"Shipping",children:(0,ua.jsx)(Hc,{...h,providerSlot:s,currencyChanging:v})}),(0,ua.jsx)(On,{ref:k("tax"),id:"tax",title:"Tax",children:(0,ua.jsx)(zc,{...h})}),(0,ua.jsx)(On,{ref:k("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:(0,ua.jsx)(jc,{...h,onChangeStart:x})})]},e)}var Zc=require("lucide-react");var xn=require("react/jsx-runtime");function Mr({siteId:e,refreshKey:t,onSaveInvoiceSettings:a,className:s}){let{site:n,isLoading:r,error:i,updateSite:l,refetch:f,saveInvoiceSettings:d}=Kn({siteId:e,refreshKey:t,onSaveInvoiceSettings:a});return r?(0,xn.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,xn.jsx)(Zc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):n?(0,xn.jsxs)("div",{className:`af-space-y-6 ${s??""}`,children:[i&&(0,xn.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i.message}),(0,xn.jsx)(On,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:(0,xn.jsx)(Wc,{site:n,save:d})}),(0,xn.jsx)(On,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:(0,xn.jsx)(qc,{site:n,updateSite:l,refetch:f})})]},e):(0,xn.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i?.message??"Could not load invoice settings."})}var Yc=require("lucide-react");var Zn=require("react/jsx-runtime");function Oo({siteId:e,refreshKey:t,className:a}){let{site:s,isLoading:n,error:r,updateSite:i,refetch:l}=Kn({siteId:e,refreshKey:t});return n?(0,Zn.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Zn.jsx)(Yc.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?(0,Zn.jsxs)("div",{className:`af-space-y-3 ${a??""}`,children:[r&&(0,Zn.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r.message}),(0,Zn.jsx)(On,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:(0,Zn.jsx)(Gc,{site:s,updateSite:i,refetch:l})})]},e):(0,Zn.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r?.message??"Could not load notification settings."})}var Qs=ce(require("react"),1);var xt=require("react/jsx-runtime");function Bo({refreshKey:e,initialInvoiceId:t,onBackToWebsite:a,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,siteId:i,onSaveInvoiceSettings:l,className:f}){let{aggregates:d,isLoading:o,error:c,refetch:b}=hs({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=Ss({refreshKey:e}),{api:m}=W(),p=g.filters,u=Qs.useCallback(()=>m.exportRetainersCsv(p),[m,p]),[v,x]=Qs.useState(!1),[k,T]=Qs.useState(null),[h,R]=Qs.useState(!1),P=(0,xt.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:c||!o&&!d?(0,xt.jsxs)("div",{role:"alert",className:"sm:af-col-span-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't load invoice totals. ",(0,xt.jsx)(y,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):o||!d?(0,xt.jsxs)(xt.Fragment,{children:[(0,xt.jsx)(gt,{label:"Outstanding",children:(0,xt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,xt.jsx)(gt,{label:"Overdue",children:(0,xt.jsx)(ae,{className:"af-h-6 af-w-24"})}),(0,xt.jsx)(gt,{label:"Paid this month",children:(0,xt.jsx)(ae,{className:"af-h-6 af-w-24"})})]}):(0,xt.jsxs)(xt.Fragment,{children:[(0,xt.jsx)(gt,{label:"Outstanding",detail:`${d.outstanding.count} open`,children:ee(d.outstanding.amount,d.currency)}),(0,xt.jsx)(gt,{label:"Overdue",detail:d.overdue.count===0?"Nothing overdue":`${d.overdue.count} overdue`,valueClassName:d.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:ee(d.overdue.amount,d.currency)}),(0,xt.jsx)(gt,{label:"Paid this month",detail:`${d.paid_this_month.count} paid`,children:ee(d.paid_this_month.amount,d.currency)})]})});return(0,xt.jsxs)(Lt,{title:"Invoices",onBackToWebsite:a,hideBackButton:v,className:f,children:[P,i&&!v&&(0,xt.jsxs)("div",{className:"af-mb-6",children:[(0,xt.jsx)(y,{type:"button",variant:"outline",size:"sm","aria-expanded":h,"aria-controls":"af-invoice-settings",onClick:()=>R(D=>!D),children:"Invoice settings"}),h&&(0,xt.jsx)("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:(0,xt.jsx)(Mr,{siteId:i,refreshKey:e,onSaveInvoiceSettings:l})})]}),!v&&(0,xt.jsx)(ys,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:k?.id??null,onShowCycles:D=>T(N=>N?.id===D.id?null:D),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded,exportCsv:u}),(0,xt.jsx)(Gn,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:x,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,retainerFilter:k?{id:k.id,label:`${k.customer_name??k.customer_email??"Recurring invoices"} \u2014 ${k.description}`}:null,onClearRetainerFilter:()=>T(null)})]})}var ta=ce(require("react"),1);var fn=ce(require("react"),1);function Zt(e,t,a){let[s,n]=fn.useState(null),[r,i]=fn.useState(!0),[l,f]=fn.useState(null),d=fn.useRef(0),o=fn.useRef(e);o.current=e;let c=fn.useRef(a);c.current=a;let b=fn.useCallback(async()=>{let m=++d.current,p=c.current;i(!0),f(null);try{let u=await o.current();m===d.current&&n({scope:p,value:u})}catch(u){m===d.current&&f(u instanceof Error?u:new Error("Request failed"))}finally{m===d.current&&i(!1)}},[]);fn.useEffect(()=>{b()},[b,t]);let g=s!==null&&s.scope===a;return{data:g?s.value:null,isLoading:r||!g&&l===null,error:l,refetch:b}}var Mi={commitBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts"},cancelBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts/{sendId}/cancel",params:["sendId"]},createDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts"},updateDraft:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},deleteDraft:{method:"DELETE",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},testSendDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/test",params:["draftId"]},setDraftTemplate:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}/template",params:["draftId"]},duplicateDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/duplicate",params:["draftId"]},copyEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/copy",params:["templateId"]},archiveEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/archive",params:["templateId"]},unarchiveEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/unarchive",params:["templateId"]},deleteEmailTemplate:{method:"DELETE",path:"/sites/{siteId}/marketing/templates/{templateId}",params:["templateId"]},importContacts:{method:"POST",path:"/sites/{siteId}/contacts/import"},exportContacts:{method:"GET",path:"/sites/{siteId}/contacts/export"},createTag:{method:"POST",path:"/sites/{siteId}/contact-tags"},updateTag:{method:"PATCH",path:"/sites/{siteId}/contact-tags/{tagId}",params:["tagId"]},bulkTagContacts:{method:"POST",path:"/sites/{siteId}/contacts/tags"},unsubscribeContact:{method:"POST",path:"/sites/{siteId}/contacts/{contactId}/unsubscribe",params:["contactId"]},updateSettings:{method:"PUT",path:"/sites/{siteId}/marketing"},setFormPurpose:{method:"PATCH",path:"/forms/{formId}",params:["formId"]},createWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps"},updateWelcomeStep:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},deleteWelcomeStep:{method:"DELETE",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},publishWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}/publish",params:["stepId"]},activateWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/activate"},pauseWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/pause"},updateWelcome:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome"},setRecoveryStep:{method:"PUT",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},publishRecoveryStep:{method:"POST",path:"/sites/{siteId}/marketing/recovery/steps/{step}/publish",params:["step"]},deleteRecoveryStep:{method:"DELETE",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},activateRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/activate"},pauseRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/pause"}};function Jc(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Mi,e)}function Xc(e,t,a){let s=Mi[e],n="params"in s?s.params:[],r={...a};delete r.siteId;let i=s.path.replace("{siteId}",encodeURIComponent(t));for(let f of n){let d=r[f];if(typeof d!="string"&&typeof d!="number")throw new Error(`${e} needs ${f}`);i=i.replace(`{${f}}`,encodeURIComponent(String(d))),delete r[f]}let l=s.method==="GET"||s.method==="DELETE"?void 0:r;return{method:s.method,path:i,body:l}}var Fo={marketing_disabled:"Email marketing is not available yet.",site_deleted:"This site has been deleted.",sending_not_enabled:"Email isn't turned on for this site yet.",sending_paused:"Sending is paused while we review this site.",domain_not_verified:"Verify your sending domain before you can send.",dmarc_missing:"Your domain needs a DMARC record before you can send.",postal_address_missing:"Add your business postal address before you can send. Every email has to show it.",allowance_exhausted:"You've used this month's email allowance. Sending resumes next month or when you upgrade.",ramp_limit:"Today's sending limit for a new domain is used up. Sending continues tomorrow.",sample_failed:"Too many emails in the first batch bounced, so the rest of this send was stopped."},Ur=new Set(["sending_not_enabled","domain_not_verified","dmarc_missing","postal_address_missing"]);function ks(e){return e?Fo[e]??"Sending is not available right now.":null}var Fn=ce(require("react"),1);var Cs=50;function $r({siteId:e,q:t="",offset:a=0,refreshKey:s=0}){let{api:n}=W(),r=Zt(()=>n.getMarketingContacts(e,{q:t||void 0,limit:Cs,offset:a}),`${e}|${t}|${a}|${s}`,e),i=Zt(()=>n.getMarketingContactStats(e),`${e}|${s}`,e),l=Zt(()=>n.getMarketingTags(e),`${e}|${s}`,e);return{contacts:r,stats:i,tags:l,refetchAll:async()=>{await Promise.all([r.refetch(),i.refetch(),l.refetch()])}}}var ar=ce(require("react"),1);var wn=ce(require("react"),1);var Sn=require("react/jsx-runtime"),Vr=e=>`af-email-settings-${e}`,Mo=wn.createContext(null);function it(){let e=wn.useContext(Mo);if(!e)throw new Error("Email panels render inside EmailView");return e}function Qc(e){let{setInlineEditOpen:t}=it();wn.useEffect(()=>(t(e),()=>t(!1)),[e,t])}function Uo(e){return e.status==="sending"||e.status==="sent"||(e.status==="cancelled"||e.status==="failed")&&e.recipients.consumed>0}function Ui(e,t){return new Set([...e.filter(a=>a.sent).map(a=>a.id),...t.filter(Uo).flatMap(a=>a.draft_id?[a.draft_id]:[])])}function Ts({onClick:e,children:t}){return(0,Sn.jsx)("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function er({reason:e}){let{openSetup:t,onOpenStoreSettings:a}=it(),s=e&&Ur.has(e)?(0,Sn.jsx)(Ts,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&a?(0,Sn.jsx)(Ts,{onClick:a,children:"Open Store settings"}):null;return s&&(0,Sn.jsxs)(Sn.Fragment,{children:[" ",s]})}function $i(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.code=="string"?t.code:typeof t.details?.code=="string"?t.details.code:null}function mn(e,t){return $i(e)===t?!0:e instanceof Error&&e.message.includes(t)}function tr(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function Ot(){let{onOrgAction:e}=it(),[t,a]=wn.useState(!1),[s,n]=wn.useState(null),r=wn.useCallback(async(i,l={})=>{a(!0),n(null);try{return{ok:!0,result:await e(i,l)}}catch(f){return n(tr(f)),{ok:!1,error:f}}finally{a(!1)}},[e]);return{busy:t,error:s,setError:n,run:r}}function Ee({tone:e="info",children:t,className:a}){return(0,Sn.jsx)("div",{role:e==="error"?"alert":"status",className:X("af-rounded-md af-border af-px-3 af-py-2 af-text-sm",e==="warning"&&"af-border-yellow-300 af-bg-yellow-50 af-text-yellow-900",e==="error"&&"af-border-destructive af-bg-destructive/10 af-text-destructive",e==="success"&&"af-border-green-300 af-bg-green-50 af-text-green-900",a),children:t})}function Ya({children:e,action:t,id:a}){return(0,Sn.jsxs)("div",{id:a,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[(0,Sn.jsx)("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function qe(e){return e.toLocaleString("en-US")}var Bt=require("react/jsx-runtime"),Vi="I confirm that everyone in this file agreed to receive marketing email from my business.",Df={invalid_email:"not a valid email address",duplicate:"listed more than once",inactive_in_source:"inactive or unsubscribed in the file",previously_unsubscribed:"unsubscribed before, so they stay unsubscribed",suppressed:"bounced or marked email as spam before",pending:"still confirming their signup"};function Hr({onImported:e}){let{canWrite:t}=it(),[a,s]=ar.useState(""),[n,r]=ar.useState(null),[i,l]=ar.useState(""),[f,d]=ar.useState(!1),[o,c]=ar.useState(null),b=Ot(),g=async()=>{if(!f||!a.trim())return;let m=i.split(",").map(u=>u.trim()).filter(Boolean),p=await b.run("importContacts",{csv:a,attested:!0,...m.length?{tags:m}:{}});if(p.ok){let u=p.result;c(u),e?.(u)}};if(o){let m=new Map;for(let p of o.skipped_rows)m.set(p.reason,(m.get(p.reason)??0)+1);return(0,Bt.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[(0,Bt.jsx)("div",{className:"af-font-medium",children:"Import finished"}),(0,Bt.jsxs)("p",{className:"af-text-sm",children:[qe(o.rows)," rows: ",qe(o.created)," new, ",qe(o.updated)," updated, ",qe(o.skipped)," skipped."]}),m.size>0&&(0,Bt.jsx)("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...m].map(([p,u])=>(0,Bt.jsxs)("li",{children:[qe(u)," ",Df[p]??p]},p))}),(0,Bt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),(0,Bt.jsx)(y,{type:"button",size:"sm",variant:"outline",onClick:()=>{c(null),s(""),r(null),d(!1)},children:"Import another file"})]})}return(0,Bt.jsxs)("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:m=>{m.preventDefault(),g()},children:[(0,Bt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Bt.jsx)("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),(0,Bt.jsx)("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async m=>{let p=m.target.files?.[0];p&&(r(p.name),s(await p.text()))}}),(0,Bt.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:'Needs an "email" column. Tags in a "tags" column are applied too.'}),n&&(0,Bt.jsx)("span",{className:"af-block af-text-xs",children:n})]}),(0,Bt.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,Bt.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),(0,Bt.jsx)(oe,{"aria-label":"Tags for imported contacts",value:i,onChange:m=>l(m.target.value)})]}),(0,Bt.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,Bt.jsx)("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:f,onChange:m=>d(m.target.checked)}),(0,Bt.jsxs)("span",{children:[Vi," Importing people who didn't agree can get your sending paused."]})]}),b.error&&(0,Bt.jsx)(Ee,{tone:"error",children:b.error}),(0,Bt.jsx)(y,{type:"submit",size:"sm",disabled:!t||!f||!a.trim()||b.busy,children:b.busy?"Importing\u2026":"Import contacts"})]})}var ve=require("react/jsx-runtime"),Af={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function ed(){let{siteId:e,canWrite:t,refreshKey:a}=it(),[s,n]=Fn.useState(""),[r,i]=Fn.useState(""),[l,f]=Fn.useState(0),[d,o]=Fn.useState(0),[c,b]=Fn.useState(new Set),[g,m]=Fn.useState(!1),p=$r({siteId:e,q:r,offset:l,refreshKey:d+a}),u=Ot(),v=()=>o(P=>P+1),x=p.stats.data,k=p.contacts.data,T=p.tags.data??[],h=x?x.growth.slice(-4).reduce((P,D)=>P+D.new_subscribers,0):null,R=async()=>{let P=await u.run("exportContacts",{});if(!P.ok||typeof P.result!="string"||typeof document>"u")return;let D=URL.createObjectURL(new Blob([P.result],{type:"text/csv;charset=utf-8"})),N=document.createElement("a");N.href=D,N.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(N),N.click(),document.body.removeChild(N),URL.revokeObjectURL(D)};return(0,ve.jsxs)("div",{children:[(0,ve.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[(0,ve.jsx)(gt,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:x?qe(x.total):(0,ve.jsx)(ae,{className:"af-h-6 af-w-16"})}),(0,ve.jsx)(gt,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:x?qe(x.mailable):(0,ve.jsx)(ae,{className:"af-h-6 af-w-16"})}),(0,ve.jsx)(gt,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:h!==null?qe(h):(0,ve.jsx)(ae,{className:"af-h-6 af-w-16"})})]}),(0,ve.jsxs)("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,ve.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:P=>{P.preventDefault(),f(0),i(s.trim())},children:[(0,ve.jsx)(oe,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:s,onChange:P=>n(P.target.value)}),(0,ve.jsx)(y,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),(0,ve.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>m(P=>!P),children:g?"Close import":"Import"}),(0,ve.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!t||u.busy,onClick:()=>void R(),children:"Export"})]}),g&&(0,ve.jsx)("div",{className:"af-mt-3",children:(0,ve.jsx)(Hr,{onImported:v})}),u.error&&(0,ve.jsx)(Ee,{tone:"error",className:"af-mt-2",children:u.error}),t&&c.size>0&&(0,ve.jsx)(Of,{tags:T.filter(P=>!P.system),count:c.size,busy:u.busy,onApply:async(P,D)=>{(await u.run("bulkTagContacts",{action:P,tag_id:D,contact_ids:[...c]})).ok&&(b(new Set),v())}}),(0,ve.jsx)("div",{className:"af-mt-3",children:p.contacts.error?(0,ve.jsx)(Et,{message:"Couldn't load contacts.",onRetry:()=>void p.contacts.refetch()}):k?k.contacts.length===0?(0,ve.jsx)(va,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):(0,ve.jsxs)(ve.Fragment,{children:[(0,ve.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:k.contacts.map(P=>(0,ve.jsx)(Lf,{contact:P,canWrite:t,busy:u.busy,selected:c.has(P.id),onSelect:D=>b(N=>{let E=new Set(N);return D?E.add(P.id):E.delete(P.id),E}),onUnsubscribe:async()=>{(await u.run("unsubscribeContact",{contactId:P.id})).ok&&v()}},P.id))}),(0,ve.jsxs)("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[(0,ve.jsxs)("span",{children:[qe(l+1),"\u2013",qe(l+k.contacts.length)," of ",qe(k.total)]}),(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:l===0,onClick:()=>f(Math.max(0,l-Cs)),children:"Previous"}),(0,ve.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:l+k.contacts.length>=k.total,onClick:()=>f(l+Cs),children:"Next"})]})]})]}):(0,ve.jsx)(ae,{className:"af-h-24 af-w-full"})}),(0,ve.jsx)(Bf,{tags:T,canWrite:t,onChanged:v})]})}function Lf({contact:e,canWrite:t,busy:a,selected:s,onSelect:n,onUnsubscribe:r}){return(0,ve.jsxs)("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&(0,ve.jsx)("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:s,onChange:i=>n(i.target.checked)}),(0,ve.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,ve.jsxs)("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?(0,ve.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),(0,ve.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[(0,ve.jsx)(ie,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":Af[e.status]}),e.tags.map(i=>(0,ve.jsx)(ie,{variant:"outline",children:i.label},i.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&(0,ve.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:r,children:"Unsubscribe"})]})}function Of({tags:e,count:t,busy:a,onApply:s}){let[n,r]=Fn.useState("");return(0,ve.jsxs)("div",{className:"af-mt-3 af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:[(0,ve.jsxs)("span",{children:[qe(t)," selected"]}),(0,ve.jsxs)("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:n,onChange:i=>r(i.target.value),children:[(0,ve.jsx)("option",{value:"",children:"Choose a tag\u2026"}),e.map(i=>(0,ve.jsx)("option",{value:i.id,children:i.label},i.id))]}),(0,ve.jsx)(y,{type:"button",size:"sm",variant:"outline",disabled:!n||a,onClick:()=>s("add",n),children:"Add tag"}),(0,ve.jsx)(y,{type:"button",size:"sm",variant:"ghost",disabled:!n||a,onClick:()=>s("remove",n),children:"Remove tag"})]})}function Bf({tags:e,canWrite:t,onChanged:a}){let[s,n]=Fn.useState(""),[r,i]=Fn.useState(null),l=Ot();return(0,ve.jsxs)("div",{children:[(0,ve.jsx)(Ya,{children:"Tags"}),e.length===0?(0,ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No tags yet. Contacts are tagged automatically with where they signed up and what they bought."}):(0,ve.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(f=>(0,ve.jsx)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:r?.id===f.id?(0,ve.jsxs)("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async d=>{d.preventDefault(),(await l.run("updateTag",{tagId:f.id,label:r.label.trim()})).ok&&(i(null),a())},children:[(0,ve.jsx)(oe,{"aria-label":`New name for ${f.label}`,value:r.label,onChange:d=>i({id:f.id,label:d.target.value})}),(0,ve.jsx)(y,{type:"submit",size:"sm",disabled:!r.label.trim()||l.busy,children:"Save"})]}):(0,ve.jsxs)(ve.Fragment,{children:[(0,ve.jsxs)("span",{children:[f.label," ",(0,ve.jsxs)("span",{className:"af-text-muted-foreground",children:["\xB7 ",qe(f.total)," contacts, ",qe(f.mailable)," can be emailed"]})]}),t&&!f.system&&(0,ve.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>i({id:f.id,label:f.label}),children:"Rename"})]})},f.id))}),t&&(0,ve.jsxs)("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async f=>{f.preventDefault(),(await l.run("createTag",{label:s.trim()})).ok&&(n(""),a())},children:[(0,ve.jsx)(oe,{"aria-label":"New tag",placeholder:"New tag",value:s,maxLength:100,onChange:f=>n(f.target.value)}),(0,ve.jsx)(y,{type:"submit",size:"sm",variant:"outline",disabled:!s.trim()||l.busy,children:"Add tag"})]}),l.error&&(0,ve.jsx)(Ee,{tone:"error",className:"af-mt-2",children:l.error})]})}var _t=ce(require("react"),1),pd=require("lucide-react");function Es({siteId:e,refreshKey:t=0}){let{api:a}=W();return Zt(()=>a.getBroadcasts(e),`${e}|${t}`,e)}function Is({siteId:e,kind:t,refreshKey:a=0}){let{api:s}=W();return Zt(()=>s.getEmailDrafts(e,t),`${e}|${t??""}|${a}`,`${e}|${t??""}`)}var Ke=ce(require("react"),1);var zr=e=>typeof e=="number"&&Number.isFinite(e);function $o(e){if(!e||typeof e!="object")return null;let t=e;return zr(t.x)&&zr(t.y)&&zr(t.width)&&zr(t.height)?{x:t.x,y:t.y,width:t.width,height:t.height}:null}var Vo=(e,t)=>Number.isInteger(e)&&e>=0&&e<t;function td(e,t,a){if(!t||e.source!==t)return null;let s=e.data;if(!s||typeof s!="object"||s.af!=="email-editor")return null;switch(s.type){case"hover":{if(s.section===null)return{type:"hover",section:null,rect:null};let n=$o(s.rect);return Vo(s.section,a)&&n?{type:"hover",section:s.section,rect:n}:null}case"focus":case"open":{let n=$o(s.rect);return Vo(s.section,a)&&n?{type:s.type,section:s.section,rect:n}:null}case"layout":{if(!zr(s.height)||!Array.isArray(s.sections))return null;let n=s.sections.flatMap(r=>{let i=r,l=i?$o(i.rect):null;return i&&Vo(i.section,a)&&l?[{section:i.section,rect:l}]:[]});return{type:"layout",height:s.height,sections:n}}case"template":return s.region==="header"||s.region==="footer"?{type:"template",region:s.region}:null;default:return null}}var qr=(e,t,a)=>Math.min(Math.max(e,t),Math.max(t,a));function Ho(e,t){let a=qr(e.x,0,t.width),s=qr(e.y,0,t.height);return{x:a,y:s,width:qr(e.width,0,t.width-a),height:qr(e.height,0,t.height-s)}}var jr={min:240,max:6e3,initial:480},ad=e=>qr(Math.ceil(e),jr.min,jr.max);var Ds=ce(require("react"),1);var ot=require("react/jsx-runtime"),zo={heading:"Heading",text:"Text",button:"Button",image:"Image",cart:"Cart"};function sd(e){switch(e){case"heading":case"text":return{type:e,text:""};case"button":return{type:e,label:"",url:"https://"};case"image":return{type:e,url:"",alt:""};case"cart":return{type:e,label:"Return to your cart"}}}function qo(e){switch(e.type){case"heading":case"text":return e.text;case"button":return`${e.label}
|
|
6
|
+
${e.url}`;case"image":return[e.url,e.alt].filter(Boolean).join(`
|
|
7
|
+
`);case"cart":return e.label}}function nd(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 Ff={...zo,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:f,className:d}){let[o,c]=Ds.useState(e),[b,g]=Ds.useState(!1),m=v=>c(x=>({...x,...v})),p=Ds.useRef(null);Ds.useEffect(()=>p.current?.focus(),[]);let u=v=>{v&&!p.current&&(p.current=v)};return(0,ot.jsx)("form",{"data-testid":"section-editor",style:f,className:d,onSubmit:v=>{v.preventDefault(),nd(o)&&r(o)},onKeyDown:v=>{v.key==="Escape"&&!a&&l()},children:(0,ot.jsxs)("div",{className:"af-space-y-2",children:[o.type==="heading"&&(0,ot.jsx)(oe,{ref:u,"aria-label":"Heading",value:o.text,maxLength:200,onChange:v=>m({text:v.target.value})}),o.type==="text"&&(0,ot.jsx)("textarea",{ref:u,"aria-label":"Text",className:"af-min-h-[120px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-font-mono af-text-sm",value:o.text,maxLength:5e3,onChange:v=>m({text:v.target.value})}),o.type==="button"&&(0,ot.jsxs)("div",{className:"af-grid af-gap-2 sm:af-grid-cols-2",children:[(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",(0,ot.jsx)(oe,{ref:u,"aria-label":"Button label",value:o.label,maxLength:80,onChange:v=>m({label:v.target.value})})]}),(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Opens",(0,ot.jsx)(oe,{"aria-label":"Button link",type:"url",value:o.url,onChange:v=>m({url:v.target.value})})]})]}),o.type==="image"&&(0,ot.jsxs)("div",{className:"af-space-y-2",children:[n?(0,ot.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[o.url&&(0,ot.jsx)("img",{src:o.url,alt:"",className:"af-h-12 af-w-12 af-rounded af-object-cover"}),(0,ot.jsx)(y,{ref:u,type:"button",variant:"outline",size:"sm",disabled:b,onClick:async()=>{g(!0);try{let v=await n();v&&c(x=>({...x,url:v.url,alt:v.alt??(x.type==="image"?x.alt:"")}))}finally{g(!1)}},children:"Choose from your site's images\u2026"})]}):(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Image address (https://\u2026)",(0,ot.jsx)(oe,{ref:u,"aria-label":"Image URL",type:"url",value:o.url,onChange:v=>m({url:v.target.value})})]}),(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Describe the image (for people who can't see it)",(0,ot.jsx)(oe,{"aria-label":"Image description",value:o.alt??"",maxLength:200,onChange:v=>m({alt:v.target.value})})]})]}),o.type==="cart"&&(0,ot.jsxs)("div",{className:"af-space-y-2",children:[(0,ot.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Each shopper sees their own cart here. There's nothing to write but the button."}),(0,ot.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",(0,ot.jsx)(oe,{ref:u,"aria-label":"Cart button label",value:o.label,maxLength:80,onChange:v=>m({label:v.target.value})})]})]}),s&&(0,ot.jsx)(Ee,{tone:"error",children:s}),(0,ot.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,ot.jsx)("span",{className:"af-grow af-text-xs af-text-muted-foreground",children:Ff[o.type]}),!t&&(0,ot.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:i,children:"Remove"}),(0,ot.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:l,children:"Cancel"}),(0,ot.jsx)(y,{type:"submit",size:"sm",disabled:a||!nd(o),children:"Done"})]})]})})}var id=ce(require("react"),1),od=require("lucide-react");var _e=require("react/jsx-runtime"),Mn="standard",Hi={create:"Create an email template that ",copyStandard:"Create an email template based on Standard that ",update:e=>`Update the "${e}" template to be `};function jo({template:e}){return e?e.status==="archived"?(0,_e.jsx)(ie,{variant:"secondary",children:"Archived"}):e.locked?(0,_e.jsx)(ie,{variant:"secondary",children:"In use"}):null:(0,_e.jsx)(ie,{variant:"secondary",children:"Built in"})}function Wo(e){return e>0?`Used by ${e} draft${e===1?"":"s"}`:null}function ld(e,t){let{api:a}=W(),{siteId:s,refreshKey:n,settings:r}=it(),i=JSON.stringify([r?.business_name,r?.postal_address,r?.brand]);return Zt(()=>a.previewEmailTemplate(s,e),`${s}|${e}|${t}|${n}|${i}`,`${s}|${e}|${t}`)}function zi({templateId:e,version:t,className:a,frame:s}){let n=ld(e,t);return(0,_e.jsx)("div",{"aria-hidden":!0,className:`af-pointer-events-none af-overflow-hidden af-bg-white ${a}`,children:n.data&&(0,_e.jsx)("iframe",{title:"",tabIndex:-1,sandbox:"",srcDoc:n.data.html,style:{width:s.width,height:s.height,border:0,transform:`scale(${s.scale})`,transformOrigin:"top left"}})})}function cd({template:e,onBack:t,onOpenTemplate:a,onOpenDraft:s,onAskAssistant:n,reload:r,refreshKey:i}){let l=ld(e?.id??Mn,e?.updated_at??"builtin");return(0,_e.jsxs)("div",{className:"af-space-y-4",children:[(0,_e.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,_e.jsx)(od.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All templates"]}),(0,_e.jsxs)("div",{className:"af-grid af-gap-4 md:af-grid-cols-[minmax(0,1fr)_280px]",children:[(0,_e.jsxs)("div",{children:[l.data?(0,_e.jsx)("iframe",{title:"Template preview",sandbox:"",srcDoc:l.data.html,className:"af-h-[520px] af-w-full af-rounded-md af-border af-bg-white"}):l.error?(0,_e.jsxs)(Ee,{tone:"warning",children:[$i(l.error)==="postal_address_missing"?"Add your business postal address to preview your emails.":"Couldn't load this preview.",(0,_e.jsx)(er,{reason:$i(l.error)})]}):(0,_e.jsx)(ae,{className:"af-h-[520px] af-w-full"}),(0,_e.jsx)("p",{className:"af-mt-2 af-text-center af-text-xs af-text-muted-foreground",children:"Shown with a sample email"})]}),(0,_e.jsxs)("div",{className:"af-space-y-3",children:[(0,_e.jsx)(Mf,{template:e,onOpenTemplate:a,onAskAssistant:n,reload:r}),(0,_e.jsx)(Uf,{templateId:e?.id??null,onOpenDraft:s,refreshKey:i})]})]})]})}function Mf({template:e,onOpenTemplate:t,onAskAssistant:a,reload:s}){let{canWrite:n}=it(),r=Ot(),[i,l]=id.useState(null),f=e?.name??"Standard",d=async(u,v)=>{let x=await r.run(u,v);l(null),x.ok&&u==="deleteEmailTemplate"&&t(null),!x.ok&&mn(x.error,"template_in_use")&&r.setError("Emails use this template now."),s()},o=async u=>{let v=await r.run("copyEmailTemplate",{templateId:u.id});v.ok&&(t(v.result.id),s())},c=u=>(0,_e.jsx)(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:r.busy,onClick:()=>void o(u),children:"Make a copy"}),b=(0,_e.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:r.busy,onClick:()=>l("delete"),children:"Delete"}),g=(0,_e.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[u,v,x]=i==="delete"?["Delete this template?","Delete",()=>d("deleteEmailTemplate",{templateId:e.id})]:["Archive this template?","Archive",()=>d("archiveEmailTemplate",{templateId:e.id})];m=(0,_e.jsxs)(_e.Fragment,{children:[(0,_e.jsx)("p",{className:"af-text-sm",children:u}),(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),(0,_e.jsx)(y,{type:"button",size:"sm",variant:i==="delete"?"destructive":"default",className:"af-ml-auto",disabled:r.busy,onClick:()=>void x(),children:v})]})]})}else e?e.status==="archived"?m=(0,_e.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,_e.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:r.busy,onClick:()=>void d("unarchiveEmailTemplate",{templateId:e.id}),children:"Unarchive"}),c(e)]}):e.locked?m=(0,_e.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_archive&&g,c(e)]}):m=(0,_e.jsxs)(_e.Fragment,{children:[a&&(0,_e.jsx)(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>a(Hi.update(e.name)),children:"\u2728 Change this template with the editor"}),(e.can_delete||e.can_archive)&&(0,_e.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_delete&&b,e.can_archive&&g]})]}):m=a&&(0,_e.jsx)(y,{type:"button",size:"sm",onClick:()=>a(Hi.copyStandard),children:"Make a copy"});let p=e&&e.status==="active"&&!e.locked?Wo(e.usage.drafts):null;return(0,_e.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,_e.jsx)("h3",{"data-testid":"template-title",className:"af-grow af-truncate af-text-sm af-font-semibold",children:f}),(0,_e.jsx)(jo,{template:e})]}),p&&(0,_e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:p}),r.error&&(0,_e.jsx)(Ee,{tone:"error",children:r.error}),m]})}function Uf({templateId:e,onOpenDraft:t,refreshKey:a}){let{siteId:s}=it(),n=Is({siteId:s,kind:"broadcast",refreshKey:a}),r=Es({siteId:s,refreshKey:a}),i=n.data?.filter(c=>(c.template?.id??null)===e)??null,l=r.data??[],f=Ui(n.data??[],l),d=new Set(l.flatMap(c=>c.draft_id&&c.status==="scheduled"?[c.draft_id]:[])),o=c=>f.has(c)?"Sent":d.has(c)?"Scheduled":"Draft";return(0,_e.jsxs)("div",{"data-testid":"template-usage",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,_e.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Emails using it"}),n.error||r.error?(0,_e.jsx)(Et,{message:"Couldn't load the emails.",onRetry:()=>{n.refetch(),r.refetch()}}):!i||!r.data?(0,_e.jsx)(ae,{className:"af-h-10 af-w-full"}):i.length===0?(0,_e.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No emails use it."}):(0,_e.jsx)("ul",{className:"af-space-y-1",children:i.map(c=>{let b=o(c.id),g=(0,_e.jsxs)(_e.Fragment,{children:[(0,_e.jsx)("span",{className:"af-block af-truncate af-text-sm",children:c.subject||"(no subject)"}),(0,_e.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["Broadcast \xB7 ",b]})]});return(0,_e.jsx)("li",{children:b==="Sent"?(0,_e.jsx)("div",{className:"af-rounded-md af-px-2 af-py-1",children:g}):(0,_e.jsx)("button",{type:"button",onClick:()=>t(c.id),className:"af-w-full af-rounded-md af-px-2 af-py-1 af-text-left hover:af-bg-muted",children:g})},c.id)})})]})}var Ja=require("react/jsx-runtime");function dd({draft:e,disabled:t,onChanged:a}){let{api:s}=W(),{siteId:n,refreshKey:r}=it(),i=Zt(()=>s.getEmailTemplates(n),`${n}|${r}`,n),l=Ot(),f=e.template?.id??Mn,d=f===Mn,o=(i.data??[]).filter(p=>p.status==="active"),c=o.find(p=>p.id===f),b=d?"Standard":e.template?.name??c?.name??"",g=d?"builtin":c?.updated_at??"current",m=async p=>{if(p===f)return;let u=await l.run("setDraftTemplate",{draftId:e.id,template_id:p===Mn?null:p,expected_version:e.version});u.ok?await a():mn(u.error,"template_missing_cart")?l.setError("This email shows the shopper's cart, and that template has no cart section. Pick another template, or keep this one."):mn(u.error,"version_conflict")?(l.setError("This email changed meanwhile. We've loaded the latest version; switch again if you still want to."),await a()):mn(u.error,"template_archived")&&(l.setError("That template is archived."),await i.refetch())};return(0,Ja.jsxs)("div",{"data-testid":"template-card",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[(0,Ja.jsx)("div",{className:"af-text-sm af-font-semibold",children:"Template"}),(0,Ja.jsxs)("div",{className:"af-flex af-items-center af-gap-3",children:[(0,Ja.jsx)(zi,{templateId:f,version:g,className:"af-h-20 af-w-[72px] af-shrink-0 af-rounded af-border",frame:{width:600,height:670,scale:.12}}),(0,Ja.jsx)("div",{className:"af-min-w-0 af-grow af-truncate af-text-sm af-font-medium",children:b})]}),(0,Ja.jsxs)("label",{className:"af-grid af-gap-1 af-text-xs af-text-muted-foreground",children:["Switch to",(0,Ja.jsxs)("select",{"aria-label":"Switch to",value:f,disabled:t||l.busy,onChange:p=>void m(p.target.value),className:"af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-text-sm af-text-foreground",children:[(0,Ja.jsx)("option",{value:Mn,children:"Standard"}),o.map(p=>(0,Ja.jsx)("option",{value:p.id,children:p.name},p.id)),!d&&!c&&(0,Ja.jsx)("option",{value:f,disabled:!0,children:b})]})]}),l.error&&(0,Ja.jsx)(Ee,{tone:"error",children:l.error})]})}var Se=require("react/jsx-runtime"),$f={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"},Vf=320,Hf=600,zf=e=>({top:Math.max(0,e.y-24),left:e.x});function qf(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 fd({draftId:e,renderCommit:t,onSaved:a,scheduled:s,onAskAssistant:n,onPickImage:r}){let{api:i}=W(),{siteId:l,canWrite:f,refreshKey:d,openSettings:o}=it(),c=f&&!s,b=Ke.useRef(c);b.current=c;let[g,m]=Ke.useState(null),[p,u]=Ke.useState(null),[v,x]=Ke.useState(null),[k,T]=Ke.useState(null),[h,R]=Ke.useState(null),[P,D]=Ke.useState(null),[N,E]=Ke.useState(null),[A,C]=Ke.useState(null),[K,Q]=Ke.useState(null),[H,de]=Ke.useState({}),[me,be]=Ke.useState(jr.initial),[V,J]=Ke.useState(!1),F=Ot(),ge=Ot(),pe=Ke.useRef(null),He=Ke.useRef(null),Pe=Ke.useRef(0),Ue=Ke.useRef(!1),ze=Ke.useRef(!1),fe=Ke.useCallback(ke=>{Ue.current=ke!==null,D(ke)},[]);Qc(P!==null);let lt=Ke.useRef(g);lt.current=g;let L=Ke.useRef(0),M=Ke.useCallback(async(ke={})=>{let ut=++L.current,tt=b.current,St=()=>tt?i.previewEmailDraft(l,e,{editable:!0}):i.previewEmailDraft(l,e),[z,Xe]=await Promise.allSettled([i.getEmailDraft(l,e),St()]),ra=Xe,Ms=()=>z.status==="fulfilled"&&ra.status==="fulfilled"&&ra.value.version!==z.value.version;if(Ms()&&ut===L.current&&([ra]=await Promise.allSettled([St()])),ut===L.current){if(ke.background&&Ue.current){ze.current=!0;return}if(T(null),x(null),z.status==="rejected"){T(tr(z.reason));return}m(z.value),ra.status==="fulfilled"?u({...ra.value,editable:tt&&!Ms()}):(u(null),x(mn(ra.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:tr(ra.reason),code:null}))}},[i,l,e]);Ke.useEffect(()=>{m(null),u(null),M()},[M]);let U=Ke.useRef(c);Ke.useEffect(()=>{U.current!==c&&(U.current=c,c||fe(null),M())},[c,M,fe]);let Te=Ke.useRef(d);Ke.useEffect(()=>{if(d!==Te.current){if(Te.current=d,Ue.current){ze.current=!0;return}M({background:!0})}},[d,M]);let ne=()=>{fe(null),F.setError(null),ze.current&&(ze.current=!1,M())},Re=async(ke,ut,tt)=>{let St=await F.run("updateDraft",{draftId:e,expected_version:ke.version,...ut});St.ok?(E(null),He.current=null,ze.current=!1,fe(null),await M(),a?.()):mn(St.error,"version_conflict")&&(F.setError(null),E(tt),ze.current=!1,fe(null),await M())},je=Ke.useRef({frame:null,html:null,count:0}),[wt,et]=Ke.useState(null),Dt=(ke,ut)=>{let tt=je.current;tt.frame!==ke.currentTarget||tt.html!==ut?je.current={frame:ke.currentTarget,html:ut,count:1}:++tt.count>1&&et(ut)},Ne=p!==null&&wt===p.html,Le=c&&p?.editable===!0&&!Ne;if(Ke.useEffect(()=>{if(!Le)return;let ke=ut=>{let tt=lt.current;if(!tt)return;let St=td(ut,pe.current?.contentWindow,tt.blocks.length);if(St)switch(St.type){case"hover":Q(St.section===null?null:{section:St.section,rect:St.rect});return;case"focus":He.current=St.section;return;case"open":if(He.current=St.section,Ue.current)return;C(null),J(!1),fe({kind:"section",base:tt,index:St.section,block:tt.blocks[St.section],isNew:!1,anchor:St.rect,key:++Pe.current});return;case"layout":be(ad(St.height));{let z=Object.fromEntries(St.sections.map(Xe=>[Xe.section,Xe.rect]));de(Xe=>qf(Xe,z)?Xe:z)}return;case"template":Ue.current||C(St.region);return}};return window.addEventListener("message",ke),()=>window.removeEventListener("message",ke)},[Le,fe]),k)return(0,Se.jsxs)(Ee,{tone:"error",children:["Couldn't load this email. ",k]});if(!g)return(0,Se.jsx)(ae,{className:"af-h-40 af-w-full"});let ct={width:pe.current?.clientWidth||Hf,height:Le?me:jr.initial},at=P?.kind==="section"?P:null,qt=(()=>{if(!at)return null;if(!at.isNew)return H[at.index]??at.anchor;let ke=H[at.index-1];return ke?{x:ke.x,y:ke.y+ke.height,width:ke.width,height:0}:null})(),Ut=qt?Ho(qt,ct):null,sa=g.kind==="recovery",dt=g.template?.name??"Standard",ht=at&&(0,Se.jsx)(rd,{block:at.block,isNew:at.isNew,busy:F.busy,error:F.error,onPickImage:r,onCancel:ne,onRemove:()=>{let{base:ke}=at;Re(ke,{subject:ke.subject,preheader:ke.preheader,blocks:ke.blocks.filter((ut,tt)=>tt!==at.index)},qo(at.block))},onDone:ke=>{let{base:ut}=at,tt=at.isNew?[...ut.blocks.slice(0,at.index),ke,...ut.blocks.slice(at.index)]:ut.blocks.map((St,z)=>z===at.index?ke:St);Re(ut,{subject:ut.subject,preheader:ut.preheader,blocks:tt},qo(ke))},className:Ut?"af-absolute af-z-10 af-rounded-md af-border af-bg-background af-p-3 af-shadow-lg":"af-rounded-md af-border af-bg-background af-p-3 af-shadow-sm",style:Ut?{top:Ut.y,left:Ut.x,width:Math.min(Math.max(Ut.width,Vf),ct.width)}:void 0},at.key);return(0,Se.jsxs)("div",{className:"af-grid af-gap-4 lg:af-grid-cols-[minmax(0,1fr)_300px]",children:[(0,Se.jsxs)("div",{className:"af-min-w-0 af-space-y-3",children:[P?.kind==="subject"?(0,Se.jsx)(jf,{draft:P.base,busy:F.busy,error:F.error,onCancel:ne,onDone:ke=>void Re(P.base,{...ke,blocks:P.base.blocks},[ke.subject,ke.preheader??""].join(`
|
|
8
|
+
`))}):Le?(0,Se.jsx)("button",{type:"button","data-testid":"subject-line",onClick:()=>{Ue.current||(C(null),fe({kind:"subject",base:g}))},className:"af-block af-w-full af-rounded-md af-border af-border-dashed af-px-3 af-py-2 af-text-left hover:af-border-primary",children:(0,Se.jsx)(ud,{draft:g})}):(0,Se.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:(0,Se.jsx)(ud,{draft:g})}),s&&(0,Se.jsxs)(Ee,{tone:"info",children:[(0,Se.jsxs)("p",{children:["This email is scheduled",s.sendsAt?` to send ${new Date(s.sendsAt).toLocaleString()}`:"",", so it can't change. Unschedule it to edit, then schedule it again."]}),(0,Se.jsx)(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:!f||s.busy,onClick:()=>void s.onUnschedule(),children:"Unschedule to edit"}),s.error&&(0,Se.jsx)("p",{className:"af-mt-1 af-text-destructive",children:s.error})]}),N!==null&&(0,Se.jsxs)(Ee,{tone:"warning",children:[(0,Se.jsx)("p",{children:"This email changed while you were editing, so your change wasn't saved. Here is the latest version; your text is below to apply again."}),(0,Se.jsx)("textarea",{readOnly:!0,"aria-label":"Your unsaved text",value:N,className:"af-mt-2 af-min-h-[72px] af-w-full af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-font-mono af-text-xs af-text-foreground"}),(0,Se.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>E(null),children:"Dismiss"})]}),A&&(0,Se.jsx)("div",{"data-testid":"template-hint",children:(0,Se.jsx)(Ee,{children:A==="header"?(0,Se.jsxs)(Se.Fragment,{children:['The header is part of the "',dt,'" template. Switch templates on the right.']}):(0,Se.jsxs)(Se.Fragment,{children:["Every email ends with this footer. Your business name and address come from"," ",(0,Se.jsx)(Ts,{onClick:()=>o("sender"),children:"Settings"}),"."]})})}),Ne&&c&&(0,Se.jsx)(Ee,{tone:"warning",children:"This template tried to open another page in the preview, so the preview can't be edited here."}),p?(0,Se.jsxs)("div",{className:"af-relative",children:[(0,Se.jsx)("iframe",{ref:pe,title:"Email preview",sandbox:Le?"allow-scripts":"",srcDoc:p.html,onLoad:Le?ke=>Dt(ke,p.html):void 0,style:{height:ct.height},className:"af-block af-w-full af-rounded-md af-border af-bg-white"},Le?"editable":"read-only"),Le&&K&&!P&&(0,Se.jsx)("div",{"aria-hidden":!0,className:"af-pointer-events-none af-absolute af-rounded af-bg-primary af-px-2 af-py-0.5 af-text-xs af-text-primary-foreground",style:zf(Ho(K.rect,ct)),children:$f[g.blocks[K.section]?.type??"text"]}),Ut&&ht]}):v?(0,Se.jsxs)(Ee,{tone:"warning",children:[v.text,(0,Se.jsx)(er,{reason:v.code})]}):(0,Se.jsx)(ae,{className:"af-h-40 af-w-full"}),!Ut&&ht,Le&&!P&&(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>J(ke=>!ke),"aria-expanded":V,children:"+ Add a section"}),V&&(0,Se.jsx)("div",{"data-testid":"add-section-menu",className:"af-flex af-flex-wrap af-gap-2",children:["text","heading","button","image",...sa?["cart"]:[]].map(ke=>(0,Se.jsx)(y,{type:"button",size:"sm",variant:"secondary",onClick:()=>{let ut=He.current!==null?He.current+1:g.blocks.length;J(!1),C(null),fe({kind:"section",base:g,index:ut,block:sd(ke),isNew:!0,anchor:null,key:++Pe.current})},children:zo[ke]},ke))})]}),(0,Se.jsx)("p",{className:"af-text-center af-text-xs af-text-muted-foreground",children:"Header and footer come from your template."})]}),(0,Se.jsxs)("div",{className:"af-space-y-3",children:[(0,Se.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[(0,Se.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:!f||ge.busy,onClick:async()=>{R(null);let ke=await ge.run("testSendDraft",{draftId:e});ke.ok&&R(ke.result?.sent_to??"your email")},children:"Send a test to me"}),h&&(0,Se.jsxs)(Ee,{tone:"success",children:["Test sent to ",h,"."]}),ge.error&&(0,Se.jsx)(Ee,{tone:"error",children:ge.error}),p&&!s&&t?.({draft:g,preview:p,reload:()=>M()})]}),(0,Se.jsx)(dd,{draft:g,disabled:!c||P!==null,onChanged:async()=>{await M(),a?.()}}),n&&f&&(0,Se.jsx)(y,{type:"button",variant:"outline",className:"af-w-full",onClick:()=>n(`Update the "${g.subject}" email to `),children:"\u2728 Change this email with the editor"})]})]})}function ud({draft:e}){return(0,Se.jsxs)(Se.Fragment,{children:[(0,Se.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Subject "}),(0,Se.jsx)("span",{className:"af-font-medium",children:e.subject||"(no subject)"}),e.preheader&&(0,Se.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:[" \u2014 ",e.preheader]})]})}function jf({draft:e,busy:t,error:a,onDone:s,onCancel:n}){let[r,i]=Ke.useState(e.subject),[l,f]=Ke.useState(e.preheader??"");return(0,Se.jsxs)("form",{className:"af-space-y-2 af-rounded-md af-border af-p-3",onSubmit:d=>{d.preventDefault(),s({subject:r,preheader:l.trim()||null})},children:[(0,Se.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Subject",(0,Se.jsx)(oe,{"aria-label":"Subject",value:r,maxLength:200,autoFocus:!0,onChange:d=>i(d.target.value)})]}),(0,Se.jsxs)("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Preview text (the grey line after the subject in the inbox)",(0,Se.jsx)(oe,{"aria-label":"Preview text",value:l,maxLength:200,onChange:d=>f(d.target.value)})]}),a&&(0,Se.jsx)(Ee,{tone:"error",children:a}),(0,Se.jsxs)("div",{className:"af-flex af-justify-end af-gap-2",children:[(0,Se.jsx)(y,{type:"button",variant:"outline",size:"sm",disabled:t,onClick:n,children:"Cancel"}),(0,Se.jsx)(y,{type:"submit",size:"sm",disabled:t,children:"Done"})]})]})}var ue=require("react/jsx-runtime"),Wf={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function gd({openDraftId:e,onOpenDraft:t,onAskAssistant:a,onPickImage:s}){let{siteId:n,canWrite:r,refreshKey:i}=it(),[l,f]=_t.useState(0),d=l+i,o=Is({siteId:n,kind:"broadcast",refreshKey:d}),c=Es({siteId:n,refreshKey:d}),b=Ot(),g=Ot(),m=Ui(o.data??[],c.data??[]),p=o.data?.filter(u=>!m.has(u.id))??null;if(e){let u=c.data?.find(v=>v.draft_id===e&&v.status==="scheduled");return(0,ue.jsxs)("div",{className:"af-space-y-4",children:[(0,ue.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>t(null),children:[(0,ue.jsx)(pd.ArrowLeft,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),!c.data&&!c.error||!o.data&&!o.error?(0,ue.jsx)(ae,{className:"af-h-40 af-w-full"}):m.has(e)?(0,ue.jsx)(Ee,{children:"This email has been sent, so it can't change. Duplicate it from the list to send it again."}):(0,ue.jsx)(fd,{draftId:e,onSaved:()=>f(v=>v+1),renderCommit:v=>(0,ue.jsx)(Yf,{...v,onCommitted:()=>f(x=>x+1)}),scheduled:u?{sendsAt:u.scheduled_at,busy:b.busy,error:b.error,onUnschedule:async()=>{(await b.run("cancelBroadcast",{sendId:u.id})).ok&&f(x=>x+1)}}:void 0,onAskAssistant:a,onPickImage:s})]})}return(0,ue.jsxs)("div",{children:[(0,ue.jsx)(Ya,{children:"Drafts"}),o.error?(0,ue.jsx)(Et,{message:"Couldn't load drafts.",onRetry:()=>void o.refetch()}):p?p.length===0?(0,ue.jsx)(va,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):(0,ue.jsx)("ul",{"data-testid":"drafts",className:"af-divide-y af-rounded-md af-border",children:p.map(u=>(0,ue.jsxs)("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[(0,ue.jsx)("span",{className:"af-truncate af-text-sm",children:u.subject||"(no subject)"}),(0,ue.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(u.id),children:"Review"})]},u.id))}):(0,ue.jsx)(ae,{className:"af-h-10 af-w-full"}),(0,ue.jsx)(Ya,{children:"Sent and scheduled"}),b.error&&(0,ue.jsx)(Ee,{tone:"error",children:b.error}),g.error&&(0,ue.jsx)(Ee,{tone:"error",children:g.error}),c.error?(0,ue.jsx)(Et,{message:"Couldn't load broadcasts.",onRetry:()=>void c.refetch()}):c.data?c.data.length===0?(0,ue.jsx)(va,{children:"Nothing sent yet."}):(0,ue.jsx)("ul",{className:"af-divide-y af-rounded-md af-border",children:c.data.map(u=>(0,ue.jsx)(Gf,{broadcast:u,canCancel:r&&(u.status==="scheduled"||u.status==="unscheduled"||u.status==="sending"),busy:b.busy||g.busy,onCancel:async()=>{(await b.run("cancelBroadcast",{sendId:u.id})).ok&&f(x=>x+1)},onDuplicate:r&&u.draft_id&&Uo(u)?async()=>{let v=await g.run("duplicateDraft",{draftId:u.draft_id});v.ok&&(f(x=>x+1),t(v.result.id))}:void 0},u.id))}):(0,ue.jsx)(ae,{className:"af-h-10 af-w-full"})]})}function Gf({broadcast:e,canCancel:t,busy:a,onCancel:s,onDuplicate:n}){return(0,ue.jsxs)("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[(0,ue.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,ue.jsx)("span",{className:"af-truncate af-text-sm af-font-medium",children:e.subject}),(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ue.jsx)(ie,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Wf[e.status]}),t&&(0,ue.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:s,children:"Cancel"}),n&&(0,ue.jsx)(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:n,children:"Duplicate"})]})]}),(0,ue.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",qe(e.recipients.planned)," recipients \xB7 ",qe(e.stats.delivered)," delivered \xB7 ",qe(e.stats.opened)," opened \xB7"," ",qe(e.stats.clicked)," clicked \xB7 ",qe(e.stats.bounced)," bounced \xB7 ",qe(e.stats.complained)," complaints \xB7"," ",qe(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&(0,ue.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:ks(e.status_reason)})]})}var vd=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function md(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:vd(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:s?Kf(a):"",suggested:t!==null||a!==null,timePassed:a!==null&&!s}}function Kf(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 Zf=(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 Yf({draft:e,preview:t,reload:a,onCommitted:s}){let{api:n}=W(),{siteId:r,canWrite:i,settings:l,refreshKey:f}=it(),[d,o]=_t.useState(null),[c,b]=_t.useState(!1),[g,m]=_t.useState(null),[p,u]=_t.useState(()=>md(e)),[v,x]=_t.useState(p.tagIds),[k,T]=_t.useState(p.match),[h,R]=_t.useState(p.scheduleAt),[P,D]=_t.useState(0),N=!Zf({tagIds:v,match:k,scheduleAt:h},p),E=vd(e);_t.useEffect(()=>{if(E===p.key||e.id===p.draftId&&N)return;let ne=md(e);u(ne),x(ne.tagIds),T(ne.match),R(ne.scheduleAt),D(0)},[E,e,p,N]);let A=_t.useMemo(()=>d?new Set(d.map(ne=>ne.id)):null,[d]),C=A!==null&&v.every(ne=>A.has(ne));_t.useEffect(()=>{if(!A||v.every(Re=>A.has(Re)))return;let ne=Re=>Re.filter(je=>A.has(je));D(Re=>Re+v.length-ne(v).length),x(ne(v)),u(Re=>({...Re,tagIds:ne(Re.tagIds)}))},[A,v]);let[K,Q]=_t.useState(null),[H,de]=_t.useState(null),[me,be]=_t.useState(null),V=Ot();_t.useEffect(()=>{n.getMarketingTags(r).then(ne=>{o(ne),b(!1)},()=>{o(null),b(!0)}),n.getMarketingContactStats(r).then(m,()=>m(null))},[n,r,f]);let J=h?new Date(h).toISOString():null,F=JSON.stringify([v,k,J]),ge=K?.plan??null,pe=K!==null&&K.key===F,He=_t.useRef(0),Pe=_t.useCallback(async()=>{let ne=++He.current;de(null);try{let Re=await n.estimateBroadcast(r,{targeting:{tag_ids:v,match:k},scheduled_at:J});ne===He.current&&Q({key:F,plan:Re})}catch(Re){if(ne!==He.current)return;Q(null),de(tr(Re))}},[n,r,v,k,J,F,f]),Ue=_t.useRef(!1);_t.useEffect(()=>{if(!C&&v.length>0)return;if(!Ue.current){Ue.current=!0,Pe();return}let ne=setTimeout(()=>void Pe(),300);return()=>clearTimeout(ne)},[Pe,C,v.length]);let ze=l&&!l.readiness.can_send?ks(l.readiness.reason):null,fe=ge!==null&&!ge.fits,lt=g?Math.max(0,g.by_status.subscribed-g.mailable):null,L=g&&ge&<!==null?Math.max(0,g.total-ge.recipients-lt):null,M=!i||V.busy||!ge||!pe||fe||ge.recipients===0||ze!==null||c&&v.length>0,U=async()=>{be(null);let ne=await V.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:v,match:k},scheduled_at:J});if(ne.ok){be({tone:"success",text:J?"Scheduled.":"Sending now."}),s();return}mn(ne.error,"version_conflict")?(V.setError(null),await a(),be({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):mn(ne.error,"over_allowance")&&await Pe()},Te=ne=>x(Re=>Re.includes(ne)?Re.filter(je=>je!==ne):[...Re,ne]);return(0,ue.jsxs)("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[p.suggested&&!N&&(0,ue.jsx)(Ee,{children:"Suggested by your assistant \u2014 review before sending."}),(0,ue.jsx)(Ya,{children:"Who gets it"}),c&&(0,ue.jsx)(Ee,{tone:"warning",children:v.length>0?"Couldn't load your tags, so this targeted send can't go out yet. Refresh to try again.":"Couldn't load your tags. Refresh to target by tag."}),P>0&&(0,ue.jsx)(Ee,{tone:"warning",children:P===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),d&&d.length>0?(0,ue.jsxs)("div",{className:"af-space-y-2",children:[(0,ue.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:d.map(ne=>(0,ue.jsxs)("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[(0,ue.jsx)("input",{type:"checkbox",checked:v.includes(ne.id),onChange:()=>Te(ne.id)}),ne.label]},ne.id))}),v.length>1&&(0,ue.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",(0,ue.jsxs)("select",{"aria-label":"Tag match",value:k,onChange:ne=>T(ne.target.value),className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,ue.jsx)("option",{value:"any",children:"any of these tags"}),(0,ue.jsx)("option",{value:"all",children:"all of these tags"})]})]}),v.length===0&&(0,ue.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):(0,ue.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Everyone who can be emailed."}),(0,ue.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,ue.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),(0,ue.jsx)(oe,{"aria-label":"Schedule time",type:"datetime-local",value:h,onChange:ne=>R(ne.target.value)})]}),p.timePassed&&!h&&(0,ue.jsx)(Ee,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),H?(0,ue.jsxs)(Ee,{tone:"error",children:["Couldn't work out the audience. ",H]}):ge?(0,ue.jsxs)("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[(0,ue.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,ue.jsx)(Go,{label:"Will receive it",value:ge.recipients}),(0,ue.jsx)(Go,{label:"Suppressed (bounced or complained)",value:lt}),(0,ue.jsx)(Go,{label:"Not included",value:L})]}),(0,ue.jsxs)("p",{className:"af-text-muted-foreground",children:[qe(ge.allowance.remaining)," of ",qe(ge.allowance.monthly)," emails left this month."]}),ge.sample_size!==null&&(0,ue.jsxs)(Ee,{children:["We'll send to ",qe(ge.sample_size)," people first and check for bounces before sending the rest."]}),ge.ramp_days.length>1&&(0,ue.jsxs)(Ee,{children:["Your domain is new, so this goes out over ",ge.ramp_days.length," days:"," ",ge.ramp_days.map(ne=>`${qe(ne.recipients)} on ${ne.date}`).join(", "),"."]})]}):(0,ue.jsx)(ae,{className:"af-h-12 af-w-full"}),fe&&ge&&(0,ue.jsxs)(Ee,{tone:"warning",children:["This send needs ",qe(ge.recipients)," emails, but only ",qe(ge.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),ze&&(0,ue.jsxs)(Ee,{tone:"warning",children:[ze,(0,ue.jsx)(er,{reason:l?.readiness.reason})]}),me&&(0,ue.jsx)(Ee,{tone:me.tone,children:me.text}),V.error&&(0,ue.jsx)(Ee,{tone:"error",children:V.error}),(0,ue.jsx)(y,{type:"button",disabled:M,onClick:()=>void U(),children:J?"Schedule":"Send now"})]})}function Go({label:e,value:t}){return(0,ue.jsxs)("div",{className:"af-rounded-md af-border af-px-2 af-py-1",children:[(0,ue.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,ue.jsx)("div",{className:"af-font-semibold",children:t===null?"\u2014":qe(t)})]})}var Na=ce(require("react"),1);var Ls=require("lucide-react");var As=ce(require("react"),1),Yt=require("lucide-react");var I=require("react/jsx-runtime"),Jf=[{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."}],Xf="hello";function Zo(e){return`${Xf}@${e}`}function bd({onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,onTurnOn:s,siteDomain:n,businessName:r}){let{api:i}=W(),{siteId:l,settings:f,canWrite:d,refreshKey:o,refetchSettings:c}=it(),b=Zt(()=>i.getMarketingContactStats(l),`${l}|${o}`,l),[g,m]=As.useState(!1),[p,u]=As.useState(null);if(!f)return null;let v=b.data?.by_status.subscribed??0,x={siteDomain:n,businessName:r};return Qf(f)?(0,I.jsx)(Yo,{settings:f,site:x,waiting:v,children:d?s&&(0,I.jsxs)("div",{className:"af-space-y-2",children:[(0,I.jsxs)(y,{disabled:g,onClick:async()=>{m(!0),u(null);try{await s(),await c()}catch(k){u(k instanceof Error?k.message:"Couldn't turn on email. Try again.")}finally{m(!1)}},children:["Get started ",(0,I.jsx)(Yt.ArrowRight,{className:"af-ml-2 af-h-4 af-w-4","aria-hidden":!0})]}),p&&(0,I.jsx)(Ee,{tone:"error",children:p})]}):(0,I.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Only the site owner can set up email."})}):(0,I.jsx)(em,{settings:f,site:x,waiting:v,onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a})}function Qf(e){return e.readiness.reason==="sending_not_enabled"}function Yo({settings:e,site:t,waiting:a=0,children:s}){return(0,I.jsx)("div",{className:"af-mx-auto af-max-w-3xl af-px-2 af-py-8",children:(0,I.jsxs)("div",{className:"af-grid af-items-center af-gap-10 md:af-grid-cols-[1fr_18rem]",children:[(0,I.jsxs)("div",{children:[(0,I.jsxs)("div",{className:"af-mb-3 af-inline-flex af-items-center af-gap-1.5 af-rounded-full af-bg-muted af-px-2.5 af-py-1 af-text-xs af-font-medium",children:[(0,I.jsx)(Yt.Mail,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0})," Email marketing"]}),(0,I.jsx)("h3",{className:"af-text-2xl af-font-semibold af-tracking-tight",children:"Turn visitors into regulars"}),(0,I.jsx)("p",{className:"af-mt-2 af-text-muted-foreground",children:"Build an email list from your website and reach those people directly, whenever you have something worth telling them."}),(0,I.jsx)("ol",{className:"af-mt-6 af-space-y-3",children:Jf.map((n,r)=>(0,I.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,I.jsx)("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-border af-text-xs af-font-semibold",children:r+1}),(0,I.jsxs)("p",{className:"af-text-sm",children:[(0,I.jsxs)("span",{className:"af-font-medium",children:[n.title,"."]})," ",(0,I.jsx)("span",{className:"af-text-muted-foreground",children:n.body})]})]},n.title))}),a>0&&(0,I.jsxs)("p",{className:"af-mt-5 af-rounded-md af-bg-amber-50 af-px-3 af-py-2 af-text-sm af-text-amber-900",children:[(0,I.jsxs)("span",{className:"af-font-semibold",children:[qe(a)," ",a===1?"person has":"people have"]})," ","already signed up and ",a===1?"is":"are"," waiting for your first email."]}),(0,I.jsx)("div",{className:"af-mt-6",children:s})]}),(0,I.jsx)(qi,{settings:e,site:t,className:"af-rotate-1"})]})})}function hd({onUpgradePlan:e}){return(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-border-violet-200 af-bg-gradient-to-r af-from-violet-50 af-to-white af-p-4",children:[(0,I.jsx)(Yt.Lock,{className:"af-h-5 af-w-5 af-shrink-0 af-text-violet-700","aria-hidden":!0}),(0,I.jsxs)("div",{className:"af-flex-1",children:[(0,I.jsx)("div",{className:"af-text-sm af-font-semibold af-text-violet-900",children:"Email marketing is part of Pro"}),(0,I.jsx)("div",{className:"af-text-sm af-text-violet-900/80",children:"Collect subscribers and send newsletters from your own domain."})]}),e&&(0,I.jsx)(y,{size:"sm",onClick:e,children:"Upgrade to Pro"})]})}function em({settings:e,site:t,waiting:a,onStartDomainSetup:s,onConnectDomain:n,onAskAssistant:r}){let{refetchSettings:i,canWrite:l}=it(),[f,d]=As.useState(null),o=p=>d(u=>u===p?null:p),{siteDomain:c}=t,b=Wr(e),g=c===null&&!e.domain.sending_domain,m=!!e.postal_address;return(0,I.jsxs)("div",{className:"af-mx-auto af-max-w-4xl af-py-4",children:[(0,I.jsxs)("div",{className:"af-mb-6 af-flex af-items-start af-justify-between af-gap-6",children:[(0,I.jsxs)("div",{children:[(0,I.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Set up email"}),(0,I.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Newsletters to your subscribers, sent from ",c??"your own domain","."]})]}),a>0&&(0,I.jsxs)("div",{className:"af-text-right",children:[(0,I.jsx)("div",{className:"af-text-2xl af-font-semibold",children:qe(a)}),(0,I.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[a===1?"subscriber":"subscribers"," waiting"]})]})]}),!l&&(0,I.jsx)(Ee,{className:"af-mb-4",children:"Only the site owner can finish setup."}),(0,I.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_16rem]",children:[(0,I.jsxs)("div",{className:"af-space-y-4",children:[(0,I.jsxs)(Ko,{title:c??"Your domain",sub:"One domain for your website and your email.",children:[c&&(0,I.jsx)(Rn,{icon:Yt.Globe,label:"Website",value:c,status:(0,I.jsx)(Nn,{tone:"green",children:"Live"})}),g?(0,I.jsx)(Rn,{icon:Yt.Mail,label:"Email sending",value:"Needs a custom domain",status:(0,I.jsx)(Nn,{tone:"gray",children:"Not available"}),action:n&&l?{label:"Connect domain",onClick:n}:void 0}):(0,I.jsxs)(Rn,{icon:Yt.Mail,label:"Email sending",value:e.domain.sending_domain??(c?`news.${c}`:"news.yourdomain.com"),status:Jo(e),action:!b&&l?{label:e.domain.sending_domain?"Details":"Set up",onClick:()=>o("sending")}:void 0,expanded:f==="sending",children:[!e.domain.sending_domain&&(0,I.jsx)("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:"Emails go out from a subdomain of your site's domain, so they reach inboxes and are clearly from you. If we manage your domain's DNS we add the records; otherwise you'll get a few to copy into your DNS provider."}),(0,I.jsx)(Xo,{settings:e,canWrite:l,onStartDomainSetup:s,onChanged:i})]})]}),(0,I.jsx)(Ko,{title:"Sender",sub:"Who your emails are from. The mailing address is legally required in every email.",children:(0,I.jsx)(Rn,{icon:Yt.PenLine,label:m?e.business_name??"Sender":"Not set",value:e.postal_address??"Name, mailing address and reply-to",status:m?(0,I.jsx)(Nn,{tone:"green",children:"Done"}):(0,I.jsx)(Nn,{tone:"gray",children:"Needed"}),action:l?{label:m?"Edit":"Add",onClick:()=>o("sender")}:void 0,expanded:f==="sender",children:(0,I.jsx)(tm,{settings:e,businessName:t.businessName,onSaved:async()=>{await i(),d(null)}})})}),(0,I.jsx)(Ko,{title:"How people join your list",sub:"Only people who asked to hear from you get your emails.",children:(0,I.jsx)(rm,{onAskAssistant:l?r:void 0})})]}),(0,I.jsxs)("aside",{className:"af-space-y-3",children:[(0,I.jsx)("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails will look like"}),(0,I.jsx)(qi,{settings:e,site:t})]})]})]})}function Ko({title:e,sub:t,children:a}){return(0,I.jsxs)("section",{className:"af-rounded-xl af-border af-bg-background",children:[(0,I.jsxs)("div",{className:"af-px-5 af-pb-3 af-pt-4",children:[(0,I.jsx)("h4",{className:"af-text-sm af-font-semibold",children:e}),(0,I.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:t})]}),(0,I.jsx)("div",{className:"af-space-y-2 af-px-3 af-pb-3",children:a})]})}function Rn({icon:e,marker:t,label:a,value:s,mono:n=!0,hint:r,status:i,action:l,expanded:f=!1,children:d}){return(0,I.jsxs)("div",{className:"af-rounded-lg af-border af-bg-muted/30",children:[(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-p-3",children:[t?(0,I.jsxs)("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-xs af-font-semibold af-text-background",children:[(0,I.jsx)("span",{"aria-hidden":!0,children:t}),(0,I.jsxs)("span",{className:"af-sr-only",children:["Shown at ",t," in the preview"]})]}):e&&(0,I.jsx)("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-background",children:(0,I.jsx)(e,{className:"af-h-4 af-w-4","aria-hidden":!0})}),(0,I.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,I.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:a}),(0,I.jsx)("div",{className:X("af-truncate af-text-sm",n&&"af-font-mono"),children:s}),r&&(0,I.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:r})]}),i,l&&(0,I.jsxs)(y,{size:"sm",variant:f?"secondary":"outline","aria-expanded":d?f:void 0,onClick:l.onClick,children:[l.label,d&&(0,I.jsx)(Yt.ChevronDown,{className:X("af-ml-1 af-h-3.5 af-w-3.5 af-transition-transform",f&&"af-rotate-180"),"aria-hidden":!0})]})]}),f&&d&&(0,I.jsx)("div",{className:"af-border-t af-bg-background af-p-4",children:d})]})}function Nn({tone:e,children:t}){return(0,I.jsx)("span",{className:X("af-inline-flex af-shrink-0 af-items-center af-rounded-full af-px-2 af-py-0.5 af-text-xs af-font-medium",e==="green"&&"af-bg-green-100 af-text-green-800",e==="amber"&&"af-bg-amber-100 af-text-amber-900",e==="gray"&&"af-bg-muted af-text-muted-foreground",e==="red"&&"af-bg-red-100 af-text-red-800"),children:t})}function Wr(e){return e.domain.status==="verified"&&e.domain.dmarc_status==="ok"}function Jo(e){let{sending_domain:t,status:a}=e.domain;return!t||a==="none"?(0,I.jsx)(Nn,{tone:"gray",children:"Not set up"}):a==="verified"?Wr(e)?(0,I.jsx)(Nn,{tone:"green",children:"Live"}):(0,I.jsx)(Nn,{tone:"amber",children:"DMARC record missing"}):a==="failed"?(0,I.jsx)(Nn,{tone:"red",children:"Records not found"}):(0,I.jsx)(Nn,{tone:"amber",children:"Waiting for DNS"})}function tm({settings:e,businessName:t,onSaved:a}){let{canWrite:s}=it(),[n,r]=As.useState(e.business_name??t??""),[i,l]=As.useState(e.postal_address??""),[f,d]=As.useState(e.reply_to??""),o=Ot();return(0,I.jsxs)("form",{className:"af-space-y-3",onSubmit:async c=>{c.preventDefault(),(await o.run("updateSettings",{business_name:n.trim()||null,postal_address:i.trim()||null,reply_to:f.trim()||null,double_opt_in:e.double_opt_in})).ok&&await a()},children:[(0,I.jsx)(am,{name:n,address:i}),(0,I.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,I.jsx)("span",{className:"af-text-sm af-font-medium",children:"Sender name"}),(0,I.jsx)(oe,{"aria-label":"Business name",value:n,disabled:!s,onChange:c=>r(c.target.value)})]}),(0,I.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,I.jsx)("span",{className:"af-text-sm af-font-medium",children:"Mailing address"}),(0,I.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:i,disabled:!s,onChange:c=>l(c.target.value)}),(0,I.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Anti-spam law requires it at the bottom of every email. A PO box works."})]}),(0,I.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,I.jsx)("span",{className:"af-text-sm af-font-medium",children:"Replies go to (optional)"}),(0,I.jsx)(oe,{"aria-label":"Reply-to email",type:"email",value:f,disabled:!s,onChange:c=>d(c.target.value)}),(0,I.jsx)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Your account email or an address on your domain."})]}),o.error&&(0,I.jsx)(Ee,{tone:"error",children:o.error}),s&&(0,I.jsx)(y,{type:"submit",size:"sm",disabled:o.busy||!i.trim(),children:"Save sender details"})]})}function am({name:e,address:t}){return(0,I.jsxs)("div",{className:"af-rounded-lg af-bg-muted/50 af-px-4 af-py-4 af-text-center af-text-xs af-leading-relaxed af-text-muted-foreground",children:[(0,I.jsx)("div",{className:"af-mb-1 af-text-[10px] af-uppercase af-tracking-wide",children:"Footer of every email"}),(0,I.jsxs)("div",{children:["\xA9 ",new Date().getFullYear()," ",(0,I.jsx)("span",{className:"af-font-medium af-text-foreground",children:e.trim()||"Your business"})]}),(0,I.jsx)("div",{className:X(!t.trim()&&"af-italic af-text-amber-700"),children:t.trim()||"No mailing address yet"}),(0,I.jsxs)("div",{children:[(0,I.jsx)("span",{className:"af-underline",children:"Manage preferences"})," | ",(0,I.jsx)("span",{className:"af-underline",children:"Unsubscribe"})]})]})}var nm={1:"From",2:"Subject and body",3:"Footer"};function qi({settings:e,site:t,className:a,numbered:s=!1,highlight:n=null,postalAddress:r}){let i=e?.business_name||t.businessName||"Your business",l=e?.domain.sending_domain??(t.siteDomain?`news.${t.siteDomain}`:"news.yourdomain.com"),f={backgroundColor:e?.brand.color??"hsl(var(--primary))"},d=r!==void 0?r.trim()||null:e?.postal_address,o=(c,b,g)=>s?(0,I.jsxs)("div",{"data-preview-region":c,"data-highlighted":n===c,className:X("af-relative af-rounded-md af-transition-shadow",n===c&&"af-ring-2 af-ring-primary af-ring-offset-2",b),children:[(0,I.jsxs)("span",{className:"af-absolute -af-left-3 -af-top-2 af-flex af-h-5 af-w-5 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-[10px] af-font-semibold af-text-background",children:[(0,I.jsx)("span",{"aria-hidden":!0,children:c}),(0,I.jsxs)("span",{className:"af-sr-only",children:[c,". ",nm[c],":"]})]}),g]}):(0,I.jsx)("div",{className:b,children:g});return(0,I.jsxs)("div",{className:X("af-rounded-lg af-border af-bg-background af-p-4 af-shadow-sm",a),"aria-hidden":s?void 0:!0,"aria-label":s?"Email preview":void 0,role:s?"group":void 0,children:[o(1,"af-flex af-items-start af-gap-3",(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-sm af-font-semibold af-text-white",style:f,children:i.slice(0,1).toUpperCase()}),(0,I.jsxs)("div",{className:"af-min-w-0",children:[(0,I.jsx)("div",{className:"af-truncate af-text-sm af-font-semibold",children:i}),(0,I.jsxs)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:["<",Zo(l),">"]}),(0,I.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:"to me"})]})]})),o(2,"af-mt-4 af-space-y-2",(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)("div",{className:"af-text-sm af-font-medium",children:"What's new this month"}),(0,I.jsx)("div",{className:"af-h-2 af-w-full af-rounded af-bg-muted"}),(0,I.jsx)("div",{className:"af-h-2 af-w-5/6 af-rounded af-bg-muted"}),(0,I.jsx)("div",{className:"af-h-2 af-w-2/3 af-rounded af-bg-muted"})]})),o(3,"af-mt-4 af-border-t af-pt-2 af-text-center af-text-[10px] af-leading-snug af-text-muted-foreground",(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)("div",{children:d??(0,I.jsx)("span",{className:"af-italic af-text-amber-700",children:"Mailing address goes here"})}),(0,I.jsx)("div",{className:"af-underline",children:"Unsubscribe"})]}))]})}var sm="Add a newsletter signup to my footer";function rm({onAskAssistant:e}){let t=Qo();if(!t.data)return null;let{signups:a,optIns:s,others:n}=el(t.data);return(0,I.jsxs)("div",{className:"af-space-y-3",children:[a.length===0?(0,I.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-gap-2 af-rounded-lg af-border af-border-dashed af-px-6 af-py-6 af-text-center",children:[(0,I.jsx)("div",{className:"af-flex af-h-10 af-w-10 af-items-center af-justify-center af-rounded-full af-bg-muted",children:(0,I.jsx)(Yt.Mail,{className:"af-h-5 af-w-5","aria-hidden":!0})}),(0,I.jsx)("div",{className:"af-text-sm af-font-medium",children:"Add a signup form to your site"}),(0,I.jsx)("p",{className:"af-max-w-sm af-text-xs af-text-muted-foreground",children:`A short "Get our news" form, usually in the footer. It's how most of your list will find you.`}),e&&(0,I.jsxs)(y,{type:"button",size:"sm",className:"af-mt-1",onClick:()=>e(sm),children:[(0,I.jsx)(Yt.Sparkles,{className:"af-mr-1.5 af-h-3.5 af-w-3.5","aria-hidden":!0}),"Add signup form"]})]}):(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[(0,I.jsx)(Yt.Check,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),(0,I.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,I.jsx)("span",{className:"af-font-medium",children:"Signup form is live"}),(0,I.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",a.map(r=>r.name).join(", ")]})]})]}),s.length>0&&(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[(0,I.jsx)(Yt.Check,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),(0,I.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,I.jsx)("span",{className:"af-font-medium",children:"Opt-in checkbox"}),(0,I.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",s.map(r=>r.name).join(", ")]})]})]}),a.length===0&&n.length>0&&(0,I.jsxs)("p",{className:"af-px-2 af-text-xs af-text-muted-foreground",children:["Your ",n.length===1?"form":"forms"," ",n.map(r=>`"${r.name}"`).join(", "),' can also add people, with a "Send me news" checkbox.',e&&(0,I.jsxs)(I.Fragment,{children:[" ",(0,I.jsx)("button",{type:"button",className:"af-font-medium af-text-foreground af-underline af-underline-offset-2",onClick:()=>e(tl(n)),children:"Add the checkbox"})]})]})]})}var te=require("react/jsx-runtime"),Gr="Subscribers confirm by email before they receive anything. Useful if many subscribers are in the EU (especially Germany), or if your forms attract fake or mistyped signups. Some signups need confirming even with this off: bursts of signups, and people re-subscribing after they unsubscribed.";function im(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 al({onStartDomainSetup:e,onAskAssistant:t}){let{settings:a,refetchSettings:s,canWrite:n,settingsSection:r}=it(),[i,l]=Na.useState(null),[f,d]=Na.useState(null),[o,c]=Na.useState(""),b=a!==null;if(Na.useEffect(()=>{b&&r&&document.getElementById(Vr(r))?.scrollIntoView?.({block:"start"})},[b,r]),!a)return(0,te.jsx)(ae,{className:"af-h-40 af-w-full"});let g=h=>d(R=>R===h?null:h),m=()=>d(null),p=async()=>{await s(),m()},u=(h,R,P)=>({id:P,"data-settings-row":h,onMouseEnter:()=>l(R),onMouseLeave:()=>l(null),onFocus:()=>l(R),onBlur:()=>l(null)}),v=Wr(a),{sending_domain:x,status:k}=a.domain,T=h=>n?{expanded:f===h}:{};return(0,te.jsx)("div",{className:"af-@container",children:(0,te.jsxs)("div",{className:"af-grid af-items-start af-gap-6 @2xl:af-grid-cols-[minmax(0,17rem)_minmax(0,1fr)]",children:[(0,te.jsxs)("aside",{className:"af-space-y-3 af-pl-3",children:[(0,te.jsx)("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails look like this"}),(0,te.jsx)(qi,{settings:a,site:{},numbered:!0,highlight:i,postalAddress:f==="address"?o:void 0}),(0,te.jsx)(fm,{settings:a})]}),(0,te.jsxs)("div",{children:[(0,te.jsx)(Ya,{children:"From"}),(0,te.jsxs)("div",{className:"af-space-y-2",children:[(0,te.jsx)("div",{...u("Sending domain",1,Vr("domain")),children:(0,te.jsx)(Rn,{marker:1,label:"Sending from",value:x?Zo(x):"No sending domain yet",status:Jo(a),action:!v&&n?{label:x?k==="verified"||k==="failed"?"Fix":"Details":"Set up",onClick:()=>g("domain")}:void 0,...T("domain"),children:(0,te.jsx)(Xo,{settings:a,canWrite:n,onStartDomainSetup:e,onChanged:s})})}),(0,te.jsx)("div",{...u("Sender name and replies",1),children:(0,te.jsx)(Rn,{marker:1,label:"Sender name and replies",mono:!1,value:`${a.business_name??"No sender name"} \xB7 replies to ${a.reply_to??"your account email"}`,action:n?{label:"Edit",onClick:()=>g("sender")}:void 0,...T("sender"),children:(0,te.jsx)(om,{settings:a,onSaved:p,onCancel:m})})})]}),(0,te.jsx)(Ya,{children:"Brand"}),(0,te.jsx)("div",{...u("Brand color and logo",2),children:(0,te.jsx)(Rn,{marker:2,label:"Brand color and logo",value:`${a.brand.color}, ${a.brand.logo_url?"with your logo":"no logo"}`,action:n?{label:"Edit",onClick:()=>g("brand")}:void 0,...T("brand"),children:(0,te.jsx)(lm,{settings:a,onSaved:p,onCancel:m})})}),(0,te.jsx)(Ya,{children:"Footer"}),(0,te.jsx)("div",{...u("Mailing address",3,Vr("sender")),children:(0,te.jsx)(Rn,{marker:3,label:"Mailing address",mono:!1,value:a.postal_address??"Not set",hint:"Anti-spam law requires it at the bottom of every email. A PO box works.",status:a.postal_address?void 0:(0,te.jsx)(Nn,{tone:"amber",children:"Needed"}),action:n?{label:a.postal_address?"Edit":"Add",onClick:()=>{c(a.postal_address??""),g("address")}}:void 0,...T("address"),children:(0,te.jsx)(cm,{settings:a,draft:o,onDraft:c,onSaved:p,onCancel:m})})}),(0,te.jsxs)("div",{id:Vr("signups"),children:[(0,te.jsx)(Ya,{children:"Who gets it"}),(0,te.jsxs)("div",{className:"af-space-y-2",children:[(0,te.jsx)("div",{...u("Double opt-in",null),children:(0,te.jsx)(dm,{settings:a,canWrite:n,onSaved:s})}),(0,te.jsx)(mm,{onAskAssistant:n?t:void 0})]})]})]})]})})}function Wi(e,t){return{business_name:e.business_name,postal_address:e.postal_address,reply_to:e.reply_to,double_opt_in:e.double_opt_in,...t}}function nl({busy:e,error:t,canSave:a=!0,onSave:s,onCancel:n,children:r}){return(0,te.jsxs)("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),await s()},children:[r,t&&(0,te.jsx)(Ee,{tone:"error",children:t}),(0,te.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,te.jsx)(y,{type:"submit",size:"sm",disabled:e||!a,children:"Save"}),(0,te.jsx)(y,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Cancel"})]})]})}function om({settings:e,onSaved:t,onCancel:a}){let[s,n]=Na.useState(e.business_name??""),[r,i]=Na.useState(e.reply_to??""),l=Ot();return(0,te.jsxs)(nl,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",Wi(e,{business_name:s.trim()||null,reply_to:r.trim()||null}))).ok&&await t()},children:[(0,te.jsx)(ji,{label:"Sender name",children:(0,te.jsx)(oe,{"aria-label":"Business name",value:s,onChange:f=>n(f.target.value)})}),(0,te.jsx)(ji,{label:"Replies go to (your account email or an address on your domain)",children:(0,te.jsx)(oe,{"aria-label":"Reply-to email",type:"email",value:r,onChange:f=>i(f.target.value)})})]})}function lm({settings:e,onSaved:t,onCancel:a}){let[s,n]=Na.useState(e.brand.color),[r,i]=Na.useState(e.brand.logo_url??""),l=Ot();return(0,te.jsx)(nl,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",Wi(e,{brand:{color:s,logo_url:r.trim()||null}}))).ok&&await t()},children:(0,te.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-3",children:[(0,te.jsx)(ji,{label:"Brand color",children:(0,te.jsx)(oe,{"aria-label":"Brand color",type:"color",className:"af-h-9 af-w-16 af-p-1",value:s,onChange:f=>n(f.target.value)})}),(0,te.jsx)(ji,{label:"Logo URL (https)",children:(0,te.jsx)(oe,{"aria-label":"Logo URL",value:r,onChange:f=>i(f.target.value)})})]})})}function cm({settings:e,draft:t,onDraft:a,onSaved:s,onCancel:n}){let r=Ot();return(0,te.jsx)(nl,{busy:r.busy,error:r.error,canSave:!!t.trim(),onCancel:n,onSave:async()=>{(await r.run("updateSettings",Wi(e,{postal_address:t.trim()}))).ok&&await s()},children:(0,te.jsx)("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:t,onChange:i=>a(i.target.value)})})}function dm({settings:e,canWrite:t,onSaved:a}){let[s,n]=Na.useState(null),[r,i]=Na.useState(!1),l=Ot(),f=s??e.double_opt_in;return(0,te.jsxs)("div",{className:"af-space-y-2",children:[(0,te.jsx)(Rn,{icon:Ls.ShieldCheck,label:"Double opt-in",mono:!1,value:f?"New subscribers confirm by email first":"New subscribers join straight away",status:(0,te.jsxs)("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[(0,te.jsx)("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:Gr,className:"af-inline-flex af-h-4 af-w-4 af-cursor-help af-items-center af-justify-center af-rounded-full af-border af-text-[10px]",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:"?"}),(0,te.jsx)("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!r,className:"af-absolute af-right-0 af-top-6 af-z-10 af-w-72 af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:Gr}),(0,te.jsx)("input",{"aria-label":"Double opt-in",type:"checkbox",role:"switch",checked:f,disabled:!t||l.busy,onChange:async d=>{let o=d.target.checked;n(o),(await l.run("updateSettings",Wi(e,{double_opt_in:o}))).ok&&await a(),n(null)}})]})}),l.error&&(0,te.jsx)(Ee,{tone:"error",children:l.error})]})}function Xo({settings:e,canWrite:t,onStartDomainSetup:a,onChanged:s}){let[n,r]=Na.useState(null),[i,l]=Na.useState(!1),[f,d]=Na.useState(null),o=Wr(e);return(0,te.jsxs)("div",{children:[(0,te.jsx)("p",{className:"af-text-sm",children:im(e)}),!o&&a&&(0,te.jsx)(y,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||i,onClick:async()=>{l(!0),d(null);try{r(await a()),await s()}catch(c){d(c instanceof Error?c.message:"Couldn't start domain setup.")}finally{l(!1)}},children:e.domain.sending_domain?"Check domain setup":"Set up sending domain"}),f&&(0,te.jsx)(Ee,{tone:"error",className:"af-mt-2",children:f}),n?.records&&n.records.length>0&&(0,te.jsxs)("div",{className:"af-mt-3 af-space-y-1",children:[(0,te.jsx)("p",{className:"af-text-sm",children:"Add these records at your domain provider:"}),(0,te.jsxs)("table",{className:"af-w-full af-text-left af-text-xs",children:[(0,te.jsx)("thead",{children:(0,te.jsxs)("tr",{children:[(0,te.jsx)("th",{className:"af-py-1 af-pr-2",children:"Type"}),(0,te.jsx)("th",{className:"af-py-1 af-pr-2",children:"Name"}),(0,te.jsx)("th",{className:"af-py-1 af-pr-2",children:"Value"}),(0,te.jsx)("th",{className:"af-py-1",children:"Priority"})]})}),(0,te.jsx)("tbody",{children:n.records.map((c,b)=>(0,te.jsxs)("tr",{className:"af-border-t af-align-top",children:[(0,te.jsx)("td",{className:"af-py-1 af-pr-2",children:c.type}),(0,te.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:c.name}),(0,te.jsx)("td",{className:"af-break-all af-py-1 af-pr-2",children:c.value}),(0,te.jsx)("td",{className:"af-py-1",children:c.priority??""})]},b))})]})]}),n&&(0,te.jsx)(um,{result:n})]})}function um({result:e}){return e.status==="no_domain"?(0,te.jsx)(Ee,{tone:"warning",className:"af-mt-2",children:"Emails send from your own domain, so this site needs a custom domain first. Connect one, then come back to finish here."}):e.status==="not_available"?(0,te.jsx)(Ee,{tone:"warning",className:"af-mt-2",children:"Email sending isn't available for this site. It needs the Pro plan."}):e.records&&e.records.length>0?null:(0,te.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",children:"We added the DNS records for you. Verification usually finishes within a few hours."})}function fm({settings:e}){let{monthly:t,sent:a,reserved:s}=e.allowance,n=a+s;return(0,te.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[qe(n)," of ",qe(t)," emails used this month (",qe(Math.max(0,t-n))," left). Receipts and form notifications don't count."]})}function Qo(){let{api:e}=W(),{siteId:t,refreshKey:a}=it();return Zt(async()=>Promise.all((await e.getForms()).map(s=>e.getForm(s.id))),`${t}|${a}`,t)}function el(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 tl(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 mm({onAskAssistant:e}){let t=Qo();if(!t.data||t.data.length===0)return null;let{signups:a,optIns:s,others:n}=el(t.data),r=[{id:"signup",label:"Signup forms",note:"Submitting one subscribes the visitor.",forms:a,icon:Ls.Check},{id:"opt_in",label:'Forms with a "Send me news" checkbox',note:"Visitors who tick the box join your list.",forms:s,icon:Ls.Check},{id:"other",label:"Other forms",note:"These don't add anyone to your list.",forms:n,icon:Ls.FileText,action:a.length===0&&e?{label:"Add the checkbox",onClick:()=>e(tl(n))}:void 0}];return(0,te.jsx)(te.Fragment,{children:r.filter(i=>i.forms.length>0).map(i=>(0,te.jsx)("div",{"data-form-group":i.id,children:(0,te.jsx)(Rn,{icon:i.icon,label:i.label,mono:!1,value:i.forms.map(l=>l.name).join(", "),hint:i.note,action:i.action})},i.id))})}function ji({label:e,children:t}){return(0,te.jsxs)("label",{className:"af-block af-space-y-1",children:[(0,te.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}var Gi=ce(require("react"),1);var bt=require("react/jsx-runtime");function xd({templateId:e,onOpenTemplate:t,onOpenDraft:a,onAskAssistant:s}){let{api:n}=W(),{siteId:r,canWrite:i,refreshKey:l}=it(),[f,d]=Gi.useState(0),o=f+l,c=Zt(()=>n.getEmailTemplates(r),`${r}|${o}`,r),b=Gi.useCallback(()=>d(u=>u+1),[]),g=i?s:void 0;if(e){let u=e===Mn?null:c.data?.find(v=>v.id===e);if(u!==void 0)return(0,bt.jsx)(cd,{template:u,onBack:()=>t(null),onOpenTemplate:t,onOpenDraft:a,onAskAssistant:g,reload:b,refreshKey:o},e);if(c.isLoading)return(0,bt.jsx)(ae,{className:"af-h-96 af-w-full"})}let m=c.data?.filter(u=>u.status!=="archived")??[],p=c.data?.filter(u=>u.status==="archived")??[];return(0,bt.jsxs)("div",{children:[(0,bt.jsxs)("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[(0,bt.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Templates"}),g&&(0,bt.jsx)(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(Hi.create),children:"\u2728 New template with the editor"})]}),(0,bt.jsxs)(yd,{children:[(0,bt.jsx)(sl,{template:null,onOpen:()=>t(Mn)}),m.map(u=>(0,bt.jsx)(sl,{template:u,onOpen:()=>t(u.id)},u.id))]}),c.error&&!c.data?(0,bt.jsx)("div",{className:"af-mt-3",children:(0,bt.jsx)(Et,{message:"Couldn't load your templates.",onRetry:()=>void c.refetch()})}):!c.data&&(0,bt.jsx)(ae,{className:"af-mt-3 af-h-10 af-w-full"}),p.length>0&&(0,bt.jsxs)("div",{"data-testid":"archived-templates",children:[(0,bt.jsx)(Ya,{children:"Archived"}),(0,bt.jsx)(yd,{children:p.map(u=>(0,bt.jsx)(sl,{template:u,onOpen:()=>t(u.id)},u.id))})]})]})}function yd({children:e}){return(0,bt.jsx)("ul",{className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:e})}function pm(e){let t=[Wo(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&&pm(e);return(0,bt.jsxs)("li",{"data-testid":"template-card",className:"af-relative af-overflow-hidden af-rounded-md af-border hover:af-border-primary",children:[(0,bt.jsx)(zi,{templateId:e?.id??Mn,version:e?.updated_at??"builtin",className:"af-h-40 af-border-b",frame:{width:600,height:400,scale:.4}}),(0,bt.jsxs)("div",{className:"af-space-y-1 af-p-2",children:[(0,bt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,bt.jsx)("span",{"data-testid":"template-name",className:"af-grow af-truncate af-text-sm af-font-medium",children:a}),(0,bt.jsx)(jo,{template:e})]}),s&&(0,bt.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:s})]}),(0,bt.jsx)("button",{type:"button","aria-label":`Open ${a}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}var Ze=require("react/jsx-runtime"),gm=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"templates",label:"Templates"},{id:"settings",label:"Settings"}];function os(e,t={}){return{tab:e,draftId:null,templateId:null,...t}}var wd=e=>!!(e.tab||e.draftId||e.templateId);function Sd(e){return e.draftId?os("broadcasts"):e.templateId?os("templates",{templateId:e.templateId}):os(e.tab==="template"?"templates":e.tab==="automations"||!e.tab?"audience":e.tab)}var vm={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function rl(e){return(0,Ze.jsx)(bm,{...e},e.siteId)}function bm({siteId:e,isOwnerSide:t,needsPaidPlan:a,initialDraftId:s,initialTab:n,templateId:r,showViewNonce:i,onOrgAction:l,onRequestReview:f,onStartDomainSetup:d,onBackToWebsite:o,onUpgradePlan:c,onConnectDomain:b,onAskAssistant:g,onPickImage:m,onTurnOn:p,siteDomain:u,businessName:v,onOpenStoreSettings:x,refreshKey:k=0,className:T}){let{api:h}=W(),R=Zt(()=>h.getMarketingSettings(e),`${e}|${k}`,e),P={tab:n,draftId:s,templateId:r},[D,N]=ta.useState(()=>Sd(P)),[E,A]=ta.useState(s??null),[C,K]=ta.useState(wd(P)),[Q,H]=ta.useState(null),[de,me]=ta.useState(!1),be=ta.useCallback(()=>K(!1),[]),V=ta.useCallback(fe=>{N(os("settings")),H(fe??null)},[]),J=fe=>{N(os(fe)),H(null)},F=ta.useCallback(fe=>N(os("broadcasts",{draftId:fe})),[]),ge=ta.useCallback(fe=>N(os("templates",{templateId:fe})),[]),pe=!C&&R.data!==null&&hm(R.data),He=R.data&&!R.error?ym(R.data):null,Pe=JSON.stringify([i??null,n??null,s??null,r??null]),Ue=ta.useRef(Pe);ta.useEffect(()=>{if(Pe===Ue.current||de)return;Ue.current=Pe;let fe={tab:n,draftId:s,templateId:r};wd(fe)&&(N(Sd(fe)),A(fe.draftId??null),H(null),K(!0))},[Pe,de,n,s,r]),ta.useEffect(()=>{if(!E||a)return;let fe=!0,lt=L=>{fe&&(N(os("broadcasts",{draftId:L})),A(null))};return h.getEmailDraft(e,E).then(L=>lt(L.kind==="broadcast"?L.id:null),()=>lt(null)),()=>{fe=!1}},[h,e,E,a]);let ze=ta.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:l,settings:R.data,refetchSettings:R.refetch,refreshKey:k,openSetup:be,openSettings:V,settingsSection:Q,onOpenStoreSettings:x,setInlineEditOpen:me}),[e,t,l,R.data,R.refetch,k,be,V,Q,x]);return a?(0,Ze.jsx)(Lt,{title:"Email Marketing",onBackToWebsite:o,className:T,children:(0,Ze.jsx)(Yo,{settings:R.data,site:{siteDomain:u,businessName:v},children:(0,Ze.jsx)(hd,{onUpgradePlan:c})})}):(0,Ze.jsx)(Lt,{title:"Email Marketing",onBackToWebsite:o,className:T,children:(0,Ze.jsx)(Mo.Provider,{value:ze,children:pe?(0,Ze.jsx)(bd,{onStartDomainSetup:d,onConnectDomain:b,onAskAssistant:g,onTurnOn:p,siteDomain:u,businessName:v}):(0,Ze.jsxs)(Ze.Fragment,{children:[R.error&&!R.data&&(0,Ze.jsx)(Et,{message:"Couldn't load email settings.",onRetry:()=>void R.refetch()}),He&&(0,Ze.jsx)(wm,{reason:He,pauseReason:R.data?.paused.reason??null,onRequestReview:f}),!t&&(0,Ze.jsx)(Ee,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),(0,Ze.jsx)("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:gm.map(fe=>(0,Ze.jsxs)("button",{type:"button",role:"tab","aria-selected":D.tab===fe.id,onClick:()=>J(fe.id),className:X("af-border-b-2 af-px-3 af-py-2 af-text-sm",D.tab===fe.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:[fe.label,fe.id==="settings"&&He&&(0,Ze.jsx)("span",{"data-testid":"settings-dot",role:"img","aria-label":"Sending is on hold",className:"af-ml-1.5 af-inline-block af-h-1.5 af-w-1.5 af-rounded-full af-bg-amber-600 af-align-middle"})]},fe.id))}),(0,Ze.jsx)("div",{role:"tabpanel",children:E?(0,Ze.jsx)(ae,{className:"af-h-24 af-w-full"}):D.tab==="audience"?(0,Ze.jsx)(ed,{}):D.tab==="broadcasts"?(0,Ze.jsx)(gd,{openDraftId:D.draftId,onOpenDraft:F,onAskAssistant:g,onPickImage:m}):D.tab==="templates"?(0,Ze.jsx)(xd,{templateId:D.templateId,onOpenTemplate:ge,onOpenDraft:F,onAskAssistant:g}):(0,Ze.jsx)(al,{onStartDomainSetup:d,onAskAssistant:g})})]})})})}function hm(e){return!e.paused.paused_at&&!e.readiness.can_send&&Ur.has(e.readiness.reason??"")}function ym(e){if(e.paused.paused_at)return"paused";let t=e.readiness.reason;return!e.readiness.can_send&&t&&Ur.has(t)?t:null}var xm={domain_not_verified:"domain",dmarc_missing:"domain",postal_address_missing:"sender"};function wm({reason:e,pauseReason:t,onRequestReview:a}){let{openSetup:s,openSettings:n}=it(),[r,i]=ta.useState("idle");if(e==="paused")return(0,Ze.jsx)("div",{"data-testid":"email-hold",className:"af-mb-3",children:(0,Ze.jsxs)(Ee,{tone:"warning",children:[(0,Ze.jsx)("div",{className:"af-font-medium",children:"Sending is paused."}),(0,Ze.jsxs)("p",{children:[vm[t??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),a&&(r==="sent"?(0,Ze.jsx)("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):(0,Ze.jsx)(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{i("sending");try{await a(),i("sent")}catch{i("failed")}},children:"Request review"})),r==="failed"&&(0,Ze.jsx)("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]})});let l=xm[e];return(0,Ze.jsx)("div",{"data-testid":"email-hold",className:"af-mb-3",children:(0,Ze.jsxs)(Ee,{tone:"warning",children:["Sending is on hold. ",ks(e)," ",l?(0,Ze.jsx)(Ts,{onClick:()=>n(l),children:"Fix in Settings"}):(0,Ze.jsx)(Ts,{onClick:s,children:"Finish setup"})]})})}var aa=ce(require("react"),1);var Sm=2e3,fa=()=>({data:null,error:null,isLoading:!0});function Os(e,{refreshKey:t,breakdowns:a=[],filters:s=[]}={}){let{api:n}=W(),[r,i]=aa.useState(fa),[l,f]=aa.useState(fa),[d,o]=aa.useState(fa),[c,b]=aa.useState(fa),[g,m]=aa.useState(fa),p=V=>Object.fromEntries(V.map(J=>[J,fa()])),[u,v]=aa.useState(()=>p(a)),x=aa.useRef(0),k=aa.useRef(0),T=aa.useRef("idle"),h=a.join(","),R=Xn()??"",P=JSON.stringify(s),D=`${e}:${h}:${P}:${R}`,[N,E]=aa.useState({api:n,fetchIdentity:D});(N.api!==n||N.fetchIdentity!==D)&&(E({api:n,fetchIdentity:D}),x.current+=1,i(fa),f(fa),o(fa),b(fa),v(p(h?h.split(","):[])));let A=`${e}:${String(t??"")}:${R}`,[C,K]=aa.useState({api:n,conversionsIdentity:A});(C.api!==n||C.conversionsIdentity!==A)&&(K({api:n,conversionsIdentity:A}),k.current+=1,T.current="idle",m(fa));let Q=aa.useCallback(async V=>{let J=++x.current,F=h?h.split(","):[];i(fa),f(fa),o(fa),b(fa),v(Object.fromEntries(F.map(L=>[L,fa()])));let ge=T.current!=="pending"&&(V?.force===!0||T.current==="idle"),pe=(L,M)=>M.then(U=>{J===x.current&&L({data:U,error:null,isLoading:!1})},U=>{J===x.current&&L({data:null,error:U instanceof Error?U:new Error("Failed to fetch report"),isLoading:!1})}),He=n.getAnalyticsStatus(),Pe=pe(i,He),Ue=Symbol("status-timeout"),ze,fe=await Promise.race([He.then(L=>L,()=>null),new Promise(L=>{ze=setTimeout(()=>L(Ue),Sm)})]);if(clearTimeout(ze),J!==x.current)return;if(fe===Ue&&i({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),fe!==null&&fe!==Ue&&(fe.collecting!==!0||fe.first_seen===null&&!fe.first_seen_unavailable||fe.first_seen!==null&&fe.first_seen_in_reports===!1)){let L={data:null,error:null,isLoading:!1};f(L),o(L),b(L),v(Object.fromEntries(F.map(M=>[M,{...L}]))),ge&&(m(L),T.current="done"),await Pe;return}await Promise.all([fe===Ue?Promise.resolve():Pe,pe(f,n.getAnalyticsSummary(e,s)),pe(o,n.getAnalyticsTimeseries(e,s)),pe(b,n.getAnalyticsChannels(e,s)),ge?(()=>{T.current="pending";let L=++k.current;return m(fa),n.getAnalyticsConversions(e).then(M=>{L===k.current&&(m({data:M,error:null,isLoading:!1}),T.current="done")},M=>{L===k.current&&(m({data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}),T.current="done")})})():Promise.resolve(),...F.map(L=>n.getAnalyticsBreakdown(L,e,s).then(M=>{J===x.current&&v(U=>({...U,[L]:{data:M,error:null,isLoading:!1}}))},M=>{J===x.current&&v(U=>({...U,[L]:{data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,P,A,R]),H=aa.useCallback(async()=>{let V=x.current;try{let J=await n.getAnalyticsStatus();if(V!==x.current)return;i({data:J,error:null,isLoading:!1})}catch(J){if(V!==x.current)return;i(F=>({data:F.data,error:J instanceof Error?J:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),de=aa.useCallback(()=>Q({force:!0}),[Q]);aa.useEffect(()=>{Q()},[Q,t]);let me=r.isLoading||l.isLoading||d.isLoading||c.isLoading||g.isLoading||Object.values(u).some(V=>V.isLoading),be=[d,l,c,g,...Object.values(u)].map(V=>V.data?.status==="ok"?V.data.timezone:void 0).find(V=>V!==void 0);return{status:r,summary:l,timeseries:d,channels:c,conversions:g,breakdowns:u,reportedZone:be,isLoading:me,refetch:de,refetchStatus:H}}var na=ce(require("react"),1);var Ki=3e4,Zi=3;function Kr(e={}){let t="collecting"in e,{collecting:a,statusFailed:s=!1,identity:n}=e,{api:r}=W(),[i,l]=na.useState(null),[f,d]=na.useState(null),[o,c]=na.useState(!1),[b,g]=na.useState(null),[m,p]=na.useState(!1),[u,v]=na.useState(!0),[x,k]=na.useState(0),T=na.useRef(0),h=na.useRef(0),R=na.useRef(void 0);a!==void 0&&(R.current=a);let P=t?R.current===!0||R.current===void 0&&s:!0,[D,N]=na.useState({api:r,identity:n}),E=n!==void 0&&n!==D.identity;(D.api!==r||E)&&(R.current=void 0,N({api:r,identity:n}),h.current+=1,T.current=0,l(null),d(null),c(!1),g(null),p(!1),v(!0),k(0));let A=na.useRef(()=>{}),C=na.useRef(null),K=na.useCallback(async()=>{if(C.current!==null&&C.current===h.current)return;let Q=++h.current;C.current=Q;try{let H=await r.getAnalyticsRealtime();if(Q!==h.current)return;if(H.status==="unreachable"){p(!0),c(!0),v(!1),k(de=>de+1);return}T.current=0,p(!1),l(H.data.current_visitors),d(H.as_of),c(!1),g(null),v(!1),k(de=>de+1)}catch(H){if(Q!==h.current)return;T.current+=1,v(!1),k(de=>de+1),c(!0),T.current>=Zi&&g(H instanceof Error?H:new Error("Realtime unavailable"))}finally{C.current===Q&&(C.current=null)}},[r]);return A.current=()=>void K(),na.useEffect(()=>{let Q,H=()=>{Q===void 0&&(Q=setInterval(()=>A.current(),Ki))},de=()=>{Q!==void 0&&(clearInterval(Q),Q=void 0)},me=()=>{typeof document<"u"&&document.hidden?de():(A.current(),H())};return P?((typeof document>"u"||!document.hidden)&&(A.current(),H()),document?.addEventListener("visibilitychange",me),()=>{de(),document?.removeEventListener("visibilitychange",me),h.current+=1}):()=>{document?.removeEventListener("visibilitychange",me)}},[D.api,D.identity,P]),{currentVisitors:i,asOf:f,isStale:o,error:b,isUnreachable:m,isInitialLoad:u,polls:x}}var Mt=ce(require("react"),1);var Nd=ce(require("react"),1);var Bs=require("react/jsx-runtime");function Nm(){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 il({value:e,chosen:t,onChange:a}){let s=rr(),n=t===null&&s!==null&&e===s,r=Nd.useMemo(()=>{let i=Nm();return i.includes(e)?i:[e,...i]},[e]);return(0,Bs.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,Bs.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,Bs.jsxs)("select",{value:n?"":e,onChange:i=>a(i.target.value===""?null:i.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[(0,Bs.jsx)("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(i=>(0,Bs.jsx)("option",{value:i,children:i.replace(/_/g," ")},i))]})]})}var Yi=(e,{published:t}={})=>{let a=t===!1,s=e!=null&&(!e.collecting||a&&e.first_seen===null&&!e.first_seen_unavailable),n=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,i=n||r;return{notCollecting:s,awaitingFirstVisit:n,firstVisitTooRecent:r,holdingForFirstData:i,nothingToReport:s||i}};var Zr=ce(require("react"),1),Rm=3e4;function Ji({status:e,holdingForFirstData:t,refetchStatus:a,refetch:s}){Zr.useEffect(()=>{if(!t)return;let r,i=()=>{r===void 0&&(r=setInterval(()=>void a(),Rm))},l=()=>{r!==void 0&&(clearInterval(r),r=void 0)},f=()=>{typeof document<"u"&&document.hidden?l():(a(),i())};return(typeof document>"u"||!document.hidden)&&i(),document?.addEventListener("visibilitychange",f),()=>{l(),document?.removeEventListener("visibilitychange",f)}},[t,a]);let n=Zr.useRef(void 0);Zr.useEffect(()=>{if(!e){n.current=void 0;return}let r=n.current;n.current=t,r===!0&&!t&&s()},[e,t,s])}var Fs=ce(require("react"),1);var _m=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ra(e){let t=Math.abs(e);if(t<1e3)return String(e);let a=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[s,n]of a)if(t>=s){let r=e/s,i=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(i)>=1e3&&s!==1e9?Ra(i*s):`${i}${n}`}return String(e)}function nr(e){return`${(e*100).toFixed(1)}%`}function Yr(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let a=Math.floor(t/60);return a<60?`${a}m ${t%60}s`:`${Math.floor(a/60)}h ${a%60}m`}function _d(e){let t=Math.max(0,Math.round(e));return t>=3600&&t%3600===0?`${t/3600}h`:t>=60&&t%60===0?`${t/60}m`:Yr(t)}function Pd(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function kd(e,t){if(!(!Number.isFinite(e)||e<=0))for(let a of t){let s=Math.ceil(e/a);if(s<=5)return Array.from({length:s+1},(n,r)=>Number((r*a).toPrecision(12)))}}function Jr(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Cd(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 ol(e){let t=Number(e.slice(5,7)),a=Number(e.slice(8,10));return`${_m[t-1]} ${a}`}function Rd(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Pm(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Td(e,t,a="UTC"){let s=new Map(t.map(i=>[i.date,i])),n=[],r=Rd(e.to,a);for(let i=Rd(e.from,a);i<r;i=Pm(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 Ed(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 Xa=require("react/jsx-runtime");function Id({what:e="This report",onRetry:t,collecting:a}){return(0,Xa.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,Xa.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,Xa.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,Xa.jsx)("button",{type:"button",onClick:t,className:"af-mt-2 af-rounded-md af-border af-border-border af-px-3 af-py-1 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Try again"}):null]})}function Xi({what:e="No data"}){return(0,Xa.jsx)("div",{className:"af-flex af-items-center af-justify-center af-rounded-md af-px-4 af-py-8 af-text-center af-text-xs af-text-muted-foreground",children:e})}function Yn({sourced:e,error:t,isLoading:a,what:s,onRetry:n,collecting:r,children:i}){return a?(0,Xa.jsx)("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,Xa.jsx)(Id,{what:s,onRetry:n,collecting:r}):!e||e.status==="unreachable"?(0,Xa.jsx)(Id,{what:s,onRetry:n,collecting:r}):(0,Xa.jsx)(Xa.Fragment,{children:i(e.data)})}var Pt=require("react/jsx-runtime");function ll({rows:e,dimension:t,metric:a,metricLabel:s,secondary:n,emptyCopy:r="No data for this period",onFilter:i,canFilter:l,maxRows:f=9}){let[d,o]=Fs.useState(!1);if(e.length===0)return(0,Pt.jsx)(Xi,{what:r});let c=e.reduce((m,p)=>Math.max(m,Number(p[a]??0)),0)||1,b=Math.max(0,e.length-f),g=d?e:e.slice(0,f);return(0,Pt.jsxs)(Pt.Fragment,{children:[(0,Pt.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Pt.jsx)("thead",{children:(0,Pt.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Pt.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,Pt.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),(0,Pt.jsx)("tbody",{children:g.map((m,p)=>{let u=Number(m[a]??0),v=m[t]??null,x=Jr(v),k=n?m[n]:null,T=v!==null&&(l?l(v,k):!0);return(0,Pt.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,Pt.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,Pt.jsx)("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,u/c*100)}%`}}),v!==null&&i&&T?(0,Pt.jsx)("button",{type:"button",onClick:()=>i(v,k),title:`Filter by ${x}`,"aria-label":`Filter by ${x}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:x}):(0,Pt.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:x}),k?(0,Pt.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:k}):null]}),(0,Pt.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Ra(u)})]},`${x}-${k??""}-${p}`)})})]}),b>0?(0,Pt.jsx)("button",{type:"button",onClick:()=>o(m=>!m),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:d?"Show fewer":`Show all ${e.length}`}):null]})}function Xr({title:e,tabs:t,defaultTabId:a,headerRight:s}){let[n,r]=Fs.useState(a),i=t.find(g=>g.id===n)??t[0],l=Fs.useId(),f=g=>`${l}-tab-${g}`,d=g=>`${l}-panel-${g}`,o=Fs.useRef(null),c=(g,m)=>{g.preventDefault();let p=(m+t.length)%t.length;r(t[p].id),o.current?.querySelectorAll('[role="tab"]')?.[p]?.focus()};return(0,Pt.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,Pt.jsxs)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:[(0,Pt.jsx)("div",{ref:o,role:"tablist","aria-label":e,onKeyDown:g=>{let m=t.findIndex(p=>p.id===n);g.key==="ArrowRight"&&c(g,m+1),g.key==="ArrowLeft"&&c(g,m-1),g.key==="Home"&&c(g,0),g.key==="End"&&c(g,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(g=>(0,Pt.jsx)("button",{id:f(g.id),role:"tab",type:"button","aria-selected":g.id===n,"aria-controls":d(g.id),tabIndex:g.id===n?0:-1,onClick:()=>r(g.id),className:g.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:g.label},g.id))}),s]}),i?(0,Pt.jsx)("div",{id:d(i.id),role:"tabpanel","aria-labelledby":f(i.id),tabIndex:0,className:"af-px-3 af-py-2",children:i.render()},i.id):null]})}var Aa=ce(require("react"),1),ds=ce(require("@radix-ui/react-popover"),1);var ls=3,cs=100;var Qe=require("react/jsx-runtime"),Qr={channel:"Channel",source:"Source",campaign:"Campaign",utm_source:"UTM source",utm_medium:"UTM medium",utm_content:"UTM content",utm_term:"UTM term",page:"Page",entry_page:"Entry page",exit_page:"Exit page",country:"Country",region:"Region",city:"City",browser:"Browser",os:"Operating system",device:"Device"},km=Object.keys(Qr);function Dd(e){let t=Qr[e.dimension],a=e.operator==="is_not"?"is not":"is",s=e.values.map(n=>Jr(n)).join(" or ");return`${t} ${a} ${s}`}function 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>cs||s.length===e[a].values.length?e:e.map((n,r)=>r===a?{...n,values:s}:n)}return t.values.length>cs||e.length>=ls?e:[...e,t]}function Cm(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 Ad(e,t){let a=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));return a>=0?e.map((s,n)=>n===a?t:s):t.values.length>cs||e.length>=ls?e:[...e,t]}function Tm(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Ld(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=Cm(e.byDimension,a);for(let[r,i]of Object.entries(s)){let l=e.foldsByLabel.get(r)??new Set;for(let f of i)l.add(f);e.foldsByLabel.set(r,l)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([r,i])=>[r,[...i]]))}}function Od(e){let{filters:t,onChange:a}=e,s=t.length>=ls;return Aa.useEffect(()=>{if(t.length===0)return;let n=r=>{let i=r.target;i&&(i.tagName==="INPUT"||i.closest('[role="dialog"]'))||r.key==="Escape"&&a([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[t.length,a]),(0,Qe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,r)=>(0,Qe.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-1 af-rounded-full af-border af-border-border af-bg-muted af-py-1 af-pl-3 af-pr-1 af-text-xs",children:[(0,Qe.jsx)("span",{className:"af-text-foreground",children:Dd(n)}),(0,Qe.jsx)("button",{type:"button","aria-label":`Remove filter ${Dd(n)}`,onClick:()=>a(t.filter((i,l)=>l!==r)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),(0,Qe.jsx)(Em,{...e,disabled:s}),t.length>0?(0,Qe.jsx)("button",{type:"button",onClick:()=>a([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Em({filters:e,onChange:t,suggestions:a,resetKey:s,disabled:n,expandValues:r}){let[i,l]=Aa.useState(!1),f=Aa.useRef(null),[d,o]=Aa.useState(null);Aa.useEffect(()=>{o(f.current?.closest(".aifeatures-admin")??null)},[]);let[c,b]=Aa.useState(null),[g,m]=Aa.useState("is"),[p,u]=Aa.useState(""),[v,x]=Aa.useState([]);Aa.useEffect(()=>{i||(b(null),m("is"),u(""),x([]))},[i]);let k=Aa.useRef(s);k.current!==s&&(k.current=s,i&&l(!1),c!==null&&b(null),v.length>0&&x([]),p!==""&&u(""),g!=="is"&&m("is"));let T=E=>{let A=Tm(E);b(A.dimension),x(A.picked),u(A.search),m(A.operator)},R=(c?a[c]??[]:[]).filter(E=>E.toLowerCase().includes(p.trim().toLowerCase())),P=c===null||v.length===0?null:cl(e,{dimension:c,operator:g,values:r?r(c,v):v}),D=P!==null&&P!==e,N=()=>{let E=P;!E||E===e||(t(E),l(!1))};return(0,Qe.jsxs)(ds.Root,{open:i,onOpenChange:l,children:[(0,Qe.jsx)(ds.Trigger,{asChild:!0,children:(0,Qe.jsx)("button",{ref:f,type:"button",disabled:!1,title:n?`At most ${ls} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),(0,Qe.jsx)(ds.Portal,{container:d,children:(0,Qe.jsx)(ds.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:c===null?(0,Qe.jsxs)("div",{children:[(0,Qe.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Qe.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:km.filter(E=>a[E]!==void 0).map(E=>{let A=a[E]?.length??0,C=!e.some(K=>K.dimension===E)&&e.length>=ls;return(0,Qe.jsxs)("button",{type:"button",onClick:()=>T(E),disabled:A===0||C,className:"af-flex af-w-full af-items-center af-justify-between af-rounded-md af-px-2 af-py-1.5 af-text-left af-text-xs af-text-foreground hover:af-bg-muted disabled:af-text-muted-foreground disabled:hover:af-bg-transparent",children:[(0,Qe.jsx)("span",{children:Qr[E]}),(0,Qe.jsx)("span",{className:"af-text-muted-foreground",children:A===0?"no data":C?"no room":A})]},E)})})]}):(0,Qe.jsxs)("div",{children:[(0,Qe.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Qe.jsx)("button",{type:"button",onClick:()=>T(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Qe.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Qr[c]}),(0,Qe.jsxs)("select",{"aria-label":"Operator",value:g,onChange:E=>m(E.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,Qe.jsx)("option",{value:"is",children:"is"}),(0,Qe.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Qe.jsx)("input",{type:"text",value:p,onChange:E=>u(E.target.value),placeholder:"Search\u2026","aria-label":`Search ${Qr[c]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),(0,Qe.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:R.length===0?(0,Qe.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",p,"\u201D."]}):R.map(E=>(0,Qe.jsxs)("label",{className:"af-flex af-cursor-pointer af-items-center af-gap-2 af-rounded-md af-px-2 af-py-1.5 af-text-xs af-text-foreground hover:af-bg-muted",children:[(0,Qe.jsx)("input",{type:"checkbox",checked:v.includes(E),disabled:!v.includes(E)&&v.length>=cs,onChange:A=>x(C=>A.target.checked?[...C,E]:C.filter(K=>K!==E))}),(0,Qe.jsx)("span",{className:"af-break-all",children:Jr(E)})]},E))}),(0,Qe.jsx)("button",{type:"button",onClick:N,disabled:!D,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:v.length<=1?"Apply filter":v.length>=cs?`Apply filter (${v.length} values \u2014 the maximum)`:`Apply filter (${v.length} values)`})]})})})]})}var Ft=require("react/jsx-runtime"),Im=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Ra,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Ra,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Ra,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:nr,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Yr,chart:"visit_duration_seconds"}];function Dm({current:e,previous:t,downIsGood:a}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let n=s>0,r=a?!n:n,i=`${n?"+":""}${(s*100).toFixed(1)}%`;return(0,Ft.jsx)("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:i})}function Bd({summary:e,selected:t,onSelect:a}){return(0,Ft.jsx)("div",{className:"af-@container",children:(0,Ft.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Im.map(s=>{let n=s.chart===t,r=a!==void 0,i=(0,Ft.jsxs)(Ft.Fragment,{children:[(0,Ft.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),(0,Ft.jsxs)("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[(0,Ft.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?(0,Ft.jsx)(Dm,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?(0,Ft.jsx)("button",{type:"button","aria-pressed":n,onClick:()=>a(s.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:i},s.key):(0,Ft.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:i},s.key)})})})}function dl({currentVisitors:e,asOf:t,isStale:a,isUnreachable:s,isInitialLoad:n=!1,scopeIsSiteWide:r=!1}){if(n&&!s)return(0,Ft.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1","aria-hidden":"true",children:[(0,Ft.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,Ft.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return(0,Ft.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let i=t?Cd(t):"freshness unknown",l=r?" across the whole site, not the current filter,":"",f=a?`${e} current visitors${l} ${i} (not updating)`:`${e} current visitors${l} ${i}`;return(0,Ft.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:f,children:[(0,Ft.jsx)("span",{"aria-hidden":"true",className:a?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),(0,Ft.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,Ft.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),(0,Ft.jsx)("span",{className:"af-sr-only",children:f})]})}var Fd=ce(require("react"),1),Md=require("lucide-react");var st=require("react/jsx-runtime");function Qi(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function eo({rows:e,denominator:t,windowPrecedesCollection:a=!1,coverageUnknown:s=!1,emptyCopy:n="No conversions in this period",maxRows:r=9,primaryConversion:i}){let[l,f]=Fd.useState(!1),d=e.filter(u=>!u.implicit||u.visitors>0||u.events>0||Qi(u,i)),o=a?(0,st.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This period starts before we began collecting for this site, so these counts cover less time than the dates suggest."}):s?(0,st.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null;if(d.length===0)return(0,st.jsxs)(st.Fragment,{children:[(0,st.jsx)(Xi,{what:n}),o]});let c=d.slice(0,r),b=i?d.find(u=>Qi(u,i)):void 0,g=b&&!c.includes(b)?d.filter(u=>c.includes(u)||u===b).slice(0,Math.max(0,r-1)).concat(b):c,m=l?e:g,p=Math.max(0,e.length-g.length);return(0,st.jsxs)(st.Fragment,{children:[(0,st.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,st.jsx)("thead",{children:(0,st.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,st.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,st.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,st.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,st.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,st.jsx)("tbody",{children:m.map((u,v)=>(0,st.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":Qi(u,i)?"true":void 0,children:[(0,st.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Qi(u,i)?(0,st.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,st.jsx)(Md.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,st.jsx)("span",{className:"af-font-medium af-text-foreground",children:u.goal}),(0,st.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):u.goal}),(0,st.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ra(u.visitors)}),(0,st.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ra(u.events)}),(0,st.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:u.conversion_rate===null?(0,st.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):nr(u.conversion_rate)})]},`${u.goal}-${v}`))})]}),p>0?(0,st.jsx)("button",{type:"button",onClick:()=>f(u=>!u),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length} goals`}):null,(0,st.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Ra(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),o]})}var La=require("recharts");var $t=require("react/jsx-runtime"),to={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},fl={visitors:Ra,visits:Ra,pageviews:Ra,views_per_visit:e=>e.toFixed(2),bounce_rate:nr,visit_duration_seconds:Yr},Am=31,Lm=new Set(["visitors","visits","pageviews"]),Om={...fl,bounce_rate:Pd,visit_duration_seconds:_d},ul=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Bm=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Fm=[.01,.02,.05,.1,.2,.25,.5,1],Mm=[.25,.5,1,2,5,10,25,50],Um={visitors:ul,visits:ul,pageviews:ul,views_per_visit:Mm,bounce_rate:Fm,visit_duration_seconds:Bm};function $m({active:e,payload:t,label:a,metric:s}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return(0,$t.jsxs)("div",{className:"af-rounded-lg af-border af-border-border af-bg-popover af-px-3 af-py-2 af-text-popover-foreground af-shadow-md",children:[(0,$t.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:to[s]}),(0,$t.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,$t.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,$t.jsx)("span",{className:"af-text-muted-foreground",children:Ed(String(a))}),(0,$t.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:fl[s](Number(n[s]??0))})]})]})}function ao({rows:e,window:t,metric:a,timeZone:s="UTC",height:n=260}){let r=Td(t,e,s),i=fl[a],l=Om[a],f=kd(r.reduce((o,c)=>Math.max(o,Number(c[a]??0)),0),Um[a]),d=`${to[a]} by day: ${r.map(o=>`${ol(o.date)}: ${i(Number(o[a]??0))}`).join("; ")}.`;return(0,$t.jsxs)("figure",{"aria-label":`${to[a]} over time`,className:"af-m-0",children:[(0,$t.jsx)(La.ResponsiveContainer,{width:"100%",height:n,children:(0,$t.jsxs)(La.AreaChart,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,$t.jsx)("defs",{children:(0,$t.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,$t.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,$t.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,$t.jsx)(La.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,$t.jsx)(La.XAxis,{dataKey:"date",tickFormatter:ol,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,$t.jsx)(La.YAxis,{allowDecimals:!Lm.has(a),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...f?{ticks:f,domain:[0,f[f.length-1]]}:{},tickFormatter:o=>l(o),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,$t.jsx)(La.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,$t.jsx)($m,{metric:a})}),(0,$t.jsx)(La.Area,{type:"linear",dataKey:a,name:to[a],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=Am?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,$t.jsx)("figcaption",{className:"af-sr-only",children:d})]})}var he=require("react/jsx-runtime"),Vm="2026-08-13",Hm=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],zm=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Ud({filters:e,onFiltersChange:t,refreshKey:a,onBackToWebsite:s,primaryConversion:n,className:r,published:i,lastPublishedAt:l}){let[f,d]=Mt.useState(30),[o,c]=Mt.useState(()=>io()),b=e!==void 0&&t!==void 0,[g,m]=Mt.useState(e??[]),{api:p}=W(),[u,v]=Mt.useState(p);u!==p&&(v(p),!b&&g.length>0&&m([]));let x=b?e:g,k=Mt.useCallback(U=>{t&&t(U),b||m(U)},[t,b]),T=Mt.useCallback((U,Te,ne)=>{let Re=Array.isArray(Te)?Te:[Te];if(Re.length===0)return null;let je=cl(x,{dimension:U,operator:"is",values:Re});if(ne&&(!ne.value||(je=Ad(je,{dimension:ne.dimension,operator:"is",values:[ne.value]}),!je.find(Dt=>Dt.dimension===ne.dimension&&Dt.operator!=="is_not")?.values.includes(ne.value))))return null;let wt=je.find(et=>et.dimension===U&&et.operator!=="is_not");return Re.every(et=>wt?.values.includes(et))?JSON.stringify(je)===JSON.stringify(x)?null:je:null},[x]),h=Mt.useCallback((U,Te,ne)=>T(U,Te,ne)!==null,[T]),R=Mt.useCallback((U,Te,ne)=>{let Re=T(U,Te,ne);Re&&k(Re)},[T,k]),[P,D]=Mt.useState("visitors"),N=Os(f,{refreshKey:a,breakdowns:zm,filters:x}),E=N.status.data,A=N.reportedZone??E?.timezone,C=A??o??rr()??"UTC",{notCollecting:K,awaitingFirstVisit:Q,firstVisitTooRecent:H,holdingForFirstData:de}=Yi(E,{published:i}),me=i===!1,be=Kr({collecting:Q||K?!1:E?.collecting,statusFailed:N.status.error!=null,identity:E?.analytics_id}),V=Mt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),J=Mt.useMemo(()=>{let U=N.breakdowns.sources?.data,Te={};if(!U||U.status!=="ok")return Te;for(let ne of U.data){let Re=ne.source,je=ne.sources;typeof Re=="string"&&Array.isArray(je)&&je.length>0&&(Te[Re]=je)}return Te},[N.breakdowns.sources?.data]),F=Mt.useMemo(()=>{let U=(Re,je)=>{let wt=N.breakdowns[Re]?.data;return!wt||wt.status!=="ok"?[]:[...new Set(wt.data.map(et=>et[je]).filter(et=>typeof et=="string"&&et!==""))]};return{channel:N.channels.data?.status==="ok"?[...new Set(N.channels.data.data.map(Re=>Re.channel))]:[],source:U("sources","source"),campaign:U("utm/campaign","campaign"),page:U("pages","pathname"),entry_page:U("entry-pages","pathname"),exit_page:U("exit-pages","pathname"),country:U("countries","country"),browser:U("browsers","browser"),os:U("operating-systems","os"),device:U("devices","device")}},[N.breakdowns,N.channels.data]),[ge,pe]=Mt.useState({}),He=JSON.stringify(F),[Pe,Ue]=Mt.useState(new Map),ze=JSON.stringify(J);Mt.useEffect(()=>{let{suggestions:U,folds:Te}=Ld(V.current,{api:p,period:f},JSON.parse(He),JSON.parse(ze));pe(U),Ue(Te)},[He,ze,p,f]);let fe=Mt.useCallback((U,Te)=>U!=="source"?Te:[...new Set(Te.flatMap(ne=>{let Re=[...Pe.get(ne)??[],...J[ne]??[]];return Re.length>0?Re:[ne]}))],[Pe,J]),lt=Mt.useMemo(()=>{let U=N.conversions.error;return U instanceof jt&&U.details?.code==="goals_exceed_report_budget"?U.message:null},[N.conversions.error]),L=Mt.useMemo(()=>{let U=[N.summary,N.timeseries,N.channels,...Object.values(N.breakdowns)];for(let Te of U){let ne=Te?.error;if(ne instanceof jt&&ne.details?.code==="filter_unsupported")return ne.message}return null},[N.summary,N.timeseries,N.channels,N.breakdowns]),M=(U,Te,ne,Re,je,wt,et,Dt,Ne)=>()=>{let Le=N.breakdowns[U];return(0,he.jsx)(Yn,{sourced:Le?.data??null,error:Le?.error,isLoading:Le?.isLoading,what:Te,collecting:E?.collecting,onRetry:N.refetch,children:ct=>{let at=qt=>Dt?fe(Dt,[qt]):qt;return(0,he.jsx)(ll,{rows:ct,dimension:ne,metric:Re,metricLabel:je,secondary:wt,emptyCopy:x.length>0?"No data for this filter":et,canFilter:Dt?(qt,Ut)=>h(Dt,at(qt),Ne?{dimension:Ne,value:Ut}:void 0):()=>!1,onFilter:Dt?(qt,Ut)=>R(Dt,at(qt),Ne?{dimension:Ne,value:Ut}:void 0):void 0})}})};if(Ji({status:E,holdingForFirstData:de,refetchStatus:N.refetchStatus,refetch:N.refetch}),K){let U=!!l&&String(l).slice(0,10)<Vm;return(0,he.jsx)(Lt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,he.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,he.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:me?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":U?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return Q?(0,he.jsx)(Lt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,he.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,he.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:"Your site is set up and analytics is running. The first visit shows up here shortly after someone lands on a published page."})]})}):H?(0,he.jsxs)(Lt,{title:"Analytics",onBackToWebsite:s,className:r,children:[(0,he.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,he.jsx)(il,{value:C,chosen:o,onChange:U=>{oo(U),c(U)}})}),(0,he.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,he.jsxs)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",E?.timezone?` ${E.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,he.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,he.jsx)(dl,{currentVisitors:be.currentVisitors,asOf:be.asOf,isStale:be.isStale,isUnreachable:be.isUnreachable||be.error!==null,isInitialLoad:be.isInitialLoad})})]})]}):(0,he.jsx)(Lt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,he.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,he.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,he.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Hm.map(U=>(0,he.jsx)("button",{type:"button","aria-pressed":U.value===f,onClick:()=>d(U.value),className:U.value===f?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:U.label},U.value))}),(0,he.jsx)(il,{value:C,chosen:o,onChange:U=>{oo(U),c(U)}}),(0,he.jsx)(dl,{currentVisitors:be.currentVisitors,asOf:be.asOf,isStale:be.isStale,isUnreachable:be.isUnreachable||be.error!==null,isInitialLoad:be.isInitialLoad,scopeIsSiteWide:x.length>0})]}),(0,he.jsx)(Od,{filters:x,onChange:k,suggestions:ge,expandValues:fe,resetKey:p}),L?(0,he.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,he.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:L}),(0,he.jsx)("button",{type:"button",onClick:()=>k([]),className:"af-mt-4 af-rounded-md af-border af-border-border af-px-3 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Clear filters"})]}):null,!L&&E?.timezone_defaulted?(0,he.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,L?null:(0,he.jsxs)(he.Fragment,{children:[(0,he.jsx)(Yn,{sourced:N.summary.data,error:N.summary.error,isLoading:N.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:N.refetch,children:U=>(0,he.jsxs)(he.Fragment,{children:[(0,he.jsx)(Bd,{summary:U,selected:P,onSelect:D}),U.previous_unavailable?(0,he.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[U.previous_unavailable_reason==="filter"?"No comparison for this filter \u2014 the previous period has too many distinct traffic sources to resolve it. Try a shorter period, or filter by source instead.":"No comparison available right now \u2014 we couldn\u2019t check how far back this site\u2019s history goes. It should return on its own."," ","The numbers above are still for the period you selected."]}):null]})}),(0,he.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,he.jsx)(Yn,{sourced:N.timeseries.data,error:N.timeseries.error,isLoading:N.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:N.refetch,children:U=>{let Te=N.timeseries.data?.status==="ok"?N.timeseries.data.window:{from:"",to:""};return(0,he.jsx)(ao,{rows:U,window:Te,metric:P,timeZone:A??"UTC"})}})}),(0,he.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,he.jsx)(Xr,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,he.jsx)(Yn,{sourced:N.channels.data,error:N.channels.error,isLoading:N.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:N.refetch,children:U=>(0,he.jsx)(ll,{rows:U,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:Te=>h("channel",Te),onFilter:Te=>R("channel",Te)})})},{id:"sources",label:"Sources",render:M("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:M("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,he.jsx)(Xr,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:M("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:M("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:M("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,he.jsx)(Xr,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:M("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:M("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:M("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,he.jsx)(Xr,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:M("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:M("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:M("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,he.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,he.jsx)("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:(0,he.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,he.jsxs)("div",{className:"af-px-3 af-py-2",children:[x.length>0?(0,he.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",x.length===1?"filter":"filters"," above."]}):null,lt!==null?(0,he.jsxs)("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[(0,he.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,he.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:lt})]}):(0,he.jsx)(Yn,{sourced:N.conversions.data,error:N.conversions.error,isLoading:N.conversions.isLoading,what:"Conversions",collecting:E?.collecting,onRetry:N.refetch,children:U=>{let Te=N.conversions.data?.status==="ok"?N.conversions.data:null;return(0,he.jsx)(he.Fragment,{children:(0,he.jsx)(eo,{rows:U,primaryConversion:n,denominator:Te?.denominator??0,windowPrecedesCollection:Te?.window_precedes_collection??!1,coverageUnknown:Te?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var jd=ce(require("react"),1),la=require("lucide-react");var pn=ce(require("react"),1),Jn=require("lucide-react");var Ae=require("react/jsx-runtime"),$d=90,Vd=100;function qm(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Hd(e){return!!e.label&&e.label!==e.target}function jm(e,t,a){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:s,with_a_value:n}=t;return s===0?e===0?"Nothing specific has converted here yet.":null:n===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":n<s?a?`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function ei(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function zd({current:e,onChange:t,onClose:a}){let{api:s}=W(),[n,r]=pn.useState(null),[i,l]=pn.useState(!1),[f,d]=pn.useState({at:"goals"}),[o,c]=pn.useState(null),[b,g]=pn.useState(null),[m,p]=pn.useState(!1),[u,v]=pn.useState(null),x=pn.useRef(0);pn.useEffect(()=>{let R=!0;return r(null),l(!1),d({at:"goals"}),c(null),g(null),p(!1),v(null),x.current+=1,s.getAnalyticsConversions($d).then(P=>{if(R){if(P.status!=="ok"){l(!0);return}r(P.data)}}).catch(()=>{R&&l(!0)}),()=>{R=!1}},[s]);let k=R=>{d({at:"targets",row:R}),c(null),g(null),p(!1),v(null);let P=++x.current;s.getAnalyticsGoalTargets(R.goal,$d,Vd).then(D=>{if(P===x.current){if(D.status!=="ok"){g("failed");return}c(D.data),p(D.truncated===!0),v(D.coverage??null)}}).catch(D=>{if(P!==x.current)return;let N=D instanceof jt?D.details?.code:void 0;g(N==="goal_has_no_targets"?"no-values":"failed")})},T=R=>{t(R),a()};if(i)return(0,Ae.jsx)("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return(0,Ae.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,Ae.jsx)(Jn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Ae.jsx)("span",{children:"Loading your conversions\u2026"})]});if(f.at==="targets"){let R=f.row,P=new Map;for(let D of o??[])P.set(D.label,(P.get(D.label)??0)+1);return(0,Ae.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[(0,Ae.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,Ae.jsxs)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>d({at:"goals"}),children:[(0,Ae.jsx)(Jn.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,Ae.jsx)("span",{children:"All conversions"})]})}),(0,Ae.jsxs)("button",{type:"button","aria-current":e&&ei(R,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:R.goal,implicit:R.implicit}),children:[e&&ei(R,e)&&!e.target&&(0,Ae.jsx)(Jn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ae.jsxs)("span",{children:["Any ",R.goal.toLowerCase()]})]}),b==="no-values"&&(0,Ae.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),b==="failed"&&(0,Ae.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,Ae.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,Ae.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>k(R),children:"Try again"})]}),!o&&b===null&&(0,Ae.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,Ae.jsx)(Jn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,Ae.jsx)("span",{children:"Loading\u2026"})]}),o&&(0,Ae.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:jm(o.length,u,m)}),m&&(0,Ae.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Vd,". If what you want isn\u2019t here, pick the conversion itself instead."]}),o?.some(Hd)&&(0,Ae.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),o?.map(D=>{let N=!!(e&&ei(R,e)&&e.target===D.target),E=P.get(D.label)>1;return Hd(D)?(0,Ae.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-3 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,Ae.jsxs)("span",{className:"af-min-w-0",children:[(0,Ae.jsx)("span",{className:"af-block af-truncate",children:D.label}),E&&(0,Ae.jsx)("span",{className:"af-block af-truncate af-text-xs",children:D.target})]}),(0,Ae.jsx)("span",{className:"af-shrink-0 af-text-xs",children:D.visitors.toLocaleString()})]},D.target):(0,Ae.jsxs)("button",{type:"button","aria-current":N?"true":void 0,className:"af-flex af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:R.goal,implicit:R.implicit,target:D.target,...D.label&&D.label!==D.target?{label:D.label}:{}}),children:[(0,Ae.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[N&&(0,Ae.jsx)(Jn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ae.jsxs)("span",{className:"af-min-w-0",children:[(0,Ae.jsx)("span",{className:"af-block af-truncate",children:D.label}),E&&(0,Ae.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:D.target})]})]}),(0,Ae.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:D.visitors.toLocaleString()})]},D.target)})]})}let h=e?.goal&&!n.some(R=>ei(R,e));return(0,Ae.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[h&&(0,Ae.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&(0,Ae.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(R=>{let P=e?ei(R,e):!1;return(0,Ae.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,Ae.jsxs)("button",{type:"button","aria-current":P?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>T({goal:R.goal,implicit:R.implicit}),children:[(0,Ae.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[P&&(0,Ae.jsx)(Jn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Ae.jsx)("span",{className:"af-truncate",children:R.goal})]}),(0,Ae.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:R.visitors.toLocaleString()})]}),qm(R)&&(0,Ae.jsx)(y,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${R.goal}`,onClick:()=>k(R),children:"Narrow"})]},R.goal)}),e?.goal&&(0,Ae.jsx)("button",{type:"button",className:"af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm af-text-muted-foreground hover:af-bg-accent",onClick:()=>T(null),children:"No main conversion"})]})}var Qa=require("react/jsx-runtime");function Wm(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 Gm(e){if(ml(e,"whatsapp"))return!0;let t=Wm(e);return t===null?!1:["wa.me","whatsapp.com"].some(a=>t===a||t.endsWith(`.${a}`))}function ml(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var qd=[{goal:"Contact",target:e=>ml(e,"tel"),icon:la.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>ml(e,"mailto"),icon:la.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:la.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Gm(e),icon:la.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:la.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:la.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:la.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:la.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:la.Download,line:"This site is set up to get your file downloaded."}];function Wd(e){let{goal:t,target:a}=e;return e.implicit!==!0?null:(a?qd.find(n=>n.goal===t&&n.target?.(a)):void 0)??qd.find(n=>n.goal===t&&!n.target)??null}function Km(e){return Wd(e)?.icon??la.Target}function Gd({primaryConversion:e,onChange:t}){let[a,s]=jd.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?Wd(e):null,i=e?.label?.trim(),l=e?Km(e):la.Target,f=e?.goal?i?`Your main conversion is ${i}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",d=(0,Qa.jsxs)(Qa.Fragment,{children:[(0,Qa.jsx)(l,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,Qa.jsx)("span",{children:f})]});return t?(0,Qa.jsxs)(gi,{open:a,onOpenChange:s,children:[(0,Qa.jsx)(vi,{asChild:!0,children:(0,Qa.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,Qa.jsx)(Pr,{align:"start",className:"af-w-80 af-p-1",children:a&&(0,Qa.jsx)(zd,{current:e,onChange:t,onClose:()=>s(!1)})})]}):(0,Qa.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:d})}var ha=require("react/jsx-runtime");function Kd({refreshKey:e,onViewAll:t,primaryConversion:a}){let s=Os(7,{refreshKey:e,breakdowns:[]}),n=s.status.data??void 0,{nothingToReport:r,notCollecting:i,holdingForFirstData:l}=Yi(n);return Ji({status:n,holdingForFirstData:l,refetchStatus:s.refetchStatus,refetch:s.refetch}),(0,ha.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ha.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,ha.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,ha.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?(0,ha.jsx)("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:i?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):(0,ha.jsxs)(ha.Fragment,{children:[(0,ha.jsx)(Yn,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:s.refetch,children:f=>{let d=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return(0,ha.jsx)(ao,{rows:f,window:d?.window??{from:"",to:""},metric:"visitors",timeZone:d?.timezone,height:140})}}),(0,ha.jsxs)("div",{className:"af-mt-3",children:[(0,ha.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,ha.jsx)(Yn,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:s.refetch,children:f=>{let d=s.conversions.data?.status==="ok"?s.conversions.data:null;return(0,ha.jsx)(eo,{rows:f,primaryConversion:a,denominator:d?.denominator??0,windowPrecedesCollection:d?.window_precedes_collection??!1,coverageUnknown:d?.first_seen_unavailable??!1})}})]})]})]})}var ca=require("react/jsx-runtime"),pl=5;function gl({title:e,viewAllLabel:t,onViewAll:a}){return(0,ca.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,ca.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),a&&(0,ca.jsx)(y,{type:"button",variant:"ghost",size:"sm",onClick:a,children:t})]})}function Zd({refreshKey:e,onBackToWebsite:t,primaryConversion:a,onChangePrimaryConversion:s,onOpenSurface:n,needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l}){let f=Ns({refreshKey:e}),d=(f.summary?.products.count??0)>0||(f.summary?.commerce?.storefront_orders??!1),o=d||(f.summary?.commerce?.invoicing??!1);return(0,ca.jsx)(Lt,{title:"Dashboard",onBackToWebsite:t,children:(0,ca.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,ca.jsx)(Gd,{primaryConversion:a,onChange:s}),(0,ca.jsx)(Kd,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:a}),(0,ca.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ca.jsx)(gl,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),(0,ca.jsx)(Or,{refreshKey:e,maxRows:pl,onViewAll:n&&(()=>n("leads"))})]}),d&&(0,ca.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ca.jsx)(gl,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),(0,ca.jsx)(jn,{refreshKey:e,maxRows:pl,onViewAll:n&&(()=>n("orders"))})]}),o&&(0,ca.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,ca.jsx)(gl,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),(0,ca.jsx)(Gn,{refreshKey:e,maxRows:pl,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});
|