@aifeatures/admin-react 0.22.0 → 0.24.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.js CHANGED
@@ -1,5 +1,8 @@
1
1
  "use client";
2
- import*as hn from"react";var Xr="aifeatures:analytics:timezone",Qr;function bs(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function ao(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function yn(){return ei()??bs()}function ei(){if(Qr!==void 0)return Qr;try{let e=window.localStorage.getItem(Xr);return ao(e)?e:null}catch{return null}}function ti(e){if(!(e!==null&&!ao(e))){Qr=e;try{e===null?window.localStorage.removeItem(Xr):window.localStorage.setItem(Xr,e)}catch{}}}function Vs(e,t){let n=new URLSearchParams({period:String(e)}),s=yn();return s&&n.set("timezone",s),t&&t.length>0&&n.set("filters",JSON.stringify(t)),n.toString()}var St=class extends Error{constructor(n,s,a){super(n);this.status=s;this.details=a;this.name="AifeaturesApiError"}};function Hs(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 ys(e,t){let n=t.toString();return n?`${e}?${n}`:e}function no(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 so(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 ai(e,t="https://aifeatures.dev"){async function n(a,r={}){let o=`${t}${a}`,u=await fetch(o,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!u.ok){let g;try{g=await u.json()}catch{}throw new St(Hs(g?.error,u.status),u.status,g)}if(u.status!==204)return u.json()}async function s(a){let r=await fetch(`${t}${a}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let o;try{o=await r.json()}catch{}throw new St(Hs(o?.error,r.status),r.status,o)}return r.blob()}return{async getForms(){return(await n("/api/v1/forms")).forms},async getForm(a){return n(`/api/v1/forms/${a}`)},async createForm(a){return n("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,r){return n(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(a){await n(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,r={}){let o=new URLSearchParams;r.limit!==void 0&&o.set("limit",String(r.limit)),r.offset!==void 0&&o.set("offset",String(r.offset));let u=o.toString(),g=`/api/v1/forms/${a}/submissions${u?`?${u}`:""}`;return n(g)},async getSubmission(a){return n(`/api/v1/submissions/${a}`)},async exportSubmissionsCsv(a,r={}){let o=new URLSearchParams;return r.includeSpam&&o.set("include_spam","true"),s(ys(`/api/v1/forms/${encodeURIComponent(a)}/submissions/export`,o))},async deleteSubmission(a){await n(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,r){let o=typeof r=="string"?{name:r}:r,u=o.name,g=o.id??o.name,l=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(g)}`,i=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){let c;try{c=await i.json()}catch{}throw new St(Hs(c?.error,i.status),i.status,c)}let d=await i.blob(),b=URL.createObjectURL(d),f=document.createElement("a");f.href=b,f.download=u,document.body.appendChild(f),f.click(),document.body.removeChild(f),URL.revokeObjectURL(b)},async getSite(a){return n(`/api/v1/sites/${encodeURIComponent(a)}`)},async updateSite(a,r){return n(`/api/v1/sites/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return n("/api/v1/payments/status")},getPromos(a){let r=new URLSearchParams({limit:"10"});return a&&r.set("cursor",a),n(`/api/v1/promos?${r}`)},getPromo(a){return n(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return n("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return n(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,r){return n(`/api/v1/promos/${encodeURIComponent(a)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(a={}){let r=new URLSearchParams;a.include&&r.set("include",a.include);let o=r.toString();return(await n(`/api/v1/products${o?`?${o}`:""}`)).products},async getProduct(a){return n(`/api/v1/products/${a}`)},async createProduct(a){return n("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,r){return n(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(a){await n(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,r){let o=new FormData;o.append("file",r);let u=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:o});if(!u.ok){let g;try{g=await u.json()}catch{}throw new St(Hs(g?.error,u.status),u.status,g)}return u.json()},async attachProductFileFromUrl(a,r){return n(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(a,r){return n(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(a,r){return n(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(a){await n(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,r){return n(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(a,r){return n(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(a){await n(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,r){return n(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(a,r){return n(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(a={}){let r=new URLSearchParams;a.email?r.set("email",a.email):a.q&&r.set("q",a.q),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/customers${o?`?${o}`:""}`)},async getCustomer(a){return n(`/api/v1/customers/${a}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(a={}){let r=no(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/orders${o?`?${o}`:""}`)},async exportOrdersCsv(a={}){return s(ys("/api/v1/orders/export",no(a)))},async getOrder(a){return n(`/api/v1/orders/${a}`)},async getInvoices(a={}){let r=new URLSearchParams;a.labels?.length&&r.set("label",a.labels.join(",")),a.customerEmail&&r.set("customer_email",a.customerEmail),a.customerId&&r.set("customer_id",a.customerId),a.q&&r.set("q",a.q),a.from&&r.set("from",a.from),a.to&&r.set("to",a.to),a.includeAggregates&&r.set("include","aggregates"),a.retainerId&&r.set("retainer_id",a.retainerId),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/invoices${o?`?${o}`:""}`)},async getInvoice(a){return n(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return n(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return n("/api/v1/invoice-settings")},async getRetainers(a={}){let r=so(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/retainers${o?`?${o}`:""}`)},async exportRetainersCsv(a={}){return s(ys("/api/v1/retainers/export",so(a)))},async getRetainer(a){return n(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await n(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return n(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,r){return n(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(a={}){let r=new URLSearchParams;a.status&&r.set("status",a.status),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/subscriptions${o?`?${o}`:""}`)},async exportSubscriptionsCsv(a={}){let r=new URLSearchParams;return a.status&&r.set("status",a.status),s(ys("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let a=new URLSearchParams,r=yn();r&&a.set("timezone",r);let o=a.toString();return n(`/api/v1/analytics/status${o?`?${o}`:""}`)},async getAnalyticsSummary(a,r){return n(`/api/v1/analytics/summary?${Vs(a,r)}`)},async getAnalyticsTimeseries(a,r){return n(`/api/v1/analytics/timeseries?${Vs(a,r)}`)},async getAnalyticsRealtime(){return n("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,r){return n(`/api/v1/analytics/channels?${Vs(a,r)}`)},async getAnalyticsConversions(a){return n((()=>{let r=new URLSearchParams({period:String(a)}),o=yn();return o&&r.set("timezone",o),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(a,r,o){let u=new URLSearchParams({goal:a,period:String(r)}),g=yn();return g&&u.set("timezone",g),o!==void 0&&u.set("limit",String(o)),n(`/api/v1/analytics/conversions/targets?${u.toString()}`)},async getAnalyticsBreakdown(a,r,o){let u=a.split("/").map(encodeURIComponent).join("/");return n(`/api/v1/analytics/${u}?${Vs(r,o)}`)},async getBusinessSummary(a){let r=new URLSearchParams;r.set("tz_offset_minutes",String(a.tzOffsetMinutes));let o=yn();return o&&r.set("timezone",o),n(`/api/v1/summary?${r.toString()}`)},async getPeople(a={}){let r=new URLSearchParams;a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/people${o?`?${o}`:""}`)},async exportPeopleCsv(a={}){let r=new URLSearchParams;return a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),s(ys("/api/v1/people/export",r))},async getPerson(a){return n(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await n("/api/v1/event-destinations")).destinations},async createEventDestination(a){return n("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,r){return n(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(a){await n(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return n(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await n(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,r){let o=r===void 0?"":`?limit=${r}`;return(await n(`/api/v1/event-destinations/${a}/deliveries${o}`)).deliveries},async retryEventDelivery(a,r){return n(`/api/v1/event-destinations/${a}/deliveries/${r}/retry`,{method:"POST"})}}}import{jsx as hs,jsxs as Pc}from"react/jsx-runtime";var ro=hn.createContext(null);function Rc(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 _c({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:n=!1,className:s,children:a}){let r=hn.useMemo(()=>Rc(e),[e]),o=hn.useMemo(()=>ai(e,t),[e,t]),u=hn.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return r?hs("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:Pc("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[hs("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),hs("p",{className:"af-text-sm af-text-destructive",children:r})]})}):hs(ro.Provider,{value:u,children:hs("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:a})})}function Q(){let e=hn.useContext(ro);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as mn from"react";import{ArrowLeft as Du,Settings as Lu,Inbox as Ou}from"lucide-react";import*as zs from"react";import*as Ua from"@radix-ui/react-tabs";import{clsx as Cc}from"clsx";import{extendTailwindMerge as Tc}from"tailwind-merge";var kc=Tc({prefix:"af-"});function K(...e){return kc(Cc(e))}import{jsx as ni}from"react/jsx-runtime";var qs=Ua.Root,xs=zs.forwardRef(({className:e,...t},n)=>ni(Ua.List,{ref:n,className:K("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}));xs.displayName=Ua.List.displayName;var Ma=zs.forwardRef(({className:e,...t},n)=>ni(Ua.Trigger,{ref:n,className:K("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}));Ma.displayName=Ua.Trigger.displayName;var $a=zs.forwardRef(({className:e,...t},n)=>ni(Ua.Content,{ref:n,className:K("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}));$a.displayName=Ua.Content.displayName;import*as io from"react";import{Slot as Ec}from"@radix-ui/react-slot";import{cva as Ic}from"class-variance-authority";import{jsx as Dc}from"react/jsx-runtime";var Ac=Ic("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"}}),w=io.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...a},r)=>Dc(s?Ec:"button",{className:K(Ac({variant:t,size:n,className:e})),ref:r,...a}));w.displayName="Button";import{Inbox as oo,Settings as Bc}from"lucide-react";import*as cn from"react";import{jsx as ln}from"react/jsx-runtime";var Ve=cn.forwardRef(({className:e,...t},n)=>ln("div",{className:"af-relative af-w-full af-overflow-auto",children:ln("table",{ref:n,className:K("af-w-full af-caption-bottom af-text-sm",e),...t})}));Ve.displayName="Table";var He=cn.forwardRef(({className:e,...t},n)=>ln("thead",{ref:n,className:K("[&_tr]:af-border-b",e),...t}));He.displayName="TableHeader";var ze=cn.forwardRef(({className:e,...t},n)=>ln("tbody",{ref:n,className:K("[&_tr:last-child]:af-border-0",e),...t}));ze.displayName="TableBody";var Lc=cn.forwardRef(({className:e,...t},n)=>ln("tfoot",{ref:n,className:K("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Lc.displayName="TableFooter";var be=cn.forwardRef(({className:e,...t},n)=>ln("tr",{ref:n,className:K("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));be.displayName="TableRow";var V=cn.forwardRef(({className:e,...t},n)=>ln("th",{ref:n,className:K("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}));V.displayName="TableHead";var H=cn.forwardRef(({className:e,...t},n)=>ln("td",{ref:n,className:K("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));H.displayName="TableCell";var Oc=cn.forwardRef(({className:e,...t},n)=>ln("caption",{ref:n,className:K("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Oc.displayName="TableCaption";import*as Va from"react";function Wn(){let{api:e}=Q(),[t,n]=Va.useState([]),[s,a]=Va.useState(!0),[r,o]=Va.useState(null),u=Va.useCallback(async()=>{try{a(!0),o(null);let d=await e.getForms();n(d)}catch(d){o(d instanceof Error?d:new Error("Failed to fetch forms"))}finally{a(!1)}},[e]);Va.useEffect(()=>{u()},[u]);let g=Va.useCallback(async d=>{let b=await e.createForm(d);return n(f=>[...f,b]),b},[e]),l=Va.useCallback(async(d,b)=>{let f=await e.updateForm(d,b);return n(c=>c.map(m=>m.id===d?f:m)),f},[e]),i=Va.useCallback(async d=>{await e.deleteForm(d),n(b=>b.filter(f=>f.id!==d))},[e]);return{forms:t,isLoading:s,error:r,refetch:u,createForm:g,updateForm:l,deleteForm:i}}import{jsx as ta,jsxs as un}from"react/jsx-runtime";function js({onSelectForm:e,className:t}){let{forms:n,isLoading:s,error:a}=Wn();return s?ta("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:ta("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):a?ta("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:un("div",{className:"af-text-destructive",children:["Error: ",a.message]})}):n.length===0?un("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[ta(oo,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),un("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",ta("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):ta("div",{className:t,children:un(Ve,{children:[ta(He,{children:un(be,{children:[ta(V,{children:"Name"}),ta(V,{className:"af-text-right",children:"Actions"})]})}),ta(ze,{children:n.map(r=>un(be,{children:[ta(H,{className:"af-font-medium",children:r.name}),ta(H,{className:"af-text-right",children:un("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[un(w,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[ta(oo,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),un(w,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[ta(Bc,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}import{AlertTriangle as $c}from"lucide-react";import{cva as Fc}from"class-variance-authority";import{jsx as Mc}from"react/jsx-runtime";var Uc=Fc("af-inline-flex af-items-center af-rounded-md af-border af-px-2.5 af-py-0.5 af-text-xs af-font-semibold af-transition-colors focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2",{variants:{variant:{default:"af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",secondary:"af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",destructive:"af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",outline:"af-text-foreground",success:"af-border-transparent af-bg-green-100 af-text-green-800",warning:"af-border-transparent af-bg-yellow-100 af-text-yellow-800"}},defaultVariants:{variant:"default"}});function te({className:e,variant:t,...n}){return Mc("div",{className:K(Uc({variant:t}),e),...n})}import{jsx as Ln,jsxs as Gs}from"react/jsx-runtime";var Vc={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 Ws(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 si(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function Hc(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 ws({deliveries:e,label:t="Email needs attention"}){return si(e)?Gs("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:[Ln($c,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Za({deliveries:e,problemsOnly:t=!1,className:n=""}){let s=(e??[]).filter(a=>!t||si([a]));return s.length?Ln("div",{className:`af-space-y-3 ${n}`,"aria-label":"Email delivery",children:s.map(a=>{let r=Ws(a),o=Hc(a);return Gs("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[Gs("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Ln("span",{className:"af-font-medium",children:Vc[a.kind]??"Email notification"}),Ln(te,{variant:r.variant,children:r.label})]}),Gs("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",a.recipients.join(", ")]}),a.recipients.length>1&&si([a])&&Ln("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&&Ln("p",{className:"af-mt-1",children:r.detail}),o&&Ln("p",{className:"af-mt-1",children:o})]},a.id)})}):null}import*as wn from"react";import{ArrowLeft as lu,ChevronLeft as cu,ChevronRight as uu,Eye as du,Inbox as fu,Paperclip as mu}from"lucide-react";import*as xn from"react";import*as Te from"@radix-ui/react-select";import{Check as zc,ChevronDown as lo,ChevronUp as qc}from"lucide-react";import{jsx as Mt,jsxs as ri}from"react/jsx-runtime";var _a=Te.Root;var Pa=Te.Value,pa=xn.forwardRef(({className:e,children:t,...n},s)=>ri(Te.Trigger,{ref:s,className:K("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...n,children:[t,Mt(Te.Icon,{asChild:!0,children:Mt(lo,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));pa.displayName=Te.Trigger.displayName;var co=xn.forwardRef(({className:e,...t},n)=>Mt(Te.ScrollUpButton,{ref:n,className:K("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:Mt(qc,{className:"af-h-4 af-w-4"})}));co.displayName=Te.ScrollUpButton.displayName;var uo=xn.forwardRef(({className:e,...t},n)=>Mt(Te.ScrollDownButton,{ref:n,className:K("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:Mt(lo,{className:"af-h-4 af-w-4"})}));uo.displayName=Te.ScrollDownButton.displayName;var ga=xn.forwardRef(({className:e,children:t,position:n="popper",...s},a)=>Mt(Te.Portal,{children:ri(Te.Content,{ref:a,className:K("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:n,...s,children:[Mt(co,{}),Mt(Te.Viewport,{className:K("af-p-1",n==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),Mt(uo,{})]})}));ga.displayName=Te.Content.displayName;var jc=xn.forwardRef(({className:e,...t},n)=>Mt(Te.Label,{ref:n,className:K("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));jc.displayName=Te.Label.displayName;var Ye=xn.forwardRef(({className:e,children:t,...n},s)=>ri(Te.Item,{ref:s,className:K("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...n,children:[Mt("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:Mt(Te.ItemIndicator,{children:Mt(zc,{className:"af-h-4 af-w-4"})})}),Mt(Te.ItemText,{children:t})]}));Ye.displayName=Te.Item.displayName;var Gc=xn.forwardRef(({className:e,...t},n)=>Mt(Te.Separator,{ref:n,className:K("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));Gc.displayName=Te.Separator.displayName;import*as Gt from"react";function Ks({formId:e,initialPageSize:t=25}){let{api:n}=Q(),[s,a]=Gt.useState([]),[r,o]=Gt.useState(0),[u,g]=Gt.useState(!0),[l,i]=Gt.useState(null),[d,b]=Gt.useState(0),[f,c]=Gt.useState(t),m=Gt.useRef(0),p=Gt.useCallback(async()=>{if(!e)return;let C=++m.current;try{g(!0),i(null);let v={limit:f,offset:d*f},S=await n.getSubmissions(e,v);if(C!==m.current)return;if(S.submissions.length===0&&d>0){b(Math.max(0,Math.ceil(S.total/f)-1));return}a(S.submissions),o(S.total)}catch(v){if(C!==m.current)return;i(v instanceof Error?v:new Error("Failed to fetch submissions"))}finally{C===m.current&&g(!1)}},[n,e,d,f]);Gt.useEffect(()=>{p()},[p]);let y=Gt.useRef(p);y.current=p;let h=Gt.useCallback(async C=>{await n.deleteSubmission(C),y.current()},[n]),R=Math.ceil(r/f);return{submissions:s,total:r,isLoading:u,error:l,page:d,pageSize:f,hasNextPage:d<R-1,hasPreviousPage:d>0,setPage:b,setPageSize:C=>{c(C),b(0)},refetch:p,deleteSubmission:h}}import*as Zs from"react";import{Trash2 as Zc}from"lucide-react";import*as Ss from"react";import*as Nt from"@radix-ui/react-dialog";import{X as Wc}from"lucide-react";import{jsx as dn,jsxs as ii}from"react/jsx-runtime";var Ca=Nt.Root;var Kc=Nt.Portal;var fo=Ss.forwardRef(({className:e,...t},n)=>dn(Nt.Overlay,{ref:n,className:K("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));fo.displayName=Nt.Overlay.displayName;var va=Ss.forwardRef(({className:e,children:t,...n},s)=>dn(Kc,{children:ii("div",{className:"aifeatures-admin",children:[dn(fo,{}),ii(Nt.Content,{ref:s,className:K("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...n,children:[t,ii(Nt.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:[dn(Wc,{className:"af-h-4 af-w-4"}),dn("span",{className:"af-sr-only",children:"Close"})]})]})]})}));va.displayName=Nt.Content.displayName;var ba=({className:e,...t})=>dn("div",{className:K("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});ba.displayName="DialogHeader";var ya=({className:e,...t})=>dn("div",{className:K("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});ya.displayName="DialogFooter";var ha=Ss.forwardRef(({className:e,...t},n)=>dn(Nt.Title,{ref:n,className:K("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));ha.displayName=Nt.Title.displayName;var xa=Ss.forwardRef(({className:e,...t},n)=>dn(Nt.Description,{ref:n,className:K("af-text-sm af-text-muted-foreground",e),...t}));xa.displayName=Nt.Description.displayName;import{Fragment as Jc,jsx as On,jsxs as Ns}from"react/jsx-runtime";function Kn({onDelete:e,iconOnly:t}){let[n,s]=Zs.useState(!1),[a,r]=Zs.useState(!1),[o,u]=Zs.useState(null);return Ns(Jc,{children:[Ns(w,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{u(null),s(!0)},children:[On(Zc,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),On(Ca,{open:n,onOpenChange:l=>{!l&&!a&&s(!1)},children:Ns(va,{children:[Ns(ba,{children:[On(ha,{children:"Delete this submission?"}),On(xa,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),o&&On("p",{className:"af-text-sm af-text-destructive",children:o}),Ns(ya,{children:[On(w,{variant:"outline",onClick:()=>s(!1),disabled:a,children:"Cancel"}),On(w,{variant:"destructive",onClick:async()=>{r(!0),u(null);try{await e(),s(!1)}catch(l){u(l instanceof Error?l.message:"Failed to delete submission")}finally{r(!1)}},disabled:a,children:a?"Deleting...":"Delete"})]})]})})]})}import*as po from"react";import{ArrowLeft as Yc,Download as Xc,Globe as Qc,Clock as eu,FileText as tu,Loader2 as au,Monitor as nu,Mail as su}from"lucide-react";import{jsx as ft,jsxs as ot}from"react/jsx-runtime";function mo(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ru(e){if(e===0)return"0 B";let t=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${n[s]}`}function Js({submission:e,onBack:t,onDelete:n}){let{api:s}=Q(),[a,r]=po.useState(null),o=l=>l.id??l.name,u=async l=>{r(o(l));try{await s.downloadAttachment(e.id,l)}catch(i){console.error("Download failed:",i)}finally{r(null)}},g=Object.entries(e.data).filter(([l])=>!l.startsWith("_"));return ot("div",{children:[ot("div",{className:"af-mb-6",children:[ot(w,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[ft(Yc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),ot("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[ot("div",{children:[ft("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),ot("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",mo(e.metadata.submitted_at)]})]}),n&&ft(Kn,{onDelete:n})]})]}),ot("div",{className:"af-space-y-6",children:[ft(Za,{deliveries:e.email_deliveries}),ot("div",{children:[ft("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),ot("div",{className:"af-space-y-3",children:[g.map(([l,i])=>ot("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[ft("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:l.replace(/_/g," ")}),ft("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof i=="string"&&i.includes(`
3
- `)?ft("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:i}):String(i)})]},l)),g.length===0&&ft("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&ot("div",{children:[ft("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),ft("div",{className:"af-space-y-2",children:e.attachments.map((l,i)=>ot("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[ot("div",{className:"af-flex af-items-center af-gap-2",children:[ft(tu,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),ft("span",{className:"af-text-sm",children:l.name}),ot("span",{className:"af-text-xs af-text-muted-foreground",children:["(",ru(l.size),")"]})]}),ot(w,{variant:"ghost",size:"sm",onClick:()=>u(l),disabled:a===o(l),children:[a===o(l)?ft(au,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):ft(Xc,{className:"af-h-4 af-w-4 af-mr-1"}),a===o(l)?"Downloading...":"Download"]})]},i))})]}),ot("div",{children:[ft("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),ot("div",{className:"af-space-y-2 af-text-sm",children:[ot("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[ft(eu,{className:"af-h-4 af-w-4"}),ft("span",{children:mo(e.metadata.submitted_at)})]}),e.metadata.ip_address&&ot("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[ft(Qc,{className:"af-h-4 af-w-4"}),ot("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&ot("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[ft(nu,{className:"af-h-4 af-w-4 af-mt-0.5"}),ft("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&ot("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[ft(su,{className:"af-h-4 af-w-4"}),ot("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{Download as ou}from"lucide-react";import*as Bn from"react";var iu=/^\+[1-9]\d{1,14}$/;function go(e){let t=e==null?"":String(e),n=!iu.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),s=n?`'${t}`:t;return n||/[",;\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function Ys(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function Xs(e,t){if(typeof document>"u")return;let n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n)}function Qs({fetchCsv:e,filename:t}){let[n,s]=Bn.useState(!1),[a,r]=Bn.useState(null),o=Bn.useRef(!1);return{exportCsv:Bn.useCallback(async()=>{if(!o.current){o.current=!0,s(!0),r(null);try{let g=await e();Xs(g,Ys(t))}catch(g){r(g instanceof Error?g:new Error("Export failed"))}finally{o.current=!1,s(!1)}}},[e,t]),exporting:n,error:a}}import{jsx as vo,jsxs as bo}from"react/jsx-runtime";function $t({fetchCsv:e,filename:t,label:n="Export CSV",disabled:s,className:a}){let{exportCsv:r,exporting:o,error:u}=Qs({fetchCsv:e,filename:t});return bo("span",{className:a,children:[bo(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||o,"aria-busy":o,children:[vo(ou,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Exporting\u2026":n]}),u&&vo("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}import{jsx as Ne,jsxs as pt}from"react/jsx-runtime";function pu(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function gu(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let n of t)if(typeof e[n]=="string")return e[n];return null}var vu=["message","comments","comment","inquiry","question","details","body","notes"];function bu(e){let t=Object.entries(e).filter(([r,o])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),n=new Map(t.map(([r,o])=>[r.toLowerCase(),o])),a=(vu.map(r=>n.get(r)).find(Boolean)??t.reduce((r,[,o])=>o.length>r.length?o:r,"")).trim().replace(/\s+/g," ");return a.length>80?a.slice(0,80)+"\u2026":a}function er({formId:e,className:t,defaultSubmissionId:n,submissionId:s,onSelectSubmission:a}){let{api:r}=Q(),{submissions:o,total:u,isLoading:g,error:l,page:i,pageSize:d,hasNextPage:b,hasPreviousPage:f,setPage:c,setPageSize:m,deleteSubmission:p}=Ks({formId:e}),y=wn.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[h,R]=wn.useState(n??null),C=a?s??null:h,v=a??R,S=$=>!!$&&$.id===C&&$.form_id===e,_=o.find(S),[k,x]=wn.useState(null),P=S(k)?k:null,[A,N]=wn.useState(null);if(wn.useEffect(()=>{if(N(null),!C||_||P)return;let $=!1;return r.getSubmission(C).then(ae=>{if(!$){if(ae.form_id!==e){N("This submission could not be found.");return}x(ae)}}).catch(()=>{$||N("This submission could not be found.")}),()=>{$=!0}},[r,e,C,_,P]),C){let $=_??P;return $?Ne("div",{className:t,children:Ne(Js,{submission:$,onBack:()=>v(null),onDelete:async()=>{await p($.id),v(null)}})}):A?pt("div",{className:t,children:[pt(w,{variant:"ghost",size:"sm",onClick:()=>v(null),className:"af-mb-2 af--ml-2",children:[Ne(lu,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Ne("p",{className:"af-text-sm af-text-destructive",children:A})]}):Ne("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ne("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(g)return Ne("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ne("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(l)return Ne("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:pt("div",{className:"af-text-destructive",children:["Error: ",l.message]})});if(o.length===0&&i===0)return pt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Ne(fu,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),pt("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",Ne("br",{}),"Submissions will appear here when visitors use your form."]})]});let G=i*d+1,j=Math.min((i+1)*d,u);return pt("div",{className:t,children:[Ne("div",{className:"af-mb-2 af-flex af-justify-end",children:Ne($t,{fetchCsv:y,filename:"submissions"})}),pt(Ve,{children:[Ne(He,{children:pt(be,{children:[Ne(V,{children:"Email"}),Ne(V,{children:"Preview"}),Ne(V,{children:"Date"}),Ne(V,{className:"af-text-right",children:"Actions"})]})}),Ne(ze,{children:o.map($=>{let ae=gu($.data),se=bu($.data);return pt(be,{children:[pt(H,{className:"af-font-medium",children:[pt("div",{className:"af-flex af-items-center af-gap-2",children:[ae||Ne("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),$.attachments.length>0&&pt("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${$.attachments.length} attachment(s)`,children:[Ne(mu,{className:"af-h-3 af-w-3"}),Ne("span",{className:"af-text-xs",children:$.attachments.length})]})]}),Ne(ws,{deliveries:$.email_deliveries,label:"Notification email needs attention"})]}),Ne(H,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:se||Ne("span",{className:"af-italic",children:"No preview available"})}),Ne(H,{className:"af-text-muted-foreground",children:pu($.metadata.submitted_at)}),pt(H,{className:"af-text-right",children:[Ne(w,{variant:"ghost",size:"icon",onClick:()=>v($.id),title:"View details",children:Ne(du,{className:"af-h-4 af-w-4"})}),Ne(Kn,{iconOnly:!0,onDelete:()=>p($.id)})]})]},$.id)})})]}),pt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[pt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[pt("span",{children:["Showing ",G,"-",j," of ",u]}),pt(_a,{value:String(d),onValueChange:$=>m(Number($)),children:[Ne(pa,{className:"af-w-[70px] af-h-8",children:Ne(Pa,{})}),pt(ga,{children:[Ne(Ye,{value:"10",children:"10"}),Ne(Ye,{value:"25",children:"25"}),Ne(Ye,{value:"50",children:"50"}),Ne(Ye,{value:"100",children:"100"})]})]}),Ne("span",{children:"per page"})]}),pt("div",{className:"af-flex af-items-center af-gap-2",children:[pt(w,{variant:"outline",size:"sm",onClick:()=>c(i-1),disabled:!f,children:[Ne(cu,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),pt(w,{variant:"outline",size:"sm",onClick:()=>c(i+1),disabled:!b,children:["Next",Ne(uu,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Sa from"react";import{Plus as ku,X as Eu,Loader2 as Iu,Check as Au}from"lucide-react";import*as yo from"react";import{jsx as yu}from"react/jsx-runtime";var ce=yo.forwardRef(({className:e,type:t,...n},s)=>yu("input",{type:t,className:K("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...n}));ce.displayName="Input";import*as ho from"react";import{cva as hu}from"class-variance-authority";import{jsx as wu}from"react/jsx-runtime";var xu=hu("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),xe=ho.forwardRef(({className:e,...t},n)=>wu("label",{ref:n,className:K(xu(),e),...t}));xe.displayName="Label";import*as ka from"react";import{Plus as Nu,Loader2 as oi,Copy as Ru,Check as _u,Trash2 as Pu,RefreshCw as Cu,AlertTriangle as Tu}from"lucide-react";import*as wa from"react";function tr(){let{api:e}=Q(),[t,n]=wa.useState([]),[s,a]=wa.useState(!0),[r,o]=wa.useState(null),u=wa.useCallback(async()=>{try{a(!0),o(null),n(await e.getEventDestinations())}catch(f){o(f instanceof Error?f:new Error("Failed to fetch webhooks"))}finally{a(!1)}},[e]);wa.useEffect(()=>{u()},[u]);let g=wa.useCallback(async f=>{let c=await e.createEventDestination(f);return n(m=>[c,...m]),c},[e]),l=wa.useCallback(async(f,c)=>{let m=await e.updateEventDestination(f,c);return n(p=>p.map(y=>y.id===f?m:y)),m},[e]),i=wa.useCallback(async f=>{await e.deleteEventDestination(f),n(c=>c.filter(m=>m.id!==f))},[e]),d=wa.useCallback(async f=>{let c=await e.rotateEventDestinationSecret(f);return n(m=>m.map(p=>p.id===f?c:p)),c},[e]),b=wa.useCallback(f=>e.getEventDestinationSecret(f),[e]);return{destinations:t,isLoading:s,error:r,refetch:u,createDestination:g,updateDestination:l,deleteDestination:i,rotateSecret:d,getSecret:b}}import*as fn from"react";import{Loader2 as xo,RotateCw as Su}from"lucide-react";import{jsx as Ta,jsxs as Rs}from"react/jsx-runtime";function ar({destinationId:e,limit:t=25,className:n}){let{api:s}=Q(),[a,r]=fn.useState([]),[o,u]=fn.useState(!0),[g,l]=fn.useState(null),[i,d]=fn.useState(null),b=fn.useCallback(async()=>{try{u(!0),l(null),r(await s.getEventDeliveries(e,t))}catch(c){l(c instanceof Error?c.message:"Failed to load deliveries")}finally{u(!1)}},[s,e,t]);fn.useEffect(()=>{b()},[b]);let f=async c=>{try{d(c.id),l(null);let m=await s.retryEventDelivery(e,c.id);r(p=>p.map(y=>y.id===c.id?m:y))}catch(m){l(m instanceof Error?m.message:"Retry failed")}finally{d(null)}};return o?Rs("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[Ta(xo,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):g?Ta("div",{className:"af-text-sm af-text-destructive af-py-2",children:g}):a.length===0?Ta("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):Ta("div",{className:n,children:Ta("div",{className:"af-divide-y af-border af-rounded",children:a.map(c=>{let m=c.delivered_at!==null;return Rs("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[Rs("div",{className:"af-min-w-0",children:[Rs("div",{className:"af-flex af-items-center af-gap-2",children:[m?Ta(te,{variant:"secondary",children:c.last_status??200}):Ta(te,{variant:"destructive",children:c.last_status??"failed"}),Ta("span",{className:"af-text-sm af-truncate",children:c.type})]}),Rs("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[c.event_id," \xB7 ",c.created_at,c.attempts>0&&` \xB7 ${c.attempts} failed ${c.attempts===1?"attempt":"attempts"}`]}),!m&&c.last_error&&Ta("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:c.last_error})]}),Ta(w,{variant:"ghost",size:"sm",title:"Send this event again",disabled:i===c.id,onClick:()=>f(c),children:i===c.id?Ta(xo,{className:"af-h-4 af-w-4 af-animate-spin"}):Ta(Su,{className:"af-h-4 af-w-4"})})]},c.id)})})})}import{jsx as Ae,jsxs as yt}from"react/jsx-runtime";function nr({formId:e,topics:t,description:n,className:s}){let{destinations:a,isLoading:r,error:o,createDestination:u,updateDestination:g,deleteDestination:l,rotateSecret:i,getSecret:d}=tr(),[b,f]=ka.useState(""),[c,m]=ka.useState(!1),[p,y]=ka.useState(null),[h,R]=ka.useState(null),[C,v]=ka.useState(null),[S,_]=ka.useState(!1),[k,x]=ka.useState(null),[P,A]=ka.useState(null),[N,G]=ka.useState(null),j=ka.useMemo(()=>a.filter(B=>B.form_id===e),[a,e]),$=async()=>{let B=b.trim();if(B){if(!B.startsWith("https://")){y("Webhook URLs must start with https://");return}try{m(!0),y(null),await u({url:B,form_id:e,...t&&t.length>0?{topics:t}:{}}),f("")}catch(ye){y(ye instanceof Error?ye.message:"Failed to add webhook")}finally{m(!1)}}},ae=async B=>{try{A(B.id),y(null),await i(B.id),_(!1),v(await d(B.id))}catch(ye){y(ye instanceof Error?ye.message:"Failed to rotate secret")}finally{A(null)}},se=async B=>{try{A(B.id),y(null),await g(B.id,{status:"active"})}catch(ye){y(ye instanceof Error?ye.message:"Failed to re-enable")}finally{A(null)}},de=async()=>{if(k)try{A(k.id),await l(k.id),x(null)}catch(B){y(B instanceof Error?B.message:"Failed to delete")}finally{A(null)}},U=async B=>{if(h===B.id){R(null),v(null);return}try{A(B.id),y(null),_(!1),R(B.id),v(await d(B.id))}catch(ye){R(null),y(ye instanceof Error?ye.message:"Failed to read secret")}finally{A(null)}},Z=async()=>{if(C)try{await navigator.clipboard.writeText(C),_(!0)}catch{}};return yt("div",{className:s,children:[yt("div",{className:"af-space-y-1",children:[Ae(xe,{children:"Webhooks"}),Ae("p",{className:"af-text-sm af-text-muted-foreground",children:n??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),yt("div",{className:"af-flex af-gap-2 af-mt-4",children:[Ae(ce,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:B=>f(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),$())},disabled:c}),yt(w,{onClick:$,disabled:c||!b.trim(),children:[c?Ae(oi,{className:"af-h-4 af-w-4 af-animate-spin"}):Ae(Nu,{className:"af-h-4 af-w-4"}),Ae("span",{className:"af-ml-1",children:"Add"})]})]}),(p||o)&&Ae("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:p||o?.message}),yt("div",{className:"af-mt-4 af-space-y-2",children:[r&&yt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ae(oi,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&j.length===0&&Ae("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),j.map(B=>yt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[yt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[yt("div",{className:"af-min-w-0",children:[yt("div",{className:"af-flex af-items-center af-gap-2",children:[Ae("span",{className:"af-font-mono af-text-sm af-truncate",children:B.url}),B.status==="disabled"?Ae(te,{variant:"destructive",children:"Disabled"}):Ae(te,{variant:"secondary",children:"Active"})]}),Ae("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:B.topics.includes("*")?"All events":B.topics.join(", ")})]}),yt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[Ae(w,{variant:"ghost",size:"sm",onClick:()=>G(N===B.id?null:B.id),children:N===B.id?"Hide log":"Deliveries"}),Ae(w,{variant:"ghost",size:"sm",onClick:()=>U(B),disabled:P===B.id,children:h===B.id?"Hide secret":"Show secret"}),Ae(w,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:P===B.id,onClick:()=>x(B),children:Ae(Pu,{className:"af-h-4 af-w-4"})})]})]}),B.status==="disabled"&&yt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[Ae(Tu,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),yt("div",{className:"af-text-sm",children:[yt("p",{children:["We stopped sending after repeated failures."," ",B.disabled_reason]}),Ae(w,{variant:"outline",size:"sm",className:"af-mt-2",disabled:P===B.id,onClick:()=>se(B),children:"Re-enable"})]})]}),h===B.id&&C&&yt("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[Ae("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."}),yt("div",{className:"af-flex af-gap-2",children:[Ae(ce,{readOnly:!0,value:C,className:"af-font-mono"}),Ae(w,{variant:"outline",title:"Copy signing secret",onClick:Z,children:S?Ae(_u,{className:"af-h-4 af-w-4"}):Ae(Ru,{className:"af-h-4 af-w-4"})}),Ae(w,{variant:"outline",title:"Rotate signing secret",disabled:P===B.id,onClick:()=>ae(B),children:P===B.id?Ae(oi,{className:"af-h-4 af-w-4 af-animate-spin"}):Ae(Cu,{className:"af-h-4 af-w-4"})})]})]}),N===B.id&&Ae(ar,{destinationId:B.id})]},B.id))]}),Ae(Ca,{open:!!k,onOpenChange:B=>{!B&&!P&&x(null)},children:yt(va,{children:[yt(ba,{children:[Ae(ha,{children:"Delete this webhook?"}),yt(xa,{children:["New submissions will stop being sent to ",k?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),yt(ya,{children:[Ae(w,{variant:"outline",onClick:()=>x(null),disabled:!!P,children:"Cancel"}),Ae(w,{variant:"destructive",onClick:de,disabled:!!P,children:P?"Deleting...":"Delete"})]})]})})]})}import{jsx as Me,jsxs as Ha}from"react/jsx-runtime";function sr({form:e,onSaved:t,className:n}){let{updateForm:s}=Wn(),[a,r]=Sa.useState(!1),[o,u]=Sa.useState(null),[g,l]=Sa.useState(null),[i,d]=Sa.useState(e.name),[b,f]=Sa.useState(e.redirect_url||""),[c,m]=Sa.useState(e.email_recipients),[p,y]=Sa.useState("");Sa.useEffect(()=>{d(e.name),f(e.redirect_url||""),m(e.email_recipients),l(null)},[e]);let h=Sa.useCallback(async _=>{try{r(!0),l(null);let k=await s(e.id,_);u(new Date),t?.(k)}catch(k){l(k instanceof Error?k.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);Sa.useEffect(()=>{if(o){let _=setTimeout(()=>u(null),2e3);return()=>clearTimeout(_)}},[o]);let R=async()=>{let _=p.trim().toLowerCase();if(!_)return;if(!_.includes("@")){l("Please enter a valid email address");return}if(c.includes(_)){l("This email is already added");return}let k=[...c,_];m(k),y(""),l(null),await h({email_recipients:k})},C=async _=>{let k=c.filter(x=>x!==_);m(k),await h({email_recipients:k})},v=async()=>{i!==e.name&&await h({name:i})},S=async()=>{let _=b||null;_!==e.redirect_url&&await h({redirect_url:_})};return Ha("div",{className:`af-space-y-6 af-relative ${n||""}`,children:[(a||o)&&Me("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:a?Ha("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:[Me(Iu,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),Me("span",{className:"af-text-sm",children:"Saving..."})]}):Ha("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:[Me(Au,{className:"af-h-4 af-w-4 af-text-green-600"}),Me("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Ha("div",{className:"af-space-y-2",children:[Me(xe,{htmlFor:"form-name",children:"Form Name"}),Me(ce,{id:"form-name",value:i,onChange:_=>d(_.target.value),onBlur:v,placeholder:"Contact Form"}),Me("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),Ha("div",{className:"af-space-y-2",children:[Me(xe,{children:"Email Recipients"}),Me("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),Ha("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[c.map(_=>Ha(te,{variant:"secondary",className:"af-gap-1",children:[_,Me("button",{type:"button",onClick:()=>C(_),className:"af-ml-1 hover:af-text-destructive",disabled:a,children:Me(Eu,{className:"af-h-3 af-w-3"})})]},_)),c.length===0&&Me("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Ha("div",{className:"af-flex af-gap-2",children:[Me(ce,{type:"email",value:p,onChange:_=>y(_.target.value),placeholder:"Add email address",onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),R())},disabled:a}),Me(w,{type:"button",variant:"outline",onClick:R,disabled:!p.trim()||a,children:Me(ku,{className:"af-h-4 af-w-4"})})]})]}),Ha("div",{className:"af-space-y-2",children:[Me(xe,{htmlFor:"redirect-url",children:"Redirect URL"}),Me(ce,{id:"redirect-url",value:b,onChange:_=>f(_.target.value),onBlur:S,placeholder:"/thank-you"}),Me("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."})]}),Ha("div",{className:"af-space-y-2",children:[Me(xe,{children:"Form Endpoint"}),Me("div",{className:"af-flex af-items-center af-gap-2",children:Me("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})}),Me("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),Ha("div",{className:"af-space-y-2",children:[Me(xe,{children:"Captcha Protection"}),Me("div",{className:"af-flex af-items-center af-gap-2",children:Me(te,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),Me("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),Me(nr,{formId:e.id}),g&&Me("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g})]})}import{jsx as aa,jsxs as Ja}from"react/jsx-runtime";function wo({className:e,location:t,onNavigate:n,submissionId:s}){let{api:a}=Q(),[r,o]=mn.useState({submissionId:s});mn.useEffect(()=>{s&&o({submissionId:s})},[s]);let u=n?t??{}:r,g=n??o,[l,i]=mn.useState(null),d=`${u.formId??""}|${u.submissionId??""}`,[b,f]=mn.useState(null),c=b?.key===d?b.message:null,m=u.formId??(l&&l.submissionId===u.submissionId?l.formId:void 0);mn.useEffect(()=>{let _=u.submissionId;if(!_||u.formId)return;let k=!1;return a.getSubmission(_).then(x=>{k||(f(null),i({submissionId:_,formId:x.form_id}))}).catch(()=>{k||f({key:d,message:"This submission could not be found."})}),()=>{k=!0}},[a,u.submissionId,u.formId,d]);let[p,y]=mn.useState(null);mn.useEffect(()=>{if(!m||p?.id===m)return;let _=!1;return a.getForm(m).then(k=>{_||(f(null),y(k))}).catch(()=>{_||f({key:d,message:"This form could not be found."})}),()=>{_=!0}},[a,m,p?.id,d]);let h=(_,k)=>{y(_),g({formId:_.id,tab:k})},R=()=>g({});if(!u.formId&&!u.submissionId)return Ja("div",{className:e,children:[Ja("div",{className:"af-mb-6",children:[aa("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),aa("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),aa(js,{onSelectForm:h})]});let v=Ja(w,{variant:"ghost",size:"sm",onClick:R,className:"af-mb-2 af--ml-2",children:[aa(Du,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(c)return Ja("div",{className:e,children:[v,aa("p",{className:"af-text-sm af-text-destructive",children:c})]});if(!m||p?.id!==m)return aa("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:aa("div",{className:"af-text-muted-foreground",children:"Loading..."})});let S=u.submissionId?"submissions":u.tab??"submissions";return Ja("div",{className:e,children:[Ja("div",{className:"af-mb-6",children:[v,aa("h2",{className:"af-text-lg af-font-semibold",children:p.name})]}),Ja(qs,{value:S,onValueChange:_=>g({formId:m,tab:_}),children:[Ja(xs,{className:"af-mb-4",children:[Ja(Ma,{value:"submissions",className:"af-gap-2",children:[aa(Ou,{className:"af-h-4 af-w-4"}),"Submissions"]}),Ja(Ma,{value:"settings",className:"af-gap-2",children:[aa(Lu,{className:"af-h-4 af-w-4"}),"Settings"]})]}),aa($a,{value:"submissions",children:aa(er,{formId:m,submissionId:u.submissionId,onSelectSubmission:_=>g({formId:m,tab:"submissions",submissionId:_??void 0})})}),aa($a,{value:"settings",children:aa(sr,{form:p,onSaved:y})})]})]})}import*as $e from"react";import*as Ya from"react";function Sn(){let{api:e}=Q(),[t,n]=Ya.useState(null),[s,a]=Ya.useState(!0),[r,o]=Ya.useState(null),u=Ya.useRef(0),g=Ya.useCallback(async()=>{let l=++u.current;try{a(!0),o(null);let i=await e.getPaymentsStatus();if(l!==u.current)return;n(i)}catch(i){if(l!==u.current)return;o(i instanceof Error?i:new Error("Failed to fetch payments status"))}finally{l===u.current&&a(!1)}},[e]);return Ya.useEffect(()=>{g()},[g]),{status:t,isLoading:s,error:r,refetch:g}}var Bu=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Ea(e){return Bu.has(e.toLowerCase())}function q(e,t,n){let s=Ea(t)?e:e/100;try{return new Intl.NumberFormat(n,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function pn(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 Ot(e,t){let n=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(n)||n<0)return null;let s=Ea(t)?n:n*100;return Math.round(s)}function lt(e,t){return Ea(t)?e:e/100}function rr(e){return e.amount_paid??Math.max(0,pn(e)-(e.credit_applied??0))}import{Fragment as Mu,jsx as Le,jsxs as je}from"react/jsx-runtime";function _s(e){return e instanceof St&&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 So(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${q(e.amount_off,e.currency)} off`:"Discount unavailable"}function Zn(){let{api:e,siteToken:t}=Q();return Le(Fu,{api:e},t)}function Fu({api:e}){let{status:t,error:n}=Sn(),[s,a]=$e.useState([]),[r,o]=$e.useState(null),[u,g]=$e.useState(null),[l,i]=$e.useState(!1),[d,b]=$e.useState(!1),[f,c]=$e.useState(""),[m,p]=$e.useState(null),[y,h]=$e.useState(null),[R,C]=$e.useState(!1),v=$e.useRef(0),S=$e.useCallback(async x=>{let P=++v.current;i(!0),c("");try{let A=await e.getPromos(x);if(P!==v.current)return;a(N=>x?[...N,...A.promos.filter(G=>!N.some(j=>j.id===G.id))]:A.promos),o(A.next_cursor),g(A.checkout_enabled)}catch(A){P===v.current&&c(_s(A))}finally{P===v.current&&i(!1)}},[e]);$e.useEffect(()=>(S(),()=>{v.current++}),[S]);async function _(x){let P=++v.current;i(!0),c(""),C(!1);try{let A=await e.getPromo(x);P===v.current&&p(A)}catch(A){P===v.current&&c(_s(A))}finally{P===v.current&&i(!1)}}async function k(){if(m){b(!0),i(!0),c("");try{let x=await e.disablePromo(m.id);if(p(x),!["inactive","expired","exhausted"].includes(x.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");C(!1),await S()}catch(x){c(_s(x))}finally{b(!1),i(!1)}}}return y?Le(Uu,{currency:t?.currency??void 0,replaces:y.replaces,onCancel:()=>h(null),onSave:async x=>{let P=y.replaces?await e.replacePromo(y.replaces.id,x):await e.createPromo(x),A=await e.getPromo(P.id);if(A.status==="pending"||A.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(A),h(null),await S()}}):je("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[je("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[Le("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),Le(w,{disabled:l||!t?.currency,onClick:()=>{c(""),h({})},children:"Create promo code"})]}),Le("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),u===!1&&Le("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&&Le("p",{className:"af-text-sm",children:n?_s(n):"Connect Stripe and set the payment currency before creating codes."}),f&&je("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[f," ",Le(w,{variant:"outline",disabled:l,onClick:()=>m?void _(m.id):void S(),children:"Refresh"})]}),m?je("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[Le(w,{variant:"ghost",disabled:d,onClick:()=>{p(null),C(!1),S()},children:"Back to codes"}),je("h4",{className:"af-font-semibold af-break-all",children:[m.code," \xB7 ",m.name]}),je("p",{children:[So(m)," \xB7 ",m.status]}),je("p",{className:"af-text-sm",children:[m.times_redeemed==null?"Usage unavailable":`${m.times_redeemed} redemptions`,m.max_redemptions!=null?` / ${m.max_redemptions} maximum`:""]}),je("p",{className:"af-text-sm",children:[m.minimum_amount!=null&&m.currency?`Minimum order: ${q(m.minimum_amount,m.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),je("p",{className:"af-text-sm",children:["Subscription discount:"," ",m.duration==="repeating"?`${m.duration_in_months} months`:m.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),Le("p",{className:"af-text-sm",children:m.expires_at?`Expires ${new Date(m.expires_at).toLocaleString()}`:"No expiry"}),je("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Le(w,{variant:"outline",disabled:l,onClick:()=>void _(m.id),children:"Refresh details"}),Le(w,{variant:"outline",disabled:l||m.status==="pending"||m.status==="unavailable"||!t?.currency,onClick:()=>h({replaces:m}),children:"Replace with new code"}),Le(w,{variant:"outline",disabled:l||!["active","pending","unavailable"].includes(m.status),onClick:()=>C(!0),children:m.status==="pending"?"Cancel pending offer":"Disable code"})]}),R&&je("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[je("p",{className:"af-text-sm",children:[m.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${m.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),Le(w,{disabled:l,onClick:()=>void k(),children:m.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",Le(w,{variant:"ghost",disabled:l,onClick:()=>C(!1),children:"Cancel"})]})]}):je(Mu,{children:[s.map(x=>je("button",{type:"button",disabled:l,onClick:()=>void _(x.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:[je("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[Le("span",{className:"af-font-semibold af-break-all",children:x.code}),Le("span",{className:"af-text-sm",children:x.status})]}),je("div",{className:"af-text-sm",children:[So(x)," \xB7"," ",x.times_redeemed==null?"Usage unavailable":`${x.times_redeemed} redemptions`]})]},x.id)),!l&&!f&&s.length===0&&Le("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&&Le("p",{role:"status",children:"Loading promo codes\u2026"}),r&&Le(w,{variant:"outline",disabled:l,onClick:()=>void S(r),children:"Load more"})]})]})}function Uu({currency:e,replaces:t,onCancel:n,onSave:s}){let[a,r]=$e.useState(""),[o,u]=$e.useState(t?.name??""),[g,l]=$e.useState(t?.amount_off!=null?"fixed":"percent"),[i,d]=$e.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(lt(t.amount_off,e)):"")),[b,f]=$e.useState(t?.minimum_amount!=null&&e?String(lt(t.minimum_amount,e)):""),[c,m]=$e.useState(()=>{if(!t?.expires_at)return"";let se=new Date(t.expires_at);return Number.isFinite(se.getTime())?new Date(se.getTime()-se.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,y]=$e.useState(t?.max_redemptions?.toString()??""),[h,R]=$e.useState(t?.duration??"once"),[C,v]=$e.useState(t?.duration_in_months?.toString()??"3"),[S,_]=$e.useState(null),[k,x]=$e.useState(!1),[P,A]=$e.useState(""),N=$e.useRef(!1),G=e&&Ea(e)?"1":"0.01";async function j(se){if(se.preventDefault(),N.current)return;A("");let de=S;if(!de){if(!e){A("Payment currency is not available.");return}if(t&&a.trim().toUpperCase()===t.code.toUpperCase()){A("Choose a different code for the replacement.");return}let U=Ot(i,e),Z=b?Ot(b,e):null;if(g==="fixed"&&(!U||U>999999999999)||b&&(!Z||Z>999999999999)){A("Enter a positive amount within the supported range.");return}if(c&&new Date(c).getTime()<=Date.now()){A("Choose a future expiry.");return}de={request_id:crypto.randomUUID(),code:a.trim().toUpperCase(),name:o.trim(),duration:h,...g==="percent"?{percent_off:Number(i)}:{amount_off:U,currency:e},...b?{minimum_amount:Z,currency:e}:{},...c?{expires_at:new Date(c).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...h==="repeating"?{duration_in_months:Number(C)}:{}},_(de)}N.current=!0,x(!0);try{await s(de)}catch(U){A(_s(U)),U instanceof St&&U.status>=400&&U.status<500&&U.details?.retryable!==!0&&_(null)}finally{N.current=!1,x(!1)}}let $=(se,de,U,Z={})=>je("label",{className:"af-grid af-gap-1 af-text-sm",children:[se,Le(ce,{"aria-label":se,value:de,onChange:B=>U(B.target.value),...Z})]}),ae="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return je("form",{onSubmit:j,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[Le("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&Le("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."}),je("fieldset",{disabled:k||!!S,className:"af-grid af-gap-4",children:[$("Code",a,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),$("Name",o,u,{required:!0,maxLength:40}),je("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",je("select",{"aria-label":"Discount type",className:ae,value:g,onChange:se=>l(se.target.value),children:[Le("option",{value:"percent",children:"Percentage"}),je("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),$("Discount",i,d,{type:"number",required:!0,min:g==="percent"?"0.01":G,max:g==="percent"?"100":void 0,step:g==="percent"?"0.01":G}),$("Minimum order amount",b,f,{type:"number",min:G,step:G,placeholder:e?.toUpperCase()}),je("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."]}),$("Expires at (local time)",c,m,{type:"datetime-local",step:1}),$("Maximum redemptions",p,y,{type:"number",min:1,max:1e6,step:1}),je("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",je("select",{"aria-label":"Subscription duration",className:ae,value:h,onChange:se=>R(se.target.value),children:[Le("option",{value:"once",children:"First invoice only"}),Le("option",{value:"forever",children:"Every invoice"}),Le("option",{value:"repeating",children:"Number of months"})]})]}),h==="repeating"&&$("Months",C,v,{type:"number",required:!0,min:1,max:36,step:1})]}),P&&Le("p",{role:"alert",className:"af-text-sm af-text-destructive",children:P}),S&&!k&&je("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",Le("span",{className:"af-break-all",children:S.request_id})]}),je("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Le(w,{type:"submit",disabled:k,children:k?"Saving\u2026":S?"Retry same request":t?"Create replacement":"Create code"}),Le(w,{type:"button",variant:"ghost",disabled:k||!!S,onClick:n,children:"Cancel"})]})]})}import*as rs from"react";import{ArrowLeft as uf,FileText as df,Package as ff,Receipt as mf,Settings as pf,Users as gf}from"lucide-react";import*as ir from"react";import{Package as $u,Pencil as Vu,Plus as No,Trash2 as Hu}from"lucide-react";import{jsx as qe,jsxs as Vt}from"react/jsx-runtime";function zu(e){if(e.allow_custom_amount){let t=e.min_amount!==null?q(e.min_amount,e.currency):"?",n=e.max_amount!==null?q(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${n})`}return e.unit_amount===null?"Varies by variant":q(e.unit_amount,e.currency)}function qu(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function or({productsState:e,onSelectProduct:t,onCreateProduct:n,className:s}){let{products:a,isLoading:r,error:o,deleteProduct:u}=e,[g,l]=ir.useState(null),[i,d]=ir.useState(!1),[b,f]=ir.useState(null),c=async()=>{if(g)try{d(!0),f(null),await u(g.id),l(null)}catch(m){f(m instanceof Error?m.message:"Failed to delete product")}finally{d(!1)}};return r?qe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:qe("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?qe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Vt("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):a.length===0?Vt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[qe($u,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Vt("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",qe("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),Vt(w,{variant:"outline",onClick:()=>n?.(),children:[qe(No,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Vt("div",{className:s,children:[qe("div",{className:"af-flex af-justify-end af-mb-4",children:Vt(w,{variant:"outline",size:"sm",onClick:()=>n?.(),children:[qe(No,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Vt(Ve,{children:[qe(He,{children:Vt(be,{children:[qe(V,{children:"Name"}),qe(V,{children:"Price"}),qe(V,{children:"Fulfillment"}),qe(V,{children:"Status"}),qe(V,{className:"af-text-right",children:"Actions"})]})}),qe(ze,{children:a.map(m=>Vt(be,{children:[qe(H,{className:"af-font-medium",children:m.name}),qe(H,{children:zu(m)}),qe(H,{className:"af-text-muted-foreground",children:qu(m)}),qe(H,{children:qe(te,{variant:m.active?"success":"secondary",children:m.active?"Active":"Inactive"})}),qe(H,{className:"af-text-right",children:Vt("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Vt(w,{variant:"ghost",size:"sm",onClick:()=>t?.(m),children:[qe(Vu,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Vt(w,{variant:"ghost",size:"sm",onClick:()=>{f(null),l(m)},children:[qe(Hu,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},m.id))})]}),qe(Ca,{open:!!g,onOpenChange:m=>{!m&&!i&&l(null)},children:Vt(va,{children:[Vt(ba,{children:[qe(ha,{children:"Delete product?"}),Vt(xa,{children:['"',g?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&qe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),Vt(ya,{children:[qe(w,{variant:"outline",onClick:()=>l(null),disabled:i,children:"Cancel"}),qe(w,{variant:"destructive",onClick:c,disabled:i,children:i?"Deleting...":"Delete"})]})]})})]})}import*as Qe from"react";import{FileText as Gu,Link2 as Wu,Loader2 as Po,Plus as Ku,Upload as Zu,X as Ju}from"lucide-react";import*as ht from"react";import{Loader2 as Ro,Plus as li,Trash2 as _o,X as ju}from"lucide-react";import{jsx as J,jsxs as pe}from"react/jsx-runtime";function ci(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function lr({productId:e,currency:t,className:n}){let{api:s}=Q(),a=Ea(t)?"1":"0.01",[r,o]=ht.useState(null),[u,g]=ht.useState(!0),[l,i]=ht.useState(null),[d,b]=ht.useState(null),[f,c]=ht.useState(!1),m=ht.useRef(!0);ht.useEffect(()=>(m.current=!0,()=>{m.current=!1}),[]);let p=ht.useCallback(async()=>{try{let E=await s.getProduct(e);if(!m.current)return;o(E)}catch(E){if(!m.current)return;i(E instanceof Error?E.message:"Failed to load product")}finally{m.current&&g(!1)}},[s,e]);ht.useEffect(()=>{p()},[p]);let y=async E=>{b(null),c(!0);try{await E(),await p()}catch(F){m.current&&b(F instanceof Error?F.message:"Something went wrong")}finally{m.current&&c(!1)}},[h,R]=ht.useState(""),[C,v]=ht.useState(""),[S,_]=ht.useState({}),k=()=>y(async()=>{let E=h.trim(),F=C.split(",").map(O=>O.trim()).filter(Boolean);if(!E)throw new Error("Option name is required");if(F.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:E,values:F}),m.current&&(R(""),v(""))}),x=E=>y(async()=>{let F=(S[E.id]??"").trim();if(!F)throw new Error("Enter a value");await s.updateOption(E.id,{add_values:[F]}),m.current&&_(O=>({...O,[E.id]:""}))}),P=(E,F)=>y(()=>s.updateOption(E.id,{remove_values:[F]})),A=E=>y(()=>s.deleteOption(E.id)),[N,G]=ht.useState(null),[j,$]=ht.useState(null),[ae,se]=ht.useState(!1),[de,U]=ht.useState(null),Z=r?.options??[],B=r?.variants??[],ye=()=>{$(null),G({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(Z.map(E=>[E.id,E.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},re=E=>{$(null);let F=E.inventory?.on_hand??0,O=F<0?"":String(F);G({variant:E,title:E.title??"",sku:E.sku??"",unitAmount:E.unit_amount!=null?String(lt(E.unit_amount,t)):"",compareAt:E.compare_at_amount!=null?String(lt(E.compare_at_amount,t)):"",active:E.active,optionValues:{},tracked:E.inventory?.tracked??!1,onHand:O,initialOnHand:O,allowBackorder:E.inventory?.allow_backorder??!1})},Xe=async()=>{if(!N)return;$(null);let E=N.variant?.allow_custom_amount??!1,F=null,O=null;if(!E){if(F=Ot(N.unitAmount,t),F===null||F<=0){$("Enter a valid price");return}if(N.compareAt.trim()&&(O=Ot(N.compareAt,t),O===null||O<=F)){$("Compare-at price must be greater than the price");return}}let me=N.onHand.trim()!==N.initialOnHand.trim(),ve=parseInt(N.onHand,10);if(N.tracked&&me&&(!Number.isFinite(ve)||ve<0)){$("On-hand quantity must be zero or more");return}try{if(se(!0),N.variant)await s.updateVariant(N.variant.id,{title:N.title.trim()||null,sku:N.sku.trim()||null,...E?{}:{unit_amount:F,compare_at_amount:O},active:N.active}),await s.setVariantInventory(N.variant.id,{tracked:N.tracked,on_hand:N.tracked&&me?ve:void 0,allow_backorder:N.allowBackorder});else{let Pe={};for(let Oe of Z){let st=N.optionValues[Oe.id];if(!st){$(`Choose a ${Oe.title}`),se(!1);return}Pe[Oe.title]=st}await s.createVariant(e,{title:N.title.trim()||null,sku:N.sku.trim()||null,unit_amount:F,compare_at_amount:O,active:N.active,option_values:Z.length>0?Pe:void 0,inventory:N.tracked?{tracked:!0,on_hand:ve,allow_backorder:N.allowBackorder}:{tracked:!1,allow_backorder:N.allowBackorder}})}await p(),m.current&&G(null)}catch(Pe){if(m.current&&$(Pe instanceof Error?Pe.message:"Failed to save variant"),N.variant)try{let Oe=await s.getProduct(e);m.current&&o(Oe)}catch{}}finally{m.current&&se(!1)}},he=()=>y(async()=>{de&&(await s.deleteVariant(de.id),m.current&&U(null))}),Ue=N?.variant?.allow_custom_amount??!1,Ze=N?.variant!=null&&N.variant.option_values.length===0&&Z.length>0&&!N.variant.active,Ee=N?.variant?.inventory!=null&&N.variant.inventory.on_hand<0?-N.variant.inventory.on_hand:null;function kt(E){let F=E.inventory;if(!F||!F.tracked)return J("span",{className:"af-text-muted-foreground",children:"Unlimited"});let O=F.available??F.on_hand;return O<0?pe("span",{children:[-O," backordered"]}):pe("span",{children:[O," in stock",F.allow_backorder&&J("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return u?J("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${n||""}`,children:J(Ro,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):l?J("div",{className:n,children:J("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l})}):pe("div",{className:`af-space-y-6 ${n||""}`,children:[pe("div",{className:"af-space-y-3",children:[pe("div",{children:[J(xe,{children:"Options"}),J("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."})]}),Z.length>0&&J("div",{className:"af-space-y-3",children:Z.map(E=>pe("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[pe("div",{className:"af-flex af-items-center af-justify-between",children:[J("span",{className:"af-text-sm af-font-medium",children:E.title}),J(w,{variant:"ghost",size:"sm",onClick:()=>A(E),disabled:f,children:J(_o,{className:"af-h-4 af-w-4"})})]}),J("div",{className:"af-flex af-flex-wrap af-gap-2",children:E.values.map(F=>pe(te,{variant:"secondary",className:"af-gap-1",children:[F.value,J("button",{type:"button",onClick:()=>P(E,F.value),className:"af-ml-1 hover:af-text-destructive",disabled:f,title:"Remove value",children:J(ju,{className:"af-h-3 af-w-3"})})]},F.id))}),pe("div",{className:"af-flex af-gap-2",children:[J(ce,{value:S[E.id]??"",onChange:F=>_(O=>({...O,[E.id]:F.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),x(E))},disabled:f}),J(w,{type:"button",variant:"outline",size:"sm",onClick:()=>x(E),disabled:f||!(S[E.id]??"").trim(),children:J(li,{className:"af-h-4 af-w-4"})})]})]},E.id))}),pe("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[pe("div",{className:"af-space-y-1",children:[J(xe,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),J(ce,{id:"new-option-title",value:h,onChange:E=>R(E.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:f})]}),pe("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[J(xe,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),J(ce,{id:"new-option-values",value:C,onChange:E=>v(E.target.value),placeholder:"S, M, L",disabled:f})]}),pe(w,{type:"button",variant:"outline",onClick:k,disabled:f||!h.trim()||!C.trim(),children:[J(li,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),pe("div",{className:"af-space-y-3",children:[pe("div",{className:"af-flex af-items-center af-justify-between",children:[J(xe,{children:"Variants"}),pe(w,{type:"button",variant:"outline",size:"sm",onClick:ye,disabled:f||Z.length===0,children:[J(li,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),Z.length===0&&J("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),B.length===0?J("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):pe(Ve,{children:[J(He,{children:pe(be,{children:[J(V,{children:"Variant"}),J(V,{children:"SKU"}),J(V,{children:"Price"}),J(V,{children:"Stock"}),J(V,{children:"Status"}),J(V,{className:"af-text-right",children:"Actions"})]})}),J(ze,{children:B.map(E=>pe(be,{children:[J(H,{className:"af-font-medium",children:ci(E)}),J(H,{className:"af-text-muted-foreground",children:E.sku||"-"}),J(H,{children:E.unit_amount!=null?pe("span",{children:[E.compare_at_amount!=null&&J("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:q(E.compare_at_amount,E.currency)}),q(E.unit_amount,E.currency)]}):E.allow_custom_amount?J("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),J(H,{children:kt(E)}),J(H,{children:J(te,{variant:E.active?"success":"secondary",children:E.active?"Active":"Inactive"})}),J(H,{className:"af-text-right",children:pe("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[J(w,{variant:"ghost",size:"sm",onClick:()=>re(E),disabled:f,children:"Edit"}),J(w,{variant:"ghost",size:"icon",onClick:()=>U(E),disabled:f,title:"Delete variant",children:J(_o,{className:"af-h-4 af-w-4"})})]})})]},E.id))})]})]}),d&&J("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d}),J(Ca,{open:N!==null,onOpenChange:E=>{!E&&!ae&&G(null)},children:pe(va,{children:[pe(ba,{children:[J(ha,{children:N?.variant?"Edit variant":"Add variant"}),J(xa,{children:"Price, markdown, and stock live on the variant."})]}),N&&pe("div",{className:"af-space-y-3",children:[N.variant?N.variant.option_values.length>0&&pe("div",{className:"af-text-sm",children:[J("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),ci(N.variant)]}):Z.map(E=>pe("div",{className:"af-space-y-1",children:[J(xe,{className:"af-text-xs af-text-muted-foreground",children:E.title}),pe(_a,{value:N.optionValues[E.id]??"",onValueChange:F=>G(O=>O&&{...O,optionValues:{...O.optionValues,[E.id]:F}}),children:[J(pa,{children:J(Pa,{placeholder:`Choose ${E.title}`})}),J(ga,{children:E.values.map(F=>J(Ye,{value:F.value,children:F.value},F.id))})]})]},E.id)),Ue?pe("div",{className:"af-space-y-1",children:[J(xe,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),J("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):pe("div",{className:"af-flex af-gap-3",children:[pe("div",{className:"af-space-y-1",children:[pe(xe,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),J(ce,{id:"variant-price",type:"number",min:"0",step:a,value:N.unitAmount,onChange:E=>G(F=>F&&{...F,unitAmount:E.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),pe("div",{className:"af-space-y-1",children:[J(xe,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),J(ce,{id:"variant-compare",type:"number",min:"0",step:a,value:N.compareAt,onChange:E=>G(F=>F&&{...F,compareAt:E.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),pe("div",{className:"af-space-y-1",children:[J(xe,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),J(ce,{id:"variant-sku",value:N.sku,onChange:E=>G(F=>F&&{...F,sku:E.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),pe("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[pe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[J("input",{type:"checkbox",checked:N.tracked,onChange:E=>G(F=>F&&{...F,tracked:E.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),N.tracked&&pe("div",{className:"af-space-y-1 af-pl-6",children:[pe("div",{className:"af-flex af-items-end af-gap-3",children:[pe("div",{className:"af-space-y-1",children:[J(xe,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),J(ce,{id:"variant-onhand",type:"number",min:"0",step:"1",value:N.onHand,onChange:E=>G(F=>F&&{...F,onHand:E.target.value}),placeholder:Ee!=null?"0":void 0,className:"af-w-[100px]"})]}),pe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[J("input",{type:"checkbox",checked:N.allowBackorder,onChange:E=>G(F=>F&&{...F,allowBackorder:E.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Ee!=null&&pe("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Ee," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),pe("div",{className:"af-space-y-1",children:[pe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[J("input",{type:"checkbox",checked:N.active,onChange:E=>G(F=>F&&{...F,active:E.target.checked}),className:"af-h-4 af-w-4",disabled:Ze}),"Active (buyers can purchase this variant)"]}),Ze&&J("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),j&&J("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:j})]}),pe(ya,{children:[J(w,{variant:"outline",onClick:()=>G(null),disabled:ae,children:"Cancel"}),pe(w,{onClick:Xe,disabled:ae,children:[ae?J(Ro,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,N?.variant?"Save":"Add variant"]})]})]})}),J(Ca,{open:de!==null,onOpenChange:E=>{!E&&!f&&U(null)},children:pe(va,{children:[pe(ba,{children:[J(ha,{children:"Delete variant?"}),J(xa,{children:de&&`"${ci(de)}" will no longer be purchasable. Past orders are unaffected.`})]}),pe(ya,{children:[J(w,{variant:"outline",onClick:()=>U(null),disabled:f,children:"Cancel"}),J(w,{variant:"destructive",onClick:he,disabled:f,children:"Delete"})]})]})})]})}import{Fragment as Xu,jsx as ge,jsxs as Ie}from"react/jsx-runtime";function Yu(e){if(e===0)return"0 B";let t=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${n[s]}`}function cr({productsState:e,product:t,currency:n,onSaved:s,className:a}){let{createProduct:r,updateProduct:o,attachProductFile:u,attachProductFileFromUrl:g}=e,l=!!t,i=t?.currency??n,d=Ea(i)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[f,c]=Qe.useState(!1),[m,p]=Qe.useState(null),y=Qe.useRef(!0);Qe.useEffect(()=>(y.current=!0,()=>{y.current=!1}),[]);let[h,R]=Qe.useState(t?.name??""),[C,v]=Qe.useState(t?.description??""),[S,_]=Qe.useState(t?.allow_custom_amount?"custom":"fixed"),[k,x]=Qe.useState(t?.unit_amount!=null?String(lt(t.unit_amount,i)):""),[P,A]=Qe.useState(t?.min_amount!=null?String(lt(t.min_amount,i)):""),[N,G]=Qe.useState(t?.max_amount!=null?String(lt(t.max_amount,i)):""),[j,$]=Qe.useState(String(t?.max_quantity??10)),ae=Qe.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(lt(t.unit_amount,i)):"",minAmount:t?.min_amount!=null?String(lt(t.min_amount,i)):"",maxAmount:t?.max_amount!=null?String(lt(t.max_amount,i)):"",maxQuantity:String(t?.max_quantity??10)}).current,[se,de]=Qe.useState(t?.collect_shipping_address??!1),[U,Z]=Qe.useState(t?.active??!0),[B,ye]=Qe.useState(t?.images??[]),[re,Xe]=Qe.useState(""),[he,Ue]=Qe.useState(t?.fulfillment??null),[Ze,Ee]=Qe.useState(!1),[kt,E]=Qe.useState(""),[F,O]=Qe.useState(null),me=Qe.useRef(null),ve=f||Ze,Pe=()=>{let oe=re.trim();if(oe){if(B.includes(oe)){p("This image URL is already added");return}ye(Ce=>[...Ce,oe]),Xe(""),p(null)}},Oe=oe=>{ye(Ce=>Ce.filter(rt=>rt!==oe))},st=async()=>{if(p(null),!h.trim()){p("Product name is required");return}let oe=null,Ce=null,rt=null,ma=!l||S!==ae.pricingMode||(S==="fixed"?k!==ae.unitAmount:P!==ae.minAmount||N!==ae.maxAmount),Lt=!l||j!==ae.maxQuantity,Xt=b||S==="fixed";if(!(b||!ma))if(S==="fixed"){if(oe=Ot(k,i),oe===null||oe<=0){p("Enter a valid price");return}}else{if(Ce=Ot(P,i),rt=Ot(N,i),Ce===null||rt===null){p("Enter valid minimum and maximum amounts");return}if(rt<Ce){p("Maximum amount must be at least the minimum amount");return}}let Ut=parseInt(j,10);if(Xt&&Lt&&(!Number.isFinite(Ut)||Ut<1)){p("Max quantity must be at least 1");return}try{c(!0);let Ke;if(l&&t){let it={name:h.trim(),description:C.trim()||null,images:B,collect_shipping_address:se,active:U};!b&&ma&&(it.allow_custom_amount=S==="custom",S==="fixed"?it.unit_amount=oe:(it.min_amount=Ce,it.max_amount=rt)),Xt&&Lt&&(it.max_quantity=Ut),Ke=await o(t.id,it),ae.pricingMode=Ke.allow_custom_amount?"custom":"fixed",ae.unitAmount=Ke.unit_amount!=null?String(lt(Ke.unit_amount,i)):"",ae.minAmount=Ke.min_amount!=null?String(lt(Ke.min_amount,i)):"",ae.maxAmount=Ke.max_amount!=null?String(lt(Ke.max_amount,i)):"",ae.maxQuantity=String(Ke.max_quantity)}else{let it={name:h.trim(),allow_custom_amount:S==="custom",collect_shipping_address:se,active:U};C.trim()&&(it.description=C.trim()),B.length>0&&(it.images=B),S==="fixed"?(it.unit_amount=oe,it.max_quantity=Ut):(it.min_amount=Ce,it.max_amount=rt),Ke=await r(it)}if(!y.current)return;Ue(Ke.fulfillment),s?.(Ke)}catch(Ke){if(!y.current)return;p(Ke instanceof Error?Ke.message:"Failed to save product")}finally{y.current&&c(!1)}},Be=async oe=>{let Ce=oe.target.files?.[0];if(!(!Ce||!t))try{Ee(!0),O(null);let rt=await u(t.id,Ce);if(!y.current)return;Ue(rt.fulfillment),s?.(rt)}catch(rt){if(!y.current)return;O(rt instanceof Error?rt.message:"Failed to upload file")}finally{y.current&&(Ee(!1),me.current&&(me.current.value=""))}},mt=async()=>{let oe=kt.trim();if(!(!oe||!t))try{Ee(!0),O(null);let Ce=await g(t.id,oe);if(!y.current)return;Ue(Ce.fulfillment),E(""),s?.(Ce)}catch(Ce){if(!y.current)return;O(Ce instanceof Error?Ce.message:"Failed to fetch file")}finally{y.current&&Ee(!1)}};return Ie("div",{className:`af-space-y-6 ${a||""}`,children:[Ie("div",{className:"af-space-y-2",children:[ge(xe,{htmlFor:"product-name",children:"Name"}),ge(ce,{id:"product-name",value:h,onChange:oe=>R(oe.target.value),placeholder:"My product"})]}),Ie("div",{className:"af-space-y-2",children:[ge(xe,{htmlFor:"product-description",children:"Description"}),ge("textarea",{id:"product-description",value:C,onChange:oe=>v(oe.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"})]}),Ie("div",{className:"af-space-y-2",children:[ge(xe,{children:"Pricing"}),b?ge("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):Ie(Xu,{children:[Ie(_a,{value:S,onValueChange:oe=>_(oe),children:[ge(pa,{className:"af-w-[260px]",children:ge(Pa,{})}),Ie(ga,{children:[ge(Ye,{value:"fixed",children:"Fixed price"}),ge(Ye,{value:"custom",children:"Buyer chooses the amount"})]})]}),S==="fixed"?ge("div",{className:"af-flex af-items-end af-gap-3",children:Ie("div",{className:"af-space-y-1",children:[Ie(xe,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",i.toUpperCase(),")"]}),ge(ce,{id:"product-price",type:"number",min:"0",step:d,value:k,onChange:oe=>x(oe.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):Ie("div",{className:"af-space-y-1",children:[Ie("div",{className:"af-flex af-items-end af-gap-3",children:[Ie("div",{className:"af-space-y-1",children:[Ie(xe,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",i.toUpperCase(),")"]}),ge(ce,{id:"product-min-amount",type:"number",min:"0",step:d,value:P,onChange:oe=>A(oe.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),Ie("div",{className:"af-space-y-1",children:[Ie(xe,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",i.toUpperCase(),")"]}),ge(ce,{id:"product-max-amount",type:"number",min:"0",step:d,value:N,onChange:oe=>G(oe.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),ge("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."})]}),Ie("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",i.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||S==="fixed")&&Ie("div",{className:"af-space-y-1",children:[ge(xe,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),ge(ce,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:j,onChange:oe=>$(oe.target.value),className:"af-w-[140px]"})]})]}),Ie("div",{className:"af-space-y-2",children:[ge(xe,{children:"Images"}),ge("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),Ie("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[B.map(oe=>Ie(te,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[ge("span",{className:"af-truncate",children:oe}),ge("button",{type:"button",onClick:()=>Oe(oe),className:"af-ml-1 hover:af-text-destructive",disabled:f,children:ge(Ju,{className:"af-h-3 af-w-3"})})]},oe)),B.length===0&&ge("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),Ie("div",{className:"af-flex af-gap-2",children:[ge(ce,{type:"url",value:re,onChange:oe=>Xe(oe.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:oe=>{oe.key==="Enter"&&(oe.preventDefault(),Pe())},disabled:f}),ge(w,{type:"button",variant:"outline",onClick:Pe,disabled:!re.trim()||f,children:ge(Ku,{className:"af-h-4 af-w-4"})})]})]}),Ie("div",{className:"af-space-y-2",children:[ge(xe,{children:"Digital File"}),ge("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?Ie("div",{className:"af-space-y-3",children:[he?.type==="download"&&Ie("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[ge(Gu,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),ge("span",{className:"af-text-sm",children:he.filename}),he.size!=null&&Ie("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Yu(he.size),")"]})]}),he?.type==="redirect"&&he.url&&Ie("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[ge(Wu,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Ie("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",he.url]})]}),Ie("div",{className:"af-flex af-items-center af-gap-2",children:[ge("input",{ref:me,type:"file",onChange:Be,className:"af-hidden",disabled:ve}),Ie(w,{type:"button",variant:"outline",size:"sm",onClick:()=>me.current?.click(),disabled:ve,children:[Ze?ge(Po,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):ge(Zu,{className:"af-h-4 af-w-4 af-mr-1"}),he?.type==="download"?"Replace file":"Upload file"]}),ge("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),ge(ce,{type:"url",value:kt,onChange:oe=>E(oe.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Ze}),ge(w,{type:"button",variant:"outline",size:"sm",onClick:mt,disabled:!kt.trim()||ve,children:"Fetch from URL"})]}),F&&ge("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:F})]}):ge("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),Ie("div",{className:"af-space-y-2",children:[ge(xe,{children:"Settings"}),Ie("div",{className:"af-space-y-2",children:[Ie("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ge("input",{type:"checkbox",checked:se,onChange:oe=>de(oe.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),Ie("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ge("input",{type:"checkbox",checked:U,onChange:oe=>Z(oe.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),l&&t&&Ie("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[ge(xe,{children:"Options & Variants"}),ge(lr,{productId:t.id,currency:i})]}),m&&ge("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m}),ge("div",{className:"af-flex af-items-center af-gap-2",children:Ie(w,{type:"button",onClick:st,disabled:ve,children:[f?ge(Po,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,l?"Save changes":"Create product"]})})]})}import*as _t from"react";import{ChevronLeft as Sd,ChevronRight as Fo,Loader2 as Nd,Receipt as Rd,Search as _d,SlidersHorizontal as Pd}from"lucide-react";import*as ct from"react";var Qu=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function ur({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=Q(),[s,a]=ct.useState([]),[r,o]=ct.useState(0),[u,g]=ct.useState(!0),[l,i]=ct.useState(null),[d,b]=ct.useState(0),[f,c]=ct.useState(e),[m,p]=ct.useState(void 0),[y,h]=ct.useState(""),[R,C]=ct.useState(""),[v,S]=ct.useState(""),[_,k]=ct.useState(!1),[x,P]=ct.useState(!1),[A,N]=ct.useState(void 0),G=A?A.join(","):"",j=ct.useMemo(()=>{if(!G)return;let U=new Set(G.split(","));return Qu.filter(Z=>!U.has(Z))},[G]),$=ct.useMemo(()=>{let U={};return m?U.status=m:j?U.excludeStatus=j:_||(U.excludeStatus=["pending","expired"]),y.trim()&&(U.customerEmail=y.trim()),R.trim()&&(U.from=R.trim()),v.trim()&&(U.to=v.trim()),x&&(U.unfulfilledOnly=!0),U},[m,j,_,y,R,v,x]),ae=ct.useRef(0),se=ct.useCallback(async()=>{let U=++ae.current;try{g(!0),i(null);let Z={...$,limit:f,offset:d*f},B=await n.getOrders(Z);if(U!==ae.current)return;a(B.orders),o(B.total)}catch(Z){if(U!==ae.current)return;i(Z instanceof Error?Z:new Error("Failed to fetch orders"))}finally{U===ae.current&&g(!1)}},[n,d,f,$,t]);ct.useEffect(()=>{se()},[se]);let de=Math.ceil(r/f);return{orders:s,total:r,isLoading:u,error:l,page:d,pageSize:f,hasNextPage:d<de-1,hasPreviousPage:d>0,setPage:b,setPageSize:U=>{c(U),b(0)},status:m,setStatus:U=>{p(U),b(0)},statusIn:A,setStatusIn:U=>{N(U&&U.length>0?U:void 0),b(0)},customerEmail:y,setCustomerEmail:U=>{h(U),b(0)},from:R,setFrom:U=>{C(U),b(0)},to:v,setTo:U=>{S(U),b(0)},showAbandoned:_,setShowAbandoned:U=>{k(U),b(0)},unfulfilledOnly:x,setUnfulfilledOnly:U=>{P(U),b(0)},clearFilters:()=>{p(void 0),N(void 0),k(!1),P(!1),h(""),C(""),S(""),b(0)},filters:$,refetch:se}}import*as gt from"react";import{ArrowLeft as ad,Check as ko,ChevronLeft as nd,ChevronRight as sd,ClipboardCopy as rd,Copy as id,Download as od,Loader2 as pr,Mail as Eo,MoreHorizontal as ld,Package as cd,RotateCcw as ud,Truck as dd,Undo2 as Io}from"lucide-react";import*as Co from"react";import*as Xa from"@radix-ui/react-popover";import{jsx as ui}from"react/jsx-runtime";var dr=Xa.Root,fr=Xa.Trigger;var Ps=Co.forwardRef(({className:e,align:t="end",sideOffset:n=4,...s},a)=>ui(Xa.Portal,{children:ui("div",{className:"aifeatures-admin",children:ui(Xa.Content,{ref:a,align:t,sideOffset:n,className:K("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})})}));Ps.displayName=Xa.Content.displayName;import{jsx as mr}from"react/jsx-runtime";var ed={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function td(e){return ed[e]??e}function To(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 Fn({status:e,className:t}){return mr(te,{variant:To(e),className:t,children:td(e)})}function Un({status:e}){return mr(Fn,{status:e})}function Jn({order:e,className:t}){return e.line_items.some(n=>n.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?mr(te,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?mr(te,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function gn(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as hd,jsx as I,jsxs as X}from"react/jsx-runtime";var Oo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Mn="af-text-xs af-text-muted-foreground";function di(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 fd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bo(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 gr=24,md=["paid","partially_refunded"],pd=["paid","partially_refunded","disputed"],gd=/^[A-Za-z0-9 _-]*$/,Ao=100;function pi(e,t,n,s,a){let r=md.includes(s);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${n} of ${gr} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${n} of ${gr} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?n<gr&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:n<gr&&e==="buyer"&&!a?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${n} attempt${n===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${s==="refunded"?"because the order was refunded":s==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function Do({title:e,recipient:t,status:n,attempts:s,side:a,orderStatus:r,action:o,delivery:u}){if(u)return X("div",{children:[I(Za,{deliveries:[u]}),o&&I("div",{className:"af-mt-2",children:o})]});let g=pi(a,n,s,r,t);return X("div",{children:[X("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[X("div",{className:"af-min-w-0",children:[I("div",{className:"af-text-sm",children:e}),t&&I("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),I(te,{variant:g.variant,className:"af-shrink-0",children:g.label})]}),g.detail&&I("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:g.detail}),o&&I("div",{className:"af-mt-2",children:o})]})}function Lo(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let n=fd(e.address)?e.address:null;if(n){for(let a of["line1","line2"]){let r=n[a];typeof r=="string"&&r&&t.push(r)}let s=["city","state","postal_code"].map(a=>n[a]).filter(a=>typeof a=="string"&&!!a).join(", ");s&&t.push(s),typeof n.country=="string"&&n.country&&t.push(n.country)}return t.length>0?t:Object.entries(e).map(([s,a])=>`${s}: ${Bo(a)}`)}function vd(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function gi({value:e,label:t,children:n,className:s,size:a="icon"}){let[r,o]=gt.useState(!1);if(!vd())return null;let u=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},g=r?I(ko,{className:"af-h-3 af-w-3"}):I(id,{className:"af-h-3 af-w-3"});return a==="icon"?I(w,{variant:"ghost",size:"icon",className:K("af-h-6 af-w-6 af-shrink-0",s),onClick:u,title:t,"aria-label":t,children:g}):X(w,{variant:"outline",size:"sm",className:s,onClick:u,"aria-label":t,children:[r?I(ko,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):I(rd,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":n]})}function fi({label:e,value:t}){return X("div",{children:[I("div",{className:Mn,children:e}),X("div",{className:"af-flex af-items-center af-gap-1",children:[I("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),I(gi,{value:t,label:`Copy ${e}`})]})]})}function bd({src:e}){let[t,n]=gt.useState(!1);return!e||t?I("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:I(cd,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):I("img",{src:e,alt:"","aria-hidden":"true",onError:()=>n(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Qa({title:e,action:t,children:n,className:s}){return X("section",{className:K("af-rounded-lg af-border af-p-4",s),children:[X("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[I("h4",{className:Oo,children:e}),t]}),I("div",{className:"af-mt-3",children:n})]})}function na({label:e,emphasis:t,divider:n,children:s}){return X("div",{className:K("af-flex af-items-baseline af-justify-between af-gap-6",n&&"af-mt-2 af-border-t af-pt-2"),children:[I("span",{className:t?"af-text-base af-font-semibold":Mn,children:e}),I("span",{className:K("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function mi({onSelect:e,disabled:t,icon:n,children:s}){return X(w,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[I("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:n}),s]})}function yd(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?t.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${q(rr(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let n=e.email_deliveries?.find(a=>a.kind==="purchase_receipt"),s=n?Ws(n):pi("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(a=>a.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let n=e.email_deliveries?.find(a=>a.kind==="merchant_sale"),s=n?Ws(n):pi("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(a=>a.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${q(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function vr({order:e,onBack:t,onRefund:n,onOrderUpdated:s,allowFulfillment:a=!1,onPrevOrder:r,onNextOrder:o,hasPrevOrder:u=!1,hasNextOrder:g=!1}){let{api:l}=Q(),[i,d]=gt.useState(e),[b,f]=gt.useState(null),[c,m]=gt.useState(null),[p,y]=gt.useState(!1),[h,R]=gt.useState(!1),[C,v]=gt.useState(!1),[S,_]=gt.useState(!1),[k,x]=gt.useState(""),[P,A]=gt.useState(!1),[N,G]=gt.useState(null),[j,$]=gt.useState(!1),[ae,se]=gt.useState(""),[de,U]=gt.useState([]),[Z,B]=gt.useState(!1),[ye,re]=gt.useState(!1),[Xe,he]=gt.useState(null);gt.useEffect(()=>{d(e)},[e]);let Ue=L=>{let De=L.id===i.id&&L.email_deliveries===void 0?{...L,email_deliveries:i.email_deliveries}:L;d(De),s?.(De)},Ze=Object.entries(i.metadata??{}),Ee=Math.max(0,rr(i)-i.amount_refunded),kt=(i.status==="paid"||i.status==="partially_refunded")&&Ee>0,E=i.exclusive_tax_total!=null,F=L=>typeof L.amountNet=="number"?L.amountNet+(L.exclusiveTax??0):(typeof L.unitAmount=="number"?L.unitAmount:0)*(typeof L.quantity=="number"&&L.quantity>0?L.quantity:1),O=Math.max(0,(i.shipping_total??0)-(i.shipping_refunded??0)),me=de.reduce((L,De)=>L+F(i.line_items[De]??{}),0)+(Z?O:0),ve=i.tax_total??0,Pe=Math.max(0,(i.exclusive_tax_total??0)-i.line_items.reduce((L,De)=>L+(De.exclusiveTax??0),0)),Oe=E?Z&&O>0?Pe:0:i.automatic_tax&&i.tax_behavior==="exclusive"&&ve>0&&i.amount_total+(i.shipping_total??0)>0?Math.min(Math.max(0,ve-(i.tax_refunded??0)),Math.round(ve*me/(i.amount_total+(i.shipping_total??0)))):0,st=i.source==="subscription"&&(i.credit_applied??0)>0&&i.line_items.length===1?Math.min(me+Oe,Ee):me+Oe,Be=de.length>0||Z,mt=Be?st:Ot(ae,i.currency),oe=Ea(i.currency)?"1":"0.01",Ce=async()=>{try{y(!0),f(null),m(null),await l.resendOrderReceipt(i.id);let L=await l.getOrder(i.id);Ue(L),m("Receipt email queued.")}catch(L){f(L instanceof Error?L.message:"Failed to resend receipt")}finally{y(!1)}},rt=async()=>{try{R(!0),f(null),m(null);let L=await l.resetOrderDownloads(i.id);Ue(L),v(!1),m("Download count reset.")}catch(L){f(L instanceof Error?L.message:"Failed to reset downloads")}finally{R(!1)}},ma=i.line_items.some(L=>L.collectShippingAddress===!0&&!L.refunded&&!L.unavailableReason),Lt=typeof i.merchant_fulfilled_at=="string",Xt=pd.includes(i.status)||i.status==="refunded"&&i.line_items.some(L=>L.collectShippingAddress===!0&&L.amountNet===0&&!L.refunded&&!L.unavailableReason),Ut=k.trim(),Ke=gd.test(Ut)&&Ut.length<=Ao,it=async L=>{try{A(!0),G(null),m(null);let De=await l.setOrderFulfillment(i.id,{fulfilled:L,...L&&Ut?{trackingNumber:Ut}:{}});Ue(De),x(""),m(L?"Marked as shipped.":"Marked as not shipped.")}catch(De){De instanceof St&&De.status===409?G(`This order is ${i.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):G(De instanceof Error?De.message:"Failed to update the order")}finally{A(!1)}},Fa=()=>{he(null),se(String(lt(Ee,i.currency))),U([]),B(!1),$(!0)},Dn=L=>U(De=>De.includes(L)?De.filter(ea=>ea!==L):[...De,L]),Qt=async(L,De)=>{if(n)try{re(!0),he(null),await n(i,L,De);let ea=await l.getOrder(i.id);Ue(ea),$(!1),m("Refund issued.")}catch(ea){he(ea instanceof Error?ea.message:"Refund failed")}finally{re(!1)}},Zr=async()=>{if(Be){if(st<=0){he("The lines you picked were charged nothing");return}if(st>Ee){he(`That selection exceeds the refundable remainder (${q(Ee,i.currency)})`);return}await Qt(st,{...de.length>0?{line_items:[...de].sort((De,ea)=>De-ea)}:{},...Z?{shipping:!0}:{}});return}let L=Ot(ae,i.currency);if(L===null||L<=0){he("Enter a valid refund amount");return}if(L>Ee){he(`Amount exceeds the refundable remainder (${q(Ee,i.currency)})`);return}await Qt(L,{amount:L})},z=()=>Qt(Ee,{full:!0}),Je=!i.subscription_history_only&&i.fulfillment_type==="download",Ka=!i.subscription_history_only&&a&&ma,Jr=yd(i),W=i.shipping_address?Lo(i.shipping_address).join(`
4
- `):"",jt=i.shipping_total!=null,Yr=i.exclusive_tax_total??(i.automatic_tax&&i.tax_behavior==="exclusive"?i.tax_total??0:0),Yi=i.exclusive_tax_total!=null?Math.max(0,(i.tax_total??0)-Yr):i.automatic_tax&&i.tax_behavior==="exclusive"?0:i.tax_total??0,Xi=Yr>0,Nc=Yi>0,Qi=i.amount_subtotal!=null||jt||Xi||(i.discount_total??0)>0,vs=[];return i.subscription_history_only||vs.push(I(mi,{icon:p?I(pr,{className:"af-h-4 af-w-4 af-animate-spin"}):I(Eo,{className:"af-h-4 af-w-4"}),disabled:p||i.fulfillment_status!=="fulfilled",onSelect:()=>{_(!1),Ce()},children:"Resend receipt"},"resend")),Je&&vs.push(I(mi,{icon:I(ud,{className:"af-h-4 af-w-4"}),disabled:h,onSelect:()=>{_(!1),v(!0)},children:"Reset download count"},"reset")),kt&&vs.push(X("div",{children:[I(mi,{icon:I(Io,{className:"af-h-4 af-w-4"}),disabled:!n,onSelect:()=>{_(!1),Fa()},children:"Refund\u2026"}),!n&&I("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),X("div",{children:[X("div",{className:"af-mb-6",children:[X(w,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[I(ad,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),X("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[X("div",{className:"af-min-w-0",children:[X("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[I("h3",{className:"af-text-xl af-font-semibold",children:gn(i)}),I(Fn,{status:i.status}),a&&!i.subscription_history_only&&I(Jn,{order:i}),i.is_test&&I(te,{variant:"outline",children:"Test"})]}),X("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",di(i.created_at)]}),i.is_test&&I("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),X("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||o)&&X("div",{className:"af-flex af-items-center",children:[I(w,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!u,"aria-label":"Previous order",children:I(nd,{className:"af-h-4 af-w-4"})}),I(w,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!g,"aria-label":"Next order",children:I(sd,{className:"af-h-4 af-w-4"})})]}),Ka&&(Lt?X("div",{className:"af-flex af-items-center af-gap-1",children:[X("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",i.merchant_fulfilled_at?` \xB7 ${di(i.merchant_fulfilled_at)}`:""]}),Xt&&X(w,{variant:"ghost",size:"sm",onClick:()=>it(!1),disabled:P,children:[P?I(pr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):I(Io,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Xt?X("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[I(ce,{value:k,onChange:L=>x(L.target.value),placeholder:"Tracking number (optional)",maxLength:Ao,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:P}),X(w,{variant:"default",className:"af-shrink-0",onClick:()=>it(!0),disabled:P||!Ke,children:[P?I(pr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):I(dd,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),vs.length>0&&X(dr,{open:S,onOpenChange:_,children:[I(fr,{asChild:!0,children:I(w,{variant:"outline",size:"icon","aria-label":"More actions",children:I(ld,{className:"af-h-4 af-w-4"})})}),I(Ps,{children:I("div",{className:"af-space-y-0.5",children:vs})})]})]})]}),Ka&&!Lt&&!Ke&&I("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."}),N&&I("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:N}),c&&I("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:c}),b&&I("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})]}),X("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[X("div",{className:"af-space-y-6",children:[i.line_items.length>0&&I(Qa,{title:"Items",children:I("ul",{className:"af-space-y-3",children:i.line_items.map((L,De)=>{let ea=typeof L.name=="string"&&L.name?L.name:"Item",eo=typeof L.quantity=="number"&&L.quantity>0?L.quantity:1,to=typeof L.unitAmount=="number";return X("li",{className:"af-flex af-items-start af-gap-3",children:[I(bd,{src:typeof L.imageUrl=="string"&&L.imageUrl?L.imageUrl:void 0}),X("div",{className:"af-min-w-0 af-flex-1",children:[X("div",{className:"af-text-sm af-font-medium",children:[ea,typeof L.variantTitle=="string"&&L.variantTitle&&X("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",L.variantTitle]})]}),X("div",{className:Mn,children:[eo," \xD7"," ",to?q(L.unitAmount,i.currency):"\u2014"]}),L.unavailableReason==="oversold"&&!L.refunded&&I(te,{variant:"secondary",className:"af-mt-1",children:L.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),L.refunded===!0&&I(te,{variant:"secondary",className:"af-mt-1",children:L.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),I("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof L.amountNet=="number"||to?q(L.amountNet??L.unitAmount*eo,i.currency):"\u2014"})]},De)})})}),Ze.length>0&&I(Qa,{title:"Order details",children:I("dl",{className:"af-space-y-2",children:Ze.map(([L,De])=>X("div",{children:[I("dt",{className:K(Mn,"af-capitalize"),children:L.replace(/_/g," ")}),I("dd",{className:"af-text-sm af-break-words",children:Bo(De)})]},L))})}),I(Qa,{title:"Totals",children:X("div",{className:"af-w-full",children:[Qi&&I(na,{label:"Subtotal",children:q(i.amount_subtotal??i.amount_total+(i.discount_total??0),i.currency)}),(i.discount_total??0)>0&&X(na,{label:"Discount",children:["\u2212",q(i.discount_total,i.currency)]}),jt&&I(na,{label:"Shipping",children:i.shipping_total===0?"Free":q(i.shipping_total??0,i.currency)}),Xi&&I(na,{label:"Tax",children:q(Yr,i.currency)}),I(na,{label:"Total",emphasis:!0,divider:Qi,children:q(pn(i),i.currency)}),(i.credit_applied??0)>0&&X(na,{label:"Credit applied",children:["\u2212",q(i.credit_applied,i.currency)]}),i.amount_paid!=null&&I(na,{label:"Amount paid",children:q(i.amount_paid,i.currency)}),Nc&&I(na,{label:"incl. tax",children:q(Yi,i.currency)}),i.base_currency!=null&&i.base_amount_total!=null&&X(na,{label:"Your price",children:[q(i.base_amount_total,i.base_currency),X("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",i.currency.toUpperCase()]})]}),i.amount_refunded>0&&X(hd,{children:[X(na,{label:"Refunded",children:["\u2212",q(i.amount_refunded,i.currency),(i.shipping_refunded??0)>0&&X("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",q(i.shipping_refunded??0,i.currency)," ","shipping"]})]}),I(na,{label:"Net",children:I("span",{className:"af-font-medium",children:q(Math.max(0,rr(i)-i.amount_refunded),i.currency)})})]})]})}),i.application_fee_state&&X(Qa,{title:"Platform fee",children:[i.application_fee_original!=null&&I(na,{label:"Collected",children:q(i.application_fee_original,i.application_fee_currency??i.currency)}),i.application_fee_returned!=null&&I(na,{label:"Returned",children:q(i.application_fee_returned,i.application_fee_currency??i.currency)}),i.application_fee_retained!=null&&I(na,{label:"Retained",children:q(i.application_fee_retained,i.application_fee_currency??i.currency)}),i.application_fee_state!=="complete"&&I("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"})]}),I(Qa,{title:"Timeline",children:I("ol",{className:"af-space-y-3",children:Jr.map(L=>X("li",{className:"af-flex af-gap-3",children:[I("span",{"aria-hidden":"true",className:K("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",L.tone==="destructive"?"af-bg-destructive":L.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),X("div",{className:"af-min-w-0",children:[I("div",{className:"af-text-sm af-break-words",children:L.text}),L.at&&I("div",{className:"af-text-xs af-text-muted-foreground",children:di(L.at)})]})]},L.key))})})]}),X("div",{className:"af-space-y-6",children:[I(Qa,{title:"Customer",children:X("div",{className:"af-space-y-2",children:[X("div",{children:[I("div",{className:Mn,children:"Email"}),X("div",{className:"af-flex af-items-center af-gap-1",children:[I("span",{className:"af-min-w-0 af-break-all af-text-sm",children:i.customer_email||I("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),i.customer_email&&I(gi,{value:i.customer_email,label:"Copy email"})]})]}),i.customer_name&&X("div",{children:[I("div",{className:Mn,children:"Name"}),I("div",{className:"af-text-sm",children:i.customer_name})]}),i.customer&&X("div",{children:[I("div",{className:Mn,children:"Customer record"}),X("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[I("span",{className:"af-break-all af-text-sm",children:i.customer.name||i.customer.email}),I(te,{variant:"secondary",children:"Linked"})]})]})]})}),i.shipping_address&&I(Qa,{title:"Ship to",action:I(gi,{value:W,label:"Copy address",size:"sm",children:"Copy address"}),children:I("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Lo(i.shipping_address).map((L,De)=>I("div",{children:L},De))})}),i.subscription_history_only?I(Qa,{title:"Subscription history",children:I("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."})}):X(Qa,{title:"Emails",children:[I(Za,{deliveries:i.email_deliveries?.filter(L=>!["purchase_receipt","merchant_sale"].includes(L.kind)),problemsOnly:!0,className:"af-mb-4"}),X("div",{className:"af-space-y-4",children:[I(Do,{side:"buyer",title:"Receipt to buyer",delivery:i.email_deliveries?.find(L=>L.kind==="purchase_receipt"),recipient:i.customer_email,status:i.buyer_email_status,attempts:i.buyer_email_attempts,orderStatus:i.status,action:X(w,{variant:"outline",size:"sm",onClick:Ce,disabled:p||i.fulfillment_status!=="fulfilled",children:[p?I(pr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):I(Eo,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),I(Do,{side:"merchant",title:"Sale alert to you",delivery:i.email_deliveries?.find(L=>L.kind==="merchant_sale"),recipient:null,status:i.merchant_email_status,attempts:i.merchant_email_attempts,orderStatus:i.status})]})]}),Je&&I(Qa,{title:"Download",children:X("div",{className:"af-space-y-2",children:[X("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[I(od,{className:"af-h-4 af-w-4"}),X("span",{children:["Downloaded ",i.download_count," time",i.download_count===1?"":"s"]})]}),i.download_url&&I("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"})]})}),X("details",{className:"af-rounded-lg af-border af-p-4",children:[I("summary",{className:K(Oo,"af-cursor-pointer af-select-none"),children:"Technical details"}),X("div",{className:"af-mt-3 af-space-y-2",children:[I(fi,{label:"Order ID",value:i.id}),i.stripe_checkout_session_id&&I(fi,{label:"Checkout session",value:i.stripe_checkout_session_id}),i.stripe_payment_intent_id&&I(fi,{label:"Payment",value:i.stripe_payment_intent_id})]})]})]})]}),I(Ca,{open:C,onOpenChange:L=>{!L&&!h&&v(!1)},children:X(va,{children:[X(ba,{children:[I(ha,{children:"Reset download count?"}),I(xa,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),X(ya,{children:[I(w,{variant:"outline",onClick:()=>v(!1),disabled:h,children:"Cancel"}),I(w,{onClick:rt,disabled:h,children:h?"Resetting...":"Reset"})]})]})}),I(Ca,{open:j,onOpenChange:L=>{!L&&!ye&&$(!1)},children:X(va,{children:[X(ba,{children:[I(ha,{children:"Refund order"}),X(xa,{children:["Refund up to ",q(Ee,i.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),X("div",{className:"af-space-y-4",children:[(i.line_items.length>0||O>0)&&X("div",{className:"af-space-y-2",children:[I(xe,{children:"Items"}),X("div",{className:"af-space-y-2",children:[i.line_items.map((L,De)=>{let ea=L.refunded===!0;return X("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[I("input",{type:"checkbox",checked:de.includes(De),onChange:()=>Dn(De),disabled:ye||ea||!!L.unavailableReason||F(L)<=0,className:"af-h-4 af-w-4"}),X("span",{className:ea?"af-text-muted-foreground af-line-through":void 0,children:[typeof L.name=="string"&&L.name?L.name:"Item",typeof L.variantTitle=="string"&&L.variantTitle?` \u2014 ${L.variantTitle}`:"",typeof L.quantity=="number"&&L.quantity>1?` \xD7 ${L.quantity}`:""]}),I("span",{className:"af-ml-auto af-text-muted-foreground",children:ea?"Refunded":q(F(L),i.currency)})]},De)}),O>0&&X("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[I("input",{type:"checkbox",checked:Z,onChange:L=>B(L.target.checked),disabled:ye,className:"af-h-4 af-w-4"}),I("span",{children:"Shipping"}),I("span",{className:"af-ml-auto af-text-muted-foreground",children:q(O,i.currency)})]})]})]}),X("div",{className:"af-space-y-2",children:[X(xe,{htmlFor:"refund-amount",children:["Amount (",i.currency.toUpperCase(),")"]}),I(ce,{id:"refund-amount",type:"number",min:"0",step:oe,value:Be?String(lt(st,i.currency)):ae,onChange:L=>se(L.target.value),disabled:ye||Be}),Be&&I("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Xe&&I("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Xe}),X(ya,{children:[I(w,{variant:"outline",onClick:()=>$(!1),disabled:ye,children:"Cancel"}),I(w,{variant:"outline",onClick:z,disabled:ye,children:"Refund everything"}),I(w,{variant:"destructive",onClick:Zr,disabled:ye,children:ye?"Refunding...":mt!==null&&mt>0?`Refund ${q(mt,i.currency)}`:"Refund"})]})]})})]})}import*as br from"react";import{ArrowLeft as xd,RefreshCw as wd}from"lucide-react";import{jsx as sa,jsxs as Nn}from"react/jsx-runtime";function Rt({title:e,onBackToWebsite:t,hideBackButton:n=!1,children:s,className:a}){let r=br.useRef(null);return br.useEffect(()=>{r.current?.focus()},[]),Nn("div",{className:K("af-bg-background",a),children:[Nn("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:[sa("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!n&&Nn(w,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[sa(xd,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),sa("div",{className:"af-p-4",children:s})]})}function ne({className:e}){return sa("div",{"aria-hidden":"true",className:K("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function ut({label:e,children:t,detail:n,valueClassName:s}){return Nn("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[sa("div",{className:"af-text-xs af-text-muted-foreground",children:e}),sa("div",{className:K("af-mt-1 af-text-lg af-font-semibold",s),children:t}),n&&sa("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:n})]})}function Na({message:e,onRetry:t}){return Nn("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[sa("span",{children:e}),Nn(w,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[sa(wd,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function za({icon:e,children:t}){return Nn("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,sa("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function Yn({icon:e,heading:t,body:n,action:s,className:a,children:r}){return Nn("div",{className:K("af-px-6 af-py-10 af-text-center",a),children:[sa(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),sa("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),sa("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:n}),s&&sa(w,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}import{jsx as M,jsxs as Re}from"react/jsx-runtime";var Cd={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Uo={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Mo(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 $o(e){let t=Array.isArray(e.line_items)?e.line_items:[],n=t[0];if(!n)return"\u2014";let s=typeof n.name=="string"&&n.name?n.name:"Item",a=typeof n.quantity=="number"&&n.quantity>0?n.quantity:1,r=a>1?`${s} \xD7${a}`:s;return t.length>1?`${r} +${t.length-1} more`:r}function yr(e){return e.customer?.name||e.customer_name||null}function Td({onRefund:e,className:t,refreshKey:n,initialOrderId:s,showFulfillment:a=!1,emptyMessage:r,onDetailOpenChange:o,maxRows:u,onViewAll:g}){let l=typeof u=="number",{api:i}=Q(),d=ur({refreshKey:n}),{orders:b,total:f,isLoading:c,error:m,page:p,pageSize:y,hasNextPage:h,hasPreviousPage:R,setPage:C,setPageSize:v,customerEmail:S,setCustomerEmail:_,setStatusIn:k,from:x,setFrom:P,to:A,setTo:N,showAbandoned:G,setShowAbandoned:j,setUnfulfilledOnly:$,filters:ae,refetch:se}=d,de=_t.useCallback(()=>i.exportOrdersCsv(ae),[i,ae]),[U,Z]=_t.useState("list"),[B,ye]=_t.useState(null),[re,Xe]=_t.useState(""),[he,Ue]=_t.useState(""),[Ze,Ee]=_t.useState(!l&&a?"needs_shipping":"all"),[kt,E]=_t.useState(!1),[F,O]=_t.useState(!!s&&!l),[me,ve]=_t.useState(null);_t.useEffect(()=>{if(!s||l)return;let W=!1;return O(!0),ve(null),i.getOrder(s).then(jt=>{W||(ye(jt),Z("detail"))}).catch(()=>{W||ve("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{W||O(!1)}),()=>{W=!0}},[i,s,l]);let Pe=_t.useCallback(W=>{Ee(W);let jt=Uo[W];k(jt.statusIn),$(jt.unfulfilledOnly)},[k,$]);_t.useEffect(()=>{a&&!l&&$(!0)},[]);let Oe=_t.useRef(!a);_t.useEffect(()=>{Oe.current||c||(Oe.current=!0,b.length===0&&Pe("all"))},[c,b.length,Pe]);let st=U==="detail"&&!!B;_t.useEffect(()=>{o?.(st)},[st,o]);let Be=(x?1:0)+(A?1:0)+(G?1:0),mt=Be>0||!!S||!!he,oe=!!x&&!!A&&x>A,Ce=!l||!!g,rt=W=>{if(l){g?.();return}ye(W),Z("detail")},ma=()=>{Z("list"),ye(null),se()},Lt=W=>{let jt=W.trim();if(!jt){Ue(""),S&&_("");return}if(jt.startsWith("#")||/^\d+$/.test(jt)){Ue(jt),S&&_("");return}Ue(""),_(jt)},Xt=()=>{Xe(""),Ue(""),_(""),P(""),N(""),j(!1),E(!1)},Ut=he.replace(/^#/,"").toLowerCase(),Ke=Ut?b.filter(W=>String(W.order_number??"")===Ut||W.id.toLowerCase().startsWith(Ut)):b,it=l?Ke.slice(0,u):Ke,Fa=B?b.findIndex(W=>W.id===B.id):-1,Dn=Fa>0,Qt=Fa>=0&&Fa<b.length-1;if(F)return M("div",{className:t,children:M("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:M(Nd,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(U==="detail"&&B)return M("div",{className:t,children:M(vr,{order:B,onBack:ma,onRefund:e,onOrderUpdated:W=>ye(W),allowFulfillment:a,onPrevOrder:Dn?()=>ye(b[Fa-1]):void 0,onNextOrder:Qt?()=>ye(b[Fa+1]):void 0,hasPrevOrder:Dn,hasNextOrder:Qt},B.id)});let z=Re("div",{className:"af-mb-4 af-space-y-3",children:[me&&M("p",{className:"af-text-xs af-text-muted-foreground",children:me}),Re("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[M("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(W=>M("button",{type:"button","aria-pressed":Ze===W,onClick:()=>Pe(W),className:K("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===W?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Cd[W]},W))}),Re("div",{className:"af-relative af-w-full af-max-w-xs",children:[M(_d,{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"}),M(ce,{type:"text",value:re,onChange:W=>Xe(W.target.value),onBlur:()=>Lt(re),onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),Lt(re))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),Re(w,{type:"button",variant:Be>0?"secondary":"ghost",size:"sm",onClick:()=>E(W=>!W),"aria-expanded":kt,children:[M(Pd,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Be>0&&M(te,{variant:"secondary",className:"af-ml-2",children:Be})]}),mt&&M(w,{type:"button",variant:"ghost",size:"sm",onClick:Xt,children:"Clear filters"}),M($t,{fetchCsv:de,filename:"orders",disabled:!!he,className:"af-ml-auto"})]}),(kt||!!x||!!A)&&Re("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:[M(xe,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),M(ce,{id:"orders-from",type:"date",value:x,max:A||void 0,onChange:W=>P(W.target.value),className:"af-w-[170px]"}),M(xe,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),M(ce,{id:"orders-to",type:"date",value:A,min:x||void 0,onChange:W=>N(W.target.value),className:"af-w-[170px]"}),!Uo[Ze].statusIn&&M(w,{type:"button",variant:G?"secondary":"ghost",size:"sm",onClick:()=>j(!G),"aria-pressed":G,children:G?"Hide abandoned":"Show abandoned"})]}),oe&&M("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(c)return Re("div",{className:t,children:[l?null:z,M("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(W=>Re("div",{className:"af-rounded-md af-border af-p-3",children:[Re("div",{className:"af-flex af-items-center af-justify-between",children:[M(ne,{className:"af-h-4 af-w-16"}),M(ne,{className:"af-h-4 af-w-14"})]}),M(ne,{className:"af-mt-2 af-h-3 af-w-40"}),M(ne,{className:"af-mt-2 af-h-3 af-w-24"})]},W))}),M("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Re(Ve,{children:[M(He,{children:Re(be,{children:[M(V,{children:"Order"}),M(V,{children:"Date"}),M(V,{children:"Customer"}),M(V,{children:"Items"}),M(V,{className:"af-text-right",children:"Total"}),M(V,{children:"Status"}),M(V,{className:"af-w-8"})]})}),M(ze,{"aria-hidden":"true",children:[0,1,2,3,4].map(W=>Re(be,{children:[M(H,{children:M(ne,{className:"af-h-4 af-w-14"})}),M(H,{children:M(ne,{className:"af-h-4 af-w-24"})}),M(H,{children:M(ne,{className:"af-h-4 af-w-40"})}),M(H,{children:M(ne,{className:"af-h-4 af-w-32"})}),M(H,{children:M(ne,{className:"af-ml-auto af-h-4 af-w-16"})}),M(H,{children:M(ne,{className:"af-h-5 af-w-16"})}),M(H,{})]},W))})]})}),M("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(m)return Re("div",{className:t,children:[l?null:z,Re("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[M("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),M(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>se(),children:"Try again"})]})]});let Je=Ze!=="all";if(Ke.length===0&&p===0)return mt||Je?Re("div",{className:t,children:[!l&&z,M(za,{children:"No orders match these filters."})]}):M("div",{className:t,children:M(Yn,{icon:Rd,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!l&&M(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>j(!0),children:"Show abandoned checkouts"})})});let Ka=p*y+1,Jr=Math.min((p+1)*y,f);return Re("div",{className:t,children:[l?null:z,M("div",{className:"af-space-y-3 lg:af-hidden",children:it.map(W=>Re("button",{type:"button",onClick:()=>rt(W),disabled:!Ce,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ce?" hover:af-bg-muted/50":""}`,children:[Re("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[M("span",{className:"af-font-medium",children:gn(W)}),M("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:q(pn(W),W.currency)})]}),Re("div",{className:"af-mt-1 af-min-w-0",children:[Re("div",{className:"af-truncate af-text-sm",children:[W.customer_email||M("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),yr(W)&&Re("span",{className:"af-text-muted-foreground",children:[" \xB7 ",yr(W)]})]}),M("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:$o(W)}),W.amount_refunded>0&&Re("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",q(W.amount_refunded,W.currency)," refunded"]})]}),Re("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[M(Fn,{status:W.status}),M(ws,{deliveries:W.email_deliveries}),W.is_test&&M(te,{variant:"outline",children:"Test"}),a&&M(Jn,{order:W}),M("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Mo(W.created_at)})]})]},W.id))}),M("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Re(Ve,{children:[M(He,{children:Re(be,{children:[M(V,{children:"Order"}),M(V,{children:"Date"}),M(V,{children:"Customer"}),M(V,{children:"Items"}),M(V,{className:"af-text-right",children:"Total"}),M(V,{children:"Status"}),M(V,{className:"af-w-8"})]})}),M(ze,{children:it.map(W=>Re(be,{onClick:Ce?()=>rt(W):void 0,className:Ce?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[Re(H,{className:"af-whitespace-nowrap af-font-medium",children:[M("button",{type:"button",onClick:jt=>{jt.stopPropagation(),rt(W)},disabled:!Ce,"aria-label":`Open order ${gn(W)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ce?" hover:af-underline":""}`,children:gn(W)}),W.is_test&&M(te,{variant:"outline",className:"af-ml-2",children:"Test"})]}),M(H,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Mo(W.created_at)}),Re(H,{className:"af-max-w-[220px]",children:[M("div",{className:"af-truncate",children:W.customer_email||M("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),yr(W)&&M("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:yr(W)})]}),M(H,{className:"af-max-w-[220px]",children:M("div",{className:"af-truncate af-text-muted-foreground",children:$o(W)})}),Re(H,{className:"af-whitespace-nowrap af-text-right",children:[M("div",{className:"af-font-medium af-tabular-nums",children:q(pn(W),W.currency)}),W.amount_refunded>0&&Re("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",q(W.amount_refunded,W.currency)," ","refunded"]})]}),M(H,{children:Re("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[M(Fn,{status:W.status}),M(ws,{deliveries:W.email_deliveries}),a&&M(Jn,{order:W})]})}),M(H,{className:"af-w-8 af-text-right",children:M(Fo,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},W.id))})]})}),l?null:Re("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Re("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[M("span",{children:Ut?`${Ke.length} matching this page`:`Showing ${Ka}-${Jr} of ${f}`}),Re(_a,{value:String(y),onValueChange:W=>v(Number(W)),children:[M(pa,{className:"af-w-[70px] af-h-8",children:M(Pa,{})}),Re(ga,{children:[M(Ye,{value:"10",children:"10"}),M(Ye,{value:"25",children:"25"}),M(Ye,{value:"50",children:"50"}),M(Ye,{value:"100",children:"100"})]})]}),M("span",{children:"per page"})]}),Re("div",{className:"af-flex af-items-center af-gap-2",children:[Re(w,{variant:"outline",size:"sm",onClick:()=>C(p-1),disabled:!R,children:[M(Sd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Re(w,{variant:"outline",size:"sm",onClick:()=>C(p+1),disabled:!h,children:["Next",M(Fo,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function Rn(e){return M(Td,{...e},e.maxRows==null?"full":"compact")}import*as Xn from"react";import{ChevronLeft as Ad,ChevronRight as Dd,Eye as Ld,Search as Od,Users as Bd}from"lucide-react";import*as ra from"react";function hr({initialPageSize:e=25}={}){let{api:t}=Q(),[n,s]=ra.useState([]),[a,r]=ra.useState(0),[o,u]=ra.useState(!0),[g,l]=ra.useState(null),[i,d]=ra.useState(0),[b,f]=ra.useState(e),[c,m]=ra.useState(""),p=ra.useRef(0),y=ra.useCallback(async()=>{let R=++p.current;try{u(!0),l(null);let C={limit:b,offset:i*b};c.trim()&&(C.email=c.trim());let v=await t.getCustomers(C);if(R!==p.current)return;s(v.customers),r(v.total)}catch(C){if(R!==p.current)return;l(C instanceof Error?C:new Error("Failed to fetch customers"))}finally{R===p.current&&u(!1)}},[t,i,b,c]);ra.useEffect(()=>{y()},[y]);let h=Math.ceil(a/b);return{customers:n,total:a,isLoading:o,error:g,page:i,pageSize:b,hasNextPage:i<h-1,hasPreviousPage:i>0,setPage:d,setPageSize:R=>{f(R),d(0)},email:c,setEmail:R=>{m(R),d(0)},refetch:y}}import*as $n from"react";import{ArrowLeft as kd,Loader2 as Ed}from"lucide-react";import{jsx as Fe,jsxs as Bt}from"react/jsx-runtime";function Vo(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 Id(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let n=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return n&&t.push(n),e.country&&t.push(e.country),t}function xr({customer:e,onBack:t,className:n}){let{api:s}=Q(),[a,r]=$n.useState(null),[o,u]=$n.useState([]),[g,l]=$n.useState(!0),[i,d]=$n.useState(null);$n.useEffect(()=>{let c=!1;return l(!0),d(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([m,p])=>{c||(r(m),u(p.orders))}).catch(m=>{c||d(m instanceof Error?m.message:"Failed to load customer")}).finally(()=>{c||l(!1)}),()=>{c=!0}},[s,e.id,e.email]);let b=a?.addresses??[],f=a?.order_count??o.length;return Bt("div",{className:n,children:[Bt("div",{className:"af-mb-6",children:[Bt(w,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[Fe(kd,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),Fe("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),Bt("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Vo(e.created_at)]})]}),g?Fe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Fe(Ed,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):i?Fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i}):Bt("div",{className:"af-space-y-6",children:[Fe(Za,{deliveries:a?.email_deliveries}),Bt("div",{children:[Fe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),Bt("div",{className:"af-space-y-1 af-text-sm",children:[Bt("div",{className:"af-flex af-gap-2",children:[Fe("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),Fe("span",{children:e.email})]}),e.name&&Bt("div",{className:"af-flex af-gap-2",children:[Fe("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),Fe("span",{children:e.name})]}),e.phone&&Bt("div",{className:"af-flex af-gap-2",children:[Fe("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),Fe("span",{children:e.phone})]}),Bt("div",{className:"af-flex af-gap-2",children:[Fe("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),Fe("span",{children:f})]})]})]}),b.length>0&&Bt("div",{children:[Fe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),Fe("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(c=>Bt("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[c.is_default&&Fe(te,{variant:"secondary",className:"af-mb-1",children:"Default"}),Id(c).map((m,p)=>Fe("div",{children:m},p))]},c.id))})]}),Bt("div",{children:[Fe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?Fe("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):Bt(Ve,{children:[Fe(He,{children:Bt(be,{children:[Fe(V,{children:"Date"}),Fe(V,{children:"Amount"}),Fe(V,{children:"Status"})]})}),Fe(ze,{children:o.map(c=>Bt(be,{children:[Fe(H,{className:"af-text-muted-foreground",children:Vo(c.created_at)}),Fe(H,{children:q(pn(c),c.currency)}),Fe(H,{children:Fe(Un,{status:c.status})})]},c.id))})]})]})]})]})}import{Fragment as Ud,jsx as _e,jsxs as xt}from"react/jsx-runtime";function Fd(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 wr({className:e}){let{customers:t,total:n,isLoading:s,error:a,page:r,pageSize:o,hasNextPage:u,hasPreviousPage:g,setPage:l,setPageSize:i,email:d,setEmail:b,refetch:f}=hr(),{api:c}=Q(),m=Xn.useCallback(()=>c.exportCustomersCsv(),[c]),[p,y]=Xn.useState("list"),[h,R]=Xn.useState(null),[C,v]=Xn.useState(""),S=A=>{R(A),y("detail")},_=()=>{y("list"),R(null),f()};if(p==="detail"&&h)return _e("div",{className:e,children:_e(xr,{customer:h,onBack:_})});let k=xt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[_e(ce,{type:"email",value:C,onChange:A=>v(A.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),b(C.trim()))}}),xt(w,{type:"button",variant:"outline",size:"sm",onClick:()=>b(C.trim()),children:[_e(Od,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),d&&_e(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{v(""),b("")},children:"Clear"}),_e($t,{fetchCsv:m,filename:"customers",className:"af-ml-auto"})]});if(s)return xt("div",{className:e,children:[k,_e("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:_e("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(a)return xt("div",{className:e,children:[k,_e("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:xt("div",{className:"af-text-destructive",children:["Error: ",a.message]})})]});if(t.length===0&&r===0)return xt("div",{className:e,children:[d&&k,xt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[_e(Bd,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),_e("p",{className:"af-text-muted-foreground af-text-center",children:d?"No customers match that email.":xt(Ud,{children:["No customers yet.",_e("br",{}),"Customers appear here after their first purchase."]})})]})]});let x=r*o+1,P=Math.min((r+1)*o,n);return xt("div",{className:e,children:[k,xt(Ve,{children:[_e(He,{children:xt(be,{children:[_e(V,{children:"Email"}),_e(V,{children:"Name"}),_e(V,{children:"Phone"}),_e(V,{children:"Customer since"}),_e(V,{className:"af-text-right",children:"Actions"})]})}),_e(ze,{children:t.map(A=>xt(be,{children:[_e(H,{className:"af-font-medium",children:A.email}),_e(H,{children:A.name||_e("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),_e(H,{children:A.phone||_e("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),_e(H,{className:"af-text-muted-foreground",children:Fd(A.created_at)}),_e(H,{className:"af-text-right",children:_e(w,{variant:"ghost",size:"icon",onClick:()=>S(A),title:"View customer",children:_e(Ld,{className:"af-h-4 af-w-4"})})})]},A.id))})]}),xt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[xt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[xt("span",{children:["Showing ",x,"-",P," of ",n]}),xt(_a,{value:String(o),onValueChange:A=>i(Number(A)),children:[_e(pa,{className:"af-w-[70px] af-h-8",children:_e(Pa,{})}),xt(ga,{children:[_e(Ye,{value:"10",children:"10"}),_e(Ye,{value:"25",children:"25"}),_e(Ye,{value:"50",children:"50"}),_e(Ye,{value:"100",children:"100"})]})]}),_e("span",{children:"per page"})]}),xt("div",{className:"af-flex af-items-center af-gap-2",children:[xt(w,{variant:"outline",size:"sm",onClick:()=>l(r-1),disabled:!g,children:[_e(Ad,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),xt(w,{variant:"outline",size:"sm",onClick:()=>l(r+1),disabled:!u,children:["Next",_e(Dd,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as ke from"react";import{ArrowLeft as Md,ChevronLeft as $d,ChevronRight as Ho,Copy as Vd,Download as Hd,ExternalLink as zd,FileText as jo,Loader2 as qd,Search as jd}from"lucide-react";import*as wt from"react";function Qn({initialPageSize:e=25,refreshKey:t,includeAggregates:n=!1}={}){let{api:s}=Q(),[a,r]=wt.useState([]),[o,u]=wt.useState(0),[g,l]=wt.useState(null),[i,d]=wt.useState(!0),[b,f]=wt.useState(null),[c,m]=wt.useState(0),[p,y]=wt.useState(e),[h,R]=wt.useState(void 0),[C,v]=wt.useState(""),[S,_]=wt.useState(""),[k,x]=wt.useState(""),[P,A]=wt.useState(""),[N,G]=wt.useState(""),j=h?h.join(","):"",$=wt.useRef(0),ae=wt.useCallback(async()=>{let de=++$.current;d(!0),f(null);try{let U={labels:j?j.split(","):void 0,customerEmail:C||void 0,q:S||void 0,from:k||void 0,to:P||void 0,retainerId:N||void 0,includeAggregates:n,limit:p,offset:c*p},Z=await s.getInvoices(U);if(de!==$.current)return;if(c>0&&c*p>=Z.total){m(Math.max(0,Math.ceil(Z.total/p)-1));return}r(Z.invoices),u(Z.total),n&&l(Z.aggregates??null)}catch(U){if(de!==$.current)return;f(U instanceof Error?U:new Error("Failed to fetch invoices"))}finally{de===$.current&&d(!1)}},[s,j,C,S,k,P,N,c,p,n]);wt.useEffect(()=>{ae()},[ae,t]);let se=de=>U=>{m(0),de(U)};return{invoices:a,total:o,aggregates:g,isLoading:i,error:b,page:c,pageSize:p,hasNextPage:(c+1)*p<o,hasPreviousPage:c>0,setPage:m,setPageSize:se(y),labels:h,setLabels:se(R),customerEmail:C,setCustomerEmail:se(v),q:S,setQ:se(_),from:k,setFrom:se(x),to:P,setTo:se(A),retainerId:N,setRetainerId:se(G),clearFilters:()=>{m(0),R(void 0),v(""),_(""),x(""),A(""),G("")},refetch:ae}}import{Fragment as Xd,jsx as D,jsxs as Y}from"react/jsx-runtime";var Gd={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 hi(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Gd[e.label]??e.label}function Wd(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 yi={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Kd={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Cs({invoice:e,className:t}){return Y("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[D(te,{variant:Wd(e.label),className:t,children:hi(e)}),e.collection_method==="charge_automatically"&&D(te,{variant:"secondary",children:"Managed in Stripe"})]})}function Rr({delivery:e,className:t}){if(!e)return null;let n=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return D(te,{variant:n,className:t,children:yi[e.state]??e.state})}function es(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function Aa(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,n=new Date(t);return Number.isNaN(n.getTime())?e:n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var zo={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Sr={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},vi=100,bi=5e3;async function Zd(e,t){let n=[],s=0;for(let a=0;a<bi;a+=vi){let r=await e.getInvoices({...t,limit:vi,offset:a});if(s=r.total,n.push(...r.invoices),r.invoices.length<vi||n.length>=s)break}return{invoices:n.slice(0,bi),total:s,truncated:s>n.length||s>bi}}function Go(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],n=e.map(s=>[s.id,es(s),hi(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),q(s.amount_subtotal,s.currency),q(s.tax_total,s.currency),q(s.amount_total,s.currency),s.amount_due===null?"":q(s.amount_due,s.currency),s.amount_paid===null?"":q(s.amount_paid,s.currency),q(s.amount_refunded,s.currency),s.payment_method??"",s.pay_url??"",s.retainer_id??"",s.replaces_order_id??"",s.replaced_by_order_id??"",s.tax_behavior??"",s.discount_total===void 0?"":q(s.discount_total,s.currency),s.collection_method??""]);return[t,...n].map(s=>s.map(go).join(",")).join(`
5
- `)}function Jd(e){Xs(new Blob([Go(e)],{type:"text/csv;charset=utf-8"}),Ys("invoices"))}function Yd({className:e,refreshKey:t,initialInvoiceId:n,onDetailOpenChange:s,onConnectStripe:a,onUpgradePlan:r,needsPaidPlan:o=!1,retainerFilter:u=null,onClearRetainerFilter:g,maxRows:l,onViewAll:i}){let d=typeof l=="number",{api:b}=Q(),{invoices:f,total:c,isLoading:m,error:p,page:y,pageSize:h,hasNextPage:R,hasPreviousPage:C,setPage:v,labels:S,setLabels:_,customerEmail:k,setCustomerEmail:x,q:P,setQ:A,from:N,setFrom:G,to:j,setTo:$,retainerId:ae,setRetainerId:se,refetch:de}=Qn({refreshKey:t}),[U,Z]=ke.useState(typeof l=="number"?"all":"open"),[B,ye]=ke.useState(""),[re,Xe]=ke.useState(null),he=ke.useRef(0),Ue=!d||!!i,Ze=ke.useCallback(z=>{if(d){i?.();return}he.current++,kt(!1),Xe(z)},[d,i]),[Ee,kt]=ke.useState(!1),[E,F]=ke.useState(0),[O,me]=ke.useState(null),[ve,Pe]=ke.useState(!1),[Oe,st]=ke.useState(0);ke.useEffect(()=>{Xe(z=>{if(!z)return z;let Je=f.find(Ka=>Ka.id===z.id);return Je&&Je!==z?Je:z})},[f]);let[Be,mt]=ke.useState(!1),[oe,Ce]=ke.useState(null),rt=async()=>{if(!Be){mt(!0),Ce(null);try{let{invoices:z,total:Je,truncated:Ka}=await Zd(b,{labels:S,customerEmail:k,q:P,from:N,to:j,retainerId:ae});Jd(z),Ce(Ka?`Exported the first ${z.length.toLocaleString()} of ${Je.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ce("Couldn't export \u2014 try again.")}finally{mt(!1)}}},ma=!k&&!P&&!N&&!j&&!ae,[Lt,Xt]=ke.useState(null);ke.useEffect(()=>{if(m||c>0||!ma||U!=="open")return;let z=!1;return b.getInvoices({limit:1}).then(Je=>{z||Xt(Je.total>0)}).catch(()=>{z||Xt(!0)}),()=>{z=!0}},[b,m,c,ma,U,t]),ke.useEffect(()=>{_(d?Sr.all:Sr.open)},[]),ke.useEffect(()=>{let z=u?.id??"";z!==ae&&(se(z),z&&(Z("all"),_(Sr.all),x(""),A(""),ye(""),G(""),$("")))},[u?.id]),ke.useEffect(()=>{let z=!1;return Pe(!1),b.getInvoiceSettings().then(Je=>{z||me({payments_active:Je.payments_active,blocked:Je.blocked})}).catch(()=>{z||Pe(!0)}),()=>{z=!0}},[b,t,Oe]),ke.useEffect(()=>{if(!n||d)return;let z=!1,Je=he.current;return kt(!1),b.getInvoice(n).then(Ka=>{!z&&Je===he.current&&Xe(Ka)}).catch(()=>{!z&&Je===he.current&&kt(!0)}),()=>{z=!0}},[b,n,E,d]),ke.useEffect(()=>{s?.(re!==null)},[re,s]);let Ut=z=>{Z(z),_(Sr[z])},Ke=z=>{let Je=z.trim();if(!Je){P&&A(""),k&&x("");return}if(Je.includes("@")){P&&A(""),x(Je);return}k&&x(""),A(Je.replace(/^#/,""))},it=f,Fa=d?it.slice(0,l):it,Dn=Ee&&Y("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. ",D(w,{type:"button",variant:"link",size:"sm",onClick:()=>F(z=>z+1),children:"Retry opening invoice"})]});if(re)return Y("div",{className:e,children:[Dn,D(xi,{invoice:re,refreshKey:t,onBack:()=>{Ze(null),de()}},re.id)]});let Qt=Y("div",{className:"af-mb-4 af-space-y-3",children:[ve&&Y("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",D(w,{type:"button",variant:"link",size:"sm",onClick:()=>st(z=>z+1),children:"Retry setup check"})]}),Dn,O?.blocked&&Y("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",O.blocked.reason?`: ${O.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),u&&Y("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[Y(te,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",u.label]}),g&&D(w,{type:"button",variant:"link",size:"sm",onClick:g,children:"Clear schedule filter"})]}),Y("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[D("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(zo).map(z=>D("button",{type:"button","aria-pressed":U===z,onClick:()=>Ut(z),className:K("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",U===z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:zo[z]},z))}),Y("div",{className:"af-relative af-w-full af-max-w-xs",children:[D(jd,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),D(ce,{type:"text",value:B,onChange:z=>ye(z.target.value),onBlur:()=>Ke(B),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),Ke(B))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),Y("div",{className:"af-flex af-items-center af-gap-2",children:[D(xe,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),D(ce,{id:"invoices-from",type:"date",value:N,max:j||void 0,onChange:z=>G(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),Y("div",{className:"af-flex af-items-center af-gap-2",children:[D(xe,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),D(ce,{id:"invoices-to",type:"date",value:j,min:N||void 0,onChange:z=>$(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),Y(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>void rt(),disabled:Be||m||!!p||c===0,"aria-busy":Be,children:[D(Hd,{className:"af-h-4 af-w-4 af-mr-1"}),Be?"Exporting\u2026":"Export CSV (all matching)"]})]}),oe&&D("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:oe})]});return m?Y("div",{className:e,children:[d?null:Qt,D("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(z=>Y("div",{className:"af-rounded-md af-border af-p-3",children:[Y("div",{className:"af-flex af-items-center af-justify-between",children:[D(ne,{className:"af-h-4 af-w-20"}),D(ne,{className:"af-h-4 af-w-16"})]}),D(ne,{className:"af-mt-2 af-h-3 af-w-40"})]},z))})]}):p?Y("div",{className:e,children:[d?null:Qt,Y("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",D(w,{type:"button",variant:"link",size:"sm",onClick:()=>void de(),children:"Retry"})]})]}):c===0&&ma&&(U==="all"||Lt===!1)&&(U==="open"||U==="all")?O?.blocked?Y("div",{className:e,children:[d?null:Qt,D(Nr,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?Y("div",{className:e,children:[d?null:Qt,D(Nr,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):O&&!O.payments_active?Y("div",{className:e,children:[d?null:Qt,D(Nr,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:a?{label:"Payment setup",onClick:a}:void 0})]}):Y("div",{className:e,children:[d?null:Qt,D(Nr,{heading:"No invoices yet",body:!O||ve?"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."})]}):Y("div",{className:e,children:[d?null:Qt,Fa.length===0?D("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."}):Y(Xd,{children:[D("div",{className:"af-space-y-3 lg:af-hidden",children:Fa.map(z=>Y("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:[Y("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[D("span",{className:"af-font-medium",children:es(z)}),D(Cs,{invoice:z})]}),D("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&&D("div",{className:"af-mt-1",children:D(Rr,{delivery:z.delivery})}),Y("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[D("span",{children:z.collection_method==="charge_automatically"?"Automatic collection":z.due_at?`Due ${Aa(z.due_at)}`:"Due on receipt"}),D("span",{className:"af-font-medium af-tabular-nums",children:q(z.amount_due??z.amount_total,z.currency)})]})]},z.id))}),D("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Y(Ve,{children:[D(He,{children:Y(be,{children:[D(V,{children:"Invoice"}),D(V,{children:"Created"}),D(V,{children:"Customer"}),D(V,{children:"Due"}),D(V,{className:"af-text-right",children:"Amount"}),D(V,{children:"Status"}),D(V,{children:"Delivery"}),D(V,{className:"af-w-8"})]})}),D(ze,{children:Fa.map(z=>Y(be,{className:Ue?"af-cursor-pointer":void 0,onClick:Ue?()=>Ze(z):void 0,children:[D(H,{className:"af-font-medium",children:D("button",{type:"button",disabled:!Ue,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ue?" hover:af-underline":""}`,onClick:Je=>{Je.stopPropagation(),Ze(z)},"aria-label":`Open invoice ${es(z)}`,children:es(z)})}),D(H,{children:Aa(z.created_at)}),Y(H,{children:[D("div",{children:z.customer_name??"\u2014"}),D("div",{className:"af-text-xs af-text-muted-foreground",children:z.customer_email})]}),D(H,{children:z.collection_method==="charge_automatically"?"Automatic":z.due_at?Aa(z.due_at):"On receipt"}),D(H,{className:"af-text-right af-tabular-nums",children:q(z.amount_due??z.amount_total,z.currency)}),D(H,{children:D(Cs,{invoice:z})}),D(H,{children:D(Rr,{delivery:z.delivery})}),D(H,{children:D(Ho,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},z.id))})]})}),d?null:Y("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[Y("span",{children:[c," invoice",c===1?"":"s"]}),Y("div",{className:"af-flex af-items-center af-gap-1",children:[D(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>v(y-1),disabled:!C,"aria-label":"Previous page",children:D($d,{className:"af-h-4 af-w-4"})}),Y("span",{className:"af-tabular-nums",children:[y*h+1,"\u2013",Math.min((y+1)*h,c)]}),D(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>v(y+1),disabled:!R,"aria-label":"Next page",children:D(Ho,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Nr({heading:e,body:t,action:n}){return D(Yn,{icon:jo,heading:e,body:t,action:n})}function Pn(e){return D(Yd,{...e},e.maxRows==null?"full":"compact")}var vn="af-text-xs af-text-muted-foreground";function qo(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function xi({invoice:e,onBack:t,refreshKey:n,className:s}){let{api:a}=Q(),r=ke.useRef(null);ke.useEffect(()=>{r.current?.focus()},[e.id]);let[o,u]=ke.useState(!1),[g,l]=ke.useState(null),[i,d]=ke.useState(!1),[b,f]=ke.useState(!1),c=ke.useRef(0),[m,p]=ke.useState(null),[y,h]=ke.useState(!1),[R,C]=ke.useState(0);ke.useEffect(()=>{let N=!1;return h(!1),a.getInvoice(e.id).then(G=>{N||p({source:e,value:G})}).catch(()=>{N||h(!0)}),()=>{N=!0}},[a,e,n,R]);let v=m?.source===e?m.value:e,S=v.collection_method==="charge_automatically";ke.useEffect(()=>(c.current++,l(null),d(!1),f(!1),u(!1),()=>{c.current++}),[a,v,n]);let _=N=>N==null?"\u2014":q(N,v.currency),k=async()=>{if(!(!v.pay_url||!qo()))try{await navigator.clipboard.writeText(v.pay_url),u(!0),setTimeout(()=>u(!1),1500)}catch{}},x=async()=>{if(g){l(null);return}let N=++c.current;f(!1),d(!0);try{let G=await a.getInvoicePreview(v.id);N===c.current&&l(G)}catch{N===c.current&&f(!0)}finally{N===c.current&&d(!1)}},P=v.bill_to,A=P?[P.company,P.name,P.address?.line1,P.address?.line2,[P.address?.city,P.address?.state,P.address?.postal_code].filter(Boolean).join(", "),P.address?.country,P.tax_id?`${P.tax_id.value}`:null,P.po_number?`PO ${P.po_number}`:null,P.service_period?`Service period: ${P.service_period}`:null].filter(N=>!!N&&N.length>0):[];return Y("div",{className:s,children:[Y("div",{className:"af-mb-4",children:[Y(w,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[D(Md,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),Y("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[Y("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",es(v)]}),D(Cs,{invoice:v}),D(Rr,{delivery:v.delivery})]}),Y("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[v.customer_name??v.customer_email,v.customer_name&&v.customer_email?` \xB7 ${v.customer_email}`:""]})]}),y&&Y("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. ",D(w,{type:"button",variant:"link",size:"sm",onClick:()=>C(N=>N+1),children:"Retry details"})]}),v.label==="failed"&&D("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),v.label==="creating"&&D("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."}),Y("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[Y("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[Y("section",{className:"af-rounded-md af-border af-p-4",children:[Y(Ve,{children:[D(He,{children:Y(be,{children:[D(V,{children:"Description"}),D(V,{className:"af-text-right",children:"Qty"}),D(V,{className:"af-text-right",children:"Amount"})]})}),D(ze,{children:v.line_items.map((N,G)=>Y(be,{children:[D(H,{style:{overflowWrap:"anywhere"},children:N.description}),D(H,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:N.quantity}),D(H,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_(N.amount)})]},G))})]}),Y("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[D(_n,{label:"Subtotal",value:_(v.amount_subtotal)}),(v.discount_total??0)>0&&D(_n,{label:"Discount",value:`-${_(v.discount_total)}`}),v.tax_total>0&&D(_n,{label:v.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:_(v.tax_total)}),D(_n,{label:"Total",value:_(v.amount_total),strong:!0}),v.credit_applied>0&&D(_n,{label:"Credit applied",value:`-${_(v.credit_applied)}`}),v.amount_due!==null&&v.amount_due!==v.amount_total&&D(_n,{label:"Amount due",value:_(v.amount_due),strong:!0}),v.amount_paid!==null&&v.amount_paid>0&&D(_n,{label:"Amount paid",value:_(v.amount_paid)}),v.amount_refunded>0&&D(_n,{label:"Refunded",value:_(v.amount_refunded)})]}),v.credit_notes?.length>0&&Y("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[D("div",{className:vn,children:"Credit notes"}),v.credit_notes.map(N=>Y("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[Y("span",{className:"af-text-muted-foreground",children:[Aa(N.created_at)," \xB7 ",N.origin==="dashboard"?"issued in Stripe":"refund",N.stripe_credit_note_id?"":" \xB7 being created"]}),Y("span",{className:"af-tabular-nums",children:["-",q(N.amount,N.currency)]})]},N.id))]})]}),(v.note||v.footer)&&Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[v.note&&Y("div",{children:[D("div",{className:vn,children:"Note"}),D("div",{className:"af-whitespace-pre-wrap af-break-words",children:v.note})]}),v.footer&&Y("div",{children:[D("div",{className:vn,children:"Footer"}),D("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:v.footer})]})]}),g&&!S&&Y("section",{className:"af-rounded-md af-border af-p-4",children:[Y("div",{className:K(vn,"af-break-words"),children:["Email preview \u2014 ",g.subject]}),D("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),D("iframe",{title:"Invoice email preview",srcDoc:g.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),Y("div",{className:"af-min-w-0 af-space-y-4",children:[Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[D(Ia,{label:"Created",value:Aa(v.created_at)}),D(Ia,{label:"Due",value:v.collection_method==="charge_automatically"?"Managed in Stripe":v.due_at?Aa(v.due_at):"On receipt"}),v.paid_at&&D(Ia,{label:"Paid",value:Aa(v.paid_at)}),v.payment_method&&D(Ia,{label:"Paid by",value:v.paid_out_of_band?`${v.payment_method} (recorded outside Stripe)`:v.payment_method}),v.payment_state!=="none"&&D(Ia,{label:"Payment",value:v.payment_state==="processing"?"Processing":v.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),v.delivery&&D(Ia,{label:"Delivery",value:`${yi[v.delivery.state]} \xB7 ${v.delivery.recipient}`}),v.marked_uncollectible_at&&D(Ia,{label:"Written off",value:Aa(v.marked_uncollectible_at)}),v.correction_reason&&D(Ia,{label:"Correction",value:v.correction_reason}),v.replaced_by_order_id&&D(Ia,{label:"Replaced by",value:v.replaced_by_order_id}),v.collection_method==="charge_automatically"?D(Ia,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):v.retainer_id&&D(Ia,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),v.replaces_order_id&&D(Ia,{label:"Replaces",value:v.replaces_order_id})]}),Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[D("div",{className:vn,children:"Reminders"}),S?D("div",{children:"View automatic payment reminders in Stripe."}):v.reminders.disabled?D("div",{children:"Off for this invoice."}):v.reminders.paused_until?Y("div",{children:["Paused until ",Aa(v.reminders.paused_until),"."]}):v.reminders.next_at?Y("div",{children:["Next on ",Aa(v.reminders.next_at),"."]}):v.reminders.final_sent_at?Y("div",{children:["Final reminder sent ",Aa(v.reminders.final_sent_at),"."]}):D("div",{children:"None scheduled."}),!S&&Y("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",v.reminders.schedule.length===0?"none":v.reminders.schedule.map(N=>N<0?`${-N}d before`:N===0?"due day":`${N}d after`).join(", ")]})]}),v.communications&&v.communications.length>0&&Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[D("div",{className:vn,children:"Email delivery history"}),v.communications.map(N=>Y("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[Y("span",{className:"af-min-w-0 af-break-words",children:[Kd[N.kind]??N.kind,N.kind==="reminder"&&N.slot!==null?` #${N.slot}`:"",Y("span",{className:"af-text-muted-foreground",children:[" \xB7 ",N.recipient]})]}),Y("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[yi[N.state]??N.state," \xB7 ",Aa(N.state_at??N.created_at)]})]},N.id))]}),A.length>0&&Y("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[D("div",{className:vn,children:"Bill to"}),A.map((N,G)=>D("div",{className:"af-break-words",children:N},G))]}),Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[v.pay_url&&Y(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void k(),disabled:!qo(),children:[D(Vd,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":S?"Copy invoice link":"Copy pay link"]}),v.pdf_url&&D(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:Y("a",{href:v.pdf_url,target:"_blank",rel:"noreferrer",children:[D(zd,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!S&&Y(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void x(),disabled:i,children:[i?D(qd,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(jo,{className:"af-h-4 af-w-4 af-mr-1"}),g?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!S&&D("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),v.pay_url&&D("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:v.pay_url}),D("p",{className:"af-text-xs af-text-muted-foreground",children:S?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function Ia({label:e,value:t}){return Y("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[D("span",{className:K(vn,"af-shrink-0"),children:e}),D("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function _n({label:e,value:t,strong:n}){return Y("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[D("dt",{className:K(vn,n&&"af-font-medium af-text-foreground"),children:e}),D("dd",{className:K("af-tabular-nums",n&&"af-font-semibold"),children:t})]})}import{Repeat as Qd}from"lucide-react";import{jsx as vt,jsxs as qa}from"react/jsx-runtime";var ef={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Wo={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function tf(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 Ko(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>Wo[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>Wo[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":ef[e.status]}function Zo(e){let t=e.interval==="year"?"every year":"every month";return`${q(e.amount,e.currency)} ${t}`}function af(e){return e.status==="canceled"?`Ended ${_r(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${_r(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 ${_r(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${_r(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function _r(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),n=new Date(t);return Number.isNaN(n.getTime())?e.slice(0,10):n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function wi({retainer:e,className:t}){return vt(te,{variant:tf(e.status),className:K("af-max-w-full af-whitespace-normal af-break-words",t),children:Ko(e)})}function ts({retainers:e,isLoading:t,error:n,onRetry:s,onShowCycles:a,activeRetainerId:r,total:o,endedTotal:u=0,isLoadingMore:g=!1,onLoadMore:l,includeEnded:i=!1,onIncludeEndedChange:d,exportCsv:b,className:f}){let c=!!d;if(!t&&!n&&e.length===0&&!(c&&(i||u>0)))return null;let m=o!==void 0?Math.max(0,o-e.length):0;return qa("section",{className:K("af-mb-6",f),"aria-label":"Recurring invoices",children:[qa("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[vt(Qd,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),vt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),vt("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),c&&vt(w,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":i,onClick:()=>d?.(!i),children:i?"Hide ended recurring invoices":u>0&&e.length===0?`Show ended recurring invoices (${u})`:"Show ended recurring invoices"}),b&&vt($t,{fetchCsv:b,filename:"retainers",className:c?void 0:"af-ml-auto"})]}),n?qa("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",vt(w,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?vt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(p=>qa("div",{className:"af-rounded-md af-border af-p-3",children:[vt(ne,{className:"af-h-4 af-w-48"}),vt(ne,{className:"af-mt-2 af-h-3 af-w-32"})]},p))}):e.length===0?vt("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:i?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):vt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(p=>{let y=r===p.id;return qa("li",{className:K("af-rounded-md af-border af-p-3",y&&"af-border-primary af-bg-muted/40"),children:[qa("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[qa("div",{className:"af-min-w-0",children:[vt("div",{className:"af-truncate af-font-medium",children:p.customer_name??p.customer_email??"\u2014"}),vt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:p.description})]}),vt(wi,{retainer:p})]}),p.collection_method==="charge_automatically"?qa("div",{className:"af-mt-2 af-space-y-1",children:[vt(te,{variant:"secondary",children:"Managed in Stripe"}),vt("p",{className:"af-text-xs af-text-muted-foreground",children:"Automatic charging is enabled in Stripe. View or change the billing terms there. To edit this schedule from the chat, switch it back to sending invoices in Stripe."})]}):vt("div",{className:"af-mt-2 af-text-sm",children:Zo(p)}),qa("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:[qa("span",{children:[af(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&&vt(w,{type:"button",variant:y?"secondary":"ghost",size:"sm",onClick:()=>a(p),"aria-pressed":y,children:y?"Showing invoices":"View invoices"})]}),p.status==="failed"&&p.operation?.last_error&&qa("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",p.operation.last_error,". Ask in the chat to try again."]})]},p.id)})}),!t&&!n&&m>0&&l&&vt("div",{className:"af-mt-2",children:vt(w,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:g,children:g?"Loading\u2026":`Load more (${m} more)`})})]})}import*as Yo from"react";import{AlertTriangle as Jo,CheckCircle2 as nf,CreditCard as Si,Loader2 as sf,RefreshCw as rf}from"lucide-react";import{jsx as et,jsxs as Et}from"react/jsx-runtime";function as({onConnectStripe:e,onUpgradePlan:t,whenActive:n,className:s}){let{status:a,isLoading:r,error:o,refetch:u}=Sn(),[g,l]=Yo.useState(!1),i=async()=>{l(!0);try{await u()}finally{l(!1)}};return r&&!a?et("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:et("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):o||!a?et("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Et("div",{className:"af-text-destructive",children:["Error: ",o?.message||"Failed to load payment status"]})}):a.status==="active"?n!==void 0?et("div",{className:s,children:n}):et("div",{className:s,children:Et("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:[et(nf,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),Et("div",{children:[et("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),Et("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."]})]})]})}):Et("div",{className:`af-space-y-4 ${s||""}`,children:[a.reason==="needs_stripe"&&Et("div",{className:"af-space-y-3",children:[Et("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[et(Si,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Et("div",{children:[et("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),et("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?Et(w,{onClick:e,children:[et(Si,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):et("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"&&Et("div",{className:"af-space-y-3",children:[Et("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[et(Jo,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Et("div",{children:[et("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),et("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?et(w,{onClick:t,children:"Upgrade plan"}):et("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),a.reason==="account_disabled"&&Et("div",{className:"af-space-y-3",children:[Et("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:[et(Jo,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),Et("div",{children:[et("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?et("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."}):et("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."})]})]}),Et("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&Et(w,{onClick:e,children:[et(Si,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),Et(w,{variant:"outline",onClick:i,disabled:g,children:[g?et(sf,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):et(rf,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as Wt from"react";function Ni(e,t,n){return e.map(s=>s.id===t?{...s,...n}:s)}function ns({includeStats:e=!1,refreshKey:t}={}){let{api:n}=Q(),[s,a]=Wt.useState([]),[r,o]=Wt.useState(!0),[u,g]=Wt.useState(null),l=Wt.useRef(0),i=Wt.useCallback(async()=>{let p=++l.current;try{o(!0),g(null);let y=await n.getProducts(e?{include:"stats"}:{});if(p!==l.current)return;a(y)}catch(y){if(p!==l.current)return;g(y instanceof Error?y:new Error("Failed to fetch products"))}finally{p===l.current&&o(!1)}},[n,e,t]);Wt.useEffect(()=>{i()},[i]);let d=Wt.useCallback(async p=>{let y=await n.createProduct(p);return a(h=>[y,...h]),y},[n]),b=Wt.useCallback(async(p,y)=>{let h=await n.updateProduct(p,y);return a(R=>Ni(R,p,h)),h},[n]),f=Wt.useCallback(async p=>{await n.deleteProduct(p),a(y=>y.filter(h=>h.id!==p))},[n]),c=Wt.useCallback(async(p,y)=>{let h=await n.attachProductFile(p,y);return a(R=>Ni(R,p,h)),h},[n]),m=Wt.useCallback(async(p,y)=>{let h=await n.attachProductFileFromUrl(p,y);return a(R=>Ni(R,p,h)),h},[n]);return{products:s,isLoading:r,error:u,refetch:i,createProduct:d,updateProduct:b,deleteProduct:f,attachProductFile:c,attachProductFileFromUrl:m}}import*as Kt from"react";var Ri=["creating","active","paused","canceling"],of=["canceled","failed"],lf={statuses:Ri},cf={};function ss({refreshKey:e,includeEnded:t=!1,limit:n=50}={}){let{api:s}=Q(),[a,r]=Kt.useState([]),[o,u]=Kt.useState(0),[g,l]=Kt.useState(0),[i,d]=Kt.useState(!0),[b,f]=Kt.useState(!1),[c,m]=Kt.useState(null),[p,y]=Kt.useState(t),h=Kt.useRef(0),R=Kt.useCallback(async()=>{let v=++h.current;d(!0),f(!1),m(null);try{let S=await s.getRetainers({statuses:p?void 0:Ri,limit:n,offset:0});if(v!==h.current)return;if(r(S.retainers),u(S.total),!p&&S.total===0){let _=await s.getRetainers({statuses:of,limit:1,offset:0});if(v!==h.current)return;l(_.total)}else l(0)}catch(S){if(v!==h.current)return;m(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{v===h.current&&d(!1)}},[s,p,n]);Kt.useEffect(()=>{R()},[R,e]);let C=Kt.useCallback(async()=>{if(i||b||a.length>=o)return;let v=h.current;f(!0);try{let S=await s.getRetainers({statuses:p?void 0:Ri,limit:n,offset:a.length});if(v!==h.current)return;r(_=>{let k=new Set(_.map(x=>x.id));return[..._,...S.retainers.filter(x=>!k.has(x.id))]}),u(S.total)}catch(S){if(v!==h.current)return;m(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{v===h.current&&f(!1)}},[s,p,n,i,b,a.length,o]);return{retainers:a,total:o,endedTotal:g,hasMore:a.length<o,isLoading:i,isLoadingMore:b,error:c,includeEnded:p,setIncludeEnded:y,loadMore:C,refetch:R,filters:p?cf:lf}}import{Fragment as bf,jsx as Ge,jsxs as ia}from"react/jsx-runtime";function Xo({className:e,defaultTab:t="products",onConnectStripe:n,onRefund:s,onUpgradePlan:a}){let[r,o]=rs.useState(t),[u,g]=rs.useState("list"),[l,i]=rs.useState(null),d=ns(),{status:b,error:f}=Sn(),c=b?.currency,m=R=>{i(R),g("edit")},p=()=>{i(null),g("create")},y=()=>{g("list"),i(null)},h=R=>{i(R),g("edit")};return ia("div",{className:e,children:[ia("div",{className:"af-mb-6",children:[Ge("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),Ge("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),ia(qs,{value:r,onValueChange:R=>o(R),children:[ia(xs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[ia(Ma,{value:"products",className:"af-gap-2",children:[Ge(ff,{className:"af-h-4 af-w-4"}),"Products"]}),ia(Ma,{value:"orders",className:"af-gap-2",children:[Ge(mf,{className:"af-h-4 af-w-4"}),"Orders"]}),ia(Ma,{value:"invoices",className:"af-gap-2",children:[Ge(df,{className:"af-h-4 af-w-4"}),"Invoices"]}),ia(Ma,{value:"customers",className:"af-gap-2",children:[Ge(gf,{className:"af-h-4 af-w-4"}),"Customers"]}),Ge(Ma,{value:"promos",children:"Promo codes"}),ia(Ma,{value:"setup",className:"af-gap-2",children:[Ge(pf,{className:"af-h-4 af-w-4"}),"Setup"]})]}),Ge($a,{value:"products",children:u==="list"?Ge(or,{productsState:d,onSelectProduct:m,onCreateProduct:p}):ia("div",{children:[ia("div",{className:"af-mb-6",children:[ia(w,{variant:"ghost",size:"sm",onClick:y,className:"af-mb-2 af--ml-2",children:[Ge(uf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),Ge("h3",{className:"af-text-lg af-font-semibold",children:u==="create"?"New Product":l?.name})]}),u==="create"&&!c?Ge("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:f?ia("div",{className:"af-text-destructive",children:["Error: ",f.message]}):Ge("div",{className:"af-text-muted-foreground",children:"Loading..."})}):Ge(cr,{productsState:d,product:u==="edit"?l:null,currency:c??"usd",onSaved:h},u==="edit"?l?.id??"edit":"new")]})}),Ge($a,{value:"orders",children:Ge(Rn,{onRefund:s})}),Ge($a,{value:"invoices",children:Ge(vf,{onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:b?.reason==="needs_paid_plan"})}),Ge($a,{value:"customers",children:Ge(wr,{})}),Ge($a,{value:"promos",children:Ge(Zn,{})}),Ge($a,{value:"setup",children:Ge(as,{onConnectStripe:n,onUpgradePlan:a})})]})]})}function vf({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:n}){let s=ss(),[a,r]=rs.useState(null),[o,u]=rs.useState(!1);return ia(bf,{children:[!o&&Ge(ts,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:a?.id??null,onShowCycles:g=>r(l=>l?.id===g.id?null:g),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),Ge(Pn,{onDetailOpenChange:u,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:n,retainerFilter:a?{id:a.id,label:`${a.customer_name??a.customer_email??"Recurring invoices"} \u2014 ${a.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}import*as el from"react";import*as en from"react";function is({refreshKey:e}={}){let{api:t}=Q(),[n,s]=en.useState(null),[a,r]=en.useState(!0),[o,u]=en.useState(null),g=en.useRef(0),l=en.useCallback(async()=>{let i=++g.current;try{r(!0),u(null);let d=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(i!==g.current)return;s(d)}catch(d){if(i!==g.current)return;u(d instanceof Error?d:new Error("Failed to fetch summary"))}finally{i===g.current&&r(!1)}},[t,e]);return en.useEffect(()=>{l()},[l]),{summary:n,isLoading:a,error:o,refetch:l}}import{Fragment as _i,jsx as It,jsxs as Pi}from"react/jsx-runtime";function Qo(e,t){if(e.settled.complete)return{headline:q(e.settled.gross,e.settled.currency),extra:[]};let n=e.totals[0];return n?{headline:q(n.gross,n.currency),extra:e.totals.slice(1).map(s=>`+ ${q(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:q(0,t),extra:[]}}function tl({refreshKey:e,initialOrderId:t,isOwner:n=!1,onRefund:s,onBackToWebsite:a,className:r}){let{summary:o,isLoading:u,error:g,refetch:l}=is({refreshKey:e}),[i,d]=el.useState(!1),b=It("div",{className:"af-mb-6",children:g&&!o?It(Na,{message:"Couldn't load your revenue summary.",onRetry:()=>l()}):It("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:u||!o?Pi(_i,{children:[It(ut,{label:"This week",children:It(ne,{className:"af-h-6 af-w-24"})}),It(ut,{label:"Today",children:It(ne,{className:"af-h-6 af-w-24"})}),It(ut,{label:"Needs attention",children:It(ne,{className:"af-h-6 af-w-10"})})]}):It(_i,{children:(()=>{let f=Qo(o.revenue.d7,o.currency),c=Qo(o.revenue.today,o.currency);return Pi(_i,{children:[It(ut,{label:"This week",detail:f.extra.length>0?It("div",{children:f.extra.map(m=>It("div",{children:m},m))}):void 0,children:f.headline}),It(ut,{label:"Today",detail:c.extra.length>0?It("div",{children:c.extra.map(m=>It("div",{children:m},m))}):void 0,children:c.headline}),It(ut,{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 Pi(Rt,{title:"Orders",onBackToWebsite:a,hideBackButton:i,className:r,children:[b,It(Rn,{refreshKey:e,initialOrderId:t,onDetailOpenChange:d,showFulfillment:!0,onRefund:n?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as Da from"react";import{ImageOff as Sf,Package as Nf,Search as Rf}from"lucide-react";import*as tn from"react";import{ArrowLeft as xf,ImageOff as wf}from"lucide-react";import{jsx as ja,jsxs as Ts}from"react/jsx-runtime";var al="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Cn="af-text-xs af-text-muted-foreground",Pr="af-text-sm af-font-medium af-tabular-nums",yf=3;function hf(e){let t=e.pricing,n=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let g=e.min_amount??t?.min_amount??null,l=e.max_amount??t?.max_amount??null;return g!==null&&l!==null?{text:`Buyer chooses (${q(g,n)} \u2013 ${q(l,n)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let a=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(a===null||r===null)return{text:"Varies by variant",compareAt:null};let o=a===r?q(a,n):`${q(a,n)} \u2013 ${q(r,n)}`,u=t?.compare_at_amount??null;return{text:o,compareAt:u!==null&&u>r?q(u,n):null}}function Cr({product:e,className:t}){let n=hf(e);return Ts("div",{className:t,children:[ja("span",{className:Pr,children:n.text}),n.compareAt&&ja("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:n.compareAt})]})}function Tr({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?ja(te,{variant:"destructive",children:"Out of stock"}):t.low_stock?Ts(te,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?ja(te,{variant:"secondary",children:"Backorder"}):t.available===null?null:Ts(te,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?ja(te,{variant:"warning",children:"Low stock"}):null}function kr(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Er(e){return e.map(t=>q(t.amount,t.currency)).join(" + ")}function nl(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${q(e.min_amount,e.currency)} \u2013 ${q(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":q(e.unit_amount,e.currency)}function sl({variant:e}){let t=e.inventory;if(!t||!t.tracked)return ja("span",{className:"af-text-muted-foreground",children:"Not tracked"});let n=t.available??0;return t.allow_backorder?Ts("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ja("span",{className:"af-tabular-nums",children:Math.max(0,n)}),ja(te,{variant:"secondary",children:n<0?`${Math.abs(n)} on backorder`:"Backorder"})]}):n<=0?ja(te,{variant:"destructive",children:"Out of stock"}):Ts("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ja("span",{className:"af-tabular-nums",children:n}),n<=yf&&ja(te,{variant:"warning",children:"Low"})]})}import{jsx as ue,jsxs as tt}from"react/jsx-runtime";function ks({title:e,children:t,className:n}){return tt("section",{className:K("af-rounded-lg af-border af-p-4",n),children:[ue("h4",{className:al,children:e}),ue("div",{className:"af-mt-3",children:t})]})}function rl({src:e,className:t}){let[n,s]=tn.useState(!1);return tn.useEffect(()=>s(!1),[e]),!e||n?ue("div",{"aria-hidden":"true",className:K("af-flex af-items-center af-justify-center af-bg-muted",t),children:ue(wf,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):ue("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:K("af-object-cover",t)})}function il({product:e,showStats:t=!1,onBack:n}){let{api:s}=Q(),[a,r]=tn.useState(null),[o,u]=tn.useState(!0),[g,l]=tn.useState(null),[i,d]=tn.useState(0),[b,f]=tn.useState(0);tn.useEffect(()=>{let v=!1;return u(!0),l(null),s.getProduct(e.id).then(S=>{v||r(S)}).catch(S=>{v||l(S instanceof Error?S:new Error("Failed to load product"))}).finally(()=>{v||u(!1)}),()=>{v=!0}},[s,e.id,i]);let c=a?{...e,...a}:e,m=c.images.length>0?c.images:e.images,p=m[b]??m[0],y=kr(c),h=t?c.stats:void 0,R=a?.variants??[],C=R.length>1;return tt("div",{children:[tt("div",{className:"af-mb-6",children:[tt(w,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[ue(xf,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),tt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ue("h3",{className:"af-text-xl af-font-semibold af-break-words",children:c.name}),ue(te,{variant:c.active?"success":"secondary",children:c.active?"Active":"Draft"}),ue(Tr,{product:c})]}),ue(Cr,{product:c,className:"af-mt-1"}),!c.active&&ue("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),tt("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[tt("div",{className:"af-space-y-2",children:[ue(rl,{src:p,className:"af-h-48 af-w-full af-rounded-md af-border"}),m.length>1&&ue("div",{className:"af-flex af-flex-wrap af-gap-2",children:m.map((v,S)=>ue("button",{type:"button",onClick:()=>f(S),"aria-label":`Show photo ${S+1} of ${m.length}`,"aria-pressed":S===b,className:K("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",S===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:ue(rl,{src:v,className:"af-h-12 af-w-12 af-rounded-md"})},`${v}-${S}`))})]}),tt("div",{className:"af-space-y-6",children:[c.description&&ue(ks,{title:"Description",children:ue("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:c.description})}),o?tt(ks,{title:"Variants",children:[ue("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(v=>tt("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[ue(ne,{className:"af-h-4 af-w-28"}),ue(ne,{className:"af-h-4 af-w-20"}),ue(ne,{className:"af-h-4 af-w-16"})]},v))}),ue("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):g?ue(Na,{message:"Couldn't load this product's variants.",onRetry:()=>d(v=>v+1)}):C?ue(ks,{title:`Variants \xB7 ${R.length}`,children:ue("div",{className:"af-overflow-x-auto",children:tt(Ve,{children:[ue(He,{children:tt(be,{children:[ue(V,{children:"Variant"}),ue(V,{children:"SKU"}),ue(V,{className:"af-text-right",children:"Price"}),ue(V,{children:"Stock"})]})}),ue(ze,{children:R.map(v=>tt(be,{children:[tt(H,{className:"af-font-medium",children:[v.title||v.option_values.map(S=>S.value).join(" / ")||"\u2014",!v.active&&ue(te,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),ue(H,{className:"af-text-muted-foreground",children:v.sku?ue("code",{className:"af-font-mono af-text-xs af-break-all",children:v.sku}):"\u2014"}),tt(H,{className:"af-whitespace-nowrap af-text-right",children:[ue("div",{className:Pr,children:nl(v)}),v.compare_at_amount!==null&&v.unit_amount!==null&&v.compare_at_amount>v.unit_amount&&ue("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:q(v.compare_at_amount,v.currency)})]}),ue(H,{className:"af-text-sm",children:ue(sl,{variant:v})})]},v.id))})]})})}):null,ue(ks,{title:"Details",children:tt("dl",{className:"af-space-y-2",children:[tt("div",{children:[ue("dt",{className:Cn,children:"Delivery"}),ue("dd",{className:"af-text-sm",children:y==="Digital download"?c.fulfillment.filename??"Digital download":y??"Nothing to deliver"})]}),c.fulfillment.type==="redirect"&&c.fulfillment.url&&tt("div",{children:[ue("dt",{className:Cn,children:"Sends buyers to"}),ue("dd",{className:"af-break-all af-text-sm",children:c.fulfillment.url})]}),tt("div",{children:[ue("dt",{className:Cn,children:"Shipping address"}),ue("dd",{className:"af-text-sm",children:c.collect_shipping_address?"Collected at checkout":"Not collected"})]}),tt("div",{children:[ue("dt",{className:Cn,children:"Most one buyer can order"}),ue("dd",{className:"af-text-sm af-tabular-nums",children:c.max_quantity})]})]})}),h&&ue(ks,{title:"Last 30 days",children:tt("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[tt("div",{children:[ue("dt",{className:Cn,children:"Units sold"}),ue("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:h.units_sold})]}),tt("div",{children:[ue("dt",{className:Cn,children:"Orders"}),ue("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:h.orders})]}),tt("div",{children:[ue("dt",{className:Cn,children:"Gross"}),ue("dd",{className:Pr,children:h.gross.length>0?Er(h.gross):"\u2014"})]})]})}),ue("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}import{Fragment as Tn,jsx as ie,jsxs as at}from"react/jsx-runtime";var _f={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Pf=["all","active","draft","low_stock","out_of_stock"];function ol(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,n=new Date(t).getTime();return Number.isNaN(n)?0:n}function ll(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Cf(e){return e.inventory?.out_of_stock??!1}function Tf(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return ll(e);case"out_of_stock":return Cf(e);default:return!0}}function kf({product:e,showStats:t,onOpen:n}){let s=e.images[0],a=t?e.stats:void 0,r=kr(e),o=e.variant_count??0;return at("button",{type:"button",onClick:n,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?ie("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):ie("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:ie(Sf,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),at("div",{className:"af-space-y-2 af-p-3",children:[at("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[at("div",{className:"af-min-w-0",children:[ie("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),ie(Cr,{product:e,className:"af-mt-0.5"})]}),!e.active&&ie(te,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),at("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ie(Tr,{product:e}),o>1&&at(te,{variant:"outline",children:[o," variants"]}),r&&ie(te,{variant:"outline",children:r})]}),a&&at("div",{className:"af-text-xs af-text-muted-foreground",children:[a.units_sold," sold",a.gross.length>0?` \xB7 ${Er(a.gross)}`:""," ",ie("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Ef(){return ie("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=>at("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[ie("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),at("div",{className:"af-space-y-2 af-p-3",children:[ie(ne,{className:"af-w-32"}),ie(ne,{className:"af-w-16"}),ie(ne,{className:"af-h-5 af-w-24"})]})]},e))})}function cl({refreshKey:e,showStats:t=!1,onBackToWebsite:n,className:s}){let{products:a,isLoading:r,error:o,refetch:u}=ns({includeStats:t,refreshKey:e}),[g,l]=Da.useState(!1),[i,d]=Da.useState(null),[b,f]=Da.useState("all"),{api:c}=Q(),m=Da.useCallback(()=>c.exportProductsCsv(),[c]),[p,y]=Da.useState(""),[h,R]=Da.useState("newest"),C=Da.useMemo(()=>{if(!t)return null;let j=null;for(let $ of a)!$.stats||$.stats.units_sold===0||(!j||$.stats.units_sold>(j.stats?.units_sold??0))&&(j=$);return j},[a,t]),v=Da.useMemo(()=>a.filter(ll).length,[a]),S=p.trim().toLowerCase(),_=Da.useMemo(()=>{let $=[...a.filter(ae=>Tf(ae,b)&&(!S||ae.name.toLowerCase().includes(S)))];return h==="name"?$.sort((ae,se)=>ae.name.localeCompare(se.name)):h==="best_selling"?$.sort((ae,se)=>(se.stats?.units_sold??0)-(ae.stats?.units_sold??0)):$.sort((ae,se)=>ol(se.created_at)-ol(ae.created_at)),$},[a,b,S,h]),k=b!=="all"||!!S,x=()=>{f("all"),y("")},P=r||o!==null&&a.length===0,A=ie("div",{className:"af-mb-6",children:ie("div",{className:K("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:P?at(Tn,{children:[ie(ut,{label:"Products",children:ie(ne,{className:"af-h-6 af-w-10"})}),t?at(Tn,{children:[ie(ut,{label:"Best seller",children:ie(ne,{className:"af-h-6 af-w-28"})}),ie(ut,{label:"Low stock",children:ie(ne,{className:"af-h-6 af-w-10"})})]}):ie(ut,{label:"Active",children:ie(ne,{className:"af-h-6 af-w-10"})})]}):at(Tn,{children:[ie(ut,{label:"Products",children:a.length}),t?at(Tn,{children:[ie(ut,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:C?`${C.stats?.units_sold??0} sold, last 30 days`:void 0,children:C?ie("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:C.name}):ie("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),ie(ut,{label:"Low stock",children:v})]}):ie(ut,{label:"Active",children:a.filter(j=>j.active).length})]})})}),N=at("div",{className:"af-mb-4 af-space-y-3",children:[at("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ie("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:Pf.map(j=>ie("button",{type:"button","aria-pressed":b===j,onClick:()=>f(j),className:K("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",b===j?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:_f[j]},j))}),at("div",{className:"af-relative af-w-full af-max-w-xs",children:[ie(Rf,{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"}),ie(ce,{type:"text",value:p,onChange:j=>y(j.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),at(_a,{value:h,onValueChange:j=>R(j),children:[ie(pa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:ie(Pa,{})}),at(ga,{children:[ie(Ye,{value:"newest",children:"Newest"}),ie(Ye,{value:"name",children:"Name A\u2013Z"}),t&&ie(Ye,{value:"best_selling",children:"Best selling"})]})]}),k&&ie(w,{type:"button",variant:"ghost",size:"sm",onClick:x,children:"Clear filters"}),ie($t,{fetchCsv:m,filename:"products",label:k?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&a.length===0?ie(ne,{className:"af-h-4 af-w-28"}):ie("p",{className:"af-text-sm af-text-muted-foreground",children:k?`${_.length} of ${a.length} products`:`${a.length} ${a.length===1?"product":"products"}${v>0?` \xB7 ${v} low stock`:""}`})]}),G;return i?G=ie(il,{product:i,showStats:t,onBack:()=>{d(null),u()}},i.id):r&&a.length===0?G=at(Tn,{children:[N,ie(Ef,{}),ie("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&a.length===0?G=ie("div",{className:"af-flex af-justify-center af-py-8",children:ie(Na,{message:"Couldn't load your products.",onRetry:()=>u()})}):a.length===0?G=at(za,{icon:ie(Nf,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",ie("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):G=at(Tn,{children:[N,o&&ie("div",{className:"af-mb-4",children:ie(Na,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>u()})}),_.length===0?at(za,{children:["No products match these filters.",ie("br",{}),ie(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:x,children:"Show all products"})]}):ie("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:_.map(j=>ie(kf,{product:j,showStats:t,onOpen:()=>d(j)},j.id))})]}),ie(Rt,{title:"Products",onBackToWebsite:n,hideBackButton:!!i,className:s,children:g?at(Tn,{children:[ie(w,{variant:"ghost",onClick:()=>l(!1),children:"Back to products"}),ie(Zn,{})]}):at(Tn,{children:[!i&&ie("div",{className:"af-mb-4 af-flex af-justify-end",children:ie(w,{variant:"outline",onClick:()=>l(!0),children:"Promo codes"})}),!i&&A,G]})})}import*as la from"react";import{ArrowLeft as gl,Check as If,ChevronLeft as ul,ChevronRight as dl,ClipboardCopy as Af,Mail as Ti,Search as Df,Users as Lf}from"lucide-react";import*as oa from"react";function Ir({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=Q(),[s,a]=oa.useState([]),[r,o]=oa.useState(!0),[u,g]=oa.useState(null),[l,i]=oa.useState(0),[d]=oa.useState(e),[b,f]=oa.useState(""),[c,m]=oa.useState(void 0),p=oa.useRef(0),y=oa.useCallback(async({afterRemoval:h=!1}={})=>{let R=++p.current;try{o(!0),g(null);let C={limit:d,offset:l*d};b.trim()&&(C.q=b.trim()),c&&(C.source=c);let v=await n.getPeople(C);if(R!==p.current)return;if(h&&v.people.length===0&&l>0){i(l-1);return}a(v.people)}catch(C){if(R!==p.current)return;g(C instanceof Error?C:new Error("Failed to fetch people"))}finally{R===p.current&&o(!1)}},[n,l,d,b,c,t]);return oa.useEffect(()=>{y()},[y]),{people:s,isLoading:r,error:u,page:l,pageSize:d,hasNextPage:s.length===d,hasPreviousPage:l>0,setPage:i,q:b,setQ:h=>{f(h),i(0)},source:c,setSource:h=>{m(h),i(0)},refetch:()=>y(),refetchAfterRemoval:()=>y({afterRemoval:!0})}}import*as an from"react";function Ar(e,{refreshKey:t}={}){let{api:n}=Q(),[s,a]=an.useState(null),[r,o]=an.useState(e!==null),[u,g]=an.useState(null),l=an.useRef(0),i=an.useCallback(async()=>{if(e===null){a(null),o(!1),g(null);return}let d=++l.current;try{o(!0),g(null);let b=await n.getPerson(e);if(d!==l.current)return;a(b)}catch(b){if(d!==l.current)return;g(b instanceof Error?b:new Error("Failed to fetch person"))}finally{d===l.current&&o(!1)}},[n,e,t]);return an.useEffect(()=>{i()},[i]),{person:s,isLoading:r,error:u,refetch:i}}import{jsx as T,jsxs as le}from"react/jsx-runtime";var Ci="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Of="af-text-xs af-text-muted-foreground";function os(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function ki(e,t){let n=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(n)}`}function Bf(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Ff({value:e,label:t}){let[n,s]=la.useState(!1);return Bf()?le(w,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[n?T(If,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):T(Af,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),n?"Copied":"Copy email"]}):null}function fl(e){return le("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&le(te,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&T(te,{variant:"secondary",children:"Contact form"})]})}function ml(e){return e.name?e.name:e.email?e.email:T("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Uf=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Mf=40;function $f(e){let t=Object.entries(e).filter(([a])=>!a.startsWith("_")),s=t.find(([a,r])=>Uf.test(a)&&typeof r=="string"&&r.trim())??t.filter(([,a])=>typeof a=="string"&&a.trim().length>=Mf).sort((a,r)=>String(r[1]).trim().length-String(a[1]).trim().length)[0];return s?{message:String(s[1]),rest:t.filter(([a])=>a!==s[0])}:{message:null,rest:t}}function Vf(e){return e.replace(/_/g," ")}function Hf(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function zf({data:e}){let{message:t,rest:n}=$f(e);return t===null&&n.length===0?T("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):le("div",{className:"af-space-y-3",children:[t!==null&&T("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),n.length>0&&T("dl",{className:"af-space-y-1",children:n.map(([s,a])=>le("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[T("dt",{className:K(Of,"af-w-28 af-shrink-0 af-capitalize"),children:Vf(s)}),T("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Hf(a)})]},s))})]})}function vl({formName:e,createdAt:t,data:n,onDelete:s}){return le("div",{className:"af-rounded-md af-border af-p-3",children:[le("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[T(te,{variant:"outline",children:"Form submission (unverified)"}),e&&T("span",{className:"af-text-xs af-text-muted-foreground",children:e}),T("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:os(t)}),T(Kn,{iconOnly:!0,onDelete:s})]}),T(zf,{data:n})]})}function qf(e){return e.charged_total??e.amount_total}function jf({email:e,refreshKey:t,onBack:n,onRemoved:s}){let{api:a}=Q(),{person:r,isLoading:o,error:u,refetch:g}=Ar(e,{refreshKey:t}),l=async d=>{await a.deleteSubmission(d),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?g():n()},i=ki(e,r?.submissions[0]?.form_name);return le("div",{children:[le("div",{className:"af-mb-6",children:[le(w,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[T(gl,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),le("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[le("div",{className:"af-min-w-0",children:[o?T(ne,{className:"af-h-7 af-w-48"}):T("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),le("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[T("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),T(Ff,{value:e,label:"Copy email address"})]})]}),T(w,{asChild:!0,children:le("a",{href:i,children:[T(Ti,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),o?le("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(d=>le("div",{className:"af-rounded-md af-border af-p-3",children:[T(ne,{className:"af-w-40"}),T(ne,{className:"af-mt-2 af-w-64"})]},d)),T("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):u||!r?T("div",{className:"af-flex af-justify-center af-py-8",children:T(Na,{message:"Couldn't load this person.",onRetry:()=>g()})}):le("div",{className:"af-space-y-6",children:[r.customer&&le("div",{children:[T("h4",{className:K(Ci,"af-mb-3"),children:"Customer"}),le("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&le("div",{className:"af-flex af-gap-2",children:[T("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),T("dd",{children:r.customer.name})]}),r.customer.phone&&le("div",{className:"af-flex af-gap-2",children:[T("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),T("dd",{children:r.customer.phone})]}),le("div",{className:"af-flex af-gap-2",children:[T("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),T("dd",{children:os(r.customer.created_at)})]})]})]}),r.orders.length>0&&le("div",{children:[T("h4",{className:K(Ci,"af-mb-3"),children:"Purchases"}),T("div",{className:"af-overflow-x-auto",children:le(Ve,{children:[T(He,{children:le(be,{children:[T(V,{children:"Order"}),T(V,{children:"Date"}),T(V,{className:"af-text-right",children:"Total"}),T(V,{children:"Status"})]})}),T(ze,{children:r.orders.map(d=>le(be,{children:[T(H,{className:"af-whitespace-nowrap af-font-medium",children:gn(d)}),T(H,{className:"af-whitespace-nowrap af-text-muted-foreground",children:os(d.created_at)}),T(H,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:q(qf(d),d.currency)}),T(H,{children:T(Un,{status:d.status})})]},d.id))})]})}),T("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&&le("div",{children:[T("h4",{className:K(Ci,"af-mb-3"),children:"Messages"}),T("div",{className:"af-space-y-3",children:r.submissions.map(d=>T(vl,{formName:d.form_name,createdAt:d.created_at,data:d.data,onDelete:()=>l(d.id)},d.id))})]})]})]})}function Gf({submissionId:e,onBack:t,onRemoved:n}){let{api:s}=Q(),[a,r]=la.useState(null),[o,u]=la.useState(!0),[g,l]=la.useState(null),[i,d]=la.useState(0);return la.useEffect(()=>{let b=!1;return u(!0),l(null),s.getSubmission(e).then(f=>{b||r(f)}).catch(f=>{b||l(f instanceof Error?f:new Error("Failed to load submission"))}).finally(()=>{b||u(!1)}),()=>{b=!0}},[s,e,i]),le("div",{children:[le("div",{className:"af-mb-6",children:[le(w,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[T(gl,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),T("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),o?T(ne,{className:"af-mt-1 af-h-4 af-w-32"}):a&&T("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:os(a.metadata.submitted_at)})]}),o?le("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[T(ne,{className:"af-w-40"}),T(ne,{className:"af-mt-2 af-w-64"}),T(ne,{className:"af-mt-2 af-w-52"}),T("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):g||!a?T("div",{className:"af-flex af-justify-center af-py-8",children:T(Na,{message:"Couldn't load this submission.",onRetry:()=>d(b=>b+1)})}):le("div",{className:"af-space-y-3",children:[T(vl,{formName:null,createdAt:a.metadata.submitted_at,data:a.data,onDelete:async()=>{await s.deleteSubmission(e),n(),t()}}),T("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 Wf={all:"All",customers:"Customers",leads:"Leads"},Kf=["all","customers","leads"],pl={all:void 0,customers:"customer",leads:"lead"};function Zf({refreshKey:e,onBackToWebsite:t,className:n,maxRows:s,onViewAll:a}){let r=typeof s=="number",{people:o,isLoading:u,error:g,page:l,pageSize:i,hasNextPage:d,hasPreviousPage:b,setPage:f,q:c,setQ:m,source:p,setSource:y,refetch:h,refetchAfterRemoval:R}=Ir({refreshKey:e}),[C,v]=la.useState({kind:"list"}),[S,_]=la.useState(""),k=p==="customer"?"customers":p==="lead"?"leads":"all",x=Z=>{pl[Z]!==p&&y(pl[Z])},{api:P}=Q(),A=la.useCallback(()=>P.exportPeopleCsv({...c?{q:c}:{},...p?{source:p}:{}}),[P,c,p]),N=!r||!!a,G=Z=>{if(r){a?.();return}Z.email?v({kind:"person",email:Z.email}):Z.submission_id&&v({kind:"submission",submissionId:Z.submission_id})},j=la.useRef(!1),$=()=>{j.current=!0},ae=()=>{v({kind:"list"}),j.current?(j.current=!1,R()):h()},se=Z=>{let B=Z.trim();B!==c&&m(B)},de=r?o.slice(0,s):o,U;if(C.kind==="person")U=T(jf,{email:C.email,refreshKey:e,onBack:ae,onRemoved:$});else if(C.kind==="submission")U=T(Gf,{submissionId:C.submissionId,onBack:ae,onRemoved:$});else{let Z=le("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[T("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:Kf.map(B=>T("button",{type:"button","aria-pressed":k===B,onClick:()=>x(B),className:K("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",k===B?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Wf[B]},B))}),le("div",{className:"af-relative af-w-full af-max-w-xs",children:[T(Df,{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"}),T(ce,{type:"text",value:S,onChange:B=>_(B.target.value),onBlur:()=>se(S),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),se(S))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),c&&T(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{_(""),m("")},children:"Clear search"}),T($t,{fetchCsv:A,filename:"people",className:"af-ml-auto"})]});if(u)U=le("div",{children:[r?null:Z,T("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(B=>le("div",{className:"af-rounded-md af-border af-p-3",children:[le("div",{className:"af-flex af-items-center af-justify-between",children:[T(ne,{className:"af-h-4 af-w-32"}),T(ne,{className:"af-h-4 af-w-16"})]}),T(ne,{className:"af-mt-2 af-h-5 af-w-28"}),T(ne,{className:"af-mt-2 af-h-3 af-w-56"})]},B))}),T("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:le(Ve,{children:[T(He,{children:le(be,{children:[T(V,{children:"Person"}),T(V,{children:"Came from"}),T(V,{children:"Latest message"}),T(V,{children:"Last activity"}),T(V,{className:"af-w-8"}),T(V,{className:"af-w-8"})]})}),T(ze,{"aria-hidden":"true",children:[0,1,2,3,4].map(B=>le(be,{children:[T(H,{children:T(ne,{className:"af-h-4 af-w-40"})}),T(H,{children:T(ne,{className:"af-h-5 af-w-24"})}),T(H,{children:T(ne,{className:"af-h-4 af-w-56"})}),T(H,{children:T(ne,{className:"af-h-4 af-w-24"})}),T(H,{}),T(H,{})]},B))})]})}),T("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(g)U=le("div",{children:[r?null:Z,T("div",{className:"af-flex af-justify-center af-py-8",children:T(Na,{message:"Couldn't load your leads.",onRetry:()=>h()})})]});else if(de.length===0&&l===0){let B=!!c||k!=="all";U=le("div",{children:[B&&Z,B?T(za,{children:c?"Nobody matches that search.":k==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):T(Yn,{icon:Lf,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)U=le("div",{children:[r?null:Z,T(za,{children:"No more results."}),T("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:le(w,{variant:"outline",size:"sm",onClick:()=>f(l-1),children:[T(ul,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let B=l*i+1,ye=l*i+o.length;U=le("div",{children:[r?null:Z,T("div",{className:"af-space-y-3 lg:af-hidden",children:de.map((re,Xe)=>le("div",{onClick:N?()=>G(re):void 0,className:`af-rounded-md af-border af-p-3${N?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[le("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[le("div",{className:"af-min-w-0",children:[T("button",{type:"button",onClick:he=>{he.stopPropagation(),G(re)},disabled:!N,"aria-label":`Open ${re.name||re.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${N?" hover:af-underline":""}`,children:ml(re)}),re.name&&re.email&&T("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:re.email})]}),le("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[T("span",{className:"af-text-xs af-text-muted-foreground",children:os(re.last_activity_at)}),re.email&&T(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:T("a",{href:ki(re.email),onClick:he=>he.stopPropagation(),"aria-label":`Email ${re.email}`,children:T(Ti,{className:"af-h-4 af-w-4"})})})]})]}),T("div",{className:"af-mt-2",children:fl(re)}),re.latest_message_excerpt&&T("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:re.latest_message_excerpt})]},re.email??re.submission_id??Xe))}),T("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:le(Ve,{children:[T(He,{children:le(be,{children:[T(V,{children:"Person"}),T(V,{children:"Came from"}),T(V,{children:"Latest message"}),T(V,{children:"Last activity"}),T(V,{className:"af-w-8",children:T("span",{className:"af-sr-only",children:"Reply"})}),T(V,{className:"af-w-8"})]})}),T(ze,{children:de.map((re,Xe)=>le(be,{onClick:N?()=>G(re):void 0,className:N?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[le(H,{className:"af-max-w-[260px] af-font-medium",children:[T("button",{type:"button",onClick:he=>{he.stopPropagation(),G(re)},disabled:!N,"aria-label":`Open ${re.name||re.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${N?" hover:af-underline":""}`,children:ml(re)}),re.name&&re.email&&T("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:re.email})]}),T(H,{children:fl(re)}),T(H,{className:"af-max-w-[320px]",children:re.latest_message_excerpt?T("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:re.latest_message_excerpt}):T("span",{className:"af-text-muted-foreground",children:"\u2014"})}),T(H,{className:"af-whitespace-nowrap af-text-muted-foreground",children:os(re.last_activity_at)}),T(H,{className:"af-w-8",children:re.email&&T(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:T("a",{href:ki(re.email),onClick:he=>he.stopPropagation(),"aria-label":`Email ${re.email}`,children:T(Ti,{className:"af-h-4 af-w-4"})})})}),T(H,{className:"af-w-8 af-text-right",children:T(dl,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},re.email??re.submission_id??Xe))})]})}),!r&&le("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[T("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${B}-${ye}`}),le("div",{className:"af-flex af-items-center af-gap-2",children:[le(w,{variant:"outline",size:"sm",onClick:()=>f(l-1),disabled:!b,children:[T(ul,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),le(w,{variant:"outline",size:"sm",onClick:()=>f(l+1),disabled:!d,children:["Next",T(dl,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?T("div",{className:n,children:U}):T(Rt,{title:"Leads",onBackToWebsite:t,hideBackButton:C.kind!=="list",className:n,children:U})}function Dr(e){return T(Zf,{...e},e.maxRows==null?"full":"compact")}import*as Sl from"react";import{ChevronLeft as bl,ChevronRight as Jf,Repeat as Yf}from"lucide-react";import*as ca from"react";function Lr({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=Q(),[s,a]=ca.useState([]),[r,o]=ca.useState(0),[u,g]=ca.useState(!0),[l,i]=ca.useState(null),[d,b]=ca.useState(0),[f,c]=ca.useState(e),[m,p]=ca.useState(void 0),y=ca.useRef(0),h=ca.useCallback(async()=>{let C=++y.current;try{g(!0),i(null);let v={limit:f,offset:d*f};m&&(v.status=m);let S=await n.getSubscriptions(v);if(C!==y.current)return;a(S.subscriptions),o(S.total)}catch(v){if(C!==y.current)return;i(v instanceof Error?v:new Error("Failed to fetch subscriptions"))}finally{C===y.current&&g(!1)}},[n,d,f,m,t]);ca.useEffect(()=>{h()},[h]);let R=Math.ceil(r/f);return{subscriptions:s,total:r,isLoading:u,error:l,page:d,pageSize:f,hasNextPage:d<R-1,hasPreviousPage:d>0,setPage:b,setPageSize:C=>{c(C),b(0)},status:m,setStatus:C=>{p(C),b(0)},refetch:h}}import{jsx as ee,jsxs as nt}from"react/jsx-runtime";function yl(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 hl({sub:e}){return e.status==="canceled"?ee(te,{variant:"outline",children:"Canceled"}):e.status==="past_due"?ee(te,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?ee(te,{variant:"warning",children:"Scheduled to cancel"}):ee(te,{variant:"success",children:"Active"}):ee(te,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Xf(e,t){let n=q(t,e.currency);return e.plan_interval_count===1?`${n} / ${e.plan_interval}`:`${n} every ${e.plan_interval_count} ${e.plan_interval}s`}function xl({sub:e}){let t=e.current_amount!==e.plan_amount;return nt("div",{children:[ee("div",{className:"af-font-medium af-tabular-nums",children:Xf(e,e.current_amount)}),t&&nt("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",q(e.plan_amount,e.currency)]})]})}function wl(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${yl(e.current_period_end)}`:"Ends at period end":e.current_period_end?yl(e.current_period_end):"\u2014"}function Nl({refreshKey:e,onBackToWebsite:t,className:n}){let{subscriptions:s,total:a,isLoading:r,error:o,page:u,pageSize:g,hasNextPage:l,hasPreviousPage:i,setPage:d,status:b,refetch:f}=Lr({refreshKey:e}),{api:c}=Q(),m=Sl.useCallback(()=>c.exportSubscriptionsCsv(b?{status:b}:{}),[c,b]),p;if(r)p=nt("div",{children:[ee("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(y=>nt("div",{className:"af-rounded-md af-border af-p-3",children:[nt("div",{className:"af-flex af-items-center af-justify-between",children:[ee(ne,{className:"af-h-4 af-w-40"}),ee(ne,{className:"af-h-4 af-w-20"})]}),ee(ne,{className:"af-mt-2 af-h-3 af-w-32"}),ee(ne,{className:"af-mt-2 af-h-5 af-w-24"})]},y))}),ee("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:nt(Ve,{children:[ee(He,{children:nt(be,{children:[ee(V,{children:"Subscriber"}),ee(V,{children:"Plan"}),ee(V,{className:"af-text-right",children:"Amount"}),ee(V,{children:"Renews"}),ee(V,{children:"Status"})]})}),ee(ze,{"aria-hidden":"true",children:[0,1,2,3,4].map(y=>nt(be,{children:[ee(H,{children:ee(ne,{className:"af-h-4 af-w-44"})}),ee(H,{children:ee(ne,{className:"af-h-4 af-w-32"})}),ee(H,{className:"af-text-right",children:ee(ne,{className:"af-ml-auto af-h-4 af-w-24"})}),ee(H,{children:ee(ne,{className:"af-h-4 af-w-24"})}),ee(H,{children:ee(ne,{className:"af-h-5 af-w-20"})})]},y))})]})}),ee("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=ee("div",{className:"af-flex af-justify-center af-py-8",children:ee(Na,{message:"Couldn't load your subscriptions.",onRetry:()=>f()})});else if(s.length===0&&u===0)p=ee(za,{icon:ee(Yf,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(s.length===0)p=nt("div",{children:[ee(za,{children:"No more results."}),ee("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:nt(w,{variant:"outline",size:"sm",onClick:()=>d(u-1),children:[ee(bl,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let y=u*g+1,h=u*g+s.length;p=nt("div",{children:[ee("div",{className:"af-mb-3 af-flex af-justify-end",children:ee($t,{fetchCsv:m,filename:"subscriptions"})}),ee("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(R=>nt("div",{className:"af-rounded-md af-border af-p-3",children:[nt("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[nt("div",{className:"af-min-w-0",children:[ee("div",{className:"af-truncate af-text-sm af-font-medium",children:R.customer_email||ee("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),ee("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:R.plan_title||"Untitled plan"})]}),ee("div",{className:"af-shrink-0 af-text-right",children:ee(xl,{sub:R})})]}),nt("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[ee(hl,{sub:R}),R.is_test&&ee(te,{variant:"outline",children:"Test"}),ee("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:wl(R)})]}),ee(Za,{deliveries:R.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},R.id))}),ee("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:nt(Ve,{children:[ee(He,{children:nt(be,{children:[ee(V,{children:"Subscriber"}),ee(V,{children:"Plan"}),ee(V,{className:"af-text-right",children:"Amount"}),ee(V,{children:"Renews"}),ee(V,{children:"Status"})]})}),ee(ze,{children:s.map(R=>nt(be,{children:[ee(H,{className:"af-max-w-[240px]",children:ee("div",{className:"af-truncate af-font-medium",children:R.customer_email||ee("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),ee(H,{className:"af-max-w-[220px]",children:ee("div",{className:"af-truncate",children:R.plan_title||ee("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),ee(H,{className:"af-whitespace-nowrap af-text-right",children:ee(xl,{sub:R})}),ee(H,{className:"af-whitespace-nowrap af-text-muted-foreground",children:wl(R)}),nt(H,{children:[nt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ee(hl,{sub:R}),R.is_test&&ee(te,{variant:"outline",children:"Test"})]}),ee(Za,{deliveries:R.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},R.id))})]})}),nt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[ee("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${y}-${h} of ${a}`}),nt("div",{className:"af-flex af-items-center af-gap-2",children:[nt(w,{variant:"outline",size:"sm",onClick:()=>d(u-1),disabled:!i,children:[ee(bl,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),nt(w,{variant:"outline",size:"sm",onClick:()=>d(u+1),disabled:!l,children:["Next",ee(Jf,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return ee(Rt,{title:"Subscriptions",onBackToWebsite:t,className:n,children:p})}import*as rn from"react";import{Loader2 as lm}from"lucide-react";import*as Ht from"react";import*as Or from"react";var Vn=typeof window>"u"?Or.useEffect:Or.useLayoutEffect;var Br=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},Qf=(e,t)=>e instanceof Error?e:new Error(t);function em(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 Rl(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:n}){let{api:s}=Q(),[a,r]=Ht.useState(null),[o,u]=Ht.useState(!0),[g,l]=Ht.useState(null),i=Ht.useRef(null),[d,b]=Ht.useState(()=>Rl(s,e)),f=d.api!==s||d.siteId!==e,c=d;f&&(c=Rl(s,e),b(c),r(null),u(!0),l(null));let m=Ht.useRef(c);Vn(()=>{m.current!==c&&(m.current=c,i.current=null)},[c]);let p=(x,P)=>m.current===x&&P>x.applied,y=(x,P,A)=>p(x,P)?(x.applied=P,i.current=A,r(A),u(!1),!0):!1,h=async x=>{for(;x.writing;)await x.idle;let P=++x.seq;try{let A=await x.api.getSite(x.siteId);return y(x,P,A)&&l(null),{seq:P,error:null}}catch(A){return{seq:P,error:Qf(A,"Failed to load store settings")}}},R=(x,P)=>{let A=async()=>{if(m.current!==x)throw new Error("Not saved: the store switched to another site first.");x.writing=!0,x.idle=new Promise(G=>{x.markIdle=G});try{return await P(++x.seq)}finally{x.writing=!1,x.markIdle()}},N=x.queue.then(A,A);return x.queue=N.catch(()=>{}),N},C=Ht.useCallback(async()=>{let x=await h(c);x.error&&p(c,x.seq)&&(l(x.error),u(!1))},[c]);Ht.useEffect(()=>{C()},[C,t]);let v=Ht.useCallback(x=>R(c,async P=>{let A=await c.api.updateSite(c.siteId,x),{currency_restatement:N,...G}=A;return y(c,P,G)&&l(j=>j instanceof Br?j:null),A}),[c]),S=Ht.useRef(n);Vn(()=>{S.current=n});let _=Ht.useCallback(async(x,P)=>{await R(c,()=>x());let A=await h(c);return A.error&&p(c,A.seq)&&i.current&&(y(c,A.seq,{...i.current,...P}),l(new Br(`Saved, but couldn't refresh settings: ${A.error.message}`))),m.current===c?i.current:null},[c]),k=Ht.useCallback(x=>{let P=S.current;return _(()=>P(x),em(x))},[_]);return{site:f?null:a,isLoading:f||o,error:f?null:g,refetch:C,updateSite:v,saveInvoiceSettings:n?k:null}}import*as Pt from"react";import{Loader2 as _l}from"lucide-react";import{jsx as La,jsxs as nn}from"react/jsx-runtime";function Fr(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var Ga="af-grid af-gap-1 af-text-sm",Pl="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",Cl="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 ua({children:e}){return La("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Es({children:e}){return La("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var sn=Pt.forwardRef(function({id:t,title:n,description:s,children:a},r){let o=`af-store-${t}-title`;return nn("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:[nn("div",{className:"af-space-y-1",children:[La("h3",{id:o,className:"af-text-sm af-font-semibold",children:n}),s&&La(ua,{children:s})]}),a]})});function Ai({label:e,description:t,checked:n,onSave:s,disabled:a=!1,disabledReason:r}){let[o,u]=Pt.useState(null),[g,l]=Pt.useState(null),i=o??n,d=async b=>{u(b),l(null);try{await s(b)}catch(f){l(Fr(f))}finally{u(null)}};return nn("div",{className:"af-space-y-1",children:[nn("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[La("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":i,checked:i,disabled:a||o!==null,onChange:b=>void d(b.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),nn("span",{className:"af-space-y-0.5",children:[nn("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,o!==null&&La(_l,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&La(ua,{children:t})]})]}),(a&&r||g)&&nn("div",{className:"af-space-y-1 af-pl-6",children:[a&&r&&La(ua,{children:r}),g&&La(Es,{children:g})]})]})}var Ii=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ei=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function tm(e,t,n,s=[]){if(!Ei(e)||!Ei(t)||!Ei(n))return{draft:Ii(e,t)?n:e,dropped:[]};let a=[],r={...n};for(let o of Object.keys(n))Ii(e[o],t[o])||(s.includes(o)?a.push(o):r[o]=e[o]);return{draft:r,dropped:a}}function ls(e,t){let n=JSON.stringify(e),[s,a]=Pt.useState(e),[r,o]=Pt.useState([]),u=Pt.useRef(e),g=Pt.useRef(e),l=Pt.useRef(s);Vn(()=>{g.current=e,l.current=s});let i=Pt.useRef(t?.when);Pt.useEffect(()=>{let b=Object.is(i.current,t?.when)?[]:t?.fields??[];if(i.current=t?.when,Ii(u.current,g.current)&&b.length===0)return;let f=tm(l.current,u.current,g.current,b);u.current=g.current,a(f.draft),f.dropped.length&&o(f.dropped)},[n,t?.when]);let d=Pt.useCallback(b=>{a(b??g.current),o([])},[]);return{draft:s,setDraft:a,dirty:JSON.stringify(s)!==n,reset:d,dropped:r}}function cs({dirty:e,saving:t,error:n,onSave:s,onDiscard:a}){return e?nn("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[nn(w,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&La(_l,{className:"af-animate-spin"}),"Save"]}),La(w,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:a,children:"Discard"}),n&&La("p",{role:"alert",className:K("af-text-sm af-text-destructive"),children:n})]}):null}function us(){let[e,t]=Pt.useState(!1),[n,s]=Pt.useState(null),a=Pt.useCallback(async r=>{t(!0),s(null);try{await r()}catch(o){s(Fr(o))}finally{t(!1)}},[]);return{saving:e,error:n,setError:s,run:a}}function Tl({what:e}){return nn(ua,{children:["Only the site owner can change ",e,"."]})}import*as Oa from"react";import{ExternalLink as am,Plus as nm,X as Al}from"lucide-react";import{Fragment as om,jsx as fe,jsxs as we}from"react/jsx-runtime";var Li=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Dl({site:e,updateSite:t}){return fe("div",{className:"af-space-y-4",children:fe(Ai,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:n=>t({collect_phone_at_checkout:n})})})}function kl(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(lt(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(lt(e.free_shipping_over,e.currency))}}function Ll({site:e,updateSite:t,refetch:n,providerSlot:s,currencyChanging:a=!1}){let{draft:r,setDraft:o,dirty:u,reset:g,dropped:l}=ls(kl(e),{when:e.currency,fields:["rates","threshold"]}),{saving:i,error:d,setError:b,run:f}=us(),c=e.currency.toUpperCase(),m=()=>f(async()=>{let y={},h=[...new Set(r.countries.split(/[\s,]+/).map(x=>x.trim().toUpperCase()).filter(Boolean))],R=h.find(x=>!/^[A-Z]{2}$/.test(x));if(R)throw new Error(`"${R}" isn't a two-letter country code (e.g. US, CA).`);let C=h.length?h:null;Li(C,e.shipping_countries)||(y.shipping_countries=C);let v=[];for(let x of r.rates){let P=x.label.trim(),A=Ot(x.amount,e.currency);if(!P)throw new Error("Every rate needs a name.");if(x.amount.trim()===""||A===null)throw new Error(`Enter a price for "${P}" (0 for free).`);v.push({label:P,amount:A})}let S=v.length?v:null;Li(S,e.shipping_rates)||(y.shipping_rates=S);let _=null;if(r.threshold.trim()!==""&&(_=Ot(r.threshold,e.currency),_===null||_===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(_!==e.free_shipping_over&&(y.free_shipping_over=_),Object.keys(y).length===0){g();return}("shipping_rates"in y||"free_shipping_over"in y)&&(y.expected_currency=e.currency);let k;try{k=await t(y)}catch(x){throw x instanceof St&&x.details?.code==="currency_changed"&&await n?.(),x}g(kl(k))}),p=(y,h)=>o({...r,rates:r.rates.map((R,C)=>C===y?{...R,...h}:R)});return we("fieldset",{disabled:i||a,className:"af-space-y-4",children:[we("label",{className:Ga,children:["Countries you ship to",fe(ce,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:y=>o({...r,countries:y.target.value})}),fe(ua,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),we("div",{className:"af-space-y-2",children:[we("p",{className:"af-text-sm",children:["Flat shipping rates (",c,")"]}),r.rates.length===0&&fe(ua,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((y,h)=>we("div",{className:"af-flex af-items-center af-gap-2",children:[fe(ce,{"aria-label":`Rate ${h+1} name`,value:y.label,placeholder:"Standard",onChange:R=>p(h,{label:R.target.value})}),fe(ce,{"aria-label":`Rate ${h+1} price`,type:"number",min:"0",step:"any",value:y.amount,placeholder:"0",className:"af-w-32",onChange:R=>p(h,{amount:R.target.value})}),fe(w,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${h+1}`,onClick:()=>o({...r,rates:r.rates.filter((R,C)=>C!==h)}),children:fe(Al,{})})]},h)),we(w,{type:"button",variant:"outline",size:"sm",onClick:()=>o({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[fe(nm,{})," Add rate"]}),fe(ua,{children:"Buyers pick one at checkout. The first is preselected."})]}),we("label",{className:Ga,children:["Free shipping over (",c,")",fe(ce,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:y=>o({...r,threshold:y.target.value})}),fe(ua,{children:"Orders at or above this get the cheapest rate free."})]}),l.length>0&&we("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",c,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),fe(cs,{dirty:u,saving:i,error:d,onSave:()=>void m(),onDiscard:()=>{b(null),g()}}),s]})}var Di="exclusive",sm=[{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 rm({href:e,children:t}){return we("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,fe(am,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function Ol({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(e.tax_behavior??Di),{saving:o,error:u,setError:g,run:l}=us(),[i,d]=Oa.useState(!1),b=e.stripe_tax_enabled,f=b||i,c=()=>l(async()=>{let y=n;if(y===e.tax_behavior){r();return}let h={tax_behavior:y};y!=="inclusive"&&e.tax_rate_bps!=null&&(h.tax_rate_bps=null);let R=await t(h);r(R.tax_behavior??Di)}),m=()=>l(async()=>{let y={stripe_tax_enabled:!0,tax_behavior:n};n!=="inclusive"&&e.tax_rate_bps!=null&&(y.tax_rate_bps=null);let h=await t(y);r(h.tax_behavior??Di),d(!1)}),p=(a||i)&&n!=="inclusive"&&e.tax_rate_bps!=null;return we("div",{className:"af-space-y-5",children:[we("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[fe("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."}),fe("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."}),fe("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:sm.map(y=>fe("li",{children:fe(rm,{href:y.href,children:y.label})},y.href))})]}),fe(Ai,{label:"Stripe automatic tax",description:b?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:f,onSave:async y=>{if(i){d(!1),g(null),r();return}if(y&&!e.tax_behavior){d(!0);return}return t({stripe_tax_enabled:y})}}),f&&we("fieldset",{disabled:o,className:"af-space-y-4 af-pl-6",children:[we("label",{className:Ga,children:["Do your prices already include tax?",we("select",{"aria-label":"Your prices",className:Pl,value:n,onChange:y=>s(y.target.value),children:[fe("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),fe("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),fe(ua,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),p&&we(ua,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),i?we("div",{className:"af-space-y-2",children:[we("div",{className:"af-flex af-gap-2",children:[fe(w,{type:"button",size:"sm",disabled:o,onClick:()=>void m(),children:"Turn on"}),fe(w,{type:"button",size:"sm",variant:"outline",disabled:o,onClick:()=>{d(!1),g(null),r()},children:"Cancel"})]}),u&&fe(Es,{children:u})]}):fe(cs,{dirty:a,saving:o,error:u,onSave:()=>void c(),onDiscard:()=>{g(null),r()}})]})]})}function El(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function Bl({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(El(e)),{saving:o,error:u,setError:g,run:l}=us(),i=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),d=()=>l(async()=>{let b={},f=null;if(i&&n.rate.trim()!==""){let y=Number(n.rate);if(!Number.isFinite(y)||y<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");f=Math.round(y*100)}i&&f!==e.tax_rate_bps&&(b.tax_rate_bps=f),f!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let c=n.taxId.trim()||null;c!==e.tax_id&&(b.tax_id=c);let m=n.label.trim()||null;if(m!==e.tax_label&&(b.tax_label=m),Object.keys(b).length===0){r();return}let p=await t(b);r(El(p))});return we("fieldset",{disabled:o,className:"af-space-y-4",children:[we("label",{className:Ga,children:["Tax rate (%)",fe(ce,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!i,value:i?n.rate:"",onChange:b=>s({...n,rate:b.target.value})}),fe(ua,{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."})]}),we("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[we("label",{className:Ga,children:["Tax ID",fe(ce,{"aria-label":"Tax ID",value:n.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...n,taxId:b.target.value})})]}),we("label",{className:Ga,children:["Tax label",fe(ce,{"aria-label":"Tax label",value:n.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...n,label:b.target.value})})]})]}),fe(cs,{dirty:a,saving:o,error:u,onSave:()=>void d(),onDiscard:()=>{g(null),r()}})]})}function Fl({site:e,updateSite:t,onChangeStart:n}){let[s,a]=Oa.useState(e.currency.toUpperCase()),[r,o]=Oa.useState(!1),[u,g]=Oa.useState(!1),[l,i]=Oa.useState(null),d=e.currency.toUpperCase(),b=Oa.useRef(d);Oa.useEffect(()=>{b.current!==d&&(a(y=>y===b.current?d:y),b.current=d)},[d]);let f=s.trim().toUpperCase(),c=f!==d,m=/^[A-Z]{3}$/.test(f),p=async()=>{g(!0);let y=n?.(),h=!1;i(null);try{let R=await t({currency:f.toLowerCase()});h=!0;let C=R.currency_restatement;C&&!C.applied?i(C.reason?`Not changed: ${C.reason}.`:"The currency was not changed."):(a(R.currency.toUpperCase()),b.current=R.currency.toUpperCase()),o(!1)}catch(R){i(Fr(R))}finally{g(!1),y?.(h)}};return we("div",{className:"af-space-y-3",children:[we("div",{className:"af-flex af-items-end af-gap-2",children:[we("label",{className:Ga,children:["Store currency",fe(ce,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:u||r,onChange:y=>{a(y.target.value),i(null)}})]}),c&&!r&&we(om,{children:[fe(w,{type:"button",size:"sm",disabled:!m,onClick:()=>o(!0),children:"Change currency"}),fe(w,{type:"button",size:"sm",variant:"ghost",onClick:()=>{a(d),i(null)},children:"Discard"})]})]}),fe(ua,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&we("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[we("p",{className:"af-text-sm",children:["Change the store currency from ",d," to ",f,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",f,":"," ",q(2e3,d)," becomes ",q(2e3,f),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),we("div",{className:"af-flex af-gap-2",children:[fe(w,{type:"button",size:"sm",disabled:u,onClick:()=>void p(),children:"Confirm change"}),fe(w,{type:"button",size:"sm",variant:"ghost",disabled:u,onClick:()=>o(!1),children:"Cancel"})]})]}),l&&fe(Es,{children:l})]})}function Il(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function im(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 Ul({site:e,save:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(Il(e)),{saving:o,error:u,setError:g,run:l}=us();if(!t)return we("div",{className:"af-space-y-2 af-text-sm",children:[we("p",{children:["Due ",e.invoice_due_days," days after sending"]}),we("p",{children:["Reminders: ",im(e.invoice_reminder_schedule)]}),we("p",{children:["Footer: ",e.invoice_footer||"None"]}),fe(Tl,{what:"invoice defaults"})]});let i=()=>l(async()=>{let d={},b=Number(n.dueDays);if(n.dueDays.trim()===""||!Number.isInteger(b)||b<0||b>90)throw new Error("Due days must be a whole number from 0 to 90.");b!==e.invoice_due_days&&(d.due_days=b);let c=n.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(c.some(h=>!Number.isInteger(h)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let m=[...new Set(c)].sort((h,R)=>h-R);Li(m,e.invoice_reminder_schedule)||(d.reminder_schedule=m);let p=n.footer.trim()||null;if(p!==e.invoice_footer&&(d.footer=p),Object.keys(d).length===0){r();return}let y=await t(d);r(y?Il(y):void 0)});return we("fieldset",{disabled:o,className:"af-space-y-4",children:[we("label",{className:Ga,children:["Days until due",fe(ce,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:n.dueDays,onChange:d=>s({...n,dueDays:d.target.value})})]}),we("label",{className:Ga,children:["Reminder schedule",fe(ce,{"aria-label":"Reminder schedule",value:n.reminders,placeholder:"Off",onChange:d=>s({...n,reminders:d.target.value})}),fe(ua,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),we("label",{className:Ga,children:["Invoice footer",fe("textarea",{"aria-label":"Invoice footer",className:Cl,maxLength:300,value:n.footer,onChange:d=>s({...n,footer:d.target.value})})]}),fe(cs,{dirty:a,saving:o,error:u,onSave:()=>void i(),onDiscard:()=>{g(null),r()}})]})}function Ml({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(e.default_email_recipients),{saving:o,error:u,setError:g,run:l}=us(),[i,d]=Oa.useState(""),[b,f]=Oa.useState(null),c=()=>{let p=i.trim().toLowerCase();if(p){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p)){f("Enter a valid email address.");return}if(n.some(y=>y.toLowerCase()===p)){f("Already added.");return}s([...n,p]),d(""),f(null)}},m=()=>l(async()=>{let p=await t({default_email_recipients:n});r(p.default_email_recipients)});return we("fieldset",{disabled:o,className:"af-space-y-3",children:[we("div",{className:"af-flex af-flex-wrap af-gap-2",children:[n.map(p=>we(te,{variant:"secondary",className:"af-gap-1",children:[p,fe("button",{type:"button","aria-label":`Remove ${p}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(n.filter(y=>y!==p)),children:fe(Al,{className:"af-h-3 af-w-3"})})]},p)),n.length===0&&fe("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),we("div",{className:"af-flex af-gap-2",children:[fe(ce,{"aria-label":"Add notification email",type:"email",value:i,placeholder:"Add email address",onChange:p=>{d(p.target.value),f(null)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),c())}}),fe(w,{type:"button",variant:"outline",disabled:!i.trim(),onClick:c,children:"Add"})]}),b&&fe(Es,{children:b}),fe(cs,{dirty:a,saving:o,error:u,onSave:()=>void m(),onDiscard:()=>{g(null),r()}})]})}import{jsx as Ra,jsxs as $l}from"react/jsx-runtime";function Vl({siteId:e,refreshKey:t,section:n,shippingProviderSlot:s,onConnectStripe:a,onUpgradePlan:r,className:o}){let{site:u,isLoading:g,error:l,refetch:i,updateSite:d}=kn({siteId:e,refreshKey:t}),b=rn.useRef(i),f=rn.useRef(e);Vn(()=>{b.current=i,f.current=e});let c=rn.useRef({}),[m,p]=rn.useState([]),y=m.some(S=>S.siteId===e),h=rn.useCallback(()=>{let S={siteId:e},_=b.current;return p(k=>[...k,S]),k=>{let x=()=>p(A=>A.filter(N=>N!==S));!(f.current===S.siteId)||k&&b.current===_?x():b.current().finally(x)}},[e]),R=S=>_=>{c.current[S]=_},C=u!==null&&u.payments_active;if(rn.useEffect(()=>{if(!C||!n)return;let S=c.current[n];S&&(S.scrollIntoView?.({behavior:"smooth",block:"start"}),S.focus({preventScroll:!0}))},[C,n]),g)return $l("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ra(lm,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!u)return Ra("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l?.message??"Could not load store settings."});if(!u.payments_active)return Ra(as,{className:o,onConnectStripe:a,onUpgradePlan:r,whenActive:Ra("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let v={site:u,updateSite:d,refetch:i};return $l("div",{className:`af-space-y-6 ${o??""}`,children:[l&&Ra("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}),Ra(sn,{ref:R("checkout"),id:"checkout",title:"Checkout",children:Ra(Dl,{...v})}),Ra(sn,{ref:R("shipping"),id:"shipping",title:"Shipping",children:Ra(Ll,{...v,providerSlot:s,currencyChanging:y})}),Ra(sn,{ref:R("tax"),id:"tax",title:"Tax",children:Ra(Ol,{...v})}),Ra(sn,{ref:R("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:Ra(Fl,{...v,onChangeStart:h})})]},e)}import{Loader2 as cm}from"lucide-react";import{jsx as Hn,jsxs as Hl}from"react/jsx-runtime";function Ur({siteId:e,refreshKey:t,onSaveInvoiceSettings:n,className:s}){let{site:a,isLoading:r,error:o,updateSite:u,refetch:g,saveInvoiceSettings:l}=kn({siteId:e,refreshKey:t,onSaveInvoiceSettings:n});return r?Hl("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Hn(cm,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):a?Hl("div",{className:`af-space-y-6 ${s??""}`,children:[o&&Hn("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}),Hn(sn,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:Hn(Ul,{site:a,save:l})}),Hn(sn,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:Hn(Bl,{site:a,updateSite:u,refetch:g})})]},e):Hn("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."})}import{Loader2 as um}from"lucide-react";import{jsx as Is,jsxs as zl}from"react/jsx-runtime";function ql({siteId:e,refreshKey:t,className:n}){let{site:s,isLoading:a,error:r,updateSite:o,refetch:u}=kn({siteId:e,refreshKey:t});return a?zl("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Is(um,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?zl("div",{className:`af-space-y-3 ${n??""}`,children:[r&&Is("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}),Is(sn,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:Is(Ml,{site:s,updateSite:o,refetch:u})})]},e):Is("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r?.message??"Could not load notification settings."})}import*as ds from"react";import{Fragment as jl,jsx as zt,jsxs as As}from"react/jsx-runtime";function Gl({refreshKey:e,initialInvoiceId:t,onBackToWebsite:n,onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:r,siteId:o,onSaveInvoiceSettings:u,className:g}){let{aggregates:l,isLoading:i,error:d,refetch:b}=Qn({refreshKey:e,initialPageSize:1,includeAggregates:!0}),f=ss({refreshKey:e}),{api:c}=Q(),m=f.filters,p=ds.useCallback(()=>c.exportRetainersCsv(m),[c,m]),[y,h]=ds.useState(!1),[R,C]=ds.useState(null),[v,S]=ds.useState(!1),_=zt("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:d||!i&&!l?As("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. ",zt(w,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):i||!l?As(jl,{children:[zt(ut,{label:"Outstanding",children:zt(ne,{className:"af-h-6 af-w-24"})}),zt(ut,{label:"Overdue",children:zt(ne,{className:"af-h-6 af-w-24"})}),zt(ut,{label:"Paid this month",children:zt(ne,{className:"af-h-6 af-w-24"})})]}):As(jl,{children:[zt(ut,{label:"Outstanding",detail:`${l.outstanding.count} open`,children:q(l.outstanding.amount,l.currency)}),zt(ut,{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:q(l.overdue.amount,l.currency)}),zt(ut,{label:"Paid this month",detail:`${l.paid_this_month.count} paid`,children:q(l.paid_this_month.amount,l.currency)})]})});return As(Rt,{title:"Invoices",onBackToWebsite:n,hideBackButton:y,className:g,children:[_,o&&!y&&As("div",{className:"af-mb-6",children:[zt(w,{type:"button",variant:"outline",size:"sm","aria-expanded":v,"aria-controls":"af-invoice-settings",onClick:()=>S(k=>!k),children:"Invoice settings"}),v&&zt("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:zt(Ur,{siteId:o,refreshKey:e,onSaveInvoiceSettings:u})})]}),!y&&zt(ts,{retainers:f.retainers,isLoading:f.isLoading,error:f.error,onRetry:()=>void f.refetch(),activeRetainerId:R?.id??null,onShowCycles:k=>C(x=>x?.id===k.id?null:k),total:f.total,endedTotal:f.endedTotal,isLoadingMore:f.isLoadingMore,onLoadMore:()=>void f.loadMore(),includeEnded:f.includeEnded,onIncludeEndedChange:f.setIncludeEnded,exportCsv:p}),zt(Pn,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:h,onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:r,retainerFilter:R?{id:R.id,label:`${R.customer_name??R.customer_email??"Recurring invoices"} \u2014 ${R.description}`}:null,onClearRetainerFilter:()=>C(null)})]})}import*as Ct from"react";var dm=2e3,Ft=()=>({data:null,error:null,isLoading:!0});function fs(e,{refreshKey:t,breakdowns:n=[],filters:s=[]}={}){let{api:a}=Q(),[r,o]=Ct.useState(Ft),[u,g]=Ct.useState(Ft),[l,i]=Ct.useState(Ft),[d,b]=Ct.useState(Ft),[f,c]=Ct.useState(Ft),m=U=>Object.fromEntries(U.map(Z=>[Z,Ft()])),[p,y]=Ct.useState(()=>m(n)),h=Ct.useRef(0),R=Ct.useRef(0),C=Ct.useRef("idle"),v=n.join(","),S=yn()??"",_=JSON.stringify(s),k=`${e}:${v}:${_}:${S}`,[x,P]=Ct.useState({api:a,fetchIdentity:k});(x.api!==a||x.fetchIdentity!==k)&&(P({api:a,fetchIdentity:k}),h.current+=1,o(Ft),g(Ft),i(Ft),b(Ft),y(m(v?v.split(","):[])));let A=`${e}:${String(t??"")}:${S}`,[N,G]=Ct.useState({api:a,conversionsIdentity:A});(N.api!==a||N.conversionsIdentity!==A)&&(G({api:a,conversionsIdentity:A}),R.current+=1,C.current="idle",c(Ft));let j=Ct.useCallback(async U=>{let Z=++h.current,B=v?v.split(","):[];o(Ft),g(Ft),i(Ft),b(Ft),y(Object.fromEntries(B.map(E=>[E,Ft()])));let ye=C.current!=="pending"&&(U?.force===!0||C.current==="idle"),re=(E,F)=>F.then(O=>{Z===h.current&&E({data:O,error:null,isLoading:!1})},O=>{Z===h.current&&E({data:null,error:O instanceof Error?O:new Error("Failed to fetch report"),isLoading:!1})}),Xe=a.getAnalyticsStatus(),he=re(o,Xe),Ue=Symbol("status-timeout"),Ze,Ee=await Promise.race([Xe.then(E=>E,()=>null),new Promise(E=>{Ze=setTimeout(()=>E(Ue),dm)})]);if(clearTimeout(Ze),Z!==h.current)return;if(Ee===Ue&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Ee!==null&&Ee!==Ue&&(Ee.collecting!==!0||Ee.first_seen===null&&!Ee.first_seen_unavailable||Ee.first_seen!==null&&Ee.first_seen_in_reports===!1)){let E={data:null,error:null,isLoading:!1};g(E),i(E),b(E),y(Object.fromEntries(B.map(F=>[F,{...E}]))),ye&&(c(E),C.current="done"),await he;return}await Promise.all([Ee===Ue?Promise.resolve():he,re(g,a.getAnalyticsSummary(e,s)),re(i,a.getAnalyticsTimeseries(e,s)),re(b,a.getAnalyticsChannels(e,s)),ye?(()=>{C.current="pending";let E=++R.current;return c(Ft),a.getAnalyticsConversions(e).then(F=>{E===R.current&&(c({data:F,error:null,isLoading:!1}),C.current="done")},F=>{E===R.current&&(c({data:null,error:F instanceof Error?F:new Error("Failed to fetch report"),isLoading:!1}),C.current="done")})})():Promise.resolve(),...B.map(E=>a.getAnalyticsBreakdown(E,e,s).then(F=>{Z===h.current&&y(O=>({...O,[E]:{data:F,error:null,isLoading:!1}}))},F=>{Z===h.current&&y(O=>({...O,[E]:{data:null,error:F instanceof Error?F:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[a,e,v,_,A,S]),$=Ct.useCallback(async()=>{let U=h.current;try{let Z=await a.getAnalyticsStatus();if(U!==h.current)return;o({data:Z,error:null,isLoading:!1})}catch(Z){if(U!==h.current)return;o(B=>({data:B.data,error:Z instanceof Error?Z:new Error("Failed to fetch status"),isLoading:!1}))}},[a]),ae=Ct.useCallback(()=>j({force:!0}),[j]);Ct.useEffect(()=>{j()},[j,t]);let se=r.isLoading||u.isLoading||l.isLoading||d.isLoading||f.isLoading||Object.values(p).some(U=>U.isLoading),de=[l,u,d,f,...Object.values(p)].map(U=>U.data?.status==="ok"?U.data.timezone:void 0).find(U=>U!==void 0);return{status:r,summary:u,timeseries:l,channels:d,conversions:f,breakdowns:p,reportedZone:de,isLoading:se,refetch:ae,refetchStatus:$}}import*as Tt from"react";var Oi=3e4,Bi=3;function Mr(e={}){let t="collecting"in e,{collecting:n,statusFailed:s=!1,identity:a}=e,{api:r}=Q(),[o,u]=Tt.useState(null),[g,l]=Tt.useState(null),[i,d]=Tt.useState(!1),[b,f]=Tt.useState(null),[c,m]=Tt.useState(!1),[p,y]=Tt.useState(!0),[h,R]=Tt.useState(0),C=Tt.useRef(0),v=Tt.useRef(0),S=Tt.useRef(void 0);n!==void 0&&(S.current=n);let _=t?S.current===!0||S.current===void 0&&s:!0,[k,x]=Tt.useState({api:r,identity:a}),P=a!==void 0&&a!==k.identity;(k.api!==r||P)&&(S.current=void 0,x({api:r,identity:a}),v.current+=1,C.current=0,u(null),l(null),d(!1),f(null),m(!1),y(!0),R(0));let A=Tt.useRef(()=>{}),N=Tt.useRef(null),G=Tt.useCallback(async()=>{if(N.current!==null&&N.current===v.current)return;let j=++v.current;N.current=j;try{let $=await r.getAnalyticsRealtime();if(j!==v.current)return;if($.status==="unreachable"){m(!0),d(!0),y(!1),R(ae=>ae+1);return}C.current=0,m(!1),u($.data.current_visitors),l($.as_of),d(!1),f(null),y(!1),R(ae=>ae+1)}catch($){if(j!==v.current)return;C.current+=1,y(!1),R(ae=>ae+1),d(!0),C.current>=Bi&&f($ instanceof Error?$:new Error("Realtime unavailable"))}finally{N.current===j&&(N.current=null)}},[r]);return A.current=()=>void G(),Tt.useEffect(()=>{let j,$=()=>{j===void 0&&(j=setInterval(()=>A.current(),Oi))},ae=()=>{j!==void 0&&(clearInterval(j),j=void 0)},se=()=>{typeof document<"u"&&document.hidden?ae():(A.current(),$())};return _?((typeof document>"u"||!document.hidden)&&(A.current(),$()),document?.addEventListener("visibilitychange",se),()=>{ae(),document?.removeEventListener("visibilitychange",se),v.current+=1}):()=>{document?.removeEventListener("visibilitychange",se)}},[k.api,k.identity,_]),{currentVisitors:o,asOf:g,isStale:i,error:b,isUnreachable:c,isInitialLoad:p,polls:h}}import*as dt from"react";import*as Kl from"react";import{jsx as Fi,jsxs as Wl}from"react/jsx-runtime";function fm(){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 Ui({value:e,chosen:t,onChange:n}){let s=bs(),a=t===null&&s!==null&&e===s,r=Kl.useMemo(()=>{let o=fm();return o.includes(e)?o:[e,...o]},[e]);return Wl("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[Fi("span",{className:"af-sr-only",children:"Reporting timezone"}),Wl("select",{value:a?"":e,onChange:o=>n(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[Fi("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(o=>Fi("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var $r=(e,{published:t}={})=>{let n=t===!1,s=e!=null&&(!e.collecting||n&&e.first_seen===null&&!e.first_seen_unavailable),a=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=a||r;return{notCollecting:s,awaitingFirstVisit:a,firstVisitTooRecent:r,holdingForFirstData:o,nothingToReport:s||o}};import*as Ds from"react";var mm=3e4;function Vr({status:e,holdingForFirstData:t,refetchStatus:n,refetch:s}){Ds.useEffect(()=>{if(!t)return;let r,o=()=>{r===void 0&&(r=setInterval(()=>void n(),mm))},u=()=>{r!==void 0&&(clearInterval(r),r=void 0)},g=()=>{typeof document<"u"&&document.hidden?u():(n(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",g),()=>{u(),document?.removeEventListener("visibilitychange",g)}},[t,n]);let a=Ds.useRef(void 0);Ds.useEffect(()=>{if(!e){a.current=void 0;return}let r=a.current;a.current=t,r===!0&&!t&&s()},[e,t,s])}import*as qn from"react";var pm=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Zt(e){let t=Math.abs(e);if(t<1e3)return String(e);let n=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[s,a]of n)if(t>=s){let r=e/s,o=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(o)>=1e3&&s!==1e9?Zt(o*s):`${o}${a}`}return String(e)}function ms(e){return`${(e*100).toFixed(1)}%`}function Ls(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`}function Jl(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`:Ls(t)}function Yl(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Xl(e,t){if(!(!Number.isFinite(e)||e<=0))for(let n of t){let s=Math.ceil(e/n);if(s<=5)return Array.from({length:s+1},(a,r)=>Number((r*n).toPrecision(12)))}}function Os(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Ql(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 Mi(e){let t=Number(e.slice(5,7)),n=Number(e.slice(8,10));return`${pm[t-1]} ${n}`}function Zl(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function gm(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function ec(e,t,n="UTC"){let s=new Map(t.map(o=>[o.date,o])),a=[],r=Zl(e.to,n);for(let o=Zl(e.from,n);o<r;o=gm(o))a.push(s.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return a}function tc(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=new Date(`${e}T00:00:00Z`);if(Number.isNaN(s.getTime()))return e;let a=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${a} ${n[s.getUTCMonth()]}`}import{Fragment as bm,jsx as En,jsxs as vm}from"react/jsx-runtime";function ac({what:e="This report",onRetry:t,collecting:n}){return vm("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:[En("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),En("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:n===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),t?En("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 Hr({what:e="No data"}){return En("div",{className:"af-flex af-items-center af-justify-center af-rounded-md af-px-4 af-py-8 af-text-center af-text-xs af-text-muted-foreground",children:e})}function bn({sourced:e,error:t,isLoading:n,what:s,onRetry:a,collecting:r,children:o}){return n?En("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?En(ac,{what:s,onRetry:a,collecting:r}):!e||e.status==="unreachable"?En(ac,{what:s,onRetry:a,collecting:r}):En(bm,{children:o(e.data)})}import{Fragment as ym,jsx as da,jsxs as zn}from"react/jsx-runtime";function $i({rows:e,dimension:t,metric:n,metricLabel:s,secondary:a,emptyCopy:r="No data for this period",onFilter:o,canFilter:u,maxRows:g=9}){let[l,i]=qn.useState(!1);if(e.length===0)return da(Hr,{what:r});let d=e.reduce((c,m)=>Math.max(c,Number(m[n]??0)),0)||1,b=Math.max(0,e.length-g),f=l?e:e.slice(0,g);return zn(ym,{children:[zn("table",{className:"af-w-full af-text-sm",children:[da("thead",{children:zn("tr",{className:"af-text-xs af-text-muted-foreground",children:[da("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),da("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),da("tbody",{children:f.map((c,m)=>{let p=Number(c[n]??0),y=c[t]??null,h=Os(y),R=a?c[a]:null,C=y!==null&&(u?u(y,R):!0);return zn("tr",{className:"af-border-t af-border-border",children:[zn("td",{className:"af-relative af-py-1.5 af-pr-2",children:[da("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,p/d*100)}%`}}),y!==null&&o&&C?da("button",{type:"button",onClick:()=>o(y,R),title:`Filter by ${h}`,"aria-label":`Filter by ${h}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:h}):da("span",{className:"af-relative af-break-words af-text-foreground",children:h}),R?da("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:R}):null]}),da("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Zt(p)})]},`${h}-${R??""}-${m}`)})})]}),b>0?da("button",{type:"button",onClick:()=>i(c=>!c),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length}`}):null]})}function Bs({title:e,tabs:t,defaultTabId:n,headerRight:s}){let[a,r]=qn.useState(n),o=t.find(f=>f.id===a)??t[0],u=qn.useId(),g=f=>`${u}-tab-${f}`,l=f=>`${u}-panel-${f}`,i=qn.useRef(null),d=(f,c)=>{f.preventDefault();let m=(c+t.length)%t.length;r(t[m].id),i.current?.querySelectorAll('[role="tab"]')?.[m]?.focus()};return zn("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[zn("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:[da("div",{ref:i,role:"tablist","aria-label":e,onKeyDown:f=>{let c=t.findIndex(m=>m.id===a);f.key==="ArrowRight"&&d(f,c+1),f.key==="ArrowLeft"&&d(f,c-1),f.key==="Home"&&d(f,0),f.key==="End"&&d(f,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(f=>da("button",{id:g(f.id),role:"tab",type:"button","aria-selected":f.id===a,"aria-controls":l(f.id),tabIndex:f.id===a?0:-1,onClick:()=>r(f.id),className:f.id===a?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:f.label},f.id))}),s]}),o?da("div",{id:l(o.id),role:"tabpanel","aria-labelledby":g(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}import*as fa from"react";import*as In from"@radix-ui/react-popover";var ps=3,gs=100;import{jsx as bt,jsxs as on}from"react/jsx-runtime";var Fs={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"},hm=Object.keys(Fs);function nc(e){let t=Fs[e.dimension],n=e.operator==="is_not"?"is not":"is",s=e.values.map(a=>Os(a)).join(" or ");return`${t} ${n} ${s}`}function Vi(e,t){let n=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));if(n>=0){let s=[...new Set([...e[n].values,...t.values])];return s.length>100||s.length===e[n].values.length?e:e.map((a,r)=>r===n?{...a,values:s}:a)}return t.values.length>100||e.length>=3?e:[...e,t]}function xm(e,t){let n={};for(let[s,a]of Object.entries(t)){let r=e.get(s)??new Set;for(let o of a)r.add(o);e.set(s,r),n[s]=[...r]}return n}function sc(e,t){let n=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));return n>=0?e.map((s,a)=>a===n?t:s):t.values.length>100||e.length>=3?e:[...e,t]}function wm(e){return{dimension:e,operator:"is",search:"",picked:[]}}function rc(e,t,n,s={}){if(e.api!==t.api||e.period!==t.period)return e.api=t.api,e.period=t.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let a=xm(e.byDimension,n);for(let[r,o]of Object.entries(s)){let u=e.foldsByLabel.get(r)??new Set;for(let g of o)u.add(g);e.foldsByLabel.set(r,u)}return{suggestions:a,folds:new Map([...e.foldsByLabel].map(([r,o])=>[r,[...o]]))}}function ic(e){let{filters:t,onChange:n}=e,s=t.length>=3;return fa.useEffect(()=>{if(t.length===0)return;let a=r=>{let o=r.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||r.key==="Escape"&&n([])};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[t.length,n]),on("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((a,r)=>on("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:[bt("span",{className:"af-text-foreground",children:nc(a)}),bt("button",{type:"button","aria-label":`Remove filter ${nc(a)}`,onClick:()=>n(t.filter((o,u)=>u!==r)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${a.dimension}-${a.operator??"is"}`)),bt(Sm,{...e,disabled:s}),t.length>0?bt("button",{type:"button",onClick:()=>n([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Sm({filters:e,onChange:t,suggestions:n,resetKey:s,disabled:a,expandValues:r}){let[o,u]=fa.useState(!1),g=fa.useRef(null),[l,i]=fa.useState(null);fa.useEffect(()=>{i(g.current?.closest(".aifeatures-admin")??null)},[]);let[d,b]=fa.useState(null),[f,c]=fa.useState("is"),[m,p]=fa.useState(""),[y,h]=fa.useState([]);fa.useEffect(()=>{o||(b(null),c("is"),p(""),h([]))},[o]);let R=fa.useRef(s);R.current!==s&&(R.current=s,o&&u(!1),d!==null&&b(null),y.length>0&&h([]),m!==""&&p(""),f!=="is"&&c("is"));let C=P=>{let A=wm(P);b(A.dimension),h(A.picked),p(A.search),c(A.operator)},S=(d?n[d]??[]:[]).filter(P=>P.toLowerCase().includes(m.trim().toLowerCase())),_=d===null||y.length===0?null:Vi(e,{dimension:d,operator:f,values:r?r(d,y):y}),k=_!==null&&_!==e,x=()=>{let P=_;!P||P===e||(t(P),u(!1))};return on(In.Root,{open:o,onOpenChange:u,children:[bt(In.Trigger,{asChild:!0,children:bt("button",{ref:g,type:"button",disabled:!1,title:a?`At most ${3} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),bt(In.Portal,{container:l,children:bt(In.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:d===null?on("div",{children:[bt("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),bt("div",{className:"af-max-h-96 af-overflow-y-auto",children:hm.filter(P=>n[P]!==void 0).map(P=>{let A=n[P]?.length??0,N=!e.some(G=>G.dimension===P)&&e.length>=3;return on("button",{type:"button",onClick:()=>C(P),disabled:A===0||N,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:[bt("span",{children:Fs[P]}),bt("span",{className:"af-text-muted-foreground",children:A===0?"no data":N?"no room":A})]},P)})})]}):on("div",{children:[on("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[bt("button",{type:"button",onClick:()=>C(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),bt("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Fs[d]}),on("select",{"aria-label":"Operator",value:f,onChange:P=>c(P.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[bt("option",{value:"is",children:"is"}),bt("option",{value:"is_not",children:"is not"})]})]}),bt("input",{type:"text",value:m,onChange:P=>p(P.target.value),placeholder:"Search\u2026","aria-label":`Search ${Fs[d]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),bt("div",{className:"af-max-h-48 af-overflow-y-auto",children:S.length===0?on("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",m,"\u201D."]}):S.map(P=>on("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:[bt("input",{type:"checkbox",checked:y.includes(P),disabled:!y.includes(P)&&y.length>=100,onChange:A=>h(N=>A.target.checked?[...N,P]:N.filter(G=>G!==P))}),bt("span",{className:"af-break-all",children:Os(P)})]},P))}),bt("button",{type:"button",onClick:x,disabled:!k,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:y.length<=1?"Apply filter":y.length>=100?`Apply filter (${y.length} values \u2014 the maximum)`:`Apply filter (${y.length} values)`})]})})})]})}import{Fragment as _m,jsx as Jt,jsxs as zr}from"react/jsx-runtime";var Nm=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Zt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Zt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Zt,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:ms,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Ls,chart:"visit_duration_seconds"}];function Rm({current:e,previous:t,downIsGood:n}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let a=s>0,r=n?!a:a,o=`${a?"+":""}${(s*100).toFixed(1)}%`;return Jt("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 oc({summary:e,selected:t,onSelect:n}){return Jt("div",{className:"af-@container",children:Jt("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Nm.map(s=>{let a=s.chart===t,r=n!==void 0,o=zr(_m,{children:[Jt("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),zr("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Jt("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?Jt(Rm,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?Jt("button",{type:"button","aria-pressed":a,onClick:()=>n(s.chart),className:a?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:o},s.key):Jt("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},s.key)})})})}function Hi({currentVisitors:e,asOf:t,isStale:n,isUnreachable:s,isInitialLoad:a=!1,scopeIsSiteWide:r=!1}){if(a&&!s)return zr("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:[Jt("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Jt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return Jt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?Ql(t):"freshness unknown",u=r?" across the whole site, not the current filter,":"",g=n?`${e} current visitors${u} ${o} (not updating)`:`${e} current visitors${u} ${o}`;return zr("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:g,children:[Jt("span",{"aria-hidden":"true",className:n?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),Jt("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Jt("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),Jt("span",{className:"af-sr-only",children:g})]})}import*as cc from"react";import{Star as Pm}from"lucide-react";import{Fragment as lc,jsx as At,jsxs as jn}from"react/jsx-runtime";function qr(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function jr({rows:e,denominator:t,windowPrecedesCollection:n=!1,coverageUnknown:s=!1,emptyCopy:a="No conversions in this period",maxRows:r=9,primaryConversion:o}){let[u,g]=cc.useState(!1),l=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||qr(p,o)),i=n?At("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?At("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 jn(lc,{children:[At(Hr,{what:a}),i]});let d=l.slice(0,r),b=o?l.find(p=>qr(p,o)):void 0,f=b&&!d.includes(b)?l.filter(p=>d.includes(p)||p===b).slice(0,Math.max(0,r-1)).concat(b):d,c=u?e:f,m=Math.max(0,e.length-f.length);return jn(lc,{children:[jn("table",{className:"af-w-full af-text-sm",children:[At("thead",{children:jn("tr",{className:"af-text-xs af-text-muted-foreground",children:[At("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),At("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),At("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),At("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),At("tbody",{children:c.map((p,y)=>jn("tr",{className:"af-border-t af-border-border","aria-current":qr(p,o)?"true":void 0,children:[At("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:qr(p,o)?jn("span",{className:"af-flex af-items-center af-gap-1.5",children:[At(Pm,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),At("span",{className:"af-font-medium af-text-foreground",children:p.goal}),At("span",{className:"af-sr-only",children:"(your main conversion)"})]}):p.goal}),At("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Zt(p.visitors)}),At("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Zt(p.events)}),At("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:p.conversion_rate===null?At("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):ms(p.conversion_rate)})]},`${p.goal}-${y}`))})]}),m>0?At("button",{type:"button",onClick:()=>g(p=>!p),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:u?"Show fewer":`Show all ${e.length} goals`}):null,jn("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Zt(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),i]})}import{Area as Cm,AreaChart as Tm,CartesianGrid as km,ResponsiveContainer as Em,Tooltip as Im,XAxis as Am,YAxis as Dm}from"recharts";import{jsx as Yt,jsxs as Us}from"react/jsx-runtime";var Gr={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},qi={visitors:Zt,visits:Zt,pageviews:Zt,views_per_visit:e=>e.toFixed(2),bounce_rate:ms,visit_duration_seconds:Ls},Lm=31,Om=new Set(["visitors","visits","pageviews"]),Bm={...qi,bounce_rate:Yl,visit_duration_seconds:Jl},zi=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Fm=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Um=[.01,.02,.05,.1,.2,.25,.5,1],Mm=[.25,.5,1,2,5,10,25,50],$m={visitors:zi,visits:zi,pageviews:zi,views_per_visit:Mm,bounce_rate:Um,visit_duration_seconds:Fm};function Vm({active:e,payload:t,label:n,metric:s}){if(!e||!t||t.length===0)return null;let a=t[0].payload;return Us("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:[Yt("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Gr[s]}),Us("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[Yt("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),Yt("span",{className:"af-text-muted-foreground",children:tc(String(n))}),Yt("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:qi[s](Number(a[s]??0))})]})]})}function Wr({rows:e,window:t,metric:n,timeZone:s="UTC",height:a=260}){let r=ec(t,e,s),o=qi[n],u=Bm[n],g=Xl(r.reduce((i,d)=>Math.max(i,Number(d[n]??0)),0),$m[n]),l=`${Gr[n]} by day: ${r.map(i=>`${Mi(i.date)}: ${o(Number(i[n]??0))}`).join("; ")}.`;return Us("figure",{"aria-label":`${Gr[n]} over time`,className:"af-m-0",children:[Yt(Em,{width:"100%",height:a,children:Us(Tm,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[Yt("defs",{children:Us("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[Yt("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),Yt("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),Yt(km,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Yt(Am,{dataKey:"date",tickFormatter:Mi,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Yt(Dm,{allowDecimals:!Om.has(n),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...g?{ticks:g,domain:[0,g[g.length-1]]}:{},tickFormatter:i=>u(i),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Yt(Im,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Yt(Vm,{metric:n})}),Yt(Cm,{type:"linear",dataKey:n,name:Gr[n],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=Lm?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),Yt("figcaption",{className:"af-sr-only",children:l})]})}import{Fragment as ji,jsx as Se,jsxs as qt}from"react/jsx-runtime";var Hm="2026-08-13",zm=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],qm=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function jm({filters:e,onFiltersChange:t,refreshKey:n,onBackToWebsite:s,primaryConversion:a,className:r,published:o,lastPublishedAt:u}){let[g,l]=dt.useState(30),[i,d]=dt.useState(()=>ei()),b=e!==void 0&&t!==void 0,[f,c]=dt.useState(e??[]),{api:m}=Q(),[p,y]=dt.useState(m);p!==m&&(y(m),!b&&f.length>0&&c([]));let h=b?e:f,R=dt.useCallback(O=>{t&&t(O),b||c(O)},[t,b]),C=dt.useCallback((O,me,ve)=>{let Pe=Array.isArray(me)?me:[me];if(Pe.length===0)return null;let Oe=Vi(h,{dimension:O,operator:"is",values:Pe});if(ve&&(!ve.value||(Oe=sc(Oe,{dimension:ve.dimension,operator:"is",values:[ve.value]}),!Oe.find(mt=>mt.dimension===ve.dimension&&mt.operator!=="is_not")?.values.includes(ve.value))))return null;let st=Oe.find(Be=>Be.dimension===O&&Be.operator!=="is_not");return Pe.every(Be=>st?.values.includes(Be))?JSON.stringify(Oe)===JSON.stringify(h)?null:Oe:null},[h]),v=dt.useCallback((O,me,ve)=>C(O,me,ve)!==null,[C]),S=dt.useCallback((O,me,ve)=>{let Pe=C(O,me,ve);Pe&&R(Pe)},[C,R]),[_,k]=dt.useState("visitors"),x=fs(g,{refreshKey:n,breakdowns:qm,filters:h}),P=x.status.data,A=x.reportedZone??P?.timezone,N=A??i??bs()??"UTC",{notCollecting:G,awaitingFirstVisit:j,firstVisitTooRecent:$,holdingForFirstData:ae}=$r(P,{published:o}),se=o===!1,de=Mr({collecting:j||G?!1:P?.collecting,statusFailed:x.status.error!=null,identity:P?.analytics_id}),U=dt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),Z=dt.useMemo(()=>{let O=x.breakdowns.sources?.data,me={};if(!O||O.status!=="ok")return me;for(let ve of O.data){let Pe=ve.source,Oe=ve.sources;typeof Pe=="string"&&Array.isArray(Oe)&&Oe.length>0&&(me[Pe]=Oe)}return me},[x.breakdowns.sources?.data]),B=dt.useMemo(()=>{let O=(Pe,Oe)=>{let st=x.breakdowns[Pe]?.data;return!st||st.status!=="ok"?[]:[...new Set(st.data.map(Be=>Be[Oe]).filter(Be=>typeof Be=="string"&&Be!==""))]};return{channel:x.channels.data?.status==="ok"?[...new Set(x.channels.data.data.map(Pe=>Pe.channel))]:[],source:O("sources","source"),campaign:O("utm/campaign","campaign"),page:O("pages","pathname"),entry_page:O("entry-pages","pathname"),exit_page:O("exit-pages","pathname"),country:O("countries","country"),browser:O("browsers","browser"),os:O("operating-systems","os"),device:O("devices","device")}},[x.breakdowns,x.channels.data]),[ye,re]=dt.useState({}),Xe=JSON.stringify(B),[he,Ue]=dt.useState(new Map),Ze=JSON.stringify(Z);dt.useEffect(()=>{let{suggestions:O,folds:me}=rc(U.current,{api:m,period:g},JSON.parse(Xe),JSON.parse(Ze));re(O),Ue(me)},[Xe,Ze,m,g]);let Ee=dt.useCallback((O,me)=>O!=="source"?me:[...new Set(me.flatMap(ve=>{let Pe=[...he.get(ve)??[],...Z[ve]??[]];return Pe.length>0?Pe:[ve]}))],[he,Z]),kt=dt.useMemo(()=>{let O=x.conversions.error;return O instanceof St&&O.details?.code==="goals_exceed_report_budget"?O.message:null},[x.conversions.error]),E=dt.useMemo(()=>{let O=[x.summary,x.timeseries,x.channels,...Object.values(x.breakdowns)];for(let me of O){let ve=me?.error;if(ve instanceof St&&ve.details?.code==="filter_unsupported")return ve.message}return null},[x.summary,x.timeseries,x.channels,x.breakdowns]),F=(O,me,ve,Pe,Oe,st,Be,mt,oe)=>()=>{let Ce=x.breakdowns[O];return Se(bn,{sourced:Ce?.data??null,error:Ce?.error,isLoading:Ce?.isLoading,what:me,collecting:P?.collecting,onRetry:x.refetch,children:rt=>{let ma=Lt=>mt?Ee(mt,[Lt]):Lt;return Se($i,{rows:rt,dimension:ve,metric:Pe,metricLabel:Oe,secondary:st,emptyCopy:h.length>0?"No data for this filter":Be,canFilter:mt?(Lt,Xt)=>v(mt,ma(Lt),oe?{dimension:oe,value:Xt}:void 0):()=>!1,onFilter:mt?(Lt,Xt)=>S(mt,ma(Lt),oe?{dimension:oe,value:Xt}:void 0):void 0})}})};if(Vr({status:P,holdingForFirstData:ae,refetchStatus:x.refetchStatus,refetch:x.refetch}),G){let O=!!u&&String(u).slice(0,10)<Hm;return Se(Rt,{title:"Analytics",onBackToWebsite:s,className:r,children:qt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Se("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),Se("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:se?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":O?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return j?Se(Rt,{title:"Analytics",onBackToWebsite:s,className:r,children:qt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Se("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),Se("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."})]})}):$?qt(Rt,{title:"Analytics",onBackToWebsite:s,className:r,children:[Se("div",{className:"af-mb-3 af-flex af-justify-end",children:Se(Ui,{value:N,chosen:i,onChange:O=>{ti(O),d(O)}})}),qt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Se("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),qt("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",P?.timezone?` ${P.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),Se("div",{className:"af-mt-4 af-flex af-justify-center",children:Se(Hi,{currentVisitors:de.currentVisitors,asOf:de.asOf,isStale:de.isStale,isUnreachable:de.isUnreachable||de.error!==null,isInitialLoad:de.isInitialLoad})})]})]}):Se(Rt,{title:"Analytics",onBackToWebsite:s,className:r,children:qt("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[qt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Se("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:zm.map(O=>Se("button",{type:"button","aria-pressed":O.value===g,onClick:()=>l(O.value),className:O.value===g?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:O.label},O.value))}),Se(Ui,{value:N,chosen:i,onChange:O=>{ti(O),d(O)}}),Se(Hi,{currentVisitors:de.currentVisitors,asOf:de.asOf,isStale:de.isStale,isUnreachable:de.isUnreachable||de.error!==null,isInitialLoad:de.isInitialLoad,scopeIsSiteWide:h.length>0})]}),Se(ic,{filters:h,onChange:R,suggestions:ye,expandValues:Ee,resetKey:m}),E?qt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Se("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),Se("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:E}),Se("button",{type:"button",onClick:()=>R([]),className:"af-mt-4 af-rounded-md af-border af-border-border af-px-3 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Clear filters"})]}):null,!E&&P?.timezone_defaulted?Se("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,E?null:qt(ji,{children:[Se(bn,{sourced:x.summary.data,error:x.summary.error,isLoading:x.summary.isLoading,what:"The traffic summary",collecting:P?.collecting,onRetry:x.refetch,children:O=>qt(ji,{children:[Se(oc,{summary:O,selected:_,onSelect:k}),O.previous_unavailable?qt("p",{className:"af-text-xs af-text-muted-foreground",children:[O.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]})}),Se("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:Se(bn,{sourced:x.timeseries.data,error:x.timeseries.error,isLoading:x.timeseries.isLoading,what:"The visitors chart",collecting:P?.collecting,onRetry:x.refetch,children:O=>{let me=x.timeseries.data?.status==="ok"?x.timeseries.data.window:{from:"",to:""};return Se(Wr,{rows:O,window:me,metric:_,timeZone:A??"UTC"})}})}),qt("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[Se(Bs,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>Se(bn,{sourced:x.channels.data,error:x.channels.error,isLoading:x.channels.isLoading,what:"Channels",collecting:P?.collecting,onRetry:x.refetch,children:O=>Se($i,{rows:O,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:h.length>0?"No data for this filter":"No data for this period",canFilter:me=>v("channel",me),onFilter:me=>S("channel",me)})})},{id:"sources",label:"Sources",render:F("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:F("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),Se(Bs,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:F("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:F("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:F("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),Se(Bs,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:F("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:F("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:F("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),Se(Bs,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:F("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:F("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:F("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),qt("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[Se("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:Se("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),qt("div",{className:"af-px-3 af-py-2",children:[h.length>0?qt("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",h.length===1?"filter":"filters"," above."]}):null,kt!==null?qt("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:[Se("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),Se("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:kt})]}):Se(bn,{sourced:x.conversions.data,error:x.conversions.error,isLoading:x.conversions.isLoading,what:"Conversions",collecting:P?.collecting,onRetry:x.refetch,children:O=>{let me=x.conversions.data?.status==="ok"?x.conversions.data:null;return Se(ji,{children:Se(jr,{rows:O,primaryConversion:a,denominator:me?.denominator??0,windowPrecedesCollection:me?.window_precedes_collection??!1,coverageUnknown:me?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import*as yc from"react";import{Phone as gc,Mail as Wi,ShoppingBag as Zm,ExternalLink as Jm,MessageCircle as Ym,Download as Xm,Target as hc}from"lucide-react";import*as Ba from"react";import{Check as Gi,ChevronLeft as Gm,Loader2 as uc}from"lucide-react";import{jsx as We,jsxs as Dt}from"react/jsx-runtime";var dc=90,fc=100;function Wm(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function mc(e){return!!e.label&&e.label!==e.target}function Km(e,t,n){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:s,with_a_value:a}=t;return s===0?e===0?"Nothing specific has converted here yet.":null:a===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":a<s?n?`These cover ${a.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${a.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function Ms(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function pc({current:e,onChange:t,onClose:n}){let{api:s}=Q(),[a,r]=Ba.useState(null),[o,u]=Ba.useState(!1),[g,l]=Ba.useState({at:"goals"}),[i,d]=Ba.useState(null),[b,f]=Ba.useState(null),[c,m]=Ba.useState(!1),[p,y]=Ba.useState(null),h=Ba.useRef(0);Ba.useEffect(()=>{let S=!0;return r(null),u(!1),l({at:"goals"}),d(null),f(null),m(!1),y(null),h.current+=1,s.getAnalyticsConversions(dc).then(_=>{if(S){if(_.status!=="ok"){u(!0);return}r(_.data)}}).catch(()=>{S&&u(!0)}),()=>{S=!1}},[s]);let R=S=>{l({at:"targets",row:S}),d(null),f(null),m(!1),y(null);let _=++h.current;s.getAnalyticsGoalTargets(S.goal,dc,fc).then(k=>{if(_===h.current){if(k.status!=="ok"){f("failed");return}d(k.data),m(k.truncated===!0),y(k.coverage??null)}}).catch(k=>{if(_!==h.current)return;let x=k instanceof St?k.details?.code:void 0;f(x==="goal_has_no_targets"?"no-values":"failed")})},C=S=>{t(S),n()};if(o)return We("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 Dt("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[We(uc,{className:"af-h-4 af-w-4 af-animate-spin"}),We("span",{children:"Loading your conversions\u2026"})]});if(g.at==="targets"){let S=g.row,_=new Map;for(let k of i??[])_.set(k.label,(_.get(k.label)??0)+1);return Dt("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:[We("header",{className:"af-flex af-items-center af-gap-1",children:Dt(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>l({at:"goals"}),children:[We(Gm,{className:"af-h-4 af-w-4"}),We("span",{children:"All conversions"})]})}),Dt("button",{type:"button","aria-current":e&&Ms(S,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>C({goal:S.goal,implicit:S.implicit}),children:[e&&Ms(S,e)&&!e.target&&We(Gi,{className:"af-h-4 af-w-4 af-shrink-0"}),Dt("span",{children:["Any ",S.goal.toLowerCase()]})]}),b==="no-values"&&We("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"&&Dt("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[We("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),We(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(S),children:"Try again"})]}),!i&&b===null&&Dt("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:[We(uc,{className:"af-h-4 af-w-4 af-animate-spin"}),We("span",{children:"Loading\u2026"})]}),i&&We("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Km(i.length,p,c)}),c&&Dt("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",fc,". If what you want isn\u2019t here, pick the conversion itself instead."]}),i?.some(mc)&&We("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(k=>{let x=!!(e&&Ms(S,e)&&e.target===k.target),P=_.get(k.label)>1;return mc(k)?Dt("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:[Dt("span",{className:"af-min-w-0",children:[We("span",{className:"af-block af-truncate",children:k.label}),P&&We("span",{className:"af-block af-truncate af-text-xs",children:k.target})]}),We("span",{className:"af-shrink-0 af-text-xs",children:k.visitors.toLocaleString()})]},k.target):Dt("button",{type:"button","aria-current":x?"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:()=>C({goal:S.goal,implicit:S.implicit,target:k.target,...k.label&&k.label!==k.target?{label:k.label}:{}}),children:[Dt("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[x&&We(Gi,{className:"af-h-4 af-w-4 af-shrink-0"}),Dt("span",{className:"af-min-w-0",children:[We("span",{className:"af-block af-truncate",children:k.label}),P&&We("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:k.target})]})]}),We("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:k.visitors.toLocaleString()})]},k.target)})]})}let v=e?.goal&&!a.some(S=>Ms(S,e));return Dt("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[v&&Dt("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&&We("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(S=>{let _=e?Ms(S,e):!1;return Dt("div",{className:"af-flex af-items-center af-gap-1",children:[Dt("button",{type:"button","aria-current":_?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>C({goal:S.goal,implicit:S.implicit}),children:[Dt("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[_&&We(Gi,{className:"af-h-4 af-w-4 af-shrink-0"}),We("span",{className:"af-truncate",children:S.goal})]}),We("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:S.visitors.toLocaleString()})]}),Wm(S)&&We(w,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${S.goal}`,onClick:()=>R(S),children:"Narrow"})]},S.goal)}),e?.goal&&We("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:()=>C(null),children:"No main conversion"})]})}import{Fragment as ap,jsx as Gn,jsxs as bc}from"react/jsx-runtime";function Qm(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let n of t)try{let{hostname:s}=new URL(n);if(s)return s.toLowerCase().replace(/^www\./,"")}catch{}return null}function ep(e){if(Ki(e,"whatsapp"))return!0;let t=Qm(e);return t===null?!1:["wa.me","whatsapp.com"].some(n=>t===n||t.endsWith(`.${n}`))}function Ki(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var vc=[{goal:"Contact",target:e=>Ki(e,"tel"),icon:gc,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Ki(e,"mailto"),icon:Wi,line:"This site is set up to get you emails."},{goal:"Contact",icon:gc,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>ep(e),icon:Ym,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:Jm,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Wi,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Wi,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:Zm,line:"This site is set up to sell."},{goal:"File Download",icon:Xm,line:"This site is set up to get your file downloaded."}];function xc(e){let{goal:t,target:n}=e;return e.implicit!==!0?null:(n?vc.find(a=>a.goal===t&&a.target?.(n)):void 0)??vc.find(a=>a.goal===t&&!a.target)??null}function tp(e){return xc(e)?.icon??hc}function wc({primaryConversion:e,onChange:t}){let[n,s]=yc.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?xc(e):null,o=e?.label?.trim(),u=e?tp(e):hc,g=e?.goal?o?`Your main conversion is ${o}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",l=bc(ap,{children:[Gn(u,{className:"af-h-4 af-w-4 af-shrink-0"}),Gn("span",{children:g})]});return t?bc(dr,{open:n,onOpenChange:s,children:[Gn(fr,{asChild:!0,children:Gn("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})}),Gn(Ps,{align:"start",className:"af-w-80 af-p-1",children:n&&Gn(pc,{current:e,onChange:t,onClose:()=>s(!1)})})]}):Gn("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:l})}import{Fragment as np,jsx as An,jsxs as Kr}from"react/jsx-runtime";function Sc({refreshKey:e,onViewAll:t,primaryConversion:n}){let s=fs(7,{refreshKey:e,breakdowns:[]}),a=s.status.data??void 0,{nothingToReport:r,notCollecting:o,holdingForFirstData:u}=$r(a);return Vr({status:a,holdingForFirstData:u,refetchStatus:s.refetchStatus,refetch:s.refetch}),Kr("section",{className:"af-rounded-md af-border af-p-3",children:[Kr("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[An("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&An(w,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?An("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."}):Kr(np,{children:[An(bn,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:a?.collecting,onRetry:s.refetch,children:g=>{let l=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return An(Wr,{rows:g,window:l?.window??{from:"",to:""},metric:"visitors",timeZone:l?.timezone,height:140})}}),Kr("div",{className:"af-mt-3",children:[An("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),An(bn,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:a?.collecting,onRetry:s.refetch,children:g=>{let l=s.conversions.data?.status==="ok"?s.conversions.data:null;return An(jr,{rows:g,primaryConversion:n,denominator:l?.denominator??0,windowPrecedesCollection:l?.window_precedes_collection??!1,coverageUnknown:l?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as Wa,jsxs as $s}from"react/jsx-runtime";var Zi=5;function Ji({title:e,viewAllLabel:t,onViewAll:n}){return $s("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Wa("h3",{className:"af-text-sm af-font-medium",children:e}),n&&Wa(w,{type:"button",variant:"ghost",size:"sm",onClick:n,children:t})]})}function sp({refreshKey:e,onBackToWebsite:t,primaryConversion:n,onChangePrimaryConversion:s,onOpenSurface:a,needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:u}){let g=is({refreshKey:e}),l=(g.summary?.products.count??0)>0||(g.summary?.commerce?.storefront_orders??!1),i=l||(g.summary?.commerce?.invoicing??!1);return Wa(Rt,{title:"Dashboard",onBackToWebsite:t,children:$s("div",{className:"af-flex af-flex-col af-gap-4",children:[Wa(wc,{primaryConversion:n,onChange:s}),Wa(Sc,{refreshKey:e,onViewAll:a&&(()=>a("analytics")),primaryConversion:n}),$s("section",{className:"af-rounded-md af-border af-p-3",children:[Wa(Ji,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:a&&(()=>a("leads"))}),Wa(Dr,{refreshKey:e,maxRows:Zi,onViewAll:a&&(()=>a("leads"))})]}),l&&$s("section",{className:"af-rounded-md af-border af-p-3",children:[Wa(Ji,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:a&&(()=>a("orders"))}),Wa(Rn,{refreshKey:e,maxRows:Zi,onViewAll:a&&(()=>a("orders"))})]}),i&&$s("section",{className:"af-rounded-md af-border af-p-3",children:[Wa(Ji,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:a&&(()=>a("invoices"))}),Wa(Pn,{refreshKey:e,maxRows:Zi,onViewAll:a&&(()=>a("invoices")),needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:u})]})]})})}export{St as AifeaturesApiError,_c as AifeaturesProvider,jm as AnalyticsView,xr as CustomerDetail,wr as CustomersList,sp as DashboardView,$t as ExportCsvButton,sr as FormSettings,er as FormSubmissions,wo as FormsDashboard,js as FormsList,xi as InvoiceDetail,Cs as InvoiceLabelBadge,Ur as InvoiceSettingsPanel,Pn as InvoicesList,Gl as InvoicesView,Dr as LeadsView,ps as MAX_ANALYTICS_FILTERS,gs as MAX_ANALYTICS_FILTER_VALUES,ql as NotificationRecipientsSettings,vr as OrderDetail,Un as OrderStatusBadge,Rn as OrdersList,tl as OrdersView,Xo as PaymentsDashboard,as as PaymentsSetup,cr as ProductSettings,or as ProductsList,cl as ProductsView,Zn as PromosPanel,Bi as REALTIME_FAILURES_BEFORE_ERROR,Oi as REALTIME_POLL_MS,wi as RetainerStatusBadge,ts as RetainersPanel,Vl as StoreSettings,Js as SubmissionDetail,Nl as SubscriptionsView,lr as VariantsEditor,Rt as ViewShell,ar as WebhookDeliveries,nr as WebhookSettings,pn as chargedTotal,ai as createApiClient,q as formatPrice,Ea as isZeroDecimalCurrency,lt as toMajorUnits,Ot as toMinorUnits,Q as useAifeatures,Q as useAifeaturesContext,fs as useAnalytics,is as useBusinessSummary,Qs as useCsvExport,hr as useCustomers,tr as useEventDestinations,Wn as useForms,Qn as useInvoices,ur as useOrders,Sn as usePaymentsStatus,Ir as usePeople,Ar as usePerson,ns as useProducts,Mr as useRealtimeVisitors,ss as useRetainers,kn as useSiteSettings,Ks as useSubmissions,Lr as useSubscriptions};
2
+ import*as as from"react";var bo="aifeatures:analytics:timezone",ho;function pr(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function ql(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function ts(){return yo()??pr()}function yo(){if(ho!==void 0)return ho;try{let e=window.localStorage.getItem(bo);return ql(e)?e:null}catch{return null}}function xo(e){if(!(e!==null&&!ql(e))){ho=e;try{e===null?window.localStorage.removeItem(bo):window.localStorage.setItem(bo,e)}catch{}}}function Wr(e,t){let a=new URLSearchParams({period:String(e)}),s=ts();return s&&a.set("timezone",s),t&&t.length>0&&a.set("filters",JSON.stringify(t)),a.toString()}var Yt=class extends Error{constructor(a,s,n){super(a);this.status=s;this.details=n;this.name="AifeaturesApiError"}};function Gr(e,t){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${t}`}function gr(e,t){let a=t.toString();return a?`${e}?${a}`:e}function jl(e){let t=new URLSearchParams;return e.status&&t.set("status",e.status),e.source&&t.set("source",e.source),e.excludeStatus?.length&&t.set("exclude_status",e.excludeStatus.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),e.from&&t.set("from",e.from),e.to&&t.set("to",e.to),e.unfulfilledOnly&&t.set("unfulfilled_only","true"),t}function Wl(e){let t=new URLSearchParams;return e.statuses?.length&&t.set("status",e.statuses.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),t}function wo(e,t="https://aifeatures.dev"){async function a(n,r={}){let i=`${t}${n}`,l=await fetch(i,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!l.ok){let u;try{u=await l.json()}catch{}throw new Yt(Gr(u?.error,l.status),l.status,u)}if(l.status!==204)return l.json()}async function s(n){let r=await fetch(`${t}${n}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let i;try{i=await r.json()}catch{}throw new Yt(Gr(i?.error,r.status),r.status,i)}return r.blob()}return{async getForms(){return(await a("/api/v1/forms")).forms},async getForm(n){return a(`/api/v1/forms/${n}`)},async createForm(n){return a("/api/v1/forms",{method:"POST",body:JSON.stringify(n)})},async updateForm(n,r){return a(`/api/v1/forms/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(n){await a(`/api/v1/forms/${n}`,{method:"DELETE"})},async getSubmissions(n,r={}){let i=new URLSearchParams;r.limit!==void 0&&i.set("limit",String(r.limit)),r.offset!==void 0&&i.set("offset",String(r.offset));let l=i.toString(),u=`/api/v1/forms/${n}/submissions${l?`?${l}`:""}`;return a(u)},async getSubmission(n){return a(`/api/v1/submissions/${n}`)},async exportSubmissionsCsv(n,r={}){let i=new URLSearchParams;return r.includeSpam&&i.set("include_spam","true"),s(gr(`/api/v1/forms/${encodeURIComponent(n)}/submissions/export`,i))},async deleteSubmission(n){await a(`/api/v1/submissions/${n}`,{method:"DELETE"})},async downloadAttachment(n,r){let i=typeof r=="string"?{name:r}:r,l=i.name,u=i.id??i.name,d=`${t}/api/v1/submissions/${n}/attachments/${encodeURIComponent(u)}`,o=await fetch(d,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok){let m;try{m=await o.json()}catch{}throw new Yt(Gr(m?.error,o.status),o.status,m)}let c=await o.blob(),b=URL.createObjectURL(c),g=document.createElement("a");g.href=b,g.download=l,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(b)},async getSite(n){return a(`/api/v1/sites/${encodeURIComponent(n)}`)},async updateSite(n,r){return a(`/api/v1/sites/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return a("/api/v1/payments/status")},getPromos(n){let r=new URLSearchParams({limit:"10"});return n&&r.set("cursor",n),a(`/api/v1/promos?${r}`)},getPromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}`)},createPromo(n){return a("/api/v1/promos",{method:"POST",body:JSON.stringify(n)})},disablePromo(n){return a(`/api/v1/promos/${encodeURIComponent(n)}/disable`,{method:"POST"})},replacePromo(n,r){return a(`/api/v1/promos/${encodeURIComponent(n)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(n={}){let r=new URLSearchParams;n.include&&r.set("include",n.include);let i=r.toString();return(await a(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(n){return a(`/api/v1/products/${n}`)},async createProduct(n){return a("/api/v1/products",{method:"POST",body:JSON.stringify(n)})},async updateProduct(n,r){return a(`/api/v1/products/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(n){await a(`/api/v1/products/${n}`,{method:"DELETE"})},async attachProductFile(n,r){let i=new FormData;i.append("file",r);let l=await fetch(`${t}/api/v1/products/${n}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!l.ok){let u;try{u=await l.json()}catch{}throw new Yt(Gr(u?.error,l.status),l.status,u)}return l.json()},async attachProductFileFromUrl(n,r){return a(`/api/v1/products/${n}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(n,r){return a(`/api/v1/products/${n}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(n,r){return a(`/api/v1/options/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(n){await a(`/api/v1/options/${n}`,{method:"DELETE"})},async createVariant(n,r){return a(`/api/v1/products/${n}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(n,r){return a(`/api/v1/variants/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(n){await a(`/api/v1/variants/${n}`,{method:"DELETE"})},async setVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(n,r){return a(`/api/v1/variants/${n}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(n={}){let r=new URLSearchParams;n.email?r.set("email",n.email):n.q&&r.set("q",n.q),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(n){return a(`/api/v1/customers/${n}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(n={}){let r=jl(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/orders${i?`?${i}`:""}`)},async exportOrdersCsv(n={}){return s(gr("/api/v1/orders/export",jl(n)))},async getOrder(n){return a(`/api/v1/orders/${n}`)},async getInvoices(n={}){let r=new URLSearchParams;n.labels?.length&&r.set("label",n.labels.join(",")),n.customerEmail&&r.set("customer_email",n.customerEmail),n.customerId&&r.set("customer_id",n.customerId),n.q&&r.set("q",n.q),n.from&&r.set("from",n.from),n.to&&r.set("to",n.to),n.includeAggregates&&r.set("include","aggregates"),n.retainerId&&r.set("retainer_id",n.retainerId),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(n){return a(`/api/v1/invoices/${n}`)},async getInvoicePreview(n){return a(`/api/v1/invoices/${n}/preview`)},async getInvoiceSettings(){return a("/api/v1/invoice-settings")},async getRetainers(n={}){let r=Wl(n);n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/retainers${i?`?${i}`:""}`)},async exportRetainersCsv(n={}){return s(gr("/api/v1/retainers/export",Wl(n)))},async getRetainer(n){return a(`/api/v1/retainers/${n}`)},async resendOrderReceipt(n){await a(`/api/v1/orders/${n}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(n){return a(`/api/v1/orders/${n}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(n,r){return a(`/api/v1/orders/${n}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(n={}){let r=new URLSearchParams;n.status&&r.set("status",n.status),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/subscriptions${i?`?${i}`:""}`)},async exportSubscriptionsCsv(n={}){let r=new URLSearchParams;return n.status&&r.set("status",n.status),s(gr("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let n=new URLSearchParams,r=ts();r&&n.set("timezone",r);let i=n.toString();return a(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(n,r){return a(`/api/v1/analytics/summary?${Wr(n,r)}`)},async getAnalyticsTimeseries(n,r){return a(`/api/v1/analytics/timeseries?${Wr(n,r)}`)},async getAnalyticsRealtime(){return a("/api/v1/analytics/realtime")},async getAnalyticsChannels(n,r){return a(`/api/v1/analytics/channels?${Wr(n,r)}`)},async getAnalyticsConversions(n){return a((()=>{let r=new URLSearchParams({period:String(n)}),i=ts();return i&&r.set("timezone",i),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(n,r,i){let l=new URLSearchParams({goal:n,period:String(r)}),u=ts();return u&&l.set("timezone",u),i!==void 0&&l.set("limit",String(i)),a(`/api/v1/analytics/conversions/targets?${l.toString()}`)},async getAnalyticsBreakdown(n,r,i){let l=n.split("/").map(encodeURIComponent).join("/");return a(`/api/v1/analytics/${l}?${Wr(r,i)}`)},async getBusinessSummary(n){let r=new URLSearchParams;r.set("tz_offset_minutes",String(n.tzOffsetMinutes));let i=ts();return i&&r.set("timezone",i),a(`/api/v1/summary?${r.toString()}`)},async getPeople(n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let i=r.toString();return a(`/api/v1/people${i?`?${i}`:""}`)},async exportPeopleCsv(n={}){let r=new URLSearchParams;return n.since&&r.set("since",n.since),n.q&&r.set("q",n.q),n.source&&r.set("source",n.source),s(gr("/api/v1/people/export",r))},async getPerson(n){return a(`/api/v1/people/${encodeURIComponent(n)}`)},async getEventDestinations(){return(await a("/api/v1/event-destinations")).destinations},async createEventDestination(n){return a("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(n)})},async updateEventDestination(n,r){return a(`/api/v1/event-destinations/${n}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(n){await a(`/api/v1/event-destinations/${n}`,{method:"DELETE"})},async rotateEventDestinationSecret(n){return a(`/api/v1/event-destinations/${n}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(n){return(await a(`/api/v1/event-destinations/${n}/secret`)).secret},async getEventDeliveries(n,r){let i=r===void 0?"":`?limit=${r}`;return(await a(`/api/v1/event-destinations/${n}/deliveries${i}`)).deliveries},async retryEventDelivery(n,r){return a(`/api/v1/event-destinations/${n}/deliveries/${r}/retry`,{method:"POST"})},async getMarketingSettings(n){return a(`${ja(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(`${ja(n)}/contacts${l?`?${l}`:""}`)},async getMarketingContactStats(n){return a(`${ja(n)}/contacts/stats`)},async getMarketingTags(n){return(await a(`${ja(n)}/contact-tags`)).tags},async getEmailDrafts(n,r){let i=r?`?kind=${r}`:"";return(await a(`${ja(n)}/marketing/drafts${i}`)).drafts},async getEmailDraft(n,r){return a(`${ja(n)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(n,r,i){let l=i?.editable?"?mode=editable":"";return a(`${ja(n)}/marketing/drafts/${encodeURIComponent(r)}/preview${l}`)},async getEmailTemplates(n){return(await a(`${ja(n)}/marketing/templates`)).templates},async previewEmailTemplate(n,r,i){let l=i?`?draft_id=${encodeURIComponent(i)}`:"";return a(`${ja(n)}/marketing/templates/${encodeURIComponent(r)}/preview${l}`)},async getBroadcasts(n){return(await a(`${ja(n)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(n,r){return a(`${ja(n)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getWelcomeSequence(n){return a(`${ja(n)}/marketing/welcome`)},async getRecoveryFlow(n){return a(`${ja(n)}/marketing/recovery`)}}}function ja(e){return`/api/v1/sites/${encodeURIComponent(e)}`}import{jsx as vr,jsxs as Vu}from"react/jsx-runtime";var Gl=as.createContext(null);function Uu(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 $u({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:n}){let r=as.useMemo(()=>Uu(e),[e]),i=as.useMemo(()=>wo(e,t),[e,t]),l=as.useMemo(()=>({siteToken:e,apiUrl:t,api:i}),[e,t,i]);return r?vr("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:Vu("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[vr("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),vr("p",{className:"af-text-sm af-text-destructive",children:r})]})}):vr(Gl.Provider,{value:l,children:vr("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:n})})}function H(){let e=as.useContext(Gl);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as Yn from"react";import{ArrowLeft as Zf,Settings as Yf,Inbox as Jf}from"lucide-react";import*as Kr from"react";import*as hn from"@radix-ui/react-tabs";import{clsx as Hu}from"clsx";import{extendTailwindMerge as zu}from"tailwind-merge";var qu=zu({prefix:"af-"});function G(...e){return qu(Hu(e))}import{jsx as So}from"react/jsx-runtime";var Zr=hn.Root,br=Kr.forwardRef(({className:e,...t},a)=>So(hn.List,{ref:a,className:G("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));br.displayName=hn.List.displayName;var yn=Kr.forwardRef(({className:e,...t},a)=>So(hn.Trigger,{ref:a,className:G("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));yn.displayName=hn.Trigger.displayName;var xn=Kr.forwardRef(({className:e,...t},a)=>So(hn.Content,{ref:a,className:G("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));xn.displayName=hn.Content.displayName;import*as Kl from"react";import{Slot as ju}from"@radix-ui/react-slot";import{cva as Wu}from"class-variance-authority";import{jsx as Ku}from"react/jsx-runtime";var Gu=Wu("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),y=Kl.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...n},r)=>Ku(s?ju:"button",{className:G(Gu({variant:t,size:a,className:e})),ref:r,...n}));y.displayName="Button";import{Inbox as Zl,Settings as Ju}from"lucide-react";import*as Wn from"react";import{jsx as jn}from"react/jsx-runtime";var lt=Wn.forwardRef(({className:e,...t},a)=>jn("div",{className:"af-relative af-w-full af-overflow-auto",children:jn("table",{ref:a,className:G("af-w-full af-caption-bottom af-text-sm",e),...t})}));lt.displayName="Table";var ct=Wn.forwardRef(({className:e,...t},a)=>jn("thead",{ref:a,className:G("[&_tr]:af-border-b",e),...t}));ct.displayName="TableHeader";var dt=Wn.forwardRef(({className:e,...t},a)=>jn("tbody",{ref:a,className:G("[&_tr:last-child]:af-border-0",e),...t}));dt.displayName="TableBody";var Zu=Wn.forwardRef(({className:e,...t},a)=>jn("tfoot",{ref:a,className:G("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Zu.displayName="TableFooter";var Ce=Wn.forwardRef(({className:e,...t},a)=>jn("tr",{ref:a,className:G("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Ce.displayName="TableRow";var q=Wn.forwardRef(({className:e,...t},a)=>jn("th",{ref:a,className:G("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));q.displayName="TableHead";var j=Wn.forwardRef(({className:e,...t},a)=>jn("td",{ref:a,className:G("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));j.displayName="TableCell";var Yu=Wn.forwardRef(({className:e,...t},a)=>jn("caption",{ref:a,className:G("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Yu.displayName="TableCaption";import*as wn from"react";function Us(){let{api:e}=H(),[t,a]=wn.useState([]),[s,n]=wn.useState(!0),[r,i]=wn.useState(null),l=wn.useCallback(async()=>{try{n(!0),i(null);let c=await e.getForms();a(c)}catch(c){i(c instanceof Error?c:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);wn.useEffect(()=>{l()},[l]);let u=wn.useCallback(async c=>{let b=await e.createForm(c);return a(g=>[...g,b]),b},[e]),d=wn.useCallback(async(c,b)=>{let g=await e.updateForm(c,b);return a(m=>m.map(p=>p.id===c?g:p)),g},[e]),o=wn.useCallback(async c=>{await e.deleteForm(c),a(b=>b.filter(g=>g.id!==c))},[e]);return{forms:t,isLoading:s,error:r,refetch:l,createForm:u,updateForm:d,deleteForm:o}}import{jsx as Da,jsxs as Gn}from"react/jsx-runtime";function Yr({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:n}=Us();return s?Da("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Da("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?Da("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Gn("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):a.length===0?Gn("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Da(Zl,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Gn("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",Da("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):Da("div",{className:t,children:Gn(lt,{children:[Da(ct,{children:Gn(Ce,{children:[Da(q,{children:"Name"}),Da(q,{className:"af-text-right",children:"Actions"})]})}),Da(dt,{children:a.map(r=>Gn(Ce,{children:[Da(j,{className:"af-font-medium",children:r.name}),Da(j,{className:"af-text-right",children:Gn("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Gn(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[Da(Zl,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Gn(y,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[Da(Ju,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}import{AlertTriangle as tf}from"lucide-react";import{cva as Xu}from"class-variance-authority";import{jsx as ef}from"react/jsx-runtime";var Qu=Xu("af-inline-flex af-items-center af-rounded-md af-border af-px-2.5 af-py-0.5 af-text-xs af-font-semibold af-transition-colors focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2",{variants:{variant:{default:"af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",secondary:"af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",destructive:"af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",outline:"af-text-foreground",success:"af-border-transparent af-bg-green-100 af-text-green-800",warning:"af-border-transparent af-bg-yellow-100 af-text-yellow-800"}},defaultVariants:{variant:"default"}});function ee({className:e,variant:t,...a}){return ef("div",{className:G(Qu({variant:t}),e),...a})}import{jsx as hs,jsxs as Jr}from"react/jsx-runtime";var af={form_notification:"Form notification",purchase_receipt:"Buyer receipt",merchant_sale:"Sale notification",subscription_payment_failed:"Payment reminder",subscription_cancellation:"Cancellation confirmation",subscription_address_change:"Address change confirmation",merchant_subscription_canceled:"Subscription cancellation notice",account_login:"Sign-in email",oversell_refund:"Refund notification",merchant_oversell:"Stock issue notification",dispute_opened:"Dispute notification"};function Xr(e){switch(e.state){case"sending":return{label:"Sending",variant:"secondary",detail:null};case"sent":return{label:"Sent",variant:"secondary",detail:"Accepted for sending. Delivery has not been confirmed yet."};case"delivered":return{label:"Delivered",variant:"success",detail:"Accepted by the recipient\u2019s email server. This does not confirm it was read."};case"delivery_delayed":return{label:"Delayed",variant:"warning",detail:"Delivery is delayed. The email provider is still trying."};case"bounced":return{label:"Bounced",variant:"destructive",detail:"A receiving email server rejected this message."};case"complained":return{label:"Marked as spam",variant:"destructive",detail:"A recipient marked this email as spam. Do not resend it to that recipient."};case"suppressed":return{label:"Delivery blocked",variant:"destructive",detail:"The email provider blocked delivery to a recipient after a previous delivery problem or spam complaint."};case"failed":return{label:"Send failed",variant:"destructive",detail:"The email provider reported a sending failure."};case"unknown":return{label:"Delivery unconfirmed",variant:"warning",detail:"We could not confirm whether the email was sent. Check with the recipient before sending it again."}}}function No(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function nf(e){return["sending","sent","delivered","delivery_delayed","unknown","complained"].includes(e.state)?null:e.kind==="form_notification"?"Check this form\u2019s notification email addresses in its settings. The submission is saved here.":e.kind==="merchant_sale"||e.kind==="merchant_oversell"?"Check your notification email addresses. You can view and fulfill this order here.":e.kind==="dispute_opened"?"Check your notification email addresses and review this dispute in Stripe.":e.kind==="merchant_subscription_canceled"?"Check your notification email addresses. The subscription status is still shown here.":e.kind==="account_login"?"Ask the customer to confirm their email address and request a new sign-in link once the delivery problem is resolved.":e.kind==="purchase_receipt"?"Contact the buyer another way to confirm their email address. Payment and download details are still available on this order.":"Contact the customer another way to confirm their email address. Email delivery does not change their subscription or payment status."}function hr({deliveries:e,label:t="Email needs attention"}){return No(e)?Jr("span",{className:"af-mt-1 af-flex af-items-center af-gap-1 af-text-xs af-font-normal af-text-amber-800 dark:af-text-amber-300",children:[hs(tf,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function In({deliveries:e,problemsOnly:t=!1,className:a=""}){let s=(e??[]).filter(n=>!t||No([n]));return s.length?hs("div",{className:`af-space-y-3 ${a}`,"aria-label":"Email delivery",children:s.map(n=>{let r=Xr(n),i=nf(n);return Jr("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[Jr("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[hs("span",{className:"af-font-medium",children:af[n.kind]??"Email notification"}),hs(ee,{variant:r.variant,children:r.label})]}),Jr("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&No([n])&&hs("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This status applies to the message sent to this group. It does not mean every recipient had a delivery problem."}),r.detail&&hs("p",{className:"af-mt-1",children:r.detail}),i&&hs("p",{className:"af-mt-1",children:i})]},n.id)})}):null}import*as ss from"react";import{ArrowLeft as Rf,ChevronLeft as _f,ChevronRight as Pf,Eye as kf,Inbox as Cf,Paperclip as Tf}from"lucide-react";import*as ns from"react";import*as Ve from"@radix-ui/react-select";import{Check as sf,ChevronDown as Yl,ChevronUp as rf}from"lucide-react";import{jsx as pa,jsxs as Ro}from"react/jsx-runtime";var sn=Ve.Root;var rn=Ve.Value,Wa=ns.forwardRef(({className:e,children:t,...a},s)=>Ro(Ve.Trigger,{ref:s,className:G("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...a,children:[t,pa(Ve.Icon,{asChild:!0,children:pa(Yl,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Wa.displayName=Ve.Trigger.displayName;var Jl=ns.forwardRef(({className:e,...t},a)=>pa(Ve.ScrollUpButton,{ref:a,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:pa(rf,{className:"af-h-4 af-w-4"})}));Jl.displayName=Ve.ScrollUpButton.displayName;var Xl=ns.forwardRef(({className:e,...t},a)=>pa(Ve.ScrollDownButton,{ref:a,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:pa(Yl,{className:"af-h-4 af-w-4"})}));Xl.displayName=Ve.ScrollDownButton.displayName;var Ga=ns.forwardRef(({className:e,children:t,position:a="popper",...s},n)=>pa(Ve.Portal,{children:Ro(Ve.Content,{ref:n,className:G("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:a,...s,children:[pa(Jl,{}),pa(Ve.Viewport,{className:G("af-p-1",a==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),pa(Xl,{})]})}));Ga.displayName=Ve.Content.displayName;var of=ns.forwardRef(({className:e,...t},a)=>pa(Ve.Label,{ref:a,className:G("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));of.displayName=Ve.Label.displayName;var xt=ns.forwardRef(({className:e,children:t,...a},s)=>Ro(Ve.Item,{ref:s,className:G("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...a,children:[pa("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:pa(Ve.ItemIndicator,{children:pa(sf,{className:"af-h-4 af-w-4"})})}),pa(Ve.ItemText,{children:t})]}));xt.displayName=Ve.Item.displayName;var lf=ns.forwardRef(({className:e,...t},a)=>pa(Ve.Separator,{ref:a,className:G("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));lf.displayName=Ve.Separator.displayName;import*as Ra from"react";function Qr({formId:e,initialPageSize:t=25}){let{api:a}=H(),[s,n]=Ra.useState([]),[r,i]=Ra.useState(0),[l,u]=Ra.useState(!0),[d,o]=Ra.useState(null),[c,b]=Ra.useState(0),[g,m]=Ra.useState(t),p=Ra.useRef(0),f=Ra.useCallback(async()=>{if(!e)return;let P=++p.current;try{u(!0),o(null);let h={limit:g,offset:c*g},S=await a.getSubmissions(e,h);if(P!==p.current)return;if(S.submissions.length===0&&c>0){b(Math.max(0,Math.ceil(S.total/g)-1));return}n(S.submissions),i(S.total)}catch(h){if(P!==p.current)return;o(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{P===p.current&&u(!1)}},[a,e,c,g]);Ra.useEffect(()=>{f()},[f]);let v=Ra.useRef(f);v.current=f;let x=Ra.useCallback(async P=>{await a.deleteSubmission(P),v.current()},[a]),R=Math.ceil(r/g);return{submissions:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<R-1,hasPreviousPage:c>0,setPage:b,setPageSize:P=>{m(P),b(0)},refetch:f,deleteSubmission:x}}import*as ei from"react";import{Trash2 as uf}from"lucide-react";import*as yr from"react";import*as Jt from"@radix-ui/react-dialog";import{X as cf}from"lucide-react";import{jsx as Kn,jsxs as _o}from"react/jsx-runtime";var on=Jt.Root;var df=Jt.Portal;var Ql=yr.forwardRef(({className:e,...t},a)=>Kn(Jt.Overlay,{ref:a,className:G("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Ql.displayName=Jt.Overlay.displayName;var Ka=yr.forwardRef(({className:e,children:t,...a},s)=>Kn(df,{children:_o("div",{className:"aifeatures-admin",children:[Kn(Ql,{}),_o(Jt.Content,{ref:s,className:G("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...a,children:[t,_o(Jt.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[Kn(cf,{className:"af-h-4 af-w-4"}),Kn("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Ka.displayName=Jt.Content.displayName;var Za=({className:e,...t})=>Kn("div",{className:G("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Za.displayName="DialogHeader";var Ya=({className:e,...t})=>Kn("div",{className:G("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ya.displayName="DialogFooter";var Ja=yr.forwardRef(({className:e,...t},a)=>Kn(Jt.Title,{ref:a,className:G("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Ja.displayName=Jt.Title.displayName;var Xa=yr.forwardRef(({className:e,...t},a)=>Kn(Jt.Description,{ref:a,className:G("af-text-sm af-text-muted-foreground",e),...t}));Xa.displayName=Jt.Description.displayName;import{Fragment as ff,jsx as ys,jsxs as xr}from"react/jsx-runtime";function $s({onDelete:e,iconOnly:t}){let[a,s]=ei.useState(!1),[n,r]=ei.useState(!1),[i,l]=ei.useState(null);return xr(ff,{children:[xr(y,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{l(null),s(!0)},children:[ys(uf,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),ys(on,{open:a,onOpenChange:d=>{!d&&!n&&s(!1)},children:xr(Ka,{children:[xr(Za,{children:[ys(Ja,{children:"Delete this submission?"}),ys(Xa,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),i&&ys("p",{className:"af-text-sm af-text-destructive",children:i}),xr(Ya,{children:[ys(y,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),ys(y,{variant:"destructive",onClick:async()=>{r(!0),l(null);try{await e(),s(!1)}catch(d){l(d instanceof Error?d.message:"Failed to delete submission")}finally{r(!1)}},disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}import*as tc from"react";import{ArrowLeft as mf,Download as pf,Globe as gf,Clock as vf,FileText as bf,Loader2 as hf,Monitor as yf,Mail as xf}from"lucide-react";import{jsx as Bt,jsxs as Tt}from"react/jsx-runtime";function ec(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function wf(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function ti({submission:e,onBack:t,onDelete:a}){let{api:s}=H(),[n,r]=tc.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)}},u=Object.entries(e.data).filter(([d])=>!d.startsWith("_"));return Tt("div",{children:[Tt("div",{className:"af-mb-6",children:[Tt(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[Bt(mf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Tt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[Tt("div",{children:[Bt("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),Tt("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",ec(e.metadata.submitted_at)]})]}),a&&Bt($s,{onDelete:a})]})]}),Tt("div",{className:"af-space-y-6",children:[Bt(In,{deliveries:e.email_deliveries}),Tt("div",{children:[Bt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),Tt("div",{className:"af-space-y-3",children:[u.map(([d,o])=>Tt("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[Bt("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:d.replace(/_/g," ")}),Bt("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof o=="string"&&o.includes(`
3
+ `)?Bt("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:o}):String(o)})]},d)),u.length===0&&Bt("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&Tt("div",{children:[Bt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),Bt("div",{className:"af-space-y-2",children:e.attachments.map((d,o)=>Tt("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[Tt("div",{className:"af-flex af-items-center af-gap-2",children:[Bt(bf,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Bt("span",{className:"af-text-sm",children:d.name}),Tt("span",{className:"af-text-xs af-text-muted-foreground",children:["(",wf(d.size),")"]})]}),Tt(y,{variant:"ghost",size:"sm",onClick:()=>l(d),disabled:n===i(d),children:[n===i(d)?Bt(hf,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Bt(pf,{className:"af-h-4 af-w-4 af-mr-1"}),n===i(d)?"Downloading...":"Download"]})]},o))})]}),Tt("div",{children:[Bt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),Tt("div",{className:"af-space-y-2 af-text-sm",children:[Tt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Bt(vf,{className:"af-h-4 af-w-4"}),Bt("span",{children:ec(e.metadata.submitted_at)})]}),e.metadata.ip_address&&Tt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Bt(gf,{className:"af-h-4 af-w-4"}),Tt("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&Tt("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[Bt(yf,{className:"af-h-4 af-w-4 af-mt-0.5"}),Bt("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&Tt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Bt(xf,{className:"af-h-4 af-w-4"}),Tt("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{Download as Nf}from"lucide-react";import*as xs from"react";var Sf=/^\+[1-9]\d{1,14}$/;function ac(e){let t=e==null?"":String(e),a=!Sf.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),s=a?`'${t}`:t;return a||/[",;\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function ai(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function ni(e,t){if(typeof document>"u")return;let a=URL.createObjectURL(e),s=document.createElement("a");s.href=a,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(a)}function si({fetchCsv:e,filename:t}){let[a,s]=xs.useState(!1),[n,r]=xs.useState(null),i=xs.useRef(!1);return{exportCsv:xs.useCallback(async()=>{if(!i.current){i.current=!0,s(!0),r(null);try{let u=await e();ni(u,ai(t))}catch(u){r(u instanceof Error?u:new Error("Export failed"))}finally{i.current=!1,s(!1)}}},[e,t]),exporting:a,error:n}}import{jsx as nc,jsxs as sc}from"react/jsx-runtime";function ga({fetchCsv:e,filename:t,label:a="Export CSV",disabled:s,className:n}){let{exportCsv:r,exporting:i,error:l}=si({fetchCsv:e,filename:t});return sc("span",{className:n,children:[sc(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||i,"aria-busy":i,children:[nc(Nf,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Exporting\u2026":a]}),l&&nc("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}import{jsx as Be,jsxs as Ut}from"react/jsx-runtime";function Ef(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function If(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 Df=["message","comments","comment","inquiry","question","details","body","notes"];function Af(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=(Df.map(r=>a.get(r)).find(Boolean)??t.reduce((r,[,i])=>i.length>r.length?i:r,"")).trim().replace(/\s+/g," ");return n.length>80?n.slice(0,80)+"\u2026":n}function ri({formId:e,className:t,defaultSubmissionId:a,submissionId:s,onSelectSubmission:n}){let{api:r}=H(),{submissions:i,total:l,isLoading:u,error:d,page:o,pageSize:c,hasNextPage:b,hasPreviousPage:g,setPage:m,setPageSize:p,deleteSubmission:f}=Qr({formId:e}),v=ss.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[x,R]=ss.useState(a??null),P=n?s??null:x,h=n??R,S=U=>!!U&&U.id===P&&U.form_id===e,N=i.find(S),[C,w]=ss.useState(null),k=S(C)?C:null,[T,_]=ss.useState(null);if(ss.useEffect(()=>{if(_(null),!P||N||k)return;let U=!1;return r.getSubmission(P).then(ae=>{if(!U){if(ae.form_id!==e){_("This submission could not be found.");return}w(ae)}}).catch(()=>{U||_("This submission could not be found.")}),()=>{U=!0}},[r,e,P,N,k]),P){let U=N??k;return U?Be("div",{className:t,children:Be(ti,{submission:U,onBack:()=>h(null),onDelete:async()=>{await f(U.id),h(null)}})}):T?Ut("div",{className:t,children:[Ut(y,{variant:"ghost",size:"sm",onClick:()=>h(null),className:"af-mb-2 af--ml-2",children:[Be(Rf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Be("p",{className:"af-text-sm af-text-destructive",children:T})]}):Be("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Be("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(u)return Be("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Be("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(d)return Be("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ut("div",{className:"af-text-destructive",children:["Error: ",d.message]})});if(i.length===0&&o===0)return Ut("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Be(Cf,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ut("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",Be("br",{}),"Submissions will appear here when visitors use your form."]})]});let z=o*c+1,Z=Math.min((o+1)*c,l);return Ut("div",{className:t,children:[Be("div",{className:"af-mb-2 af-flex af-justify-end",children:Be(ga,{fetchCsv:v,filename:"submissions"})}),Ut(lt,{children:[Be(ct,{children:Ut(Ce,{children:[Be(q,{children:"Email"}),Be(q,{children:"Preview"}),Be(q,{children:"Date"}),Be(q,{className:"af-text-right",children:"Actions"})]})}),Be(dt,{children:i.map(U=>{let ae=If(U.data),le=Af(U.data);return Ut(Ce,{children:[Ut(j,{className:"af-font-medium",children:[Ut("div",{className:"af-flex af-items-center af-gap-2",children:[ae||Be("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),U.attachments.length>0&&Ut("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${U.attachments.length} attachment(s)`,children:[Be(Tf,{className:"af-h-3 af-w-3"}),Be("span",{className:"af-text-xs",children:U.attachments.length})]})]}),Be(hr,{deliveries:U.email_deliveries,label:"Notification email needs attention"})]}),Be(j,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:le||Be("span",{className:"af-italic",children:"No preview available"})}),Be(j,{className:"af-text-muted-foreground",children:Ef(U.metadata.submitted_at)}),Ut(j,{className:"af-text-right",children:[Be(y,{variant:"ghost",size:"icon",onClick:()=>h(U.id),title:"View details",children:Be(kf,{className:"af-h-4 af-w-4"})}),Be($s,{iconOnly:!0,onDelete:()=>f(U.id)})]})]},U.id)})})]}),Ut("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Ut("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ut("span",{children:["Showing ",z,"-",Z," of ",l]}),Ut(sn,{value:String(c),onValueChange:U=>p(Number(U)),children:[Be(Wa,{className:"af-w-[70px] af-h-8",children:Be(rn,{})}),Ut(Ga,{children:[Be(xt,{value:"10",children:"10"}),Be(xt,{value:"25",children:"25"}),Be(xt,{value:"50",children:"50"}),Be(xt,{value:"100",children:"100"})]})]}),Be("span",{children:"per page"})]}),Ut("div",{className:"af-flex af-items-center af-gap-2",children:[Ut(y,{variant:"outline",size:"sm",onClick:()=>m(o-1),disabled:!g,children:[Be(_f,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ut(y,{variant:"outline",size:"sm",onClick:()=>m(o+1),disabled:!b,children:["Next",Be(Pf,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as en from"react";import{Plus as jf,X as Wf,Loader2 as Gf,Check as Kf}from"lucide-react";import*as rc from"react";import{jsx as Lf}from"react/jsx-runtime";var te=rc.forwardRef(({className:e,type:t,...a},s)=>Lf("input",{type:t,className:G("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...a}));te.displayName="Input";import*as ic from"react";import{cva as Of}from"class-variance-authority";import{jsx as Ff}from"react/jsx-runtime";var Bf=Of("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Ie=ic.forwardRef(({className:e,...t},a)=>Ff("label",{ref:a,className:G(Bf(),e),...t}));Ie.displayName="Label";import*as cn from"react";import{Plus as Uf,Loader2 as Po,Copy as $f,Check as Vf,Trash2 as Hf,RefreshCw as zf,AlertTriangle as qf}from"lucide-react";import*as Qa from"react";function ii(){let{api:e}=H(),[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 u=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(f=>f.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(f=>f.id===g?m:f)),m},[e]),b=Qa.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:s,error:r,refetch:l,createDestination:u,updateDestination:d,deleteDestination:o,rotateSecret:c,getSecret:b}}import*as Zn from"react";import{Loader2 as oc,RotateCw as Mf}from"lucide-react";import{jsx as ln,jsxs as wr}from"react/jsx-runtime";function oi({destinationId:e,limit:t=25,className:a}){let{api:s}=H(),[n,r]=Zn.useState([]),[i,l]=Zn.useState(!0),[u,d]=Zn.useState(null),[o,c]=Zn.useState(null),b=Zn.useCallback(async()=>{try{l(!0),d(null),r(await s.getEventDeliveries(e,t))}catch(m){d(m instanceof Error?m.message:"Failed to load deliveries")}finally{l(!1)}},[s,e,t]);Zn.useEffect(()=>{b()},[b]);let g=async m=>{try{c(m.id),d(null);let p=await s.retryEventDelivery(e,m.id);r(f=>f.map(v=>v.id===m.id?p:v))}catch(p){d(p instanceof Error?p.message:"Retry failed")}finally{c(null)}};return i?wr("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[ln(oc,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):u?ln("div",{className:"af-text-sm af-text-destructive af-py-2",children:u}):n.length===0?ln("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):ln("div",{className:a,children:ln("div",{className:"af-divide-y af-border af-rounded",children:n.map(m=>{let p=m.delivered_at!==null;return wr("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[wr("div",{className:"af-min-w-0",children:[wr("div",{className:"af-flex af-items-center af-gap-2",children:[p?ln(ee,{variant:"secondary",children:m.last_status??200}):ln(ee,{variant:"destructive",children:m.last_status??"failed"}),ln("span",{className:"af-text-sm af-truncate",children:m.type})]}),wr("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[m.event_id," \xB7 ",m.created_at,m.attempts>0&&` \xB7 ${m.attempts} failed ${m.attempts===1?"attempt":"attempts"}`]}),!p&&m.last_error&&ln("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:m.last_error})]}),ln(y,{variant:"ghost",size:"sm",title:"Send this event again",disabled:o===m.id,onClick:()=>g(m),children:o===m.id?ln(oc,{className:"af-h-4 af-w-4 af-animate-spin"}):ln(Mf,{className:"af-h-4 af-w-4"})})]},m.id)})})})}import{jsx as Ye,jsxs as qt}from"react/jsx-runtime";function li({formId:e,topics:t,description:a,className:s}){let{destinations:n,isLoading:r,error:i,createDestination:l,updateDestination:u,deleteDestination:d,rotateSecret:o,getSecret:c}=ii(),[b,g]=cn.useState(""),[m,p]=cn.useState(!1),[f,v]=cn.useState(null),[x,R]=cn.useState(null),[P,h]=cn.useState(null),[S,N]=cn.useState(!1),[C,w]=cn.useState(null),[k,T]=cn.useState(null),[_,z]=cn.useState(null),Z=cn.useMemo(()=>n.filter(A=>A.form_id===e),[n,e]),U=async()=>{let A=b.trim();if(A){if(!A.startsWith("https://")){v("Webhook URLs must start with https://");return}try{p(!0),v(null),await l({url:A,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(de){v(de instanceof Error?de.message:"Failed to add webhook")}finally{p(!1)}}},ae=async A=>{try{T(A.id),v(null),await o(A.id),N(!1),h(await c(A.id))}catch(de){v(de instanceof Error?de.message:"Failed to rotate secret")}finally{T(null)}},le=async A=>{try{T(A.id),v(null),await u(A.id,{status:"active"})}catch(de){v(de instanceof Error?de.message:"Failed to re-enable")}finally{T(null)}},fe=async()=>{if(C)try{T(C.id),await d(C.id),w(null)}catch(A){v(A instanceof Error?A.message:"Failed to delete")}finally{T(null)}},M=async A=>{if(x===A.id){R(null),h(null);return}try{T(A.id),v(null),N(!1),R(A.id),h(await c(A.id))}catch(de){R(null),v(de instanceof Error?de.message:"Failed to read secret")}finally{T(null)}},W=async()=>{if(P)try{await navigator.clipboard.writeText(P),N(!0)}catch{}};return qt("div",{className:s,children:[qt("div",{className:"af-space-y-1",children:[Ye(Ie,{children:"Webhooks"}),Ye("p",{className:"af-text-sm af-text-muted-foreground",children:a??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),qt("div",{className:"af-flex af-gap-2 af-mt-4",children:[Ye(te,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:A=>g(A.target.value),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),U())},disabled:m}),qt(y,{onClick:U,disabled:m||!b.trim(),children:[m?Ye(Po,{className:"af-h-4 af-w-4 af-animate-spin"}):Ye(Uf,{className:"af-h-4 af-w-4"}),Ye("span",{className:"af-ml-1",children:"Add"})]})]}),(f||i)&&Ye("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:f||i?.message}),qt("div",{className:"af-mt-4 af-space-y-2",children:[r&&qt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ye(Po,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&Z.length===0&&Ye("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),Z.map(A=>qt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[qt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[qt("div",{className:"af-min-w-0",children:[qt("div",{className:"af-flex af-items-center af-gap-2",children:[Ye("span",{className:"af-font-mono af-text-sm af-truncate",children:A.url}),A.status==="disabled"?Ye(ee,{variant:"destructive",children:"Disabled"}):Ye(ee,{variant:"secondary",children:"Active"})]}),Ye("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:A.topics.includes("*")?"All events":A.topics.join(", ")})]}),qt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[Ye(y,{variant:"ghost",size:"sm",onClick:()=>z(_===A.id?null:A.id),children:_===A.id?"Hide log":"Deliveries"}),Ye(y,{variant:"ghost",size:"sm",onClick:()=>M(A),disabled:k===A.id,children:x===A.id?"Hide secret":"Show secret"}),Ye(y,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:k===A.id,onClick:()=>w(A),children:Ye(Hf,{className:"af-h-4 af-w-4"})})]})]}),A.status==="disabled"&&qt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[Ye(qf,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),qt("div",{className:"af-text-sm",children:[qt("p",{children:["We stopped sending after repeated failures."," ",A.disabled_reason]}),Ye(y,{variant:"outline",size:"sm",className:"af-mt-2",disabled:k===A.id,onClick:()=>le(A),children:"Re-enable"})]})]}),x===A.id&&P&&qt("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[Ye("p",{className:"af-text-xs af-text-muted-foreground",children:"Optional. Use this if you want your endpoint to check that a delivery really came from us. Rotating replaces it."}),qt("div",{className:"af-flex af-gap-2",children:[Ye(te,{readOnly:!0,value:P,className:"af-font-mono"}),Ye(y,{variant:"outline",title:"Copy signing secret",onClick:W,children:S?Ye(Vf,{className:"af-h-4 af-w-4"}):Ye($f,{className:"af-h-4 af-w-4"})}),Ye(y,{variant:"outline",title:"Rotate signing secret",disabled:k===A.id,onClick:()=>ae(A),children:k===A.id?Ye(Po,{className:"af-h-4 af-w-4 af-animate-spin"}):Ye(zf,{className:"af-h-4 af-w-4"})})]})]}),_===A.id&&Ye(oi,{destinationId:A.id})]},A.id))]}),Ye(on,{open:!!C,onOpenChange:A=>{!A&&!k&&w(null)},children:qt(Ka,{children:[qt(Za,{children:[Ye(Ja,{children:"Delete this webhook?"}),qt(Xa,{children:["New submissions will stop being sent to ",C?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),qt(Ya,{children:[Ye(y,{variant:"outline",onClick:()=>w(null),disabled:!!k,children:"Cancel"}),Ye(y,{variant:"destructive",onClick:fe,disabled:!!k,children:k?"Deleting...":"Delete"})]})]})})]})}import{jsx as tt,jsxs as Sn}from"react/jsx-runtime";function ci({form:e,onSaved:t,className:a}){let{updateForm:s}=Us(),[n,r]=en.useState(!1),[i,l]=en.useState(null),[u,d]=en.useState(null),[o,c]=en.useState(e.name),[b,g]=en.useState(e.redirect_url||""),[m,p]=en.useState(e.email_recipients),[f,v]=en.useState("");en.useEffect(()=>{c(e.name),g(e.redirect_url||""),p(e.email_recipients),d(null)},[e]);let x=en.useCallback(async N=>{try{r(!0),d(null);let C=await s(e.id,N);l(new Date),t?.(C)}catch(C){d(C instanceof Error?C.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);en.useEffect(()=>{if(i){let N=setTimeout(()=>l(null),2e3);return()=>clearTimeout(N)}},[i]);let R=async()=>{let N=f.trim().toLowerCase();if(!N)return;if(!N.includes("@")){d("Please enter a valid email address");return}if(m.includes(N)){d("This email is already added");return}let C=[...m,N];p(C),v(""),d(null),await x({email_recipients:C})},P=async N=>{let C=m.filter(w=>w!==N);p(C),await x({email_recipients:C})},h=async()=>{o!==e.name&&await x({name:o})},S=async()=>{let N=b||null;N!==e.redirect_url&&await x({redirect_url:N})};return Sn("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(n||i)&&tt("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?Sn("div",{className:"af-flex af-items-center af-gap-2 af-bg-background af-border af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[tt(Gf,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),tt("span",{className:"af-text-sm",children:"Saving..."})]}):Sn("div",{className:"af-flex af-items-center af-gap-2 af-bg-green-50 af-border af-border-green-200 af-shadow-lg af-rounded-lg af-px-4 af-py-3",children:[tt(Kf,{className:"af-h-4 af-w-4 af-text-green-600"}),tt("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{htmlFor:"form-name",children:"Form Name"}),tt(te,{id:"form-name",value:o,onChange:N=>c(N.target.value),onBlur:h,placeholder:"Contact Form"}),tt("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{children:"Email Recipients"}),tt("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),Sn("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[m.map(N=>Sn(ee,{variant:"secondary",className:"af-gap-1",children:[N,tt("button",{type:"button",onClick:()=>P(N),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:tt(Wf,{className:"af-h-3 af-w-3"})})]},N)),m.length===0&&tt("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Sn("div",{className:"af-flex af-gap-2",children:[tt(te,{type:"email",value:f,onChange:N=>v(N.target.value),placeholder:"Add email address",onKeyDown:N=>{N.key==="Enter"&&(N.preventDefault(),R())},disabled:n}),tt(y,{type:"button",variant:"outline",onClick:R,disabled:!f.trim()||n,children:tt(jf,{className:"af-h-4 af-w-4"})})]})]}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{htmlFor:"redirect-url",children:"Redirect URL"}),tt(te,{id:"redirect-url",value:b,onChange:N=>g(N.target.value),onBlur:S,placeholder:"/thank-you"}),tt("p",{className:"af-text-xs af-text-muted-foreground",children:"Where to send visitors after a successful submission. Use a site path (/thank-you) or a full URL (https://example.com/thank-you). Leave empty for a default success page."})]}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{children:"Form Endpoint"}),tt("div",{className:"af-flex af-items-center af-gap-2",children:tt("code",{className:"af-flex-1 af-text-xs af-bg-muted af-px-3 af-py-2 af-rounded af-border",children:e.endpoint_url})}),tt("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),Sn("div",{className:"af-space-y-2",children:[tt(Ie,{children:"Captcha Protection"}),tt("div",{className:"af-flex af-items-center af-gap-2",children:tt(ee,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),tt("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),tt(li,{formId:e.id}),u&&tt("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})]})}import{jsx as Aa,jsxs as Dn}from"react/jsx-runtime";function lc({className:e,location:t,onNavigate:a,submissionId:s}){let{api:n}=H(),[r,i]=Yn.useState({submissionId:s});Yn.useEffect(()=>{s&&i({submissionId:s})},[s]);let l=a?t??{}:r,u=a??i,[d,o]=Yn.useState(null),c=`${l.formId??""}|${l.submissionId??""}`,[b,g]=Yn.useState(null),m=b?.key===c?b.message:null,p=l.formId??(d&&d.submissionId===l.submissionId?d.formId:void 0);Yn.useEffect(()=>{let N=l.submissionId;if(!N||l.formId)return;let C=!1;return n.getSubmission(N).then(w=>{C||(g(null),o({submissionId:N,formId:w.form_id}))}).catch(()=>{C||g({key:c,message:"This submission could not be found."})}),()=>{C=!0}},[n,l.submissionId,l.formId,c]);let[f,v]=Yn.useState(null);Yn.useEffect(()=>{if(!p||f?.id===p)return;let N=!1;return n.getForm(p).then(C=>{N||(g(null),v(C))}).catch(()=>{N||g({key:c,message:"This form could not be found."})}),()=>{N=!0}},[n,p,f?.id,c]);let x=(N,C)=>{v(N),u({formId:N.id,tab:C})},R=()=>u({});if(!l.formId&&!l.submissionId)return Dn("div",{className:e,children:[Dn("div",{className:"af-mb-6",children:[Aa("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),Aa("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),Aa(Yr,{onSelectForm:x})]});let h=Dn(y,{variant:"ghost",size:"sm",onClick:R,className:"af-mb-2 af--ml-2",children:[Aa(Zf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(m)return Dn("div",{className:e,children:[h,Aa("p",{className:"af-text-sm af-text-destructive",children:m})]});if(!p||f?.id!==p)return Aa("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:Aa("div",{className:"af-text-muted-foreground",children:"Loading..."})});let S=l.submissionId?"submissions":l.tab??"submissions";return Dn("div",{className:e,children:[Dn("div",{className:"af-mb-6",children:[h,Aa("h2",{className:"af-text-lg af-font-semibold",children:f.name})]}),Dn(Zr,{value:S,onValueChange:N=>u({formId:p,tab:N}),children:[Dn(br,{className:"af-mb-4",children:[Dn(yn,{value:"submissions",className:"af-gap-2",children:[Aa(Jf,{className:"af-h-4 af-w-4"}),"Submissions"]}),Dn(yn,{value:"settings",className:"af-gap-2",children:[Aa(Yf,{className:"af-h-4 af-w-4"}),"Settings"]})]}),Aa(xn,{value:"submissions",children:Aa(ri,{formId:p,submissionId:l.submissionId,onSelectSubmission:N=>u({formId:p,tab:"submissions",submissionId:N??void 0})})}),Aa(xn,{value:"settings",children:Aa(ci,{form:f,onSaved:v})})]})]})}import*as at from"react";import*as An from"react";function rs(){let{api:e}=H(),[t,a]=An.useState(null),[s,n]=An.useState(!0),[r,i]=An.useState(null),l=An.useRef(0),u=An.useCallback(async()=>{let d=++l.current;try{n(!0),i(null);let o=await e.getPaymentsStatus();if(d!==l.current)return;a(o)}catch(o){if(d!==l.current)return;i(o instanceof Error?o:new Error("Failed to fetch payments status"))}finally{d===l.current&&n(!1)}},[e]);return An.useEffect(()=>{u()},[u]),{status:t,isLoading:s,error:r,refetch:u}}var Xf=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function dn(e){return Xf.has(e.toLowerCase())}function Y(e,t,a){let s=dn(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Jn(e){let t=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+t}function ua(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=dn(t)?a:a*100;return Math.round(s)}function Et(e,t){return dn(t)?e:e/100}function di(e){return e.amount_paid??Math.max(0,Jn(e)-(e.credit_applied??0))}import{Fragment as tm,jsx as Qe,jsxs as ft}from"react/jsx-runtime";function Sr(e){return e instanceof Yt&&e.status===404?"Promo management is not available yet. Try again after the service is updated.":e instanceof Error?e.message:"Could not complete the request."}function cc(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${Y(e.amount_off,e.currency)} off`:"Discount unavailable"}function Vs(){let{api:e,siteToken:t}=H();return Qe(Qf,{api:e},t)}function Qf({api:e}){let{status:t,error:a}=rs(),[s,n]=at.useState([]),[r,i]=at.useState(null),[l,u]=at.useState(null),[d,o]=at.useState(!1),[c,b]=at.useState(!1),[g,m]=at.useState(""),[p,f]=at.useState(null),[v,x]=at.useState(null),[R,P]=at.useState(!1),h=at.useRef(0),S=at.useCallback(async w=>{let k=++h.current;o(!0),m("");try{let T=await e.getPromos(w);if(k!==h.current)return;n(_=>w?[..._,...T.promos.filter(z=>!_.some(Z=>Z.id===z.id))]:T.promos),i(T.next_cursor),u(T.checkout_enabled)}catch(T){k===h.current&&m(Sr(T))}finally{k===h.current&&o(!1)}},[e]);at.useEffect(()=>(S(),()=>{h.current++}),[S]);async function N(w){let k=++h.current;o(!0),m(""),P(!1);try{let T=await e.getPromo(w);k===h.current&&f(T)}catch(T){k===h.current&&m(Sr(T))}finally{k===h.current&&o(!1)}}async function C(){if(p){b(!0),o(!0),m("");try{let w=await e.disablePromo(p.id);if(f(w),!["inactive","expired","exhausted"].includes(w.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");P(!1),await S()}catch(w){m(Sr(w))}finally{b(!1),o(!1)}}}return v?Qe(em,{currency:t?.currency??void 0,replaces:v.replaces,onCancel:()=>x(null),onSave:async w=>{let k=v.replaces?await e.replacePromo(v.replaces.id,w):await e.createPromo(w),T=await e.getPromo(k.id);if(T.status==="pending"||T.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");f(T),x(null),await S()}}):ft("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[ft("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[Qe("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),Qe(y,{disabled:d||!t?.currency,onClick:()=>{m(""),x({})},children:"Create promo code"})]}),Qe("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),l===!1&&Qe("p",{role:"status",className:"af-rounded-md af-border af-p-3 af-text-sm",children:"Checkout code entry is not enabled yet. You can prepare codes, but buyers cannot enter them in our checkout until it is enabled."}),!t?.currency&&Qe("p",{className:"af-text-sm",children:a?Sr(a):"Connect Stripe and set the payment currency before creating codes."}),g&&ft("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",Qe(y,{variant:"outline",disabled:d,onClick:()=>p?void N(p.id):void S(),children:"Refresh"})]}),p?ft("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[Qe(y,{variant:"ghost",disabled:c,onClick:()=>{f(null),P(!1),S()},children:"Back to codes"}),ft("h4",{className:"af-font-semibold af-break-all",children:[p.code," \xB7 ",p.name]}),ft("p",{children:[cc(p)," \xB7 ",p.status]}),ft("p",{className:"af-text-sm",children:[p.times_redeemed==null?"Usage unavailable":`${p.times_redeemed} redemptions`,p.max_redemptions!=null?` / ${p.max_redemptions} maximum`:""]}),ft("p",{className:"af-text-sm",children:[p.minimum_amount!=null&&p.currency?`Minimum order: ${Y(p.minimum_amount,p.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),ft("p",{className:"af-text-sm",children:["Subscription discount:"," ",p.duration==="repeating"?`${p.duration_in_months} months`:p.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),Qe("p",{className:"af-text-sm",children:p.expires_at?`Expires ${new Date(p.expires_at).toLocaleString()}`:"No expiry"}),ft("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Qe(y,{variant:"outline",disabled:d,onClick:()=>void N(p.id),children:"Refresh details"}),Qe(y,{variant:"outline",disabled:d||p.status==="pending"||p.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:p}),children:"Replace with new code"}),Qe(y,{variant:"outline",disabled:d||!["active","pending","unavailable"].includes(p.status),onClick:()=>P(!0),children:p.status==="pending"?"Cancel pending offer":"Disable code"})]}),R&&ft("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[ft("p",{className:"af-text-sm",children:[p.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${p.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),Qe(y,{disabled:d,onClick:()=>void C(),children:p.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",Qe(y,{variant:"ghost",disabled:d,onClick:()=>P(!1),children:"Cancel"})]})]}):ft(tm,{children:[s.map(w=>ft("button",{type:"button",disabled:d,onClick:()=>void N(w.id),className:"af-w-full af-rounded-lg af-border af-p-4 af-text-left hover:af-bg-muted focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[ft("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[Qe("span",{className:"af-font-semibold af-break-all",children:w.code}),Qe("span",{className:"af-text-sm",children:w.status})]}),ft("div",{className:"af-text-sm",children:[cc(w)," \xB7"," ",w.times_redeemed==null?"Usage unavailable":`${w.times_redeemed} redemptions`]})]},w.id)),!d&&!g&&s.length===0&&Qe("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),d&&Qe("p",{role:"status",children:"Loading promo codes\u2026"}),r&&Qe(y,{variant:"outline",disabled:d,onClick:()=>void S(r),children:"Load more"})]})]})}function em({currency:e,replaces:t,onCancel:a,onSave:s}){let[n,r]=at.useState(""),[i,l]=at.useState(t?.name??""),[u,d]=at.useState(t?.amount_off!=null?"fixed":"percent"),[o,c]=at.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(Et(t.amount_off,e)):"")),[b,g]=at.useState(t?.minimum_amount!=null&&e?String(Et(t.minimum_amount,e)):""),[m,p]=at.useState(()=>{if(!t?.expires_at)return"";let le=new Date(t.expires_at);return Number.isFinite(le.getTime())?new Date(le.getTime()-le.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[f,v]=at.useState(t?.max_redemptions?.toString()??""),[x,R]=at.useState(t?.duration??"once"),[P,h]=at.useState(t?.duration_in_months?.toString()??"3"),[S,N]=at.useState(null),[C,w]=at.useState(!1),[k,T]=at.useState(""),_=at.useRef(!1),z=e&&dn(e)?"1":"0.01";async function Z(le){if(le.preventDefault(),_.current)return;T("");let fe=S;if(!fe){if(!e){T("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){T("Choose a different code for the replacement.");return}let M=ua(o,e),W=b?ua(b,e):null;if(u==="fixed"&&(!M||M>999999999999)||b&&(!W||W>999999999999)){T("Enter a positive amount within the supported range.");return}if(m&&new Date(m).getTime()<=Date.now()){T("Choose a future expiry.");return}fe={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:i.trim(),duration:x,...u==="percent"?{percent_off:Number(o)}:{amount_off:M,currency:e},...b?{minimum_amount:W,currency:e}:{},...m?{expires_at:new Date(m).toISOString()}:{},...f?{max_redemptions:Number(f)}:{},...x==="repeating"?{duration_in_months:Number(P)}:{}},N(fe)}_.current=!0,w(!0);try{await s(fe)}catch(M){T(Sr(M)),M instanceof Yt&&M.status>=400&&M.status<500&&M.details?.retryable!==!0&&N(null)}finally{_.current=!1,w(!1)}}let U=(le,fe,M,W={})=>ft("label",{className:"af-grid af-gap-1 af-text-sm",children:[le,Qe(te,{"aria-label":le,value:fe,onChange:A=>M(A.target.value),...W})]}),ae="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return ft("form",{onSubmit:Z,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[Qe("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&Qe("p",{className:"af-text-sm",children:"Use a different code. The old code will be disabled only after the replacement is created. Existing subscription discounts continue."}),ft("fieldset",{disabled:C||!!S,className:"af-grid af-gap-4",children:[U("Code",n,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),U("Name",i,l,{required:!0,maxLength:40}),ft("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",ft("select",{"aria-label":"Discount type",className:ae,value:u,onChange:le=>d(le.target.value),children:[Qe("option",{value:"percent",children:"Percentage"}),ft("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),U("Discount",o,c,{type:"number",required:!0,min:u==="percent"?"0.01":z,max:u==="percent"?"100":void 0,step:u==="percent"?"0.01":z}),U("Minimum order amount",b,g,{type:"number",min:z,step:z,placeholder:e?.toUpperCase()}),ft("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),U("Expires at (local time)",m,p,{type:"datetime-local",step:1}),U("Maximum redemptions",f,v,{type:"number",min:1,max:1e6,step:1}),ft("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",ft("select",{"aria-label":"Subscription duration",className:ae,value:x,onChange:le=>R(le.target.value),children:[Qe("option",{value:"once",children:"First invoice only"}),Qe("option",{value:"forever",children:"Every invoice"}),Qe("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&U("Months",P,h,{type:"number",required:!0,min:1,max:36,step:1})]}),k&&Qe("p",{role:"alert",className:"af-text-sm af-text-destructive",children:k}),S&&!C&&ft("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",Qe("span",{className:"af-break-all",children:S.request_id})]}),ft("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Qe(y,{type:"submit",disabled:C,children:C?"Saving\u2026":S?"Retry same request":t?"Create replacement":"Create code"}),Qe(y,{type:"button",variant:"ghost",disabled:C||!!S,onClick:a,children:"Cancel"})]})]})}import*as Js from"react";import{ArrowLeft as _p,FileText as Pp,Package as kp,Receipt as Cp,Settings as Tp,Users as Ep}from"lucide-react";import*as ui from"react";import{Package as am,Pencil as nm,Plus as dc,Trash2 as sm}from"lucide-react";import{jsx as ut,jsxs as va}from"react/jsx-runtime";function rm(e){if(e.allow_custom_amount){let t=e.min_amount!==null?Y(e.min_amount,e.currency):"?",a=e.max_amount!==null?Y(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":Y(e.unit_amount,e.currency)}function im(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function fi({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:n,isLoading:r,error:i,deleteProduct:l}=e,[u,d]=ui.useState(null),[o,c]=ui.useState(!1),[b,g]=ui.useState(null),m=async()=>{if(u)try{c(!0),g(null),await l(u.id),d(null)}catch(p){g(p instanceof Error?p.message:"Failed to delete product")}finally{c(!1)}};return r?ut("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ut("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):i?ut("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:va("div",{className:"af-text-destructive",children:["Error: ",i.message]})}):n.length===0?va("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[ut(am,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),va("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",ut("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),va(y,{variant:"outline",onClick:()=>a?.(),children:[ut(dc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):va("div",{className:s,children:[ut("div",{className:"af-flex af-justify-end af-mb-4",children:va(y,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[ut(dc,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),va(lt,{children:[ut(ct,{children:va(Ce,{children:[ut(q,{children:"Name"}),ut(q,{children:"Price"}),ut(q,{children:"Fulfillment"}),ut(q,{children:"Status"}),ut(q,{className:"af-text-right",children:"Actions"})]})}),ut(dt,{children:n.map(p=>va(Ce,{children:[ut(j,{className:"af-font-medium",children:p.name}),ut(j,{children:rm(p)}),ut(j,{className:"af-text-muted-foreground",children:im(p)}),ut(j,{children:ut(ee,{variant:p.active?"success":"secondary",children:p.active?"Active":"Inactive"})}),ut(j,{className:"af-text-right",children:va("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[va(y,{variant:"ghost",size:"sm",onClick:()=>t?.(p),children:[ut(nm,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),va(y,{variant:"ghost",size:"sm",onClick:()=>{g(null),d(p)},children:[ut(sm,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},p.id))})]}),ut(on,{open:!!u,onOpenChange:p=>{!p&&!o&&d(null)},children:va(Ka,{children:[va(Za,{children:[ut(Ja,{children:"Delete product?"}),va(Xa,{children:['"',u?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&ut("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),va(Ya,{children:[ut(y,{variant:"outline",onClick:()=>d(null),disabled:o,children:"Cancel"}),ut(y,{variant:"destructive",onClick:m,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})}import*as St from"react";import{FileText as lm,Link2 as cm,Loader2 as mc,Plus as dm,Upload as um,X as fm}from"lucide-react";import*as jt from"react";import{Loader2 as uc,Plus as ko,Trash2 as fc,X as om}from"lucide-react";import{jsx as ne,jsxs as _e}from"react/jsx-runtime";function Co(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function mi({productId:e,currency:t,className:a}){let{api:s}=H(),n=dn(t)?"1":"0.01",[r,i]=jt.useState(null),[l,u]=jt.useState(!0),[d,o]=jt.useState(null),[c,b]=jt.useState(null),[g,m]=jt.useState(!1),p=jt.useRef(!0);jt.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);let f=jt.useCallback(async()=>{try{let E=await s.getProduct(e);if(!p.current)return;i(E)}catch(E){if(!p.current)return;o(E instanceof Error?E.message:"Failed to load product")}finally{p.current&&u(!1)}},[s,e]);jt.useEffect(()=>{f()},[f]);let v=async E=>{b(null),m(!0);try{await E(),await f()}catch(O){p.current&&b(O instanceof Error?O.message:"Something went wrong")}finally{p.current&&m(!1)}},[x,R]=jt.useState(""),[P,h]=jt.useState(""),[S,N]=jt.useState({}),C=()=>v(async()=>{let E=x.trim(),O=P.split(",").map(B=>B.trim()).filter(Boolean);if(!E)throw new Error("Option name is required");if(O.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:E,values:O}),p.current&&(R(""),h(""))}),w=E=>v(async()=>{let O=(S[E.id]??"").trim();if(!O)throw new Error("Enter a value");await s.updateOption(E.id,{add_values:[O]}),p.current&&N(B=>({...B,[E.id]:""}))}),k=(E,O)=>v(()=>s.updateOption(E.id,{remove_values:[O]})),T=E=>v(()=>s.deleteOption(E.id)),[_,z]=jt.useState(null),[Z,U]=jt.useState(null),[ae,le]=jt.useState(!1),[fe,M]=jt.useState(null),W=r?.options??[],A=r?.variants??[],de=()=>{U(null),z({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(W.map(E=>[E.id,E.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},ce=E=>{U(null);let O=E.inventory?.on_hand??0,B=O<0?"":String(O);z({variant:E,title:E.title??"",sku:E.sku??"",unitAmount:E.unit_amount!=null?String(Et(E.unit_amount,t)):"",compareAt:E.compare_at_amount!=null?String(Et(E.compare_at_amount,t)):"",active:E.active,optionValues:{},tracked:E.inventory?.tracked??!1,onHand:B,initialOnHand:B,allowBackorder:E.inventory?.allow_backorder??!1})},Le=async()=>{if(!_)return;U(null);let E=_.variant?.allow_custom_amount??!1,O=null,B=null;if(!E){if(O=ua(_.unitAmount,t),O===null||O<=0){U("Enter a valid price");return}if(_.compareAt.trim()&&(B=ua(_.compareAt,t),B===null||B<=O)){U("Compare-at price must be greater than the price");return}}let we=_.onHand.trim()!==_.initialOnHand.trim(),X=parseInt(_.onHand,10);if(_.tracked&&we&&(!Number.isFinite(X)||X<0)){U("On-hand quantity must be zero or more");return}try{if(le(!0),_.variant)await s.updateVariant(_.variant.id,{title:_.title.trim()||null,sku:_.sku.trim()||null,...E?{}:{unit_amount:O,compare_at_amount:B},active:_.active}),await s.setVariantInventory(_.variant.id,{tracked:_.tracked,on_hand:_.tracked&&we?X:void 0,allow_backorder:_.allowBackorder});else{let ve={};for(let Me of W){let ht=_.optionValues[Me.id];if(!ht){U(`Choose a ${Me.title}`),le(!1);return}ve[Me.title]=ht}await s.createVariant(e,{title:_.title.trim()||null,sku:_.sku.trim()||null,unit_amount:O,compare_at_amount:B,active:_.active,option_values:W.length>0?ve:void 0,inventory:_.tracked?{tracked:!0,on_hand:X,allow_backorder:_.allowBackorder}:{tracked:!1,allow_backorder:_.allowBackorder}})}await f(),p.current&&z(null)}catch(ve){if(p.current&&U(ve instanceof Error?ve.message:"Failed to save variant"),_.variant)try{let Me=await s.getProduct(e);p.current&&i(Me)}catch{}}finally{p.current&&le(!1)}},ye=()=>v(async()=>{fe&&(await s.deleteVariant(fe.id),p.current&&M(null))}),Te=_?.variant?.allow_custom_amount??!1,Oe=_?.variant!=null&&_.variant.option_values.length===0&&W.length>0&&!_.variant.active,oe=_?.variant?.inventory!=null&&_.variant.inventory.on_hand<0?-_.variant.inventory.on_hand:null;function st(E){let O=E.inventory;if(!O||!O.tracked)return ne("span",{className:"af-text-muted-foreground",children:"Unlimited"});let B=O.available??O.on_hand;return B<0?_e("span",{children:[-B," backordered"]}):_e("span",{children:[B," in stock",O.allow_backorder&&ne("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return l?ne("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:ne(uc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):d?ne("div",{className:a,children:ne("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})}):_e("div",{className:`af-space-y-6 ${a||""}`,children:[_e("div",{className:"af-space-y-3",children:[_e("div",{children:[ne(Ie,{children:"Options"}),ne("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),W.length>0&&ne("div",{className:"af-space-y-3",children:W.map(E=>_e("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[_e("div",{className:"af-flex af-items-center af-justify-between",children:[ne("span",{className:"af-text-sm af-font-medium",children:E.title}),ne(y,{variant:"ghost",size:"sm",onClick:()=>T(E),disabled:g,children:ne(fc,{className:"af-h-4 af-w-4"})})]}),ne("div",{className:"af-flex af-flex-wrap af-gap-2",children:E.values.map(O=>_e(ee,{variant:"secondary",className:"af-gap-1",children:[O.value,ne("button",{type:"button",onClick:()=>k(E,O.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:ne(om,{className:"af-h-3 af-w-3"})})]},O.id))}),_e("div",{className:"af-flex af-gap-2",children:[ne(te,{value:S[E.id]??"",onChange:O=>N(B=>({...B,[E.id]:O.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),w(E))},disabled:g}),ne(y,{type:"button",variant:"outline",size:"sm",onClick:()=>w(E),disabled:g||!(S[E.id]??"").trim(),children:ne(ko,{className:"af-h-4 af-w-4"})})]})]},E.id))}),_e("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[_e("div",{className:"af-space-y-1",children:[ne(Ie,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),ne(te,{id:"new-option-title",value:x,onChange:E=>R(E.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),_e("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[ne(Ie,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),ne(te,{id:"new-option-values",value:P,onChange:E=>h(E.target.value),placeholder:"S, M, L",disabled:g})]}),_e(y,{type:"button",variant:"outline",onClick:C,disabled:g||!x.trim()||!P.trim(),children:[ne(ko,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),_e("div",{className:"af-space-y-3",children:[_e("div",{className:"af-flex af-items-center af-justify-between",children:[ne(Ie,{children:"Variants"}),_e(y,{type:"button",variant:"outline",size:"sm",onClick:de,disabled:g||W.length===0,children:[ne(ko,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),W.length===0&&ne("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),A.length===0?ne("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):_e(lt,{children:[ne(ct,{children:_e(Ce,{children:[ne(q,{children:"Variant"}),ne(q,{children:"SKU"}),ne(q,{children:"Price"}),ne(q,{children:"Stock"}),ne(q,{children:"Status"}),ne(q,{className:"af-text-right",children:"Actions"})]})}),ne(dt,{children:A.map(E=>_e(Ce,{children:[ne(j,{className:"af-font-medium",children:Co(E)}),ne(j,{className:"af-text-muted-foreground",children:E.sku||"-"}),ne(j,{children:E.unit_amount!=null?_e("span",{children:[E.compare_at_amount!=null&&ne("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:Y(E.compare_at_amount,E.currency)}),Y(E.unit_amount,E.currency)]}):E.allow_custom_amount?ne("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),ne(j,{children:st(E)}),ne(j,{children:ne(ee,{variant:E.active?"success":"secondary",children:E.active?"Active":"Inactive"})}),ne(j,{className:"af-text-right",children:_e("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[ne(y,{variant:"ghost",size:"sm",onClick:()=>ce(E),disabled:g,children:"Edit"}),ne(y,{variant:"ghost",size:"icon",onClick:()=>M(E),disabled:g,title:"Delete variant",children:ne(fc,{className:"af-h-4 af-w-4"})})]})})]},E.id))})]})]}),c&&ne("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c}),ne(on,{open:_!==null,onOpenChange:E=>{!E&&!ae&&z(null)},children:_e(Ka,{children:[_e(Za,{children:[ne(Ja,{children:_?.variant?"Edit variant":"Add variant"}),ne(Xa,{children:"Price, markdown, and stock live on the variant."})]}),_&&_e("div",{className:"af-space-y-3",children:[_.variant?_.variant.option_values.length>0&&_e("div",{className:"af-text-sm",children:[ne("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Co(_.variant)]}):W.map(E=>_e("div",{className:"af-space-y-1",children:[ne(Ie,{className:"af-text-xs af-text-muted-foreground",children:E.title}),_e(sn,{value:_.optionValues[E.id]??"",onValueChange:O=>z(B=>B&&{...B,optionValues:{...B.optionValues,[E.id]:O}}),children:[ne(Wa,{children:ne(rn,{placeholder:`Choose ${E.title}`})}),ne(Ga,{children:E.values.map(O=>ne(xt,{value:O.value,children:O.value},O.id))})]})]},E.id)),Te?_e("div",{className:"af-space-y-1",children:[ne(Ie,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),ne("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):_e("div",{className:"af-flex af-gap-3",children:[_e("div",{className:"af-space-y-1",children:[_e(Ie,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),ne(te,{id:"variant-price",type:"number",min:"0",step:n,value:_.unitAmount,onChange:E=>z(O=>O&&{...O,unitAmount:E.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),_e("div",{className:"af-space-y-1",children:[ne(Ie,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),ne(te,{id:"variant-compare",type:"number",min:"0",step:n,value:_.compareAt,onChange:E=>z(O=>O&&{...O,compareAt:E.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),_e("div",{className:"af-space-y-1",children:[ne(Ie,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),ne(te,{id:"variant-sku",value:_.sku,onChange:E=>z(O=>O&&{...O,sku:E.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),_e("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[_e("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ne("input",{type:"checkbox",checked:_.tracked,onChange:E=>z(O=>O&&{...O,tracked:E.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),_.tracked&&_e("div",{className:"af-space-y-1 af-pl-6",children:[_e("div",{className:"af-flex af-items-end af-gap-3",children:[_e("div",{className:"af-space-y-1",children:[ne(Ie,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),ne(te,{id:"variant-onhand",type:"number",min:"0",step:"1",value:_.onHand,onChange:E=>z(O=>O&&{...O,onHand:E.target.value}),placeholder:oe!=null?"0":void 0,className:"af-w-[100px]"})]}),_e("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[ne("input",{type:"checkbox",checked:_.allowBackorder,onChange:E=>z(O=>O&&{...O,allowBackorder:E.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),oe!=null&&_e("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",oe," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),_e("div",{className:"af-space-y-1",children:[_e("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ne("input",{type:"checkbox",checked:_.active,onChange:E=>z(O=>O&&{...O,active:E.target.checked}),className:"af-h-4 af-w-4",disabled:Oe}),"Active (buyers can purchase this variant)"]}),Oe&&ne("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),Z&&ne("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Z})]}),_e(Ya,{children:[ne(y,{variant:"outline",onClick:()=>z(null),disabled:ae,children:"Cancel"}),_e(y,{onClick:Le,disabled:ae,children:[ae?ne(uc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,_?.variant?"Save":"Add variant"]})]})]})}),ne(on,{open:fe!==null,onOpenChange:E=>{!E&&!g&&M(null)},children:_e(Ka,{children:[_e(Za,{children:[ne(Ja,{children:"Delete variant?"}),ne(Xa,{children:fe&&`"${Co(fe)}" will no longer be purchasable. Past orders are unaffected.`})]}),_e(Ya,{children:[ne(y,{variant:"outline",onClick:()=>M(null),disabled:g,children:"Cancel"}),ne(y,{variant:"destructive",onClick:ye,disabled:g,children:"Delete"})]})]})})]})}import{Fragment as pm,jsx as Pe,jsxs as qe}from"react/jsx-runtime";function mm(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function pi({productsState:e,product:t,currency:a,onSaved:s,className:n}){let{createProduct:r,updateProduct:i,attachProductFile:l,attachProductFileFromUrl:u}=e,d=!!t,o=t?.currency??a,c=dn(o)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,m]=St.useState(!1),[p,f]=St.useState(null),v=St.useRef(!0);St.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);let[x,R]=St.useState(t?.name??""),[P,h]=St.useState(t?.description??""),[S,N]=St.useState(t?.allow_custom_amount?"custom":"fixed"),[C,w]=St.useState(t?.unit_amount!=null?String(Et(t.unit_amount,o)):""),[k,T]=St.useState(t?.min_amount!=null?String(Et(t.min_amount,o)):""),[_,z]=St.useState(t?.max_amount!=null?String(Et(t.max_amount,o)):""),[Z,U]=St.useState(String(t?.max_quantity??10)),ae=St.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(Et(t.unit_amount,o)):"",minAmount:t?.min_amount!=null?String(Et(t.min_amount,o)):"",maxAmount:t?.max_amount!=null?String(Et(t.max_amount,o)):"",maxQuantity:String(t?.max_quantity??10)}).current,[le,fe]=St.useState(t?.collect_shipping_address??!1),[M,W]=St.useState(t?.active??!0),[A,de]=St.useState(t?.images??[]),[ce,Le]=St.useState(""),[ye,Te]=St.useState(t?.fulfillment??null),[Oe,oe]=St.useState(!1),[st,E]=St.useState(""),[O,B]=St.useState(null),we=St.useRef(null),X=g||Oe,ve=()=>{let pe=ce.trim();if(pe){if(A.includes(pe)){f("This image URL is already added");return}de(ke=>[...ke,pe]),Le(""),f(null)}},Me=pe=>{de(ke=>ke.filter(rt=>rt!==pe))},ht=async()=>{if(f(null),!x.trim()){f("Product name is required");return}let pe=null,ke=null,rt=null,Je=!d||S!==ae.pricingMode||(S==="fixed"?C!==ae.unitAmount:k!==ae.minAmount||_!==ae.maxAmount),zt=!d||Z!==ae.maxQuantity,Ot=b||S==="fixed";if(!(b||!Je))if(S==="fixed"){if(pe=ua(C,o),pe===null||pe<=0){f("Enter a valid price");return}}else{if(ke=ua(k,o),rt=ua(_,o),ke===null||rt===null){f("Enter valid minimum and maximum amounts");return}if(rt<ke){f("Maximum amount must be at least the minimum amount");return}}let sa=parseInt(Z,10);if(Ot&&zt&&(!Number.isFinite(sa)||sa<1)){f("Max quantity must be at least 1");return}try{m(!0);let it;if(d&&t){let vt={name:x.trim(),description:P.trim()||null,images:A,collect_shipping_address:le,active:M};!b&&Je&&(vt.allow_custom_amount=S==="custom",S==="fixed"?vt.unit_amount=pe:(vt.min_amount=ke,vt.max_amount=rt)),Ot&&zt&&(vt.max_quantity=sa),it=await i(t.id,vt),ae.pricingMode=it.allow_custom_amount?"custom":"fixed",ae.unitAmount=it.unit_amount!=null?String(Et(it.unit_amount,o)):"",ae.minAmount=it.min_amount!=null?String(Et(it.min_amount,o)):"",ae.maxAmount=it.max_amount!=null?String(Et(it.max_amount,o)):"",ae.maxQuantity=String(it.max_quantity)}else{let vt={name:x.trim(),allow_custom_amount:S==="custom",collect_shipping_address:le,active:M};P.trim()&&(vt.description=P.trim()),A.length>0&&(vt.images=A),S==="fixed"?(vt.unit_amount=pe,vt.max_quantity=sa):(vt.min_amount=ke,vt.max_amount=rt),it=await r(vt)}if(!v.current)return;Te(it.fulfillment),s?.(it)}catch(it){if(!v.current)return;f(it instanceof Error?it.message:"Failed to save product")}finally{v.current&&m(!1)}},Ke=async pe=>{let ke=pe.target.files?.[0];if(!(!ke||!t))try{oe(!0),B(null);let rt=await l(t.id,ke);if(!v.current)return;Te(rt.fulfillment),s?.(rt)}catch(rt){if(!v.current)return;B(rt instanceof Error?rt.message:"Failed to upload file")}finally{v.current&&(oe(!1),we.current&&(we.current.value=""))}},Ct=async()=>{let pe=st.trim();if(!(!pe||!t))try{oe(!0),B(null);let ke=await u(t.id,pe);if(!v.current)return;Te(ke.fulfillment),E(""),s?.(ke)}catch(ke){if(!v.current)return;B(ke instanceof Error?ke.message:"Failed to fetch file")}finally{v.current&&oe(!1)}};return qe("div",{className:`af-space-y-6 ${n||""}`,children:[qe("div",{className:"af-space-y-2",children:[Pe(Ie,{htmlFor:"product-name",children:"Name"}),Pe(te,{id:"product-name",value:x,onChange:pe=>R(pe.target.value),placeholder:"My product"})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{htmlFor:"product-description",children:"Description"}),Pe("textarea",{id:"product-description",value:P,onChange:pe=>h(pe.target.value),rows:3,placeholder:"Shown on the Stripe checkout page.",className:"af-flex af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring"})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{children:"Pricing"}),b?Pe("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):qe(pm,{children:[qe(sn,{value:S,onValueChange:pe=>N(pe),children:[Pe(Wa,{className:"af-w-[260px]",children:Pe(rn,{})}),qe(Ga,{children:[Pe(xt,{value:"fixed",children:"Fixed price"}),Pe(xt,{value:"custom",children:"Buyer chooses the amount"})]})]}),S==="fixed"?Pe("div",{className:"af-flex af-items-end af-gap-3",children:qe("div",{className:"af-space-y-1",children:[qe(Ie,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",o.toUpperCase(),")"]}),Pe(te,{id:"product-price",type:"number",min:"0",step:c,value:C,onChange:pe=>w(pe.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):qe("div",{className:"af-space-y-1",children:[qe("div",{className:"af-flex af-items-end af-gap-3",children:[qe("div",{className:"af-space-y-1",children:[qe(Ie,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",o.toUpperCase(),")"]}),Pe(te,{id:"product-min-amount",type:"number",min:"0",step:c,value:k,onChange:pe=>T(pe.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),qe("div",{className:"af-space-y-1",children:[qe(Ie,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",o.toUpperCase(),")"]}),Pe(te,{id:"product-max-amount",type:"number",min:"0",step:c,value:_,onChange:pe=>z(pe.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),Pe("p",{className:"af-text-xs af-text-muted-foreground",children:"Buyers pick their own amount within these bounds (tip jar, pay-what-you-want). Quantity is always 1."})]}),qe("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",o.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||S==="fixed")&&qe("div",{className:"af-space-y-1",children:[Pe(Ie,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),Pe(te,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:Z,onChange:pe=>U(pe.target.value),className:"af-w-[140px]"})]})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{children:"Images"}),Pe("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),qe("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[A.map(pe=>qe(ee,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[Pe("span",{className:"af-truncate",children:pe}),Pe("button",{type:"button",onClick:()=>Me(pe),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:Pe(fm,{className:"af-h-3 af-w-3"})})]},pe)),A.length===0&&Pe("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),qe("div",{className:"af-flex af-gap-2",children:[Pe(te,{type:"url",value:ce,onChange:pe=>Le(pe.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:pe=>{pe.key==="Enter"&&(pe.preventDefault(),ve())},disabled:g}),Pe(y,{type:"button",variant:"outline",onClick:ve,disabled:!ce.trim()||g,children:Pe(dm,{className:"af-h-4 af-w-4"})})]})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{children:"Digital File"}),Pe("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, Word, Excel, PowerPoint, CSV, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),d?qe("div",{className:"af-space-y-3",children:[ye?.type==="download"&&qe("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Pe(lm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Pe("span",{className:"af-text-sm",children:ye.filename}),ye.size!=null&&qe("span",{className:"af-text-xs af-text-muted-foreground",children:["(",mm(ye.size),")"]})]}),ye?.type==="redirect"&&ye.url&&qe("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[Pe(cm,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),qe("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",ye.url]})]}),qe("div",{className:"af-flex af-items-center af-gap-2",children:[Pe("input",{ref:we,type:"file",onChange:Ke,className:"af-hidden",disabled:X}),qe(y,{type:"button",variant:"outline",size:"sm",onClick:()=>we.current?.click(),disabled:X,children:[Oe?Pe(mc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Pe(um,{className:"af-h-4 af-w-4 af-mr-1"}),ye?.type==="download"?"Replace file":"Upload file"]}),Pe("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),Pe(te,{type:"url",value:st,onChange:pe=>E(pe.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Oe}),Pe(y,{type:"button",variant:"outline",size:"sm",onClick:Ct,disabled:!st.trim()||X,children:"Fetch from URL"})]}),O&&Pe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:O})]}):Pe("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),qe("div",{className:"af-space-y-2",children:[Pe(Ie,{children:"Settings"}),qe("div",{className:"af-space-y-2",children:[qe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Pe("input",{type:"checkbox",checked:le,onChange:pe=>fe(pe.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),qe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Pe("input",{type:"checkbox",checked:M,onChange:pe=>W(pe.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),d&&t&&qe("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[Pe(Ie,{children:"Options & Variants"}),Pe(mi,{productId:t.id,currency:o})]}),p&&Pe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:p}),Pe("div",{className:"af-flex af-items-center af-gap-2",children:qe(y,{type:"button",onClick:ht,disabled:X,children:[g?Pe(mc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?"Save changes":"Create product"]})})]})}import*as Xt from"react";import{ChevronLeft as Mm,ChevronRight as Rc,Loader2 as Um,Receipt as $m,Search as Vm,SlidersHorizontal as Hm}from"lucide-react";import*as It from"react";var gm=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function gi({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=It.useState([]),[r,i]=It.useState(0),[l,u]=It.useState(!0),[d,o]=It.useState(null),[c,b]=It.useState(0),[g,m]=It.useState(e),[p,f]=It.useState(void 0),[v,x]=It.useState(""),[R,P]=It.useState(""),[h,S]=It.useState(""),[N,C]=It.useState(!1),[w,k]=It.useState(!1),[T,_]=It.useState(void 0),z=T?T.join(","):"",Z=It.useMemo(()=>{if(!z)return;let M=new Set(z.split(","));return gm.filter(W=>!M.has(W))},[z]),U=It.useMemo(()=>{let M={};return p?M.status=p:Z?M.excludeStatus=Z:N||(M.excludeStatus=["pending","expired"]),v.trim()&&(M.customerEmail=v.trim()),R.trim()&&(M.from=R.trim()),h.trim()&&(M.to=h.trim()),w&&(M.unfulfilledOnly=!0),M},[p,Z,N,v,R,h,w]),ae=It.useRef(0),le=It.useCallback(async()=>{let M=++ae.current;try{u(!0),o(null);let W={...U,limit:g,offset:c*g},A=await a.getOrders(W);if(M!==ae.current)return;n(A.orders),i(A.total)}catch(W){if(M!==ae.current)return;o(W instanceof Error?W:new Error("Failed to fetch orders"))}finally{M===ae.current&&u(!1)}},[a,c,g,U,t]);It.useEffect(()=>{le()},[le]);let fe=Math.ceil(r/g);return{orders:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<fe-1,hasPreviousPage:c>0,setPage:b,setPageSize:M=>{m(M),b(0)},status:p,setStatus:M=>{f(M),b(0)},statusIn:T,setStatusIn:M=>{_(M&&M.length>0?M:void 0),b(0)},customerEmail:v,setCustomerEmail:M=>{x(M),b(0)},from:R,setFrom:M=>{P(M),b(0)},to:h,setTo:M=>{S(M),b(0)},showAbandoned:N,setShowAbandoned:M=>{C(M),b(0)},unfulfilledOnly:w,setUnfulfilledOnly:M=>{k(M),b(0)},clearFilters:()=>{f(void 0),_(void 0),C(!1),k(!1),x(""),P(""),S(""),b(0)},filters:U,refetch:le}}import*as $t from"react";import{ArrowLeft as hm,Check as vc,ChevronLeft as ym,ChevronRight as xm,ClipboardCopy as wm,Copy as Sm,Download as Nm,Loader2 as yi,Mail as bc,MoreHorizontal as Rm,Package as _m,RotateCcw as Pm,Truck as km,Undo2 as hc}from"lucide-react";import*as pc from"react";import*as Ln from"@radix-ui/react-popover";import{jsx as To}from"react/jsx-runtime";var vi=Ln.Root,bi=Ln.Trigger;var Nr=pc.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},n)=>To(Ln.Portal,{children:To("div",{className:"aifeatures-admin",children:To(Ln.Content,{ref:n,align:t,sideOffset:a,className:G("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...s})})}));Nr.displayName=Ln.Content.displayName;import{jsx as hi}from"react/jsx-runtime";var vm={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function bm(e){return vm[e]??e}function gc(e){switch(e){case"paid":return"success";case"pending":return"secondary";case"refunded":case"partially_refunded":return"warning";case"disputed":return"destructive";default:return"outline"}}function ws({status:e,className:t}){return hi(ee,{variant:gc(e),className:t,children:bm(e)})}function Ss({status:e}){return hi(ws,{status:e})}function Hs({order:e,className:t}){return e.line_items.some(a=>a.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?hi(ee,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?hi(ee,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Xn(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as Om,jsx as D,jsxs as re}from"react/jsx-runtime";var Sc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ns="af-text-xs af-text-muted-foreground";function Eo(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Cm(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 xi=24,Tm=["paid","partially_refunded"],Em=["paid","partially_refunded","disputed"],Im=/^[A-Za-z0-9 _-]*$/,yc=100;function Ao(e,t,a,s,n){let r=Tm.includes(s);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${a} of ${xi} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${xi} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?a<xi&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:a<xi&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${a} attempt${a===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${s==="refunded"?"because the order was refunded":s==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function xc({title:e,recipient:t,status:a,attempts:s,side:n,orderStatus:r,action:i,delivery:l}){if(l)return re("div",{children:[D(In,{deliveries:[l]}),i&&D("div",{className:"af-mt-2",children:i})]});let u=Ao(n,a,s,r,t);return re("div",{children:[re("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[re("div",{className:"af-min-w-0",children:[D("div",{className:"af-text-sm",children:e}),t&&D("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),D(ee,{variant:u.variant,className:"af-shrink-0",children:u.label})]}),u.detail&&D("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:u.detail}),i&&D("div",{className:"af-mt-2",children:i})]})}function wc(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=Cm(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 Dm(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Lo({value:e,label:t,children:a,className:s,size:n="icon"}){let[r,i]=$t.useState(!1);if(!Dm())return null;let l=async()=>{try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch{}},u=r?D(vc,{className:"af-h-3 af-w-3"}):D(Sm,{className:"af-h-3 af-w-3"});return n==="icon"?D(y,{variant:"ghost",size:"icon",className:G("af-h-6 af-w-6 af-shrink-0",s),onClick:l,title:t,"aria-label":t,children:u}):re(y,{variant:"outline",size:"sm",className:s,onClick:l,"aria-label":t,children:[r?D(vc,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):D(wm,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":a]})}function Io({label:e,value:t}){return re("div",{children:[D("div",{className:Ns,children:e}),re("div",{className:"af-flex af-items-center af-gap-1",children:[D("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),D(Lo,{value:t,label:`Copy ${e}`})]})]})}function Am({src:e}){let[t,a]=$t.useState(!1);return!e||t?D("div",{"aria-hidden":"true",className:"af-flex af-h-10 af-w-10 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-muted",children:D(_m,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):D("img",{src:e,alt:"","aria-hidden":"true",onError:()=>a(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function On({title:e,action:t,children:a,className:s}){return re("section",{className:G("af-rounded-lg af-border af-p-4",s),children:[re("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[D("h4",{className:Sc,children:e}),t]}),D("div",{className:"af-mt-3",children:a})]})}function La({label:e,emphasis:t,divider:a,children:s}){return re("div",{className:G("af-flex af-items-baseline af-justify-between af-gap-6",a&&"af-mt-2 af-border-t af-pt-2"),children:[D("span",{className:t?"af-text-base af-font-semibold":Ns,children:e}),D("span",{className:G("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function Do({onSelect:e,disabled:t,icon:a,children:s}){return re(y,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[D("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function Lm(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?t.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${Y(di(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),s=a?Xr(a):Ao("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let a=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),s=a?Xr(a):Ao("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${Y(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function wi({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:n=!1,onPrevOrder:r,onNextOrder:i,hasPrevOrder:l=!1,hasNextOrder:u=!1}){let{api:d}=H(),[o,c]=$t.useState(e),[b,g]=$t.useState(null),[m,p]=$t.useState(null),[f,v]=$t.useState(!1),[x,R]=$t.useState(!1),[P,h]=$t.useState(!1),[S,N]=$t.useState(!1),[C,w]=$t.useState(""),[k,T]=$t.useState(!1),[_,z]=$t.useState(null),[Z,U]=$t.useState(!1),[ae,le]=$t.useState(""),[fe,M]=$t.useState([]),[W,A]=$t.useState(!1),[de,ce]=$t.useState(!1),[Le,ye]=$t.useState(null);$t.useEffect(()=>{c(e)},[e]);let Te=F=>{let Xe=F.id===o.id&&F.email_deliveries===void 0?{...F,email_deliveries:o.email_deliveries}:F;c(Xe),s?.(Xe)},Oe=Object.entries(o.metadata??{}),oe=Math.max(0,di(o)-o.amount_refunded),st=(o.status==="paid"||o.status==="partially_refunded")&&oe>0,E=o.exclusive_tax_total!=null,O=F=>typeof F.amountNet=="number"?F.amountNet+(F.exclusiveTax??0):(typeof F.unitAmount=="number"?F.unitAmount:0)*(typeof F.quantity=="number"&&F.quantity>0?F.quantity:1),B=Math.max(0,(o.shipping_total??0)-(o.shipping_refunded??0)),we=fe.reduce((F,Xe)=>F+O(o.line_items[Xe]??{}),0)+(W?B:0),X=o.tax_total??0,ve=Math.max(0,(o.exclusive_tax_total??0)-o.line_items.reduce((F,Xe)=>F+(Xe.exclusiveTax??0),0)),Me=E?W&&B>0?ve:0:o.automatic_tax&&o.tax_behavior==="exclusive"&&X>0&&o.amount_total+(o.shipping_total??0)>0?Math.min(Math.max(0,X-(o.tax_refunded??0)),Math.round(X*we/(o.amount_total+(o.shipping_total??0)))):0,ht=o.source==="subscription"&&(o.credit_applied??0)>0&&o.line_items.length===1?Math.min(we+Me,oe):we+Me,Ke=fe.length>0||W,Ct=Ke?ht:ua(ae,o.currency),pe=dn(o.currency)?"1":"0.01",ke=async()=>{try{v(!0),g(null),p(null),await d.resendOrderReceipt(o.id);let F=await d.getOrder(o.id);Te(F),p("Receipt email queued.")}catch(F){g(F instanceof Error?F.message:"Failed to resend receipt")}finally{v(!1)}},rt=async()=>{try{R(!0),g(null),p(null);let F=await d.resetOrderDownloads(o.id);Te(F),h(!1),p("Download count reset.")}catch(F){g(F instanceof Error?F.message:"Failed to reset downloads")}finally{R(!1)}},Je=o.line_items.some(F=>F.collectShippingAddress===!0&&!F.refunded&&!F.unavailableReason),zt=typeof o.merchant_fulfilled_at=="string",Ot=Em.includes(o.status)||o.status==="refunded"&&o.line_items.some(F=>F.collectShippingAddress===!0&&F.amountNet===0&&!F.refunded&&!F.unavailableReason),sa=C.trim(),it=Im.test(sa)&&sa.length<=yc,vt=async F=>{try{T(!0),z(null),p(null);let Xe=await d.setOrderFulfillment(o.id,{fulfilled:F,...F&&sa?{trackingNumber:sa}:{}});Te(Xe),w(""),p(F?"Marked as shipped.":"Marked as not shipped.")}catch(Xe){Xe instanceof Yt&&Xe.status===409?z(`This order is ${o.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):z(Xe instanceof Error?Xe.message:"Failed to update the order")}finally{T(!1)}},xe=()=>{ye(null),le(String(Et(oe,o.currency))),M([]),A(!1),U(!0)},ot=F=>M(Xe=>Xe.includes(F)?Xe.filter(Ia=>Ia!==F):[...Xe,F]),Ze=async(F,Xe)=>{if(a)try{ce(!0),ye(null),await a(o,F,Xe);let Ia=await d.getOrder(o.id);Te(Ia),U(!1),p("Refund issued.")}catch(Ia){ye(Ia instanceof Error?Ia.message:"Refund failed")}finally{ce(!1)}},yt=async()=>{if(Ke){if(ht<=0){ye("The lines you picked were charged nothing");return}if(ht>oe){ye(`That selection exceeds the refundable remainder (${Y(oe,o.currency)})`);return}await Ze(ht,{...fe.length>0?{line_items:[...fe].sort((Xe,Ia)=>Xe-Ia)}:{},...W?{shipping:!0}:{}});return}let F=ua(ae,o.currency);if(F===null||F<=0){ye("Enter a valid refund amount");return}if(F>oe){ye(`Amount exceeds the refundable remainder (${Y(oe,o.currency)})`);return}await Ze(F,{amount:F})},$=()=>Ze(oe,{full:!0}),Ge=!o.subscription_history_only&&o.fulfillment_type==="download",ra=!o.subscription_history_only&&n&&Je,Ms=Lm(o),Q=o.shipping_address?wc(o.shipping_address).join(`
4
+ `):"",Na=o.shipping_total!=null,vo=o.exclusive_tax_total??(o.automatic_tax&&o.tax_behavior==="exclusive"?o.tax_total??0:0),Ul=o.exclusive_tax_total!=null?Math.max(0,(o.tax_total??0)-vo):o.automatic_tax&&o.tax_behavior==="exclusive"?0:o.tax_total??0,$l=vo>0,Mu=Ul>0,Vl=o.amount_subtotal!=null||Na||$l||(o.discount_total??0)>0,mr=[];return o.subscription_history_only||mr.push(D(Do,{icon:f?D(yi,{className:"af-h-4 af-w-4 af-animate-spin"}):D(bc,{className:"af-h-4 af-w-4"}),disabled:f||o.fulfillment_status!=="fulfilled",onSelect:()=>{N(!1),ke()},children:"Resend receipt"},"resend")),Ge&&mr.push(D(Do,{icon:D(Pm,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{N(!1),h(!0)},children:"Reset download count"},"reset")),st&&mr.push(re("div",{children:[D(Do,{icon:D(hc,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{N(!1),xe()},children:"Refund\u2026"}),!a&&D("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),re("div",{children:[re("div",{className:"af-mb-6",children:[re(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[D(hm,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),re("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[re("div",{className:"af-min-w-0",children:[re("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[D("h3",{className:"af-text-xl af-font-semibold",children:Xn(o)}),D(ws,{status:o.status}),n&&!o.subscription_history_only&&D(Hs,{order:o}),o.is_test&&D(ee,{variant:"outline",children:"Test"})]}),re("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Eo(o.created_at)]}),o.is_test&&D("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),re("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||i)&&re("div",{className:"af-flex af-items-center",children:[D(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!l,"aria-label":"Previous order",children:D(ym,{className:"af-h-4 af-w-4"})}),D(y,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:i,disabled:!u,"aria-label":"Next order",children:D(xm,{className:"af-h-4 af-w-4"})})]}),ra&&(zt?re("div",{className:"af-flex af-items-center af-gap-1",children:[re("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",o.merchant_fulfilled_at?` \xB7 ${Eo(o.merchant_fulfilled_at)}`:""]}),Ot&&re(y,{variant:"ghost",size:"sm",onClick:()=>vt(!1),disabled:k,children:[k?D(yi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(hc,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Ot?re("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[D(te,{value:C,onChange:F=>w(F.target.value),placeholder:"Tracking number (optional)",maxLength:yc,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:k}),re(y,{variant:"default",className:"af-shrink-0",onClick:()=>vt(!0),disabled:k||!it,children:[k?D(yi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(km,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),mr.length>0&&re(vi,{open:S,onOpenChange:N,children:[D(bi,{asChild:!0,children:D(y,{variant:"outline",size:"icon","aria-label":"More actions",children:D(Rm,{className:"af-h-4 af-w-4"})})}),D(Nr,{children:D("div",{className:"af-space-y-0.5",children:mr})})]})]})]}),ra&&!zt&&!it&&D("p",{className:"af-mt-2 af-text-xs af-text-destructive",children:"Tracking numbers can use letters, numbers, spaces, dashes and underscores \u2014 up to 100 characters."}),_&&D("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:_}),m&&D("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:m}),b&&D("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:b})]}),re("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[re("div",{className:"af-space-y-6",children:[o.line_items.length>0&&D(On,{title:"Items",children:D("ul",{className:"af-space-y-3",children:o.line_items.map((F,Xe)=>{let Ia=typeof F.name=="string"&&F.name?F.name:"Item",Hl=typeof F.quantity=="number"&&F.quantity>0?F.quantity:1,zl=typeof F.unitAmount=="number";return re("li",{className:"af-flex af-items-start af-gap-3",children:[D(Am,{src:typeof F.imageUrl=="string"&&F.imageUrl?F.imageUrl:void 0}),re("div",{className:"af-min-w-0 af-flex-1",children:[re("div",{className:"af-text-sm af-font-medium",children:[Ia,typeof F.variantTitle=="string"&&F.variantTitle&&re("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",F.variantTitle]})]}),re("div",{className:Ns,children:[Hl," \xD7"," ",zl?Y(F.unitAmount,o.currency):"\u2014"]}),F.unavailableReason==="oversold"&&!F.refunded&&D(ee,{variant:"secondary",className:"af-mt-1",children:F.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),F.refunded===!0&&D(ee,{variant:"secondary",className:"af-mt-1",children:F.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),D("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof F.amountNet=="number"||zl?Y(F.amountNet??F.unitAmount*Hl,o.currency):"\u2014"})]},Xe)})})}),Oe.length>0&&D(On,{title:"Order details",children:D("dl",{className:"af-space-y-2",children:Oe.map(([F,Xe])=>re("div",{children:[D("dt",{className:G(Ns,"af-capitalize"),children:F.replace(/_/g," ")}),D("dd",{className:"af-text-sm af-break-words",children:Nc(Xe)})]},F))})}),D(On,{title:"Totals",children:re("div",{className:"af-w-full",children:[Vl&&D(La,{label:"Subtotal",children:Y(o.amount_subtotal??o.amount_total+(o.discount_total??0),o.currency)}),(o.discount_total??0)>0&&re(La,{label:"Discount",children:["\u2212",Y(o.discount_total,o.currency)]}),Na&&D(La,{label:"Shipping",children:o.shipping_total===0?"Free":Y(o.shipping_total??0,o.currency)}),$l&&D(La,{label:"Tax",children:Y(vo,o.currency)}),D(La,{label:"Total",emphasis:!0,divider:Vl,children:Y(Jn(o),o.currency)}),(o.credit_applied??0)>0&&re(La,{label:"Credit applied",children:["\u2212",Y(o.credit_applied,o.currency)]}),o.amount_paid!=null&&D(La,{label:"Amount paid",children:Y(o.amount_paid,o.currency)}),Mu&&D(La,{label:"incl. tax",children:Y(Ul,o.currency)}),o.base_currency!=null&&o.base_amount_total!=null&&re(La,{label:"Your price",children:[Y(o.base_amount_total,o.base_currency),re("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",o.currency.toUpperCase()]})]}),o.amount_refunded>0&&re(Om,{children:[re(La,{label:"Refunded",children:["\u2212",Y(o.amount_refunded,o.currency),(o.shipping_refunded??0)>0&&re("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",Y(o.shipping_refunded??0,o.currency)," ","shipping"]})]}),D(La,{label:"Net",children:D("span",{className:"af-font-medium",children:Y(Math.max(0,di(o)-o.amount_refunded),o.currency)})})]})]})}),o.application_fee_state&&re(On,{title:"Platform fee",children:[o.application_fee_original!=null&&D(La,{label:"Collected",children:Y(o.application_fee_original,o.application_fee_currency??o.currency)}),o.application_fee_returned!=null&&D(La,{label:"Returned",children:Y(o.application_fee_returned,o.application_fee_currency??o.currency)}),o.application_fee_retained!=null&&D(La,{label:"Retained",children:Y(o.application_fee_retained,o.application_fee_currency??o.currency)}),o.application_fee_state!=="complete"&&D("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:o.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),D(On,{title:"Timeline",children:D("ol",{className:"af-space-y-3",children:Ms.map(F=>re("li",{className:"af-flex af-gap-3",children:[D("span",{"aria-hidden":"true",className:G("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",F.tone==="destructive"?"af-bg-destructive":F.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),re("div",{className:"af-min-w-0",children:[D("div",{className:"af-text-sm af-break-words",children:F.text}),F.at&&D("div",{className:"af-text-xs af-text-muted-foreground",children:Eo(F.at)})]})]},F.key))})})]}),re("div",{className:"af-space-y-6",children:[D(On,{title:"Customer",children:re("div",{className:"af-space-y-2",children:[re("div",{children:[D("div",{className:Ns,children:"Email"}),re("div",{className:"af-flex af-items-center af-gap-1",children:[D("span",{className:"af-min-w-0 af-break-all af-text-sm",children:o.customer_email||D("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),o.customer_email&&D(Lo,{value:o.customer_email,label:"Copy email"})]})]}),o.customer_name&&re("div",{children:[D("div",{className:Ns,children:"Name"}),D("div",{className:"af-text-sm",children:o.customer_name})]}),o.customer&&re("div",{children:[D("div",{className:Ns,children:"Customer record"}),re("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[D("span",{className:"af-break-all af-text-sm",children:o.customer.name||o.customer.email}),D(ee,{variant:"secondary",children:"Linked"})]})]})]})}),o.shipping_address&&D(On,{title:"Ship to",action:D(Lo,{value:Q,label:"Copy address",size:"sm",children:"Copy address"}),children:D("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:wc(o.shipping_address).map((F,Xe)=>D("div",{children:F},Xe))})}),o.subscription_history_only?D(On,{title:"Subscription history",children:D("p",{className:"af-text-sm af-text-muted-foreground",children:"This renewal had no payment due. No items were fulfilled and no purchase receipt was sent."})}):re(On,{title:"Emails",children:[D(In,{deliveries:o.email_deliveries?.filter(F=>!["purchase_receipt","merchant_sale"].includes(F.kind)),problemsOnly:!0,className:"af-mb-4"}),re("div",{className:"af-space-y-4",children:[D(xc,{side:"buyer",title:"Receipt to buyer",delivery:o.email_deliveries?.find(F=>F.kind==="purchase_receipt"),recipient:o.customer_email,status:o.buyer_email_status,attempts:o.buyer_email_attempts,orderStatus:o.status,action:re(y,{variant:"outline",size:"sm",onClick:ke,disabled:f||o.fulfillment_status!=="fulfilled",children:[f?D(yi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(bc,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),D(xc,{side:"merchant",title:"Sale alert to you",delivery:o.email_deliveries?.find(F=>F.kind==="merchant_sale"),recipient:null,status:o.merchant_email_status,attempts:o.merchant_email_attempts,orderStatus:o.status})]})]}),Ge&&D(On,{title:"Download",children:re("div",{className:"af-space-y-2",children:[re("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[D(Nm,{className:"af-h-4 af-w-4"}),re("span",{children:["Downloaded ",o.download_count," time",o.download_count===1?"":"s"]})]}),o.download_url&&D("a",{href:o.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),re("details",{className:"af-rounded-lg af-border af-p-4",children:[D("summary",{className:G(Sc,"af-cursor-pointer af-select-none"),children:"Technical details"}),re("div",{className:"af-mt-3 af-space-y-2",children:[D(Io,{label:"Order ID",value:o.id}),o.stripe_checkout_session_id&&D(Io,{label:"Checkout session",value:o.stripe_checkout_session_id}),o.stripe_payment_intent_id&&D(Io,{label:"Payment",value:o.stripe_payment_intent_id})]})]})]})]}),D(on,{open:P,onOpenChange:F=>{!F&&!x&&h(!1)},children:re(Ka,{children:[re(Za,{children:[D(Ja,{children:"Reset download count?"}),D(Xa,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),re(Ya,{children:[D(y,{variant:"outline",onClick:()=>h(!1),disabled:x,children:"Cancel"}),D(y,{onClick:rt,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),D(on,{open:Z,onOpenChange:F=>{!F&&!de&&U(!1)},children:re(Ka,{children:[re(Za,{children:[D(Ja,{children:"Refund order"}),re(Xa,{children:["Refund up to ",Y(oe,o.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),re("div",{className:"af-space-y-4",children:[(o.line_items.length>0||B>0)&&re("div",{className:"af-space-y-2",children:[D(Ie,{children:"Items"}),re("div",{className:"af-space-y-2",children:[o.line_items.map((F,Xe)=>{let Ia=F.refunded===!0;return re("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[D("input",{type:"checkbox",checked:fe.includes(Xe),onChange:()=>ot(Xe),disabled:de||Ia||!!F.unavailableReason||O(F)<=0,className:"af-h-4 af-w-4"}),re("span",{className:Ia?"af-text-muted-foreground af-line-through":void 0,children:[typeof F.name=="string"&&F.name?F.name:"Item",typeof F.variantTitle=="string"&&F.variantTitle?` \u2014 ${F.variantTitle}`:"",typeof F.quantity=="number"&&F.quantity>1?` \xD7 ${F.quantity}`:""]}),D("span",{className:"af-ml-auto af-text-muted-foreground",children:Ia?"Refunded":Y(O(F),o.currency)})]},Xe)}),B>0&&re("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[D("input",{type:"checkbox",checked:W,onChange:F=>A(F.target.checked),disabled:de,className:"af-h-4 af-w-4"}),D("span",{children:"Shipping"}),D("span",{className:"af-ml-auto af-text-muted-foreground",children:Y(B,o.currency)})]})]})]}),re("div",{className:"af-space-y-2",children:[re(Ie,{htmlFor:"refund-amount",children:["Amount (",o.currency.toUpperCase(),")"]}),D(te,{id:"refund-amount",type:"number",min:"0",step:pe,value:Ke?String(Et(ht,o.currency)):ae,onChange:F=>le(F.target.value),disabled:de||Ke}),Ke&&D("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Le&&D("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Le}),re(Ya,{children:[D(y,{variant:"outline",onClick:()=>U(!1),disabled:de,children:"Cancel"}),D(y,{variant:"outline",onClick:$,disabled:de,children:"Refund everything"}),D(y,{variant:"destructive",onClick:yt,disabled:de,children:de?"Refunding...":Ct!==null&&Ct>0?`Refund ${Y(Ct,o.currency)}`:"Refund"})]})]})})]})}import*as Si from"react";import{ArrowLeft as Bm,RefreshCw as Fm}from"lucide-react";import{jsx as Oa,jsxs as is}from"react/jsx-runtime";function Ft({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:n}){let r=Si.useRef(null);return Si.useEffect(()=>{r.current?.focus()},[]),is("div",{className:G("af-bg-background",n),children:[is("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[Oa("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!a&&is(y,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[Oa(Bm,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Oa("div",{className:"af-p-4",children:s})]})}function J({className:e}){return Oa("div",{"aria-hidden":"true",className:G("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function mt({label:e,children:t,detail:a,valueClassName:s}){return is("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Oa("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Oa("div",{className:G("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&Oa("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function Nt({message:e,onRetry:t}){return is("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Oa("span",{children:e}),is(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[Oa(Fm,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function ba({icon:e,children:t}){return is("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Oa("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function zs({icon:e,heading:t,body:a,action:s,className:n,children:r}){return is("div",{className:G("af-px-6 af-py-10 af-text-center",n),children:[Oa(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),Oa("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),Oa("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&Oa(y,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}import{jsx as V,jsxs as Ue}from"react/jsx-runtime";var zm={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},_c={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Pc(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 kc(e){let t=Array.isArray(e.line_items)?e.line_items:[],a=t[0];if(!a)return"\u2014";let s=typeof a.name=="string"&&a.name?a.name:"Item",n=typeof a.quantity=="number"&&a.quantity>0?a.quantity:1,r=n>1?`${s} \xD7${n}`:s;return t.length>1?`${r} +${t.length-1} more`:r}function Ni(e){return e.customer?.name||e.customer_name||null}function qm({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:n=!1,emptyMessage:r,onDetailOpenChange:i,maxRows:l,onViewAll:u}){let d=typeof l=="number",{api:o}=H(),c=gi({refreshKey:a}),{orders:b,total:g,isLoading:m,error:p,page:f,pageSize:v,hasNextPage:x,hasPreviousPage:R,setPage:P,setPageSize:h,customerEmail:S,setCustomerEmail:N,setStatusIn:C,from:w,setFrom:k,to:T,setTo:_,showAbandoned:z,setShowAbandoned:Z,setUnfulfilledOnly:U,filters:ae,refetch:le}=c,fe=Xt.useCallback(()=>o.exportOrdersCsv(ae),[o,ae]),[M,W]=Xt.useState("list"),[A,de]=Xt.useState(null),[ce,Le]=Xt.useState(""),[ye,Te]=Xt.useState(""),[Oe,oe]=Xt.useState(!d&&n?"needs_shipping":"all"),[st,E]=Xt.useState(!1),[O,B]=Xt.useState(!!s&&!d),[we,X]=Xt.useState(null);Xt.useEffect(()=>{if(!s||d)return;let Q=!1;return B(!0),X(null),o.getOrder(s).then(Na=>{Q||(de(Na),W("detail"))}).catch(()=>{Q||X("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{Q||B(!1)}),()=>{Q=!0}},[o,s,d]);let ve=Xt.useCallback(Q=>{oe(Q);let Na=_c[Q];C(Na.statusIn),U(Na.unfulfilledOnly)},[C,U]);Xt.useEffect(()=>{n&&!d&&U(!0)},[]);let Me=Xt.useRef(!n);Xt.useEffect(()=>{Me.current||m||(Me.current=!0,b.length===0&&ve("all"))},[m,b.length,ve]);let ht=M==="detail"&&!!A;Xt.useEffect(()=>{i?.(ht)},[ht,i]);let Ke=(w?1:0)+(T?1:0)+(z?1:0),Ct=Ke>0||!!S||!!ye,pe=!!w&&!!T&&w>T,ke=!d||!!u,rt=Q=>{if(d){u?.();return}de(Q),W("detail")},Je=()=>{W("list"),de(null),le()},zt=Q=>{let Na=Q.trim();if(!Na){Te(""),S&&N("");return}if(Na.startsWith("#")||/^\d+$/.test(Na)){Te(Na),S&&N("");return}Te(""),N(Na)},Ot=()=>{Le(""),Te(""),N(""),k(""),_(""),Z(!1),E(!1)},sa=ye.replace(/^#/,"").toLowerCase(),it=sa?b.filter(Q=>String(Q.order_number??"")===sa||Q.id.toLowerCase().startsWith(sa)):b,vt=d?it.slice(0,l):it,xe=A?b.findIndex(Q=>Q.id===A.id):-1,ot=xe>0,Ze=xe>=0&&xe<b.length-1;if(O)return V("div",{className:t,children:V("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:V(Um,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(M==="detail"&&A)return V("div",{className:t,children:V(wi,{order:A,onBack:Je,onRefund:e,onOrderUpdated:Q=>de(Q),allowFulfillment:n,onPrevOrder:ot?()=>de(b[xe-1]):void 0,onNextOrder:Ze?()=>de(b[xe+1]):void 0,hasPrevOrder:ot,hasNextOrder:Ze},A.id)});let $=Ue("div",{className:"af-mb-4 af-space-y-3",children:[we&&V("p",{className:"af-text-xs af-text-muted-foreground",children:we}),Ue("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[V("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(Q=>V("button",{type:"button","aria-pressed":Oe===Q,onClick:()=>ve(Q),className:G("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Oe===Q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:zm[Q]},Q))}),Ue("div",{className:"af-relative af-w-full af-max-w-xs",children:[V(Vm,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),V(te,{type:"text",value:ce,onChange:Q=>Le(Q.target.value),onBlur:()=>zt(ce),onKeyDown:Q=>{Q.key==="Enter"&&(Q.preventDefault(),zt(ce))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),Ue(y,{type:"button",variant:Ke>0?"secondary":"ghost",size:"sm",onClick:()=>E(Q=>!Q),"aria-expanded":st,children:[V(Hm,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ke>0&&V(ee,{variant:"secondary",className:"af-ml-2",children:Ke})]}),Ct&&V(y,{type:"button",variant:"ghost",size:"sm",onClick:Ot,children:"Clear filters"}),V(ga,{fetchCsv:fe,filename:"orders",disabled:!!ye,className:"af-ml-auto"})]}),(st||!!w||!!T)&&Ue("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2",children:[V(Ie,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),V(te,{id:"orders-from",type:"date",value:w,max:T||void 0,onChange:Q=>k(Q.target.value),className:"af-w-[170px]"}),V(Ie,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),V(te,{id:"orders-to",type:"date",value:T,min:w||void 0,onChange:Q=>_(Q.target.value),className:"af-w-[170px]"}),!_c[Oe].statusIn&&V(y,{type:"button",variant:z?"secondary":"ghost",size:"sm",onClick:()=>Z(!z),"aria-pressed":z,children:z?"Hide abandoned":"Show abandoned"})]}),pe&&V("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(m)return Ue("div",{className:t,children:[d?null:$,V("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(Q=>Ue("div",{className:"af-rounded-md af-border af-p-3",children:[Ue("div",{className:"af-flex af-items-center af-justify-between",children:[V(J,{className:"af-h-4 af-w-16"}),V(J,{className:"af-h-4 af-w-14"})]}),V(J,{className:"af-mt-2 af-h-3 af-w-40"}),V(J,{className:"af-mt-2 af-h-3 af-w-24"})]},Q))}),V("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ue(lt,{children:[V(ct,{children:Ue(Ce,{children:[V(q,{children:"Order"}),V(q,{children:"Date"}),V(q,{children:"Customer"}),V(q,{children:"Items"}),V(q,{className:"af-text-right",children:"Total"}),V(q,{children:"Status"}),V(q,{className:"af-w-8"})]})}),V(dt,{"aria-hidden":"true",children:[0,1,2,3,4].map(Q=>Ue(Ce,{children:[V(j,{children:V(J,{className:"af-h-4 af-w-14"})}),V(j,{children:V(J,{className:"af-h-4 af-w-24"})}),V(j,{children:V(J,{className:"af-h-4 af-w-40"})}),V(j,{children:V(J,{className:"af-h-4 af-w-32"})}),V(j,{children:V(J,{className:"af-ml-auto af-h-4 af-w-16"})}),V(j,{children:V(J,{className:"af-h-5 af-w-16"})}),V(j,{})]},Q))})]})}),V("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(p)return Ue("div",{className:t,children:[d?null:$,Ue("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[V("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),V(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>le(),children:"Try again"})]})]});let Ge=Oe!=="all";if(it.length===0&&f===0)return Ct||Ge?Ue("div",{className:t,children:[!d&&$,V(ba,{children:"No orders match these filters."})]}):V("div",{className:t,children:V(zs,{icon:$m,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!d&&V(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>Z(!0),children:"Show abandoned checkouts"})})});let ra=f*v+1,Ms=Math.min((f+1)*v,g);return Ue("div",{className:t,children:[d?null:$,V("div",{className:"af-space-y-3 lg:af-hidden",children:vt.map(Q=>Ue("button",{type:"button",onClick:()=>rt(Q),disabled:!ke,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${ke?" hover:af-bg-muted/50":""}`,children:[Ue("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[V("span",{className:"af-font-medium",children:Xn(Q)}),V("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:Y(Jn(Q),Q.currency)})]}),Ue("div",{className:"af-mt-1 af-min-w-0",children:[Ue("div",{className:"af-truncate af-text-sm",children:[Q.customer_email||V("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Ni(Q)&&Ue("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Ni(Q)]})]}),V("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:kc(Q)}),Q.amount_refunded>0&&Ue("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Y(Q.amount_refunded,Q.currency)," refunded"]})]}),Ue("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[V(ws,{status:Q.status}),V(hr,{deliveries:Q.email_deliveries}),Q.is_test&&V(ee,{variant:"outline",children:"Test"}),n&&V(Hs,{order:Q}),V("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Pc(Q.created_at)})]})]},Q.id))}),V("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ue(lt,{children:[V(ct,{children:Ue(Ce,{children:[V(q,{children:"Order"}),V(q,{children:"Date"}),V(q,{children:"Customer"}),V(q,{children:"Items"}),V(q,{className:"af-text-right",children:"Total"}),V(q,{children:"Status"}),V(q,{className:"af-w-8"})]})}),V(dt,{children:vt.map(Q=>Ue(Ce,{onClick:ke?()=>rt(Q):void 0,className:ke?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[Ue(j,{className:"af-whitespace-nowrap af-font-medium",children:[V("button",{type:"button",onClick:Na=>{Na.stopPropagation(),rt(Q)},disabled:!ke,"aria-label":`Open order ${Xn(Q)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${ke?" hover:af-underline":""}`,children:Xn(Q)}),Q.is_test&&V(ee,{variant:"outline",className:"af-ml-2",children:"Test"})]}),V(j,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Pc(Q.created_at)}),Ue(j,{className:"af-max-w-[220px]",children:[V("div",{className:"af-truncate",children:Q.customer_email||V("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Ni(Q)&&V("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Ni(Q)})]}),V(j,{className:"af-max-w-[220px]",children:V("div",{className:"af-truncate af-text-muted-foreground",children:kc(Q)})}),Ue(j,{className:"af-whitespace-nowrap af-text-right",children:[V("div",{className:"af-font-medium af-tabular-nums",children:Y(Jn(Q),Q.currency)}),Q.amount_refunded>0&&Ue("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",Y(Q.amount_refunded,Q.currency)," ","refunded"]})]}),V(j,{children:Ue("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[V(ws,{status:Q.status}),V(hr,{deliveries:Q.email_deliveries}),n&&V(Hs,{order:Q})]})}),V(j,{className:"af-w-8 af-text-right",children:V(Rc,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},Q.id))})]})}),d?null:Ue("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Ue("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[V("span",{children:sa?`${it.length} matching this page`:`Showing ${ra}-${Ms} of ${g}`}),Ue(sn,{value:String(v),onValueChange:Q=>h(Number(Q)),children:[V(Wa,{className:"af-w-[70px] af-h-8",children:V(rn,{})}),Ue(Ga,{children:[V(xt,{value:"10",children:"10"}),V(xt,{value:"25",children:"25"}),V(xt,{value:"50",children:"50"}),V(xt,{value:"100",children:"100"})]})]}),V("span",{children:"per page"})]}),Ue("div",{className:"af-flex af-items-center af-gap-2",children:[Ue(y,{variant:"outline",size:"sm",onClick:()=>P(f-1),disabled:!R,children:[V(Mm,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ue(y,{variant:"outline",size:"sm",onClick:()=>P(f+1),disabled:!x,children:["Next",V(Rc,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function os(e){return V(qm,{...e},e.maxRows==null?"full":"compact")}import*as qs from"react";import{ChevronLeft as Km,ChevronRight as Zm,Eye as Ym,Search as Jm,Users as Xm}from"lucide-react";import*as Ba from"react";function Ri({initialPageSize:e=25}={}){let{api:t}=H(),[a,s]=Ba.useState([]),[n,r]=Ba.useState(0),[i,l]=Ba.useState(!0),[u,d]=Ba.useState(null),[o,c]=Ba.useState(0),[b,g]=Ba.useState(e),[m,p]=Ba.useState(""),f=Ba.useRef(0),v=Ba.useCallback(async()=>{let R=++f.current;try{l(!0),d(null);let P={limit:b,offset:o*b};m.trim()&&(P.email=m.trim());let h=await t.getCustomers(P);if(R!==f.current)return;s(h.customers),r(h.total)}catch(P){if(R!==f.current)return;d(P instanceof Error?P:new Error("Failed to fetch customers"))}finally{R===f.current&&l(!1)}},[t,o,b,m]);Ba.useEffect(()=>{v()},[v]);let x=Math.ceil(n/b);return{customers:a,total:n,isLoading:i,error:u,page:o,pageSize:b,hasNextPage:o<x-1,hasPreviousPage:o>0,setPage:c,setPageSize:R=>{g(R),c(0)},email:m,setEmail:R=>{p(R),c(0)},refetch:v}}import*as Rs from"react";import{ArrowLeft as jm,Loader2 as Wm}from"lucide-react";import{jsx as et,jsxs as fa}from"react/jsx-runtime";function Cc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Gm(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let a=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return a&&t.push(a),e.country&&t.push(e.country),t}function _i({customer:e,onBack:t,className:a}){let{api:s}=H(),[n,r]=Rs.useState(null),[i,l]=Rs.useState([]),[u,d]=Rs.useState(!0),[o,c]=Rs.useState(null);Rs.useEffect(()=>{let m=!1;return d(!0),c(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([p,f])=>{m||(r(p),l(f.orders))}).catch(p=>{m||c(p instanceof Error?p.message:"Failed to load customer")}).finally(()=>{m||d(!1)}),()=>{m=!0}},[s,e.id,e.email]);let b=n?.addresses??[],g=n?.order_count??i.length;return fa("div",{className:a,children:[fa("div",{className:"af-mb-6",children:[fa(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[et(jm,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),et("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),fa("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Cc(e.created_at)]})]}),u?et("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:et(Wm,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):o?et("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o}):fa("div",{className:"af-space-y-6",children:[et(In,{deliveries:n?.email_deliveries}),fa("div",{children:[et("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),fa("div",{className:"af-space-y-1 af-text-sm",children:[fa("div",{className:"af-flex af-gap-2",children:[et("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),et("span",{children:e.email})]}),e.name&&fa("div",{className:"af-flex af-gap-2",children:[et("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),et("span",{children:e.name})]}),e.phone&&fa("div",{className:"af-flex af-gap-2",children:[et("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),et("span",{children:e.phone})]}),fa("div",{className:"af-flex af-gap-2",children:[et("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),et("span",{children:g})]})]})]}),b.length>0&&fa("div",{children:[et("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),et("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(m=>fa("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[m.is_default&&et(ee,{variant:"secondary",className:"af-mb-1",children:"Default"}),Gm(m).map((p,f)=>et("div",{children:p},f))]},m.id))})]}),fa("div",{children:[et("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),i.length===0?et("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):fa(lt,{children:[et(ct,{children:fa(Ce,{children:[et(q,{children:"Date"}),et(q,{children:"Amount"}),et(q,{children:"Status"})]})}),et(dt,{children:i.map(m=>fa(Ce,{children:[et(j,{className:"af-text-muted-foreground",children:Cc(m.created_at)}),et(j,{children:Y(Jn(m),m.currency)}),et(j,{children:et(Ss,{status:m.status})})]},m.id))})]})]})]})]})}import{Fragment as ep,jsx as $e,jsxs as Wt}from"react/jsx-runtime";function Qm(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Pi({className:e}){let{customers:t,total:a,isLoading:s,error:n,page:r,pageSize:i,hasNextPage:l,hasPreviousPage:u,setPage:d,setPageSize:o,email:c,setEmail:b,refetch:g}=Ri(),{api:m}=H(),p=qs.useCallback(()=>m.exportCustomersCsv(),[m]),[f,v]=qs.useState("list"),[x,R]=qs.useState(null),[P,h]=qs.useState(""),S=T=>{R(T),v("detail")},N=()=>{v("list"),R(null),g()};if(f==="detail"&&x)return $e("div",{className:e,children:$e(_i,{customer:x,onBack:N})});let C=Wt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[$e(te,{type:"email",value:P,onChange:T=>h(T.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),b(P.trim()))}}),Wt(y,{type:"button",variant:"outline",size:"sm",onClick:()=>b(P.trim()),children:[$e(Jm,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),c&&$e(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),b("")},children:"Clear"}),$e(ga,{fetchCsv:p,filename:"customers",className:"af-ml-auto"})]});if(s)return Wt("div",{className:e,children:[C,$e("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:$e("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return Wt("div",{className:e,children:[C,$e("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Wt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&r===0)return Wt("div",{className:e,children:[c&&C,Wt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[$e(Xm,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),$e("p",{className:"af-text-muted-foreground af-text-center",children:c?"No customers match that email.":Wt(ep,{children:["No customers yet.",$e("br",{}),"Customers appear here after their first purchase."]})})]})]});let w=r*i+1,k=Math.min((r+1)*i,a);return Wt("div",{className:e,children:[C,Wt(lt,{children:[$e(ct,{children:Wt(Ce,{children:[$e(q,{children:"Email"}),$e(q,{children:"Name"}),$e(q,{children:"Phone"}),$e(q,{children:"Customer since"}),$e(q,{className:"af-text-right",children:"Actions"})]})}),$e(dt,{children:t.map(T=>Wt(Ce,{children:[$e(j,{className:"af-font-medium",children:T.email}),$e(j,{children:T.name||$e("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),$e(j,{children:T.phone||$e("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),$e(j,{className:"af-text-muted-foreground",children:Qm(T.created_at)}),$e(j,{className:"af-text-right",children:$e(y,{variant:"ghost",size:"icon",onClick:()=>S(T),title:"View customer",children:$e(Ym,{className:"af-h-4 af-w-4"})})})]},T.id))})]}),Wt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Wt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Wt("span",{children:["Showing ",w,"-",k," of ",a]}),Wt(sn,{value:String(i),onValueChange:T=>o(Number(T)),children:[$e(Wa,{className:"af-w-[70px] af-h-8",children:$e(rn,{})}),Wt(Ga,{children:[$e(xt,{value:"10",children:"10"}),$e(xt,{value:"25",children:"25"}),$e(xt,{value:"50",children:"50"}),$e(xt,{value:"100",children:"100"})]})]}),$e("span",{children:"per page"})]}),Wt("div",{className:"af-flex af-items-center af-gap-2",children:[Wt(y,{variant:"outline",size:"sm",onClick:()=>d(r-1),disabled:!u,children:[$e(Km,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Wt(y,{variant:"outline",size:"sm",onClick:()=>d(r+1),disabled:!l,children:["Next",$e(Zm,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as He from"react";import{ArrowLeft as tp,ChevronLeft as ap,ChevronRight as Tc,Copy as np,Download as sp,ExternalLink as rp,FileText as Dc,Loader2 as ip,Search as op}from"lucide-react";import*as Gt from"react";function js({initialPageSize:e=25,refreshKey:t,includeAggregates:a=!1}={}){let{api:s}=H(),[n,r]=Gt.useState([]),[i,l]=Gt.useState(0),[u,d]=Gt.useState(null),[o,c]=Gt.useState(!0),[b,g]=Gt.useState(null),[m,p]=Gt.useState(0),[f,v]=Gt.useState(e),[x,R]=Gt.useState(void 0),[P,h]=Gt.useState(""),[S,N]=Gt.useState(""),[C,w]=Gt.useState(""),[k,T]=Gt.useState(""),[_,z]=Gt.useState(""),Z=x?x.join(","):"",U=Gt.useRef(0),ae=Gt.useCallback(async()=>{let fe=++U.current;c(!0),g(null);try{let M={labels:Z?Z.split(","):void 0,customerEmail:P||void 0,q:S||void 0,from:C||void 0,to:k||void 0,retainerId:_||void 0,includeAggregates:a,limit:f,offset:m*f},W=await s.getInvoices(M);if(fe!==U.current)return;if(m>0&&m*f>=W.total){p(Math.max(0,Math.ceil(W.total/f)-1));return}r(W.invoices),l(W.total),a&&d(W.aggregates??null)}catch(M){if(fe!==U.current)return;g(M instanceof Error?M:new Error("Failed to fetch invoices"))}finally{fe===U.current&&c(!1)}},[s,Z,P,S,C,k,_,m,f,a]);Gt.useEffect(()=>{ae()},[ae,t]);let le=fe=>M=>{p(0),fe(M)};return{invoices:n,total:i,aggregates:u,isLoading:o,error:b,page:m,pageSize:f,hasNextPage:(m+1)*f<i,hasPreviousPage:m>0,setPage:p,setPageSize:le(v),labels:x,setLabels:le(R),customerEmail:P,setCustomerEmail:le(h),q:S,setQ:le(N),from:C,setFrom:le(w),to:k,setTo:le(T),retainerId:_,setRetainerId:le(z),clearFilters:()=>{p(0),R(void 0),h(""),N(""),w(""),T(""),z("")},refetch:ae}}import{Fragment as pp,jsx as L,jsxs as se}from"react/jsx-runtime";var lp={creating:"Creating",failed:"Failed",awaiting_payment:"Awaiting payment",overdue:"Overdue",payment_processing:"Payment processing",awaiting_authentication:"Awaiting authentication",paid:"Paid",paid_outside_stripe:"Paid outside Stripe",paid_by_credit:"Paid by credit",partially_refunded:"Partially refunded",refunded:"Refunded",disputed:"Disputed",voided:"Voided",uncollectible:"Marked uncollectible"};function Mo(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:lp[e.label]??e.label}function cp(e){switch(e){case"paid":case"paid_outside_stripe":case"paid_by_credit":return"success";case"overdue":case"disputed":case"failed":return"destructive";case"partially_refunded":case"refunded":case"payment_processing":case"awaiting_authentication":return"warning";case"awaiting_payment":return"secondary";default:return"outline"}}var Fo={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},dp={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Rr({invoice:e,className:t}){return se("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[L(ee,{variant:cp(e.label),className:t,children:Mo(e)}),e.collection_method==="charge_automatically"&&L(ee,{variant:"secondary",children:"Managed in Stripe"})]})}function Ti({delivery:e,className:t}){if(!e)return null;let a=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return L(ee,{variant:a,className:t,children:Fo[e.state]??e.state})}function Ws(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function fn(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 Ec={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},ki={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},Oo=100,Bo=5e3;async function up(e,t){let a=[],s=0;for(let n=0;n<Bo;n+=Oo){let r=await e.getInvoices({...t,limit:Oo,offset:n});if(s=r.total,a.push(...r.invoices),r.invoices.length<Oo||a.length>=s)break}return{invoices:a.slice(0,Bo),total:s,truncated:s>a.length||s>Bo}}function Ac(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],a=e.map(s=>[s.id,Ws(s),Mo(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),Y(s.amount_subtotal,s.currency),Y(s.tax_total,s.currency),Y(s.amount_total,s.currency),s.amount_due===null?"":Y(s.amount_due,s.currency),s.amount_paid===null?"":Y(s.amount_paid,s.currency),Y(s.amount_refunded,s.currency),s.payment_method??"",s.pay_url??"",s.retainer_id??"",s.replaces_order_id??"",s.replaced_by_order_id??"",s.tax_behavior??"",s.discount_total===void 0?"":Y(s.discount_total,s.currency),s.collection_method??""]);return[t,...a].map(s=>s.map(ac).join(",")).join(`
5
+ `)}function fp(e){ni(new Blob([Ac(e)],{type:"text/csv;charset=utf-8"}),ai("invoices"))}function mp({className:e,refreshKey:t,initialInvoiceId:a,onDetailOpenChange:s,onConnectStripe:n,onUpgradePlan:r,needsPaidPlan:i=!1,retainerFilter:l=null,onClearRetainerFilter:u,maxRows:d,onViewAll:o}){let c=typeof d=="number",{api:b}=H(),{invoices:g,total:m,isLoading:p,error:f,page:v,pageSize:x,hasNextPage:R,hasPreviousPage:P,setPage:h,labels:S,setLabels:N,customerEmail:C,setCustomerEmail:w,q:k,setQ:T,from:_,setFrom:z,to:Z,setTo:U,retainerId:ae,setRetainerId:le,refetch:fe}=js({refreshKey:t}),[M,W]=He.useState(typeof d=="number"?"all":"open"),[A,de]=He.useState(""),[ce,Le]=He.useState(null),ye=He.useRef(0),Te=!c||!!o,Oe=He.useCallback($=>{if(c){o?.();return}ye.current++,st(!1),Le($)},[c,o]),[oe,st]=He.useState(!1),[E,O]=He.useState(0),[B,we]=He.useState(null),[X,ve]=He.useState(!1),[Me,ht]=He.useState(0);He.useEffect(()=>{Le($=>{if(!$)return $;let Ge=g.find(ra=>ra.id===$.id);return Ge&&Ge!==$?Ge:$})},[g]);let[Ke,Ct]=He.useState(!1),[pe,ke]=He.useState(null),rt=async()=>{if(!Ke){Ct(!0),ke(null);try{let{invoices:$,total:Ge,truncated:ra}=await up(b,{labels:S,customerEmail:C,q:k,from:_,to:Z,retainerId:ae});fp($),ke(ra?`Exported the first ${$.length.toLocaleString()} of ${Ge.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{ke("Couldn't export \u2014 try again.")}finally{Ct(!1)}}},Je=!C&&!k&&!_&&!Z&&!ae,[zt,Ot]=He.useState(null);He.useEffect(()=>{if(p||m>0||!Je||M!=="open")return;let $=!1;return b.getInvoices({limit:1}).then(Ge=>{$||Ot(Ge.total>0)}).catch(()=>{$||Ot(!0)}),()=>{$=!0}},[b,p,m,Je,M,t]),He.useEffect(()=>{N(c?ki.all:ki.open)},[]),He.useEffect(()=>{let $=l?.id??"";$!==ae&&(le($),$&&(W("all"),N(ki.all),w(""),T(""),de(""),z(""),U("")))},[l?.id]),He.useEffect(()=>{let $=!1;return ve(!1),b.getInvoiceSettings().then(Ge=>{$||we({payments_active:Ge.payments_active,blocked:Ge.blocked})}).catch(()=>{$||ve(!0)}),()=>{$=!0}},[b,t,Me]),He.useEffect(()=>{if(!a||c)return;let $=!1,Ge=ye.current;return st(!1),b.getInvoice(a).then(ra=>{!$&&Ge===ye.current&&Le(ra)}).catch(()=>{!$&&Ge===ye.current&&st(!0)}),()=>{$=!0}},[b,a,E,c]),He.useEffect(()=>{s?.(ce!==null)},[ce,s]);let sa=$=>{W($),N(ki[$])},it=$=>{let Ge=$.trim();if(!Ge){k&&T(""),C&&w("");return}if(Ge.includes("@")){k&&T(""),w(Ge);return}C&&w(""),T(Ge.replace(/^#/,""))},vt=g,xe=c?vt.slice(0,d):vt,ot=oe&&se("div",{role:"alert",className:"af-mb-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't open the requested invoice. ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>O($=>$+1),children:"Retry opening invoice"})]});if(ce)return se("div",{className:e,children:[ot,L(Uo,{invoice:ce,refreshKey:t,onBack:()=>{Oe(null),fe()}},ce.id)]});let Ze=se("div",{className:"af-mb-4 af-space-y-3",children:[X&&se("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>ht($=>$+1),children:"Retry setup check"})]}),ot,B?.blocked&&se("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",B.blocked.reason?`: ${B.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),l&&se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[se(ee,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",l.label]}),u&&L(y,{type:"button",variant:"link",size:"sm",onClick:u,children:"Clear schedule filter"})]}),se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[L("div",{role:"group","aria-label":"Invoice views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Object.keys(Ec).map($=>L("button",{type:"button","aria-pressed":M===$,onClick:()=>sa($),className:G("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",M===$?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ec[$]},$))}),se("div",{className:"af-relative af-w-full af-max-w-xs",children:[L(op,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),L(te,{type:"text",value:A,onChange:$=>de($.target.value),onBlur:()=>it(A),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),it(A))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),se("div",{className:"af-flex af-items-center af-gap-2",children:[L(Ie,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),L(te,{id:"invoices-from",type:"date",value:_,max:Z||void 0,onChange:$=>z($.target.value),className:"af-invoice-date af-w-[150px]"})]}),se("div",{className:"af-flex af-items-center af-gap-2",children:[L(Ie,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),L(te,{id:"invoices-to",type:"date",value:Z,min:_||void 0,onChange:$=>U($.target.value),className:"af-invoice-date af-w-[150px]"})]}),se(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>void rt(),disabled:Ke||p||!!f||m===0,"aria-busy":Ke,children:[L(sp,{className:"af-h-4 af-w-4 af-mr-1"}),Ke?"Exporting\u2026":"Export CSV (all matching)"]})]}),pe&&L("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:pe})]});return p?se("div",{className:e,children:[c?null:Ze,L("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map($=>se("div",{className:"af-rounded-md af-border af-p-3",children:[se("div",{className:"af-flex af-items-center af-justify-between",children:[L(J,{className:"af-h-4 af-w-20"}),L(J,{className:"af-h-4 af-w-16"})]}),L(J,{className:"af-mt-2 af-h-3 af-w-40"})]},$))})]}):f?se("div",{className:e,children:[c?null:Ze,se("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>void fe(),children:"Retry"})]})]}):m===0&&Je&&(M==="all"||zt===!1)&&(M==="open"||M==="all")?B?.blocked?se("div",{className:e,children:[c?null:Ze,L(Ci,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):i?se("div",{className:e,children:[c?null:Ze,L(Ci,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):B&&!B.payments_active?se("div",{className:e,children:[c?null:Ze,L(Ci,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):se("div",{className:e,children:[c?null:Ze,L(Ci,{heading:"No invoices yet",body:!B||X?"Once invoice setup is ready, you can send invoices from the chat.":"Ask in the chat to send an invoice to a client for your services."})]}):se("div",{className:e,children:[c?null:Ze,xe.length===0?L("div",{className:"af-rounded-md af-border af-px-3 af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:"No invoices match."}):se(pp,{children:[L("div",{className:"af-space-y-3 lg:af-hidden",children:xe.map($=>se("button",{type:"button",onClick:()=>Oe($),disabled:!Te,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Te?" hover:af-bg-muted/50":""}`,children:[se("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[L("span",{className:"af-font-medium",children:Ws($)}),L(Rr,{invoice:$})]}),L("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:$.customer_name??$.customer_email??"\u2014"}),$.delivery&&L("div",{className:"af-mt-1",children:L(Ti,{delivery:$.delivery})}),se("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[L("span",{children:$.collection_method==="charge_automatically"?"Automatic collection":$.due_at?`Due ${fn($.due_at)}`:"Due on receipt"}),L("span",{className:"af-font-medium af-tabular-nums",children:Y($.amount_due??$.amount_total,$.currency)})]})]},$.id))}),L("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:se(lt,{children:[L(ct,{children:se(Ce,{children:[L(q,{children:"Invoice"}),L(q,{children:"Created"}),L(q,{children:"Customer"}),L(q,{children:"Due"}),L(q,{className:"af-text-right",children:"Amount"}),L(q,{children:"Status"}),L(q,{children:"Delivery"}),L(q,{className:"af-w-8"})]})}),L(dt,{children:xe.map($=>se(Ce,{className:Te?"af-cursor-pointer":void 0,onClick:Te?()=>Oe($):void 0,children:[L(j,{className:"af-font-medium",children:L("button",{type:"button",disabled:!Te,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Te?" hover:af-underline":""}`,onClick:Ge=>{Ge.stopPropagation(),Oe($)},"aria-label":`Open invoice ${Ws($)}`,children:Ws($)})}),L(j,{children:fn($.created_at)}),se(j,{children:[L("div",{children:$.customer_name??"\u2014"}),L("div",{className:"af-text-xs af-text-muted-foreground",children:$.customer_email})]}),L(j,{children:$.collection_method==="charge_automatically"?"Automatic":$.due_at?fn($.due_at):"On receipt"}),L(j,{className:"af-text-right af-tabular-nums",children:Y($.amount_due??$.amount_total,$.currency)}),L(j,{children:L(Rr,{invoice:$})}),L(j,{children:L(Ti,{delivery:$.delivery})}),L(j,{children:L(Tc,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},$.id))})]})}),c?null:se("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[se("span",{children:[m," invoice",m===1?"":"s"]}),se("div",{className:"af-flex af-items-center af-gap-1",children:[L(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(v-1),disabled:!P,"aria-label":"Previous page",children:L(ap,{className:"af-h-4 af-w-4"})}),se("span",{className:"af-tabular-nums",children:[v*x+1,"\u2013",Math.min((v+1)*x,m)]}),L(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>h(v+1),disabled:!R,"aria-label":"Next page",children:L(Tc,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Ci({heading:e,body:t,action:a}){return L(zs,{icon:Dc,heading:e,body:t,action:a})}function cs(e){return L(mp,{...e},e.maxRows==null?"full":"compact")}var Qn="af-text-xs af-text-muted-foreground";function Ic(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Uo({invoice:e,onBack:t,refreshKey:a,className:s}){let{api:n}=H(),r=He.useRef(null);He.useEffect(()=>{r.current?.focus()},[e.id]);let[i,l]=He.useState(!1),[u,d]=He.useState(null),[o,c]=He.useState(!1),[b,g]=He.useState(!1),m=He.useRef(0),[p,f]=He.useState(null),[v,x]=He.useState(!1),[R,P]=He.useState(0);He.useEffect(()=>{let _=!1;return x(!1),n.getInvoice(e.id).then(z=>{_||f({source:e,value:z})}).catch(()=>{_||x(!0)}),()=>{_=!0}},[n,e,a,R]);let h=p?.source===e?p.value:e,S=h.collection_method==="charge_automatically";He.useEffect(()=>(m.current++,d(null),c(!1),g(!1),l(!1),()=>{m.current++}),[n,h,a]);let N=_=>_==null?"\u2014":Y(_,h.currency),C=async()=>{if(!(!h.pay_url||!Ic()))try{await navigator.clipboard.writeText(h.pay_url),l(!0),setTimeout(()=>l(!1),1500)}catch{}},w=async()=>{if(u){d(null);return}let _=++m.current;g(!1),c(!0);try{let z=await n.getInvoicePreview(h.id);_===m.current&&d(z)}catch{_===m.current&&g(!0)}finally{_===m.current&&c(!1)}},k=h.bill_to,T=k?[k.company,k.name,k.address?.line1,k.address?.line2,[k.address?.city,k.address?.state,k.address?.postal_code].filter(Boolean).join(", "),k.address?.country,k.tax_id?`${k.tax_id.value}`:null,k.po_number?`PO ${k.po_number}`:null,k.service_period?`Service period: ${k.service_period}`:null].filter(_=>!!_&&_.length>0):[];return se("div",{className:s,children:[se("div",{className:"af-mb-4",children:[se(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[L(tp,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[se("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",Ws(h)]}),L(Rr,{invoice:h}),L(Ti,{delivery:h.delivery})]}),se("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[h.customer_name??h.customer_email,h.customer_name&&h.customer_email?` \xB7 ${h.customer_email}`:""]})]}),v&&se("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't refresh this invoice. These details may be out of date. ",L(y,{type:"button",variant:"link",size:"sm",onClick:()=>P(_=>_+1),children:"Retry details"})]}),h.label==="failed"&&L("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),h.label==="creating"&&L("p",{role:"status",className:"af-mb-4 af-text-sm af-text-muted-foreground",children:"This invoice is still being created. Its final details will appear when it is ready."}),se("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[se("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[se("section",{className:"af-rounded-md af-border af-p-4",children:[se(lt,{children:[L(ct,{children:se(Ce,{children:[L(q,{children:"Description"}),L(q,{className:"af-text-right",children:"Qty"}),L(q,{className:"af-text-right",children:"Amount"})]})}),L(dt,{children:h.line_items.map((_,z)=>se(Ce,{children:[L(j,{style:{overflowWrap:"anywhere"},children:_.description}),L(j,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_.quantity}),L(j,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:N(_.amount)})]},z))})]}),se("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[L(ls,{label:"Subtotal",value:N(h.amount_subtotal)}),(h.discount_total??0)>0&&L(ls,{label:"Discount",value:`-${N(h.discount_total)}`}),h.tax_total>0&&L(ls,{label:h.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:N(h.tax_total)}),L(ls,{label:"Total",value:N(h.amount_total),strong:!0}),h.credit_applied>0&&L(ls,{label:"Credit applied",value:`-${N(h.credit_applied)}`}),h.amount_due!==null&&h.amount_due!==h.amount_total&&L(ls,{label:"Amount due",value:N(h.amount_due),strong:!0}),h.amount_paid!==null&&h.amount_paid>0&&L(ls,{label:"Amount paid",value:N(h.amount_paid)}),h.amount_refunded>0&&L(ls,{label:"Refunded",value:N(h.amount_refunded)})]}),h.credit_notes?.length>0&&se("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[L("div",{className:Qn,children:"Credit notes"}),h.credit_notes.map(_=>se("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[se("span",{className:"af-text-muted-foreground",children:[fn(_.created_at)," \xB7 ",_.origin==="dashboard"?"issued in Stripe":"refund",_.stripe_credit_note_id?"":" \xB7 being created"]}),se("span",{className:"af-tabular-nums",children:["-",Y(_.amount,_.currency)]})]},_.id))]})]}),(h.note||h.footer)&&se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[h.note&&se("div",{children:[L("div",{className:Qn,children:"Note"}),L("div",{className:"af-whitespace-pre-wrap af-break-words",children:h.note})]}),h.footer&&se("div",{children:[L("div",{className:Qn,children:"Footer"}),L("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:h.footer})]})]}),u&&!S&&se("section",{className:"af-rounded-md af-border af-p-4",children:[se("div",{className:G(Qn,"af-break-words"),children:["Email preview \u2014 ",u.subject]}),L("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),L("iframe",{title:"Invoice email preview",srcDoc:u.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),se("div",{className:"af-min-w-0 af-space-y-4",children:[se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[L(un,{label:"Created",value:fn(h.created_at)}),L(un,{label:"Due",value:h.collection_method==="charge_automatically"?"Managed in Stripe":h.due_at?fn(h.due_at):"On receipt"}),h.paid_at&&L(un,{label:"Paid",value:fn(h.paid_at)}),h.payment_method&&L(un,{label:"Paid by",value:h.paid_out_of_band?`${h.payment_method} (recorded outside Stripe)`:h.payment_method}),h.payment_state!=="none"&&L(un,{label:"Payment",value:h.payment_state==="processing"?"Processing":h.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),h.delivery&&L(un,{label:"Delivery",value:`${Fo[h.delivery.state]} \xB7 ${h.delivery.recipient}`}),h.marked_uncollectible_at&&L(un,{label:"Written off",value:fn(h.marked_uncollectible_at)}),h.correction_reason&&L(un,{label:"Correction",value:h.correction_reason}),h.replaced_by_order_id&&L(un,{label:"Replaced by",value:h.replaced_by_order_id}),h.collection_method==="charge_automatically"?L(un,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):h.retainer_id&&L(un,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),h.replaces_order_id&&L(un,{label:"Replaces",value:h.replaces_order_id})]}),se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[L("div",{className:Qn,children:"Reminders"}),S?L("div",{children:"View automatic payment reminders in Stripe."}):h.reminders.disabled?L("div",{children:"Off for this invoice."}):h.reminders.paused_until?se("div",{children:["Paused until ",fn(h.reminders.paused_until),"."]}):h.reminders.next_at?se("div",{children:["Next on ",fn(h.reminders.next_at),"."]}):h.reminders.final_sent_at?se("div",{children:["Final reminder sent ",fn(h.reminders.final_sent_at),"."]}):L("div",{children:"None scheduled."}),!S&&se("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",h.reminders.schedule.length===0?"none":h.reminders.schedule.map(_=>_<0?`${-_}d before`:_===0?"due day":`${_}d after`).join(", ")]})]}),h.communications&&h.communications.length>0&&se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[L("div",{className:Qn,children:"Email delivery history"}),h.communications.map(_=>se("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[se("span",{className:"af-min-w-0 af-break-words",children:[dp[_.kind]??_.kind,_.kind==="reminder"&&_.slot!==null?` #${_.slot}`:"",se("span",{className:"af-text-muted-foreground",children:[" \xB7 ",_.recipient]})]}),se("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Fo[_.state]??_.state," \xB7 ",fn(_.state_at??_.created_at)]})]},_.id))]}),T.length>0&&se("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[L("div",{className:Qn,children:"Bill to"}),T.map((_,z)=>L("div",{className:"af-break-words",children:_},z))]}),se("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[h.pay_url&&se(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void C(),disabled:!Ic(),children:[L(np,{className:"af-h-4 af-w-4 af-mr-1"}),i?"Copied":S?"Copy invoice link":"Copy pay link"]}),h.pdf_url&&L(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:se("a",{href:h.pdf_url,target:"_blank",rel:"noreferrer",children:[L(rp,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!S&&se(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void w(),disabled:o,children:[o?L(ip,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):L(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),u?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!S&&L("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),h.pay_url&&L("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:h.pay_url}),L("p",{className:"af-text-xs af-text-muted-foreground",children:S?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function un({label:e,value:t}){return se("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[L("span",{className:G(Qn,"af-shrink-0"),children:e}),L("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function ls({label:e,value:t,strong:a}){return se("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[L("dt",{className:G(Qn,a&&"af-font-medium af-text-foreground"),children:e}),L("dd",{className:G("af-tabular-nums",a&&"af-font-semibold"),children:t})]})}import{Repeat as gp}from"lucide-react";import{jsx as Vt,jsxs as Nn}from"react/jsx-runtime";var vp={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Lc={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function bp(e){switch(e){case"active":return"success";case"paused":case"canceling":return"warning";case"failed":return"destructive";case"canceled":return"outline";default:return"secondary"}}function Oc(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>Lc[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>Lc[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":vp[e.status]}function Bc(e){let t=e.interval==="year"?"every year":"every month";return`${Y(e.amount,e.currency)} ${t}`}function hp(e){return e.status==="canceled"?`Ended ${Ei(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Ei(e.next_cycle_at)}`:"Ends this period":e.collection_method==="charge_automatically"?"Billing schedule managed in Stripe":e.status==="paused"?"Future invoices paused":e.status==="failed"||e.status==="creating"?"Next invoice not scheduled yet":e.skip_next_cycle?e.next_cycle_at?`Skipping ${Ei(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Ei(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Ei(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),a=new Date(t);return Number.isNaN(a.getTime())?e.slice(0,10):a.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function $o({retainer:e,className:t}){return Vt(ee,{variant:bp(e.status),className:G("af-max-w-full af-whitespace-normal af-break-words",t),children:Oc(e)})}function Gs({retainers:e,isLoading:t,error:a,onRetry:s,onShowCycles:n,activeRetainerId:r,total:i,endedTotal:l=0,isLoadingMore:u=!1,onLoadMore:d,includeEnded:o=!1,onIncludeEndedChange:c,exportCsv:b,className:g}){let m=!!c;if(!t&&!a&&e.length===0&&!(m&&(o||l>0)))return null;let p=i!==void 0?Math.max(0,i-e.length):0;return Nn("section",{className:G("af-mb-6",g),"aria-label":"Recurring invoices",children:[Nn("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[Vt(gp,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),Vt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),Vt("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),m&&Vt(y,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":o,onClick:()=>c?.(!o),children:o?"Hide ended recurring invoices":l>0&&e.length===0?`Show ended recurring invoices (${l})`:"Show ended recurring invoices"}),b&&Vt(ga,{fetchCsv:b,filename:"retainers",className:m?void 0:"af-ml-auto"})]}),a?Nn("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",Vt(y,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?Vt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(f=>Nn("div",{className:"af-rounded-md af-border af-p-3",children:[Vt(J,{className:"af-h-4 af-w-48"}),Vt(J,{className:"af-mt-2 af-h-3 af-w-32"})]},f))}):e.length===0?Vt("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:o?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):Vt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(f=>{let v=r===f.id;return Nn("li",{className:G("af-rounded-md af-border af-p-3",v&&"af-border-primary af-bg-muted/40"),children:[Nn("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[Nn("div",{className:"af-min-w-0",children:[Vt("div",{className:"af-truncate af-font-medium",children:f.customer_name??f.customer_email??"\u2014"}),Vt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:f.description})]}),Vt($o,{retainer:f})]}),f.collection_method==="charge_automatically"?Nn("div",{className:"af-mt-2 af-space-y-1",children:[Vt(ee,{variant:"secondary",children:"Managed in Stripe"}),Vt("p",{className:"af-text-xs af-text-muted-foreground",children:"Automatic charging is enabled in Stripe. View or change the billing terms there. To edit this schedule from the chat, switch it back to sending invoices in Stripe."})]}):Vt("div",{className:"af-mt-2 af-text-sm",children:Bc(f)}),Nn("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-text-xs af-text-muted-foreground",children:[Nn("span",{children:[hp(f)," \xB7 ",f.cycles.count===0?"no invoices yet":`${f.cycles.paid} paid${f.cycles.open>0?`, ${f.cycles.open} open`:""}`]}),f.cycles.count>0&&Vt(y,{type:"button",variant:v?"secondary":"ghost",size:"sm",onClick:()=>n(f),"aria-pressed":v,children:v?"Showing invoices":"View invoices"})]}),f.status==="failed"&&f.operation?.last_error&&Nn("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",f.operation.last_error,". Ask in the chat to try again."]})]},f.id)})}),!t&&!a&&p>0&&d&&Vt("div",{className:"af-mt-2",children:Vt(y,{type:"button",variant:"outline",size:"sm",onClick:d,disabled:u,children:u?"Loading\u2026":`Load more (${p} more)`})})]})}import*as Mc from"react";import{AlertTriangle as Fc,CheckCircle2 as yp,CreditCard as Vo,Loader2 as xp,RefreshCw as wp}from"lucide-react";import{jsx as Rt,jsxs as ia}from"react/jsx-runtime";function Ks({onConnectStripe:e,onUpgradePlan:t,whenActive:a,className:s}){let{status:n,isLoading:r,error:i,refetch:l}=rs(),[u,d]=Mc.useState(!1),o=async()=>{d(!0);try{await l()}finally{d(!1)}};return r&&!n?Rt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Rt("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!n?Rt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ia("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):n.status==="active"?a!==void 0?Rt("div",{className:s,children:a}):Rt("div",{className:s,children:ia("div",{className:"af-flex af-items-start af-gap-3 af-bg-green-50 af-border af-border-green-200 af-rounded-lg af-p-4",children:[Rt(yp,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),ia("div",{children:[Rt("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),ia("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",n.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):ia("div",{className:`af-space-y-4 ${s||""}`,children:[n.reason==="needs_stripe"&&ia("div",{className:"af-space-y-3",children:[ia("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Rt(Vo,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),ia("div",{children:[Rt("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),Rt("p",{className:"af-text-sm af-text-muted-foreground",children:"It only takes a few minutes. You'll enter your details with Stripe, who handle the payments, and money from sales goes straight to your own bank."})]})]}),e?ia(y,{onClick:e,children:[Rt(Vo,{className:"af-h-4 af-w-4 af-mr-1"}),n.stripe_account_connected?"Finish setting up":"Set up payments"]}):Rt("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),n.reason==="needs_paid_plan"&&ia("div",{className:"af-space-y-3",children:[ia("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Rt(Fc,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),ia("div",{children:[Rt("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),Rt("p",{className:"af-text-sm af-text-muted-foreground",children:"Your products are saved as drafts. Upgrade to a paid plan to start accepting payments on your site."})]})]}),t?Rt(y,{onClick:t,children:"Upgrade plan"}):Rt("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),n.reason==="account_disabled"&&ia("div",{className:"af-space-y-3",children:[ia("div",{className:"af-flex af-items-start af-gap-3 af-bg-yellow-50 af-border af-border-yellow-200 af-rounded-lg af-p-4",children:[Rt(Fc,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),ia("div",{children:[Rt("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),n.stripe_account_connected?Rt("p",{className:"af-text-sm af-text-yellow-800",children:"Your Stripe account can't currently accept charges. Check your Stripe account for outstanding requirements or notifications \u2014 once Stripe re-enables charges, payments resume here automatically."}):Rt("p",{className:"af-text-sm af-text-yellow-800",children:"Payments are currently paused for this site. If you think this is a mistake, get in touch with support and we'll look into it with you."})]})]}),ia("div",{className:"af-flex af-gap-2",children:[e&&n.stripe_account_connected&&ia(y,{onClick:e,children:[Rt(Vo,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),ia(y,{variant:"outline",onClick:o,disabled:u,children:[u?Rt(xp,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Rt(wp,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as _a from"react";function Ho(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function Zs({includeStats:e=!1,refreshKey:t}={}){let{api:a}=H(),[s,n]=_a.useState([]),[r,i]=_a.useState(!0),[l,u]=_a.useState(null),d=_a.useRef(0),o=_a.useCallback(async()=>{let f=++d.current;try{i(!0),u(null);let v=await a.getProducts(e?{include:"stats"}:{});if(f!==d.current)return;n(v)}catch(v){if(f!==d.current)return;u(v instanceof Error?v:new Error("Failed to fetch products"))}finally{f===d.current&&i(!1)}},[a,e,t]);_a.useEffect(()=>{o()},[o]);let c=_a.useCallback(async f=>{let v=await a.createProduct(f);return n(x=>[v,...x]),v},[a]),b=_a.useCallback(async(f,v)=>{let x=await a.updateProduct(f,v);return n(R=>Ho(R,f,x)),x},[a]),g=_a.useCallback(async f=>{await a.deleteProduct(f),n(v=>v.filter(x=>x.id!==f))},[a]),m=_a.useCallback(async(f,v)=>{let x=await a.attachProductFile(f,v);return n(R=>Ho(R,f,x)),x},[a]),p=_a.useCallback(async(f,v)=>{let x=await a.attachProductFileFromUrl(f,v);return n(R=>Ho(R,f,x)),x},[a]);return{products:s,isLoading:r,error:l,refetch:o,createProduct:c,updateProduct:b,deleteProduct:g,attachProductFile:m,attachProductFileFromUrl:p}}import*as Pa from"react";var zo=["creating","active","paused","canceling"],Sp=["canceled","failed"],Np={statuses:zo},Rp={};function Ys({refreshKey:e,includeEnded:t=!1,limit:a=50}={}){let{api:s}=H(),[n,r]=Pa.useState([]),[i,l]=Pa.useState(0),[u,d]=Pa.useState(0),[o,c]=Pa.useState(!0),[b,g]=Pa.useState(!1),[m,p]=Pa.useState(null),[f,v]=Pa.useState(t),x=Pa.useRef(0),R=Pa.useCallback(async()=>{let h=++x.current;c(!0),g(!1),p(null);try{let S=await s.getRetainers({statuses:f?void 0:zo,limit:a,offset:0});if(h!==x.current)return;if(r(S.retainers),l(S.total),!f&&S.total===0){let N=await s.getRetainers({statuses:Sp,limit:1,offset:0});if(h!==x.current)return;d(N.total)}else d(0)}catch(S){if(h!==x.current)return;p(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{h===x.current&&c(!1)}},[s,f,a]);Pa.useEffect(()=>{R()},[R,e]);let P=Pa.useCallback(async()=>{if(o||b||n.length>=i)return;let h=x.current;g(!0);try{let S=await s.getRetainers({statuses:f?void 0:zo,limit:a,offset:n.length});if(h!==x.current)return;r(N=>{let C=new Set(N.map(w=>w.id));return[...N,...S.retainers.filter(w=>!C.has(w.id))]}),l(S.total)}catch(S){if(h!==x.current)return;p(S instanceof Error?S:new Error("Failed to fetch retainers"))}finally{h===x.current&&g(!1)}},[s,f,a,o,b,n.length,i]);return{retainers:n,total:i,endedTotal:u,hasMore:n.length<i,isLoading:o,isLoadingMore:b,error:m,includeEnded:f,setIncludeEnded:v,loadMore:P,refetch:R,filters:f?Rp:Np}}import{Fragment as Dp,jsx as pt,jsxs as Fa}from"react/jsx-runtime";function Uc({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:n}){let[r,i]=Js.useState(t),[l,u]=Js.useState("list"),[d,o]=Js.useState(null),c=Zs(),{status:b,error:g}=rs(),m=b?.currency,p=R=>{o(R),u("edit")},f=()=>{o(null),u("create")},v=()=>{u("list"),o(null)},x=R=>{o(R),u("edit")};return Fa("div",{className:e,children:[Fa("div",{className:"af-mb-6",children:[pt("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),pt("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Fa(Zr,{value:r,onValueChange:R=>i(R),children:[Fa(br,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Fa(yn,{value:"products",className:"af-gap-2",children:[pt(kp,{className:"af-h-4 af-w-4"}),"Products"]}),Fa(yn,{value:"orders",className:"af-gap-2",children:[pt(Cp,{className:"af-h-4 af-w-4"}),"Orders"]}),Fa(yn,{value:"invoices",className:"af-gap-2",children:[pt(Pp,{className:"af-h-4 af-w-4"}),"Invoices"]}),Fa(yn,{value:"customers",className:"af-gap-2",children:[pt(Ep,{className:"af-h-4 af-w-4"}),"Customers"]}),pt(yn,{value:"promos",children:"Promo codes"}),Fa(yn,{value:"setup",className:"af-gap-2",children:[pt(Tp,{className:"af-h-4 af-w-4"}),"Setup"]})]}),pt(xn,{value:"products",children:l==="list"?pt(fi,{productsState:c,onSelectProduct:p,onCreateProduct:f}):Fa("div",{children:[Fa("div",{className:"af-mb-6",children:[Fa(y,{variant:"ghost",size:"sm",onClick:v,className:"af-mb-2 af--ml-2",children:[pt(_p,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),pt("h3",{className:"af-text-lg af-font-semibold",children:l==="create"?"New Product":d?.name})]}),l==="create"&&!m?pt("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?Fa("div",{className:"af-text-destructive",children:["Error: ",g.message]}):pt("div",{className:"af-text-muted-foreground",children:"Loading..."})}):pt(pi,{productsState:c,product:l==="edit"?d:null,currency:m??"usd",onSaved:x},l==="edit"?d?.id??"edit":"new")]})}),pt(xn,{value:"orders",children:pt(os,{onRefund:s})}),pt(xn,{value:"invoices",children:pt(Ip,{onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),pt(xn,{value:"customers",children:pt(Pi,{})}),pt(xn,{value:"promos",children:pt(Vs,{})}),pt(xn,{value:"setup",children:pt(Ks,{onConnectStripe:a,onUpgradePlan:n})})]})]})}function Ip({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a}){let s=Ys(),[n,r]=Js.useState(null),[i,l]=Js.useState(!1);return Fa(Dp,{children:[!i&&pt(Gs,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:n?.id??null,onShowCycles:u=>r(d=>d?.id===u.id?null:u),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),pt(cs,{onDetailOpenChange:l,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:a,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}import*as Vc from"react";import*as Bn from"react";function Xs({refreshKey:e}={}){let{api:t}=H(),[a,s]=Bn.useState(null),[n,r]=Bn.useState(!0),[i,l]=Bn.useState(null),u=Bn.useRef(0),d=Bn.useCallback(async()=>{let o=++u.current;try{r(!0),l(null);let c=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(o!==u.current)return;s(c)}catch(c){if(o!==u.current)return;l(c instanceof Error?c:new Error("Failed to fetch summary"))}finally{o===u.current&&r(!1)}},[t,e]);return Bn.useEffect(()=>{d()},[d]),{summary:a,isLoading:n,error:i,refetch:d}}import{Fragment as qo,jsx as oa,jsxs as jo}from"react/jsx-runtime";function $c(e,t){if(e.settled.complete)return{headline:Y(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:Y(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${Y(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:Y(0,t),extra:[]}}function Hc({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:n,className:r}){let{summary:i,isLoading:l,error:u,refetch:d}=Xs({refreshKey:e}),[o,c]=Vc.useState(!1),b=oa("div",{className:"af-mb-6",children:u&&!i?oa(Nt,{message:"Couldn't load your revenue summary.",onRetry:()=>d()}):oa("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:l||!i?jo(qo,{children:[oa(mt,{label:"This week",children:oa(J,{className:"af-h-6 af-w-24"})}),oa(mt,{label:"Today",children:oa(J,{className:"af-h-6 af-w-24"})}),oa(mt,{label:"Needs attention",children:oa(J,{className:"af-h-6 af-w-10"})})]}):oa(qo,{children:(()=>{let g=$c(i.revenue.d7,i.currency),m=$c(i.revenue.today,i.currency);return jo(qo,{children:[oa(mt,{label:"This week",detail:g.extra.length>0?oa("div",{children:g.extra.map(p=>oa("div",{children:p},p))}):void 0,children:g.headline}),oa(mt,{label:"Today",detail:m.extra.length>0?oa("div",{children:m.extra.map(p=>oa("div",{children:p},p))}):void 0,children:m.headline}),oa(mt,{label:"Needs attention",valueClassName:i.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:i.needs_attention.count===0?"All clear":i.needs_attention.items[0]?.title??void 0,children:i.needs_attention.count})]})})()})})});return jo(Ft,{title:"Orders",onBackToWebsite:n,hideBackButton:o,className:r,children:[b,oa(os,{refreshKey:e,initialOrderId:t,onDetailOpenChange:c,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as mn from"react";import{ImageOff as Fp,Package as Mp,Search as Up}from"lucide-react";import*as Fn from"react";import{ArrowLeft as Op,ImageOff as Bp}from"lucide-react";import{jsx as Rn,jsxs as _r}from"react/jsx-runtime";var zc="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ds="af-text-xs af-text-muted-foreground",Ii="af-text-sm af-font-medium af-tabular-nums",Ap=3;function Lp(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let u=e.min_amount??t?.min_amount??null,d=e.max_amount??t?.max_amount??null;return u!==null&&d!==null?{text:`Buyer chooses (${Y(u,a)} \u2013 ${Y(d,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(n===null||r===null)return{text:"Varies by variant",compareAt:null};let i=n===r?Y(n,a):`${Y(n,a)} \u2013 ${Y(r,a)}`,l=t?.compare_at_amount??null;return{text:i,compareAt:l!==null&&l>r?Y(l,a):null}}function Di({product:e,className:t}){let a=Lp(e);return _r("div",{className:t,children:[Rn("span",{className:Ii,children:a.text}),a.compareAt&&Rn("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function Ai({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?Rn(ee,{variant:"destructive",children:"Out of stock"}):t.low_stock?_r(ee,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?Rn(ee,{variant:"secondary",children:"Backorder"}):t.available===null?null:_r(ee,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?Rn(ee,{variant:"warning",children:"Low stock"}):null}function Li(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Oi(e){return e.map(t=>Y(t.amount,t.currency)).join(" + ")}function qc(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${Y(e.min_amount,e.currency)} \u2013 ${Y(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":Y(e.unit_amount,e.currency)}function jc({variant:e}){let t=e.inventory;if(!t||!t.tracked)return Rn("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?_r("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Rn("span",{className:"af-tabular-nums",children:Math.max(0,a)}),Rn(ee,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?Rn(ee,{variant:"destructive",children:"Out of stock"}):_r("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Rn("span",{className:"af-tabular-nums",children:a}),a<=Ap&&Rn(ee,{variant:"warning",children:"Low"})]})}import{jsx as he,jsxs as _t}from"react/jsx-runtime";function Pr({title:e,children:t,className:a}){return _t("section",{className:G("af-rounded-lg af-border af-p-4",a),children:[he("h4",{className:zc,children:e}),he("div",{className:"af-mt-3",children:t})]})}function Wc({src:e,className:t}){let[a,s]=Fn.useState(!1);return Fn.useEffect(()=>s(!1),[e]),!e||a?he("div",{"aria-hidden":"true",className:G("af-flex af-items-center af-justify-center af-bg-muted",t),children:he(Bp,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):he("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:G("af-object-cover",t)})}function Gc({product:e,showStats:t=!1,onBack:a}){let{api:s}=H(),[n,r]=Fn.useState(null),[i,l]=Fn.useState(!0),[u,d]=Fn.useState(null),[o,c]=Fn.useState(0),[b,g]=Fn.useState(0);Fn.useEffect(()=>{let h=!1;return l(!0),d(null),s.getProduct(e.id).then(S=>{h||r(S)}).catch(S=>{h||d(S instanceof Error?S:new Error("Failed to load product"))}).finally(()=>{h||l(!1)}),()=>{h=!0}},[s,e.id,o]);let m=n?{...e,...n}:e,p=m.images.length>0?m.images:e.images,f=p[b]??p[0],v=Li(m),x=t?m.stats:void 0,R=n?.variants??[],P=R.length>1;return _t("div",{children:[_t("div",{className:"af-mb-6",children:[_t(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[he(Op,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),_t("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[he("h3",{className:"af-text-xl af-font-semibold af-break-words",children:m.name}),he(ee,{variant:m.active?"success":"secondary",children:m.active?"Active":"Draft"}),he(Ai,{product:m})]}),he(Di,{product:m,className:"af-mt-1"}),!m.active&&he("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),_t("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[_t("div",{className:"af-space-y-2",children:[he(Wc,{src:f,className:"af-h-48 af-w-full af-rounded-md af-border"}),p.length>1&&he("div",{className:"af-flex af-flex-wrap af-gap-2",children:p.map((h,S)=>he("button",{type:"button",onClick:()=>g(S),"aria-label":`Show photo ${S+1} of ${p.length}`,"aria-pressed":S===b,className:G("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",S===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:he(Wc,{src:h,className:"af-h-12 af-w-12 af-rounded-md"})},`${h}-${S}`))})]}),_t("div",{className:"af-space-y-6",children:[m.description&&he(Pr,{title:"Description",children:he("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:m.description})}),i?_t(Pr,{title:"Variants",children:[he("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(h=>_t("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[he(J,{className:"af-h-4 af-w-28"}),he(J,{className:"af-h-4 af-w-20"}),he(J,{className:"af-h-4 af-w-16"})]},h))}),he("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):u?he(Nt,{message:"Couldn't load this product's variants.",onRetry:()=>c(h=>h+1)}):P?he(Pr,{title:`Variants \xB7 ${R.length}`,children:he("div",{className:"af-overflow-x-auto",children:_t(lt,{children:[he(ct,{children:_t(Ce,{children:[he(q,{children:"Variant"}),he(q,{children:"SKU"}),he(q,{className:"af-text-right",children:"Price"}),he(q,{children:"Stock"})]})}),he(dt,{children:R.map(h=>_t(Ce,{children:[_t(j,{className:"af-font-medium",children:[h.title||h.option_values.map(S=>S.value).join(" / ")||"\u2014",!h.active&&he(ee,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),he(j,{className:"af-text-muted-foreground",children:h.sku?he("code",{className:"af-font-mono af-text-xs af-break-all",children:h.sku}):"\u2014"}),_t(j,{className:"af-whitespace-nowrap af-text-right",children:[he("div",{className:Ii,children:qc(h)}),h.compare_at_amount!==null&&h.unit_amount!==null&&h.compare_at_amount>h.unit_amount&&he("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:Y(h.compare_at_amount,h.currency)})]}),he(j,{className:"af-text-sm",children:he(jc,{variant:h})})]},h.id))})]})})}):null,he(Pr,{title:"Details",children:_t("dl",{className:"af-space-y-2",children:[_t("div",{children:[he("dt",{className:ds,children:"Delivery"}),he("dd",{className:"af-text-sm",children:v==="Digital download"?m.fulfillment.filename??"Digital download":v??"Nothing to deliver"})]}),m.fulfillment.type==="redirect"&&m.fulfillment.url&&_t("div",{children:[he("dt",{className:ds,children:"Sends buyers to"}),he("dd",{className:"af-break-all af-text-sm",children:m.fulfillment.url})]}),_t("div",{children:[he("dt",{className:ds,children:"Shipping address"}),he("dd",{className:"af-text-sm",children:m.collect_shipping_address?"Collected at checkout":"Not collected"})]}),_t("div",{children:[he("dt",{className:ds,children:"Most one buyer can order"}),he("dd",{className:"af-text-sm af-tabular-nums",children:m.max_quantity})]})]})}),x&&he(Pr,{title:"Last 30 days",children:_t("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[_t("div",{children:[he("dt",{className:ds,children:"Units sold"}),he("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),_t("div",{children:[he("dt",{className:ds,children:"Orders"}),he("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),_t("div",{children:[he("dt",{className:ds,children:"Gross"}),he("dd",{className:Ii,children:x.gross.length>0?Oi(x.gross):"\u2014"})]})]})}),he("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}import{Fragment as us,jsx as me,jsxs as Pt}from"react/jsx-runtime";var $p={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Vp=["all","active","draft","low_stock","out_of_stock"];function Kc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function Zc(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Hp(e){return e.inventory?.out_of_stock??!1}function zp(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Zc(e);case"out_of_stock":return Hp(e);default:return!0}}function qp({product:e,showStats:t,onOpen:a}){let s=e.images[0],n=t?e.stats:void 0,r=Li(e),i=e.variant_count??0;return Pt("button",{type:"button",onClick:a,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[s?me("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):me("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:me(Fp,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Pt("div",{className:"af-space-y-2 af-p-3",children:[Pt("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Pt("div",{className:"af-min-w-0",children:[me("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),me(Di,{product:e,className:"af-mt-0.5"})]}),!e.active&&me(ee,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Pt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[me(Ai,{product:e}),i>1&&Pt(ee,{variant:"outline",children:[i," variants"]}),r&&me(ee,{variant:"outline",children:r})]}),n&&Pt("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Oi(n.gross)}`:""," ",me("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function jp(){return me("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:[0,1,2,3,4,5].map(e=>Pt("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[me("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),Pt("div",{className:"af-space-y-2 af-p-3",children:[me(J,{className:"af-w-32"}),me(J,{className:"af-w-16"}),me(J,{className:"af-h-5 af-w-24"})]})]},e))})}function Yc({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:n,isLoading:r,error:i,refetch:l}=Zs({includeStats:t,refreshKey:e}),[u,d]=mn.useState(!1),[o,c]=mn.useState(null),[b,g]=mn.useState("all"),{api:m}=H(),p=mn.useCallback(()=>m.exportProductsCsv(),[m]),[f,v]=mn.useState(""),[x,R]=mn.useState("newest"),P=mn.useMemo(()=>{if(!t)return null;let Z=null;for(let U of n)!U.stats||U.stats.units_sold===0||(!Z||U.stats.units_sold>(Z.stats?.units_sold??0))&&(Z=U);return Z},[n,t]),h=mn.useMemo(()=>n.filter(Zc).length,[n]),S=f.trim().toLowerCase(),N=mn.useMemo(()=>{let U=[...n.filter(ae=>zp(ae,b)&&(!S||ae.name.toLowerCase().includes(S)))];return x==="name"?U.sort((ae,le)=>ae.name.localeCompare(le.name)):x==="best_selling"?U.sort((ae,le)=>(le.stats?.units_sold??0)-(ae.stats?.units_sold??0)):U.sort((ae,le)=>Kc(le.created_at)-Kc(ae.created_at)),U},[n,b,S,x]),C=b!=="all"||!!S,w=()=>{g("all"),v("")},k=r||i!==null&&n.length===0,T=me("div",{className:"af-mb-6",children:me("div",{className:G("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:k?Pt(us,{children:[me(mt,{label:"Products",children:me(J,{className:"af-h-6 af-w-10"})}),t?Pt(us,{children:[me(mt,{label:"Best seller",children:me(J,{className:"af-h-6 af-w-28"})}),me(mt,{label:"Low stock",children:me(J,{className:"af-h-6 af-w-10"})})]}):me(mt,{label:"Active",children:me(J,{className:"af-h-6 af-w-10"})})]}):Pt(us,{children:[me(mt,{label:"Products",children:n.length}),t?Pt(us,{children:[me(mt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:P?`${P.stats?.units_sold??0} sold, last 30 days`:void 0,children:P?me("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:P.name}):me("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),me(mt,{label:"Low stock",children:h})]}):me(mt,{label:"Active",children:n.filter(Z=>Z.active).length})]})})}),_=Pt("div",{className:"af-mb-4 af-space-y-3",children:[Pt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[me("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Vp.map(Z=>me("button",{type:"button","aria-pressed":b===Z,onClick:()=>g(Z),className:G("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",b===Z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:$p[Z]},Z))}),Pt("div",{className:"af-relative af-w-full af-max-w-xs",children:[me(Up,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),me(te,{type:"text",value:f,onChange:Z=>v(Z.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Pt(sn,{value:x,onValueChange:Z=>R(Z),children:[me(Wa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:me(rn,{})}),Pt(Ga,{children:[me(xt,{value:"newest",children:"Newest"}),me(xt,{value:"name",children:"Name A\u2013Z"}),t&&me(xt,{value:"best_selling",children:"Best selling"})]})]}),C&&me(y,{type:"button",variant:"ghost",size:"sm",onClick:w,children:"Clear filters"}),me(ga,{fetchCsv:p,filename:"products",label:C?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&n.length===0?me(J,{className:"af-h-4 af-w-28"}):me("p",{className:"af-text-sm af-text-muted-foreground",children:C?`${N.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),z;return o?z=me(Gc,{product:o,showStats:t,onBack:()=>{c(null),l()}},o.id):r&&n.length===0?z=Pt(us,{children:[_,me(jp,{}),me("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):i&&n.length===0?z=me("div",{className:"af-flex af-justify-center af-py-8",children:me(Nt,{message:"Couldn't load your products.",onRetry:()=>l()})}):n.length===0?z=Pt(ba,{icon:me(Mp,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",me("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):z=Pt(us,{children:[_,i&&me("div",{className:"af-mb-4",children:me(Nt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>l()})}),N.length===0?Pt(ba,{children:["No products match these filters.",me("br",{}),me(y,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:w,children:"Show all products"})]}):me("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:N.map(Z=>me(qp,{product:Z,showStats:t,onOpen:()=>c(Z)},Z.id))})]}),me(Ft,{title:"Products",onBackToWebsite:a,hideBackButton:!!o,className:s,children:u?Pt(us,{children:[me(y,{variant:"ghost",onClick:()=>d(!1),children:"Back to products"}),me(Vs,{})]}):Pt(us,{children:[!o&&me("div",{className:"af-mb-4 af-flex af-justify-end",children:me(y,{variant:"outline",onClick:()=>d(!0),children:"Promo codes"})}),!o&&T,z]})})}import*as Ua from"react";import{ArrowLeft as ad,Check as Wp,ChevronLeft as Jc,ChevronRight as Xc,ClipboardCopy as Gp,Mail as Go,Search as Kp,Users as Zp}from"lucide-react";import*as Ma from"react";function Bi({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=Ma.useState([]),[r,i]=Ma.useState(!0),[l,u]=Ma.useState(null),[d,o]=Ma.useState(0),[c]=Ma.useState(e),[b,g]=Ma.useState(""),[m,p]=Ma.useState(void 0),f=Ma.useRef(0),v=Ma.useCallback(async({afterRemoval:x=!1}={})=>{let R=++f.current;try{i(!0),u(null);let P={limit:c,offset:d*c};b.trim()&&(P.q=b.trim()),m&&(P.source=m);let h=await a.getPeople(P);if(R!==f.current)return;if(x&&h.people.length===0&&d>0){o(d-1);return}n(h.people)}catch(P){if(R!==f.current)return;u(P instanceof Error?P:new Error("Failed to fetch people"))}finally{R===f.current&&i(!1)}},[a,d,c,b,m,t]);return Ma.useEffect(()=>{v()},[v]),{people:s,isLoading:r,error:l,page:d,pageSize:c,hasNextPage:s.length===c,hasPreviousPage:d>0,setPage:o,q:b,setQ:x=>{g(x),o(0)},source:m,setSource:x=>{p(x),o(0)},refetch:()=>v(),refetchAfterRemoval:()=>v({afterRemoval:!0})}}import*as Mn from"react";function Fi(e,{refreshKey:t}={}){let{api:a}=H(),[s,n]=Mn.useState(null),[r,i]=Mn.useState(e!==null),[l,u]=Mn.useState(null),d=Mn.useRef(0),o=Mn.useCallback(async()=>{if(e===null){n(null),i(!1),u(null);return}let c=++d.current;try{i(!0),u(null);let b=await a.getPerson(e);if(c!==d.current)return;n(b)}catch(b){if(c!==d.current)return;u(b instanceof Error?b:new Error("Failed to fetch person"))}finally{c===d.current&&i(!1)}},[a,e,t]);return Mn.useEffect(()=>{o()},[o]),{person:s,isLoading:r,error:l,refetch:o}}import{jsx as I,jsxs as be}from"react/jsx-runtime";var Wo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Yp="af-text-xs af-text-muted-foreground";function Qs(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Ko(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function Jp(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Xp({value:e,label:t}){let[a,s]=Ua.useState(!1);return Jp()?be(y,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[a?I(Wp,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):I(Gp,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function Qc(e){return be("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&be(ee,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&I(ee,{variant:"secondary",children:"Contact form"})]})}function ed(e){return e.name?e.name:e.email?e.email:I("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Qp=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,eg=40;function tg(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),s=t.find(([n,r])=>Qp.test(n)&&typeof r=="string"&&r.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=eg).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 ag(e){return e.replace(/_/g," ")}function ng(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function sg({data:e}){let{message:t,rest:a}=tg(e);return t===null&&a.length===0?I("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):be("div",{className:"af-space-y-3",children:[t!==null&&I("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),a.length>0&&I("dl",{className:"af-space-y-1",children:a.map(([s,n])=>be("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[I("dt",{className:G(Yp,"af-w-28 af-shrink-0 af-capitalize"),children:ag(s)}),I("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:ng(n)})]},s))})]})}function nd({formName:e,createdAt:t,data:a,onDelete:s}){return be("div",{className:"af-rounded-md af-border af-p-3",children:[be("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[I(ee,{variant:"outline",children:"Form submission (unverified)"}),e&&I("span",{className:"af-text-xs af-text-muted-foreground",children:e}),I("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Qs(t)}),I($s,{iconOnly:!0,onDelete:s})]}),I(sg,{data:a})]})}function rg(e){return e.charged_total??e.amount_total}function ig({email:e,refreshKey:t,onBack:a,onRemoved:s}){let{api:n}=H(),{person:r,isLoading:i,error:l,refetch:u}=Fi(e,{refreshKey:t}),d=async c=>{await n.deleteSubmission(c),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?u():a()},o=Ko(e,r?.submissions[0]?.form_name);return be("div",{children:[be("div",{className:"af-mb-6",children:[be(y,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[I(ad,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),be("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[be("div",{className:"af-min-w-0",children:[i?I(J,{className:"af-h-7 af-w-48"}):I("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),be("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[I("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),I(Xp,{value:e,label:"Copy email address"})]})]}),I(y,{asChild:!0,children:be("a",{href:o,children:[I(Go,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),i?be("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(c=>be("div",{className:"af-rounded-md af-border af-p-3",children:[I(J,{className:"af-w-40"}),I(J,{className:"af-mt-2 af-w-64"})]},c)),I("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):l||!r?I("div",{className:"af-flex af-justify-center af-py-8",children:I(Nt,{message:"Couldn't load this person.",onRetry:()=>u()})}):be("div",{className:"af-space-y-6",children:[r.customer&&be("div",{children:[I("h4",{className:G(Wo,"af-mb-3"),children:"Customer"}),be("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&be("div",{className:"af-flex af-gap-2",children:[I("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),I("dd",{children:r.customer.name})]}),r.customer.phone&&be("div",{className:"af-flex af-gap-2",children:[I("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),I("dd",{children:r.customer.phone})]}),be("div",{className:"af-flex af-gap-2",children:[I("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),I("dd",{children:Qs(r.customer.created_at)})]})]})]}),r.orders.length>0&&be("div",{children:[I("h4",{className:G(Wo,"af-mb-3"),children:"Purchases"}),I("div",{className:"af-overflow-x-auto",children:be(lt,{children:[I(ct,{children:be(Ce,{children:[I(q,{children:"Order"}),I(q,{children:"Date"}),I(q,{className:"af-text-right",children:"Total"}),I(q,{children:"Status"})]})}),I(dt,{children:r.orders.map(c=>be(Ce,{children:[I(j,{className:"af-whitespace-nowrap af-font-medium",children:Xn(c)}),I(j,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Qs(c.created_at)}),I(j,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:Y(rg(c),c.currency)}),I(j,{children:I(Ss,{status:c.status})})]},c.id))})]})}),I("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),r.submissions.length>0&&be("div",{children:[I("h4",{className:G(Wo,"af-mb-3"),children:"Messages"}),I("div",{className:"af-space-y-3",children:r.submissions.map(c=>I(nd,{formName:c.form_name,createdAt:c.created_at,data:c.data,onDelete:()=>d(c.id)},c.id))})]})]})]})}function og({submissionId:e,onBack:t,onRemoved:a}){let{api:s}=H(),[n,r]=Ua.useState(null),[i,l]=Ua.useState(!0),[u,d]=Ua.useState(null),[o,c]=Ua.useState(0);return Ua.useEffect(()=>{let b=!1;return l(!0),d(null),s.getSubmission(e).then(g=>{b||r(g)}).catch(g=>{b||d(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{b||l(!1)}),()=>{b=!0}},[s,e,o]),be("div",{children:[be("div",{className:"af-mb-6",children:[be(y,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[I(ad,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),I("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?I(J,{className:"af-mt-1 af-h-4 af-w-32"}):n&&I("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Qs(n.metadata.submitted_at)})]}),i?be("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[I(J,{className:"af-w-40"}),I(J,{className:"af-mt-2 af-w-64"}),I(J,{className:"af-mt-2 af-w-52"}),I("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):u||!n?I("div",{className:"af-flex af-justify-center af-py-8",children:I(Nt,{message:"Couldn't load this submission.",onRetry:()=>c(b=>b+1)})}):be("div",{className:"af-space-y-3",children:[I(nd,{formName:null,createdAt:n.metadata.submitted_at,data:n.data,onDelete:async()=>{await s.deleteSubmission(e),a(),t()}}),I("p",{className:"af-text-xs af-text-muted-foreground",children:"No email address came with this submission, so there is nobody to reply to."})]})]})}var lg={all:"All",customers:"Customers",leads:"Leads"},cg=["all","customers","leads"],td={all:void 0,customers:"customer",leads:"lead"};function dg({refreshKey:e,onBackToWebsite:t,className:a,maxRows:s,onViewAll:n}){let r=typeof s=="number",{people:i,isLoading:l,error:u,page:d,pageSize:o,hasNextPage:c,hasPreviousPage:b,setPage:g,q:m,setQ:p,source:f,setSource:v,refetch:x,refetchAfterRemoval:R}=Bi({refreshKey:e}),[P,h]=Ua.useState({kind:"list"}),[S,N]=Ua.useState(""),C=f==="customer"?"customers":f==="lead"?"leads":"all",w=W=>{td[W]!==f&&v(td[W])},{api:k}=H(),T=Ua.useCallback(()=>k.exportPeopleCsv({...m?{q:m}:{},...f?{source:f}:{}}),[k,m,f]),_=!r||!!n,z=W=>{if(r){n?.();return}W.email?h({kind:"person",email:W.email}):W.submission_id&&h({kind:"submission",submissionId:W.submission_id})},Z=Ua.useRef(!1),U=()=>{Z.current=!0},ae=()=>{h({kind:"list"}),Z.current?(Z.current=!1,R()):x()},le=W=>{let A=W.trim();A!==m&&p(A)},fe=r?i.slice(0,s):i,M;if(P.kind==="person")M=I(ig,{email:P.email,refreshKey:e,onBack:ae,onRemoved:U});else if(P.kind==="submission")M=I(og,{submissionId:P.submissionId,onBack:ae,onRemoved:U});else{let W=be("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[I("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:cg.map(A=>I("button",{type:"button","aria-pressed":C===A,onClick:()=>w(A),className:G("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",C===A?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:lg[A]},A))}),be("div",{className:"af-relative af-w-full af-max-w-xs",children:[I(Kp,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),I(te,{type:"text",value:S,onChange:A=>N(A.target.value),onBlur:()=>le(S),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),le(S))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),m&&I(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>{N(""),p("")},children:"Clear search"}),I(ga,{fetchCsv:T,filename:"people",className:"af-ml-auto"})]});if(l)M=be("div",{children:[r?null:W,I("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(A=>be("div",{className:"af-rounded-md af-border af-p-3",children:[be("div",{className:"af-flex af-items-center af-justify-between",children:[I(J,{className:"af-h-4 af-w-32"}),I(J,{className:"af-h-4 af-w-16"})]}),I(J,{className:"af-mt-2 af-h-5 af-w-28"}),I(J,{className:"af-mt-2 af-h-3 af-w-56"})]},A))}),I("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:be(lt,{children:[I(ct,{children:be(Ce,{children:[I(q,{children:"Person"}),I(q,{children:"Came from"}),I(q,{children:"Latest message"}),I(q,{children:"Last activity"}),I(q,{className:"af-w-8"}),I(q,{className:"af-w-8"})]})}),I(dt,{"aria-hidden":"true",children:[0,1,2,3,4].map(A=>be(Ce,{children:[I(j,{children:I(J,{className:"af-h-4 af-w-40"})}),I(j,{children:I(J,{className:"af-h-5 af-w-24"})}),I(j,{children:I(J,{className:"af-h-4 af-w-56"})}),I(j,{children:I(J,{className:"af-h-4 af-w-24"})}),I(j,{}),I(j,{})]},A))})]})}),I("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(u)M=be("div",{children:[r?null:W,I("div",{className:"af-flex af-justify-center af-py-8",children:I(Nt,{message:"Couldn't load your leads.",onRetry:()=>x()})})]});else if(fe.length===0&&d===0){let A=!!m||C!=="all";M=be("div",{children:[A&&W,A?I(ba,{children:m?"Nobody matches that search.":C==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):I(zs,{icon:Zp,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(i.length===0)M=be("div",{children:[r?null:W,I(ba,{children:"No more results."}),I("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:be(y,{variant:"outline",size:"sm",onClick:()=>g(d-1),children:[I(Jc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let A=d*o+1,de=d*o+i.length;M=be("div",{children:[r?null:W,I("div",{className:"af-space-y-3 lg:af-hidden",children:fe.map((ce,Le)=>be("div",{onClick:_?()=>z(ce):void 0,className:`af-rounded-md af-border af-p-3${_?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[be("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[be("div",{className:"af-min-w-0",children:[I("button",{type:"button",onClick:ye=>{ye.stopPropagation(),z(ce)},disabled:!_,"aria-label":`Open ${ce.name||ce.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${_?" hover:af-underline":""}`,children:ed(ce)}),ce.name&&ce.email&&I("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ce.email})]}),be("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[I("span",{className:"af-text-xs af-text-muted-foreground",children:Qs(ce.last_activity_at)}),ce.email&&I(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:I("a",{href:Ko(ce.email),onClick:ye=>ye.stopPropagation(),"aria-label":`Email ${ce.email}`,children:I(Go,{className:"af-h-4 af-w-4"})})})]})]}),I("div",{className:"af-mt-2",children:Qc(ce)}),ce.latest_message_excerpt&&I("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:ce.latest_message_excerpt})]},ce.email??ce.submission_id??Le))}),I("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:be(lt,{children:[I(ct,{children:be(Ce,{children:[I(q,{children:"Person"}),I(q,{children:"Came from"}),I(q,{children:"Latest message"}),I(q,{children:"Last activity"}),I(q,{className:"af-w-8",children:I("span",{className:"af-sr-only",children:"Reply"})}),I(q,{className:"af-w-8"})]})}),I(dt,{children:fe.map((ce,Le)=>be(Ce,{onClick:_?()=>z(ce):void 0,className:_?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[be(j,{className:"af-max-w-[260px] af-font-medium",children:[I("button",{type:"button",onClick:ye=>{ye.stopPropagation(),z(ce)},disabled:!_,"aria-label":`Open ${ce.name||ce.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${_?" hover:af-underline":""}`,children:ed(ce)}),ce.name&&ce.email&&I("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:ce.email})]}),I(j,{children:Qc(ce)}),I(j,{className:"af-max-w-[320px]",children:ce.latest_message_excerpt?I("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:ce.latest_message_excerpt}):I("span",{className:"af-text-muted-foreground",children:"\u2014"})}),I(j,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Qs(ce.last_activity_at)}),I(j,{className:"af-w-8",children:ce.email&&I(y,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:I("a",{href:Ko(ce.email),onClick:ye=>ye.stopPropagation(),"aria-label":`Email ${ce.email}`,children:I(Go,{className:"af-h-4 af-w-4"})})})}),I(j,{className:"af-w-8 af-text-right",children:I(Xc,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},ce.email??ce.submission_id??Le))})]})}),!r&&be("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[I("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${A}-${de}`}),be("div",{className:"af-flex af-items-center af-gap-2",children:[be(y,{variant:"outline",size:"sm",onClick:()=>g(d-1),disabled:!b,children:[I(Jc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),be(y,{variant:"outline",size:"sm",onClick:()=>g(d+1),disabled:!c,children:["Next",I(Xc,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?I("div",{className:a,children:M}):I(Ft,{title:"Leads",onBackToWebsite:t,hideBackButton:P.kind!=="list",className:a,children:M})}function Mi(e){return I(dg,{...e},e.maxRows==null?"full":"compact")}import*as cd from"react";import{ChevronLeft as sd,ChevronRight as ug,Repeat as fg}from"lucide-react";import*as $a from"react";function Ui({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=H(),[s,n]=$a.useState([]),[r,i]=$a.useState(0),[l,u]=$a.useState(!0),[d,o]=$a.useState(null),[c,b]=$a.useState(0),[g,m]=$a.useState(e),[p,f]=$a.useState(void 0),v=$a.useRef(0),x=$a.useCallback(async()=>{let P=++v.current;try{u(!0),o(null);let h={limit:g,offset:c*g};p&&(h.status=p);let S=await a.getSubscriptions(h);if(P!==v.current)return;n(S.subscriptions),i(S.total)}catch(h){if(P!==v.current)return;o(h instanceof Error?h:new Error("Failed to fetch subscriptions"))}finally{P===v.current&&u(!1)}},[a,c,g,p,t]);$a.useEffect(()=>{x()},[x]);let R=Math.ceil(r/g);return{subscriptions:s,total:r,isLoading:l,error:d,page:c,pageSize:g,hasNextPage:c<R-1,hasPreviousPage:c>0,setPage:b,setPageSize:P=>{m(P),b(0)},status:p,setStatus:P=>{f(P),b(0)},refetch:x}}import{jsx as ie,jsxs as kt}from"react/jsx-runtime";function rd(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 id({sub:e}){return e.status==="canceled"?ie(ee,{variant:"outline",children:"Canceled"}):e.status==="past_due"?ie(ee,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?ie(ee,{variant:"warning",children:"Scheduled to cancel"}):ie(ee,{variant:"success",children:"Active"}):ie(ee,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function mg(e,t){let a=Y(t,e.currency);return e.plan_interval_count===1?`${a} / ${e.plan_interval}`:`${a} every ${e.plan_interval_count} ${e.plan_interval}s`}function od({sub:e}){let t=e.current_amount!==e.plan_amount;return kt("div",{children:[ie("div",{className:"af-font-medium af-tabular-nums",children:mg(e,e.current_amount)}),t&&kt("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",Y(e.plan_amount,e.currency)]})]})}function ld(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${rd(e.current_period_end)}`:"Ends at period end":e.current_period_end?rd(e.current_period_end):"\u2014"}function dd({refreshKey:e,onBackToWebsite:t,className:a}){let{subscriptions:s,total:n,isLoading:r,error:i,page:l,pageSize:u,hasNextPage:d,hasPreviousPage:o,setPage:c,status:b,refetch:g}=Ui({refreshKey:e}),{api:m}=H(),p=cd.useCallback(()=>m.exportSubscriptionsCsv(b?{status:b}:{}),[m,b]),f;if(r)f=kt("div",{children:[ie("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(v=>kt("div",{className:"af-rounded-md af-border af-p-3",children:[kt("div",{className:"af-flex af-items-center af-justify-between",children:[ie(J,{className:"af-h-4 af-w-40"}),ie(J,{className:"af-h-4 af-w-20"})]}),ie(J,{className:"af-mt-2 af-h-3 af-w-32"}),ie(J,{className:"af-mt-2 af-h-5 af-w-24"})]},v))}),ie("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:kt(lt,{children:[ie(ct,{children:kt(Ce,{children:[ie(q,{children:"Subscriber"}),ie(q,{children:"Plan"}),ie(q,{className:"af-text-right",children:"Amount"}),ie(q,{children:"Renews"}),ie(q,{children:"Status"})]})}),ie(dt,{"aria-hidden":"true",children:[0,1,2,3,4].map(v=>kt(Ce,{children:[ie(j,{children:ie(J,{className:"af-h-4 af-w-44"})}),ie(j,{children:ie(J,{className:"af-h-4 af-w-32"})}),ie(j,{className:"af-text-right",children:ie(J,{className:"af-ml-auto af-h-4 af-w-24"})}),ie(j,{children:ie(J,{className:"af-h-4 af-w-24"})}),ie(j,{children:ie(J,{className:"af-h-5 af-w-20"})})]},v))})]})}),ie("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(i)f=ie("div",{className:"af-flex af-justify-center af-py-8",children:ie(Nt,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(s.length===0&&l===0)f=ie(ba,{icon:ie(fg,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(s.length===0)f=kt("div",{children:[ie(ba,{children:"No more results."}),ie("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:kt(y,{variant:"outline",size:"sm",onClick:()=>c(l-1),children:[ie(sd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let v=l*u+1,x=l*u+s.length;f=kt("div",{children:[ie("div",{className:"af-mb-3 af-flex af-justify-end",children:ie(ga,{fetchCsv:p,filename:"subscriptions"})}),ie("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(R=>kt("div",{className:"af-rounded-md af-border af-p-3",children:[kt("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[kt("div",{className:"af-min-w-0",children:[ie("div",{className:"af-truncate af-text-sm af-font-medium",children:R.customer_email||ie("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),ie("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:R.plan_title||"Untitled plan"})]}),ie("div",{className:"af-shrink-0 af-text-right",children:ie(od,{sub:R})})]}),kt("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[ie(id,{sub:R}),R.is_test&&ie(ee,{variant:"outline",children:"Test"}),ie("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:ld(R)})]}),ie(In,{deliveries:R.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},R.id))}),ie("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:kt(lt,{children:[ie(ct,{children:kt(Ce,{children:[ie(q,{children:"Subscriber"}),ie(q,{children:"Plan"}),ie(q,{className:"af-text-right",children:"Amount"}),ie(q,{children:"Renews"}),ie(q,{children:"Status"})]})}),ie(dt,{children:s.map(R=>kt(Ce,{children:[ie(j,{className:"af-max-w-[240px]",children:ie("div",{className:"af-truncate af-font-medium",children:R.customer_email||ie("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),ie(j,{className:"af-max-w-[220px]",children:ie("div",{className:"af-truncate",children:R.plan_title||ie("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),ie(j,{className:"af-whitespace-nowrap af-text-right",children:ie(od,{sub:R})}),ie(j,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ld(R)}),kt(j,{children:[kt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ie(id,{sub:R}),R.is_test&&ie(ee,{variant:"outline",children:"Test"})]}),ie(In,{deliveries:R.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},R.id))})]})}),kt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[ie("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${v}-${x} of ${n}`}),kt("div",{className:"af-flex af-items-center af-gap-2",children:[kt(y,{variant:"outline",size:"sm",onClick:()=>c(l-1),disabled:!o,children:[ie(sd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),kt(y,{variant:"outline",size:"sm",onClick:()=>c(l+1),disabled:!d,children:["Next",ie(ug,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return ie(Ft,{title:"Subscriptions",onBackToWebsite:t,className:a,children:f})}import*as Vn from"react";import{Loader2 as Ng}from"lucide-react";import*as ha from"react";import*as $i from"react";var _s=typeof window>"u"?$i.useEffect:$i.useLayoutEffect;var Vi=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},pg=(e,t)=>e instanceof Error?e:new Error(t);function gg(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 ud(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function fs({siteId:e,refreshKey:t,onSaveInvoiceSettings:a}){let{api:s}=H(),[n,r]=ha.useState(null),[i,l]=ha.useState(!0),[u,d]=ha.useState(null),o=ha.useRef(null),[c,b]=ha.useState(()=>ud(s,e)),g=c.api!==s||c.siteId!==e,m=c;g&&(m=ud(s,e),b(m),r(null),l(!0),d(null));let p=ha.useRef(m);_s(()=>{p.current!==m&&(p.current=m,o.current=null)},[m]);let f=(w,k)=>p.current===w&&k>w.applied,v=(w,k,T)=>f(w,k)?(w.applied=k,o.current=T,r(T),l(!1),!0):!1,x=async w=>{for(;w.writing;)await w.idle;let k=++w.seq;try{let T=await w.api.getSite(w.siteId);return v(w,k,T)&&d(null),{seq:k,error:null}}catch(T){return{seq:k,error:pg(T,"Failed to load store settings")}}},R=(w,k)=>{let T=async()=>{if(p.current!==w)throw new Error("Not saved: the store switched to another site first.");w.writing=!0,w.idle=new Promise(z=>{w.markIdle=z});try{return await k(++w.seq)}finally{w.writing=!1,w.markIdle()}},_=w.queue.then(T,T);return w.queue=_.catch(()=>{}),_},P=ha.useCallback(async()=>{let w=await x(m);w.error&&f(m,w.seq)&&(d(w.error),l(!1))},[m]);ha.useEffect(()=>{P()},[P,t]);let h=ha.useCallback(w=>R(m,async k=>{let T=await m.api.updateSite(m.siteId,w),{currency_restatement:_,...z}=T;return v(m,k,z)&&d(Z=>Z instanceof Vi?Z:null),T}),[m]),S=ha.useRef(a);_s(()=>{S.current=a});let N=ha.useCallback(async(w,k)=>{await R(m,()=>w());let T=await x(m);return T.error&&f(m,T.seq)&&o.current&&(v(m,T.seq,{...o.current,...k}),d(new Vi(`Saved, but couldn't refresh settings: ${T.error.message}`))),p.current===m?o.current:null},[m]),C=ha.useCallback(w=>{let k=S.current;return N(()=>k(w),gg(w))},[N]);return{site:g?null:n,isLoading:g||i,error:g?null:u,refetch:P,updateSite:h,saveInvoiceSettings:a?C:null}}import*as Qt from"react";import{Loader2 as fd}from"lucide-react";import{jsx as pn,jsxs as Un}from"react/jsx-runtime";function Hi(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var _n="af-grid af-gap-1 af-text-sm",md="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",pd="af-min-h-[72px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50";function Va({children:e}){return pn("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function kr({children:e}){return pn("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var $n=Qt.forwardRef(function({id:t,title:a,description:s,children:n},r){let i=`af-store-${t}-title`;return Un("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":i,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[Un("div",{className:"af-space-y-1",children:[pn("h3",{id:i,className:"af-text-sm af-font-semibold",children:a}),s&&pn(Va,{children:s})]}),n]})});function zi({label:e,description:t,checked:a,onSave:s,disabled:n=!1,disabledReason:r}){let[i,l]=Qt.useState(null),[u,d]=Qt.useState(null),o=i??a,c=async b=>{l(b),d(null);try{await s(b)}catch(g){d(Hi(g))}finally{l(null)}};return Un("div",{className:"af-space-y-1",children:[Un("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[pn("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":o,checked:o,disabled:n||i!==null,onChange:b=>void c(b.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),Un("span",{className:"af-space-y-0.5",children:[Un("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,i!==null&&pn(fd,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&pn(Va,{children:t})]})]}),(n&&r||u)&&Un("div",{className:"af-space-y-1 af-pl-6",children:[n&&r&&pn(Va,{children:r}),u&&pn(kr,{children:u})]})]})}var Yo=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Zo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function vg(e,t,a,s=[]){if(!Zo(e)||!Zo(t)||!Zo(a))return{draft:Yo(e,t)?a:e,dropped:[]};let n=[],r={...a};for(let i of Object.keys(a))Yo(e[i],t[i])||(s.includes(i)?n.push(i):r[i]=e[i]);return{draft:r,dropped:n}}function er(e,t){let a=JSON.stringify(e),[s,n]=Qt.useState(e),[r,i]=Qt.useState([]),l=Qt.useRef(e),u=Qt.useRef(e),d=Qt.useRef(s);_s(()=>{u.current=e,d.current=s});let o=Qt.useRef(t?.when);Qt.useEffect(()=>{let b=Object.is(o.current,t?.when)?[]:t?.fields??[];if(o.current=t?.when,Yo(l.current,u.current)&&b.length===0)return;let g=vg(d.current,l.current,u.current,b);l.current=u.current,n(g.draft),g.dropped.length&&i(g.dropped)},[a,t?.when]);let c=Qt.useCallback(b=>{n(b??u.current),i([])},[]);return{draft:s,setDraft:n,dirty:JSON.stringify(s)!==a,reset:c,dropped:r}}function tr({dirty:e,saving:t,error:a,onSave:s,onDiscard:n}){return e?Un("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[Un(y,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&pn(fd,{className:"af-animate-spin"}),"Save"]}),pn(y,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:n,children:"Discard"}),a&&pn("p",{role:"alert",className:G("af-text-sm af-text-destructive"),children:a})]}):null}function ar(){let[e,t]=Qt.useState(!1),[a,s]=Qt.useState(null),n=Qt.useCallback(async r=>{t(!0),s(null);try{await r()}catch(i){s(Hi(i))}finally{t(!1)}},[]);return{saving:e,error:a,setError:s,run:n}}function gd({what:e}){return Un(Va,{children:["Only the site owner can change ",e,"."]})}import*as gn from"react";import{ExternalLink as bg,Plus as hg,X as yd}from"lucide-react";import{Fragment as Sg,jsx as Se,jsxs as Ee}from"react/jsx-runtime";var Xo=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function xd({site:e,updateSite:t}){return Ee("div",{className:"af-space-y-4",children:[Se(zi,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:a=>t({collect_phone_at_checkout:a})}),e.checkout_marketing_consent!==void 0&&Se(zi,{label:"Ask buyers for marketing consent at checkout",description:"Adds Stripe's consent checkbox to your checkout. Buyers who tick it join your email list, and buyers who leave without paying can get your abandoned-cart recovery emails.",checked:e.checkout_marketing_consent&&e.stripe_account_country==="US",disabled:e.stripe_account_country!=="US",disabledReason:e.stripe_account_country?'Only available for US stores: Stripe offers its consent checkbox to US businesses only. Your checkout shows an "Email me" box instead.':"Available once your Stripe account is connected and its country has synced.",onSave:a=>t({checkout_marketing_consent:a})})]})}function vd(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(Et(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(Et(e.free_shipping_over,e.currency))}}function wd({site:e,updateSite:t,refetch:a,providerSlot:s,currencyChanging:n=!1}){let{draft:r,setDraft:i,dirty:l,reset:u,dropped:d}=er(vd(e),{when:e.currency,fields:["rates","threshold"]}),{saving:o,error:c,setError:b,run:g}=ar(),m=e.currency.toUpperCase(),p=()=>g(async()=>{let v={},x=[...new Set(r.countries.split(/[\s,]+/).map(w=>w.trim().toUpperCase()).filter(Boolean))],R=x.find(w=>!/^[A-Z]{2}$/.test(w));if(R)throw new Error(`"${R}" isn't a two-letter country code (e.g. US, CA).`);let P=x.length?x:null;Xo(P,e.shipping_countries)||(v.shipping_countries=P);let h=[];for(let w of r.rates){let k=w.label.trim(),T=ua(w.amount,e.currency);if(!k)throw new Error("Every rate needs a name.");if(w.amount.trim()===""||T===null)throw new Error(`Enter a price for "${k}" (0 for free).`);h.push({label:k,amount:T})}let S=h.length?h:null;Xo(S,e.shipping_rates)||(v.shipping_rates=S);let N=null;if(r.threshold.trim()!==""&&(N=ua(r.threshold,e.currency),N===null||N===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(N!==e.free_shipping_over&&(v.free_shipping_over=N),Object.keys(v).length===0){u();return}("shipping_rates"in v||"free_shipping_over"in v)&&(v.expected_currency=e.currency);let C;try{C=await t(v)}catch(w){throw w instanceof Yt&&w.details?.code==="currency_changed"&&await a?.(),w}u(vd(C))}),f=(v,x)=>i({...r,rates:r.rates.map((R,P)=>P===v?{...R,...x}:R)});return Ee("fieldset",{disabled:o||n,className:"af-space-y-4",children:[Ee("label",{className:_n,children:["Countries you ship to",Se(te,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:v=>i({...r,countries:v.target.value})}),Se(Va,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),Ee("div",{className:"af-space-y-2",children:[Ee("p",{className:"af-text-sm",children:["Flat shipping rates (",m,")"]}),r.rates.length===0&&Se(Va,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((v,x)=>Ee("div",{className:"af-flex af-items-center af-gap-2",children:[Se(te,{"aria-label":`Rate ${x+1} name`,value:v.label,placeholder:"Standard",onChange:R=>f(x,{label:R.target.value})}),Se(te,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:v.amount,placeholder:"0",className:"af-w-32",onChange:R=>f(x,{amount:R.target.value})}),Se(y,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${x+1}`,onClick:()=>i({...r,rates:r.rates.filter((R,P)=>P!==x)}),children:Se(yd,{})})]},x)),Ee(y,{type:"button",variant:"outline",size:"sm",onClick:()=>i({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[Se(hg,{})," Add rate"]}),Se(Va,{children:"Buyers pick one at checkout. The first is preselected."})]}),Ee("label",{className:_n,children:["Free shipping over (",m,")",Se(te,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:v=>i({...r,threshold:v.target.value})}),Se(Va,{children:"Orders at or above this get the cheapest rate free."})]}),d.length>0&&Ee("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",m,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),Se(tr,{dirty:l,saving:o,error:c,onSave:()=>void p(),onDiscard:()=>{b(null),u()}}),s]})}var Jo="exclusive",yg=[{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 xg({href:e,children:t}){return Ee("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"af-inline-flex af-items-center af-gap-1 af-font-medium af-underline af-underline-offset-2 hover:af-text-foreground",children:[t,Se(bg,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function Sd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=er(e.tax_behavior??Jo),{saving:i,error:l,setError:u,run:d}=ar(),[o,c]=gn.useState(!1),b=e.stripe_tax_enabled,g=b||o,m=()=>d(async()=>{let v=a;if(v===e.tax_behavior){r();return}let x={tax_behavior:v};v!=="inclusive"&&e.tax_rate_bps!=null&&(x.tax_rate_bps=null);let R=await t(x);r(R.tax_behavior??Jo)}),p=()=>d(async()=>{let v={stripe_tax_enabled:!0,tax_behavior:a};a!=="inclusive"&&e.tax_rate_bps!=null&&(v.tax_rate_bps=null);let x=await t(v);r(x.tax_behavior??Jo),c(!1)}),f=(n||o)&&a!=="inclusive"&&e.tax_rate_bps!=null;return Ee("div",{className:"af-space-y-5",children:[Ee("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[Se("p",{children:"Tax at checkout is calculated by Stripe Tax, which you set up in your Stripe Dashboard (Settings \u2192 Tax): your business address, a default product tax code, and the places you're registered to collect tax."}),Se("p",{children:"Stripe only collects tax where you've added a registration; anywhere else the tax comes out as zero. Stripe Tax has its own fees, and what it covers (such as filing) depends on your Stripe Tax plan."}),Se("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:yg.map(v=>Se("li",{children:Se(xg,{href:v.href,children:v.label})},v.href))})]}),Se(zi,{label:"Stripe automatic tax",description:b?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:g,onSave:async v=>{if(o){c(!1),u(null),r();return}if(v&&!e.tax_behavior){c(!0);return}return t({stripe_tax_enabled:v})}}),g&&Ee("fieldset",{disabled:i,className:"af-space-y-4 af-pl-6",children:[Ee("label",{className:_n,children:["Do your prices already include tax?",Ee("select",{"aria-label":"Your prices",className:md,value:a,onChange:v=>s(v.target.value),children:[Se("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),Se("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),Se(Va,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),f&&Ee(Va,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),o?Ee("div",{className:"af-space-y-2",children:[Ee("div",{className:"af-flex af-gap-2",children:[Se(y,{type:"button",size:"sm",disabled:i,onClick:()=>void p(),children:"Turn on"}),Se(y,{type:"button",size:"sm",variant:"outline",disabled:i,onClick:()=>{c(!1),u(null),r()},children:"Cancel"})]}),l&&Se(kr,{children:l})]}):Se(tr,{dirty:n,saving:i,error:l,onSave:()=>void m(),onDiscard:()=>{u(null),r()}})]})]})}function bd(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function Nd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=er(bd(e)),{saving:i,error:l,setError:u,run:d}=ar(),o=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),c=()=>d(async()=>{let b={},g=null;if(o&&a.rate.trim()!==""){let v=Number(a.rate);if(!Number.isFinite(v)||v<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(v*100)}o&&g!==e.tax_rate_bps&&(b.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let m=a.taxId.trim()||null;m!==e.tax_id&&(b.tax_id=m);let p=a.label.trim()||null;if(p!==e.tax_label&&(b.tax_label=p),Object.keys(b).length===0){r();return}let f=await t(b);r(bd(f))});return Ee("fieldset",{disabled:i,className:"af-space-y-4",children:[Ee("label",{className:_n,children:["Tax rate (%)",Se(te,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!o,value:o?a.rate:"",onChange:b=>s({...a,rate:b.target.value})}),Se(Va,{children:o?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),Ee("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[Ee("label",{className:_n,children:["Tax ID",Se(te,{"aria-label":"Tax ID",value:a.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...a,taxId:b.target.value})})]}),Ee("label",{className:_n,children:["Tax label",Se(te,{"aria-label":"Tax label",value:a.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...a,label:b.target.value})})]})]}),Se(tr,{dirty:n,saving:i,error:l,onSave:()=>void c(),onDiscard:()=>{u(null),r()}})]})}function Rd({site:e,updateSite:t,onChangeStart:a}){let[s,n]=gn.useState(e.currency.toUpperCase()),[r,i]=gn.useState(!1),[l,u]=gn.useState(!1),[d,o]=gn.useState(null),c=e.currency.toUpperCase(),b=gn.useRef(c);gn.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),f=async()=>{u(!0);let v=a?.(),x=!1;o(null);try{let R=await t({currency:g.toLowerCase()});x=!0;let P=R.currency_restatement;P&&!P.applied?o(P.reason?`Not changed: ${P.reason}.`:"The currency was not changed."):(n(R.currency.toUpperCase()),b.current=R.currency.toUpperCase()),i(!1)}catch(R){o(Hi(R))}finally{u(!1),v?.(x)}};return Ee("div",{className:"af-space-y-3",children:[Ee("div",{className:"af-flex af-items-end af-gap-2",children:[Ee("label",{className:_n,children:["Store currency",Se(te,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:l||r,onChange:v=>{n(v.target.value),o(null)}})]}),m&&!r&&Ee(Sg,{children:[Se(y,{type:"button",size:"sm",disabled:!p,onClick:()=>i(!0),children:"Change currency"}),Se(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>{n(c),o(null)},children:"Discard"})]})]}),Se(Va,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&Ee("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[Ee("p",{className:"af-text-sm",children:["Change the store currency from ",c," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",Y(2e3,c)," becomes ",Y(2e3,g),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),Ee("div",{className:"af-flex af-gap-2",children:[Se(y,{type:"button",size:"sm",disabled:l,onClick:()=>void f(),children:"Confirm change"}),Se(y,{type:"button",size:"sm",variant:"ghost",disabled:l,onClick:()=>i(!1),children:"Cancel"})]})]}),d&&Se(kr,{children:d})]})}function hd(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function wg(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 _d({site:e,save:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=er(hd(e)),{saving:i,error:l,setError:u,run:d}=ar();if(!t)return Ee("div",{className:"af-space-y-2 af-text-sm",children:[Ee("p",{children:["Due ",e.invoice_due_days," days after sending"]}),Ee("p",{children:["Reminders: ",wg(e.invoice_reminder_schedule)]}),Ee("p",{children:["Footer: ",e.invoice_footer||"None"]}),Se(gd,{what:"invoice defaults"})]});let o=()=>d(async()=>{let c={},b=Number(a.dueDays);if(a.dueDays.trim()===""||!Number.isInteger(b)||b<0||b>90)throw new Error("Due days must be a whole number from 0 to 90.");b!==e.invoice_due_days&&(c.due_days=b);let m=a.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(m.some(x=>!Number.isInteger(x)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let p=[...new Set(m)].sort((x,R)=>x-R);Xo(p,e.invoice_reminder_schedule)||(c.reminder_schedule=p);let f=a.footer.trim()||null;if(f!==e.invoice_footer&&(c.footer=f),Object.keys(c).length===0){r();return}let v=await t(c);r(v?hd(v):void 0)});return Ee("fieldset",{disabled:i,className:"af-space-y-4",children:[Ee("label",{className:_n,children:["Days until due",Se(te,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:a.dueDays,onChange:c=>s({...a,dueDays:c.target.value})})]}),Ee("label",{className:_n,children:["Reminder schedule",Se(te,{"aria-label":"Reminder schedule",value:a.reminders,placeholder:"Off",onChange:c=>s({...a,reminders:c.target.value})}),Se(Va,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),Ee("label",{className:_n,children:["Invoice footer",Se("textarea",{"aria-label":"Invoice footer",className:pd,maxLength:300,value:a.footer,onChange:c=>s({...a,footer:c.target.value})})]}),Se(tr,{dirty:n,saving:i,error:l,onSave:()=>void o(),onDiscard:()=>{u(null),r()}})]})}function Pd({site:e,updateSite:t}){let{draft:a,setDraft:s,dirty:n,reset:r}=er(e.default_email_recipients),{saving:i,error:l,setError:u,run:d}=ar(),[o,c]=gn.useState(""),[b,g]=gn.useState(null),m=()=>{let f=o.trim().toLowerCase();if(f){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f)){g("Enter a valid email address.");return}if(a.some(v=>v.toLowerCase()===f)){g("Already added.");return}s([...a,f]),c(""),g(null)}},p=()=>d(async()=>{let f=await t({default_email_recipients:a});r(f.default_email_recipients)});return Ee("fieldset",{disabled:i,className:"af-space-y-3",children:[Ee("div",{className:"af-flex af-flex-wrap af-gap-2",children:[a.map(f=>Ee(ee,{variant:"secondary",className:"af-gap-1",children:[f,Se("button",{type:"button","aria-label":`Remove ${f}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(a.filter(v=>v!==f)),children:Se(yd,{className:"af-h-3 af-w-3"})})]},f)),a.length===0&&Se("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),Ee("div",{className:"af-flex af-gap-2",children:[Se(te,{"aria-label":"Add notification email",type:"email",value:o,placeholder:"Add email address",onChange:f=>{c(f.target.value),g(null)},onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),m())}}),Se(y,{type:"button",variant:"outline",disabled:!o.trim(),onClick:m,children:"Add"})]}),b&&Se(kr,{children:b}),Se(tr,{dirty:n,saving:i,error:l,onSave:()=>void p(),onDiscard:()=>{u(null),r()}})]})}import{jsx as tn,jsxs as kd}from"react/jsx-runtime";function Cd({siteId:e,refreshKey:t,section:a,shippingProviderSlot:s,onConnectStripe:n,onUpgradePlan:r,className:i}){let{site:l,isLoading:u,error:d,refetch:o,updateSite:c}=fs({siteId:e,refreshKey:t}),b=Vn.useRef(o),g=Vn.useRef(e);_s(()=>{b.current=o,g.current=e});let m=Vn.useRef({}),[p,f]=Vn.useState([]),v=p.some(S=>S.siteId===e),x=Vn.useCallback(()=>{let S={siteId:e},N=b.current;return f(C=>[...C,S]),C=>{let w=()=>f(T=>T.filter(_=>_!==S));!(g.current===S.siteId)||C&&b.current===N?w():b.current().finally(w)}},[e]),R=S=>N=>{m.current[S]=N},P=l!==null&&l.payments_active;if(Vn.useEffect(()=>{if(!P||!a)return;let S=m.current[a];S&&(S.scrollIntoView?.({behavior:"smooth",block:"start"}),S.focus({preventScroll:!0}))},[P,a]),u)return kd("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[tn(Ng,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!l)return tn("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 tn(Ks,{className:i,onConnectStripe:n,onUpgradePlan:r,whenActive:tn("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 kd("div",{className:`af-space-y-6 ${i??""}`,children:[d&&tn("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}),tn($n,{ref:R("checkout"),id:"checkout",title:"Checkout",children:tn(xd,{...h})}),tn($n,{ref:R("shipping"),id:"shipping",title:"Shipping",children:tn(wd,{...h,providerSlot:s,currencyChanging:v})}),tn($n,{ref:R("tax"),id:"tax",title:"Tax",children:tn(Sd,{...h})}),tn($n,{ref:R("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:tn(Rd,{...h,onChangeStart:x})})]},e)}import{Loader2 as Rg}from"lucide-react";import{jsx as Ps,jsxs as Td}from"react/jsx-runtime";function qi({siteId:e,refreshKey:t,onSaveInvoiceSettings:a,className:s}){let{site:n,isLoading:r,error:i,updateSite:l,refetch:u,saveInvoiceSettings:d}=fs({siteId:e,refreshKey:t,onSaveInvoiceSettings:a});return r?Td("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ps(Rg,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):n?Td("div",{className:`af-space-y-6 ${s??""}`,children:[i&&Ps("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i.message}),Ps($n,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:Ps(_d,{site:n,save:d})}),Ps($n,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:Ps(Nd,{site:n,updateSite:l,refetch:u})})]},e):Ps("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i?.message??"Could not load invoice settings."})}import{Loader2 as _g}from"lucide-react";import{jsx as Cr,jsxs as Ed}from"react/jsx-runtime";function Id({siteId:e,refreshKey:t,className:a}){let{site:s,isLoading:n,error:r,updateSite:i,refetch:l}=fs({siteId:e,refreshKey:t});return n?Ed("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Cr(_g,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?Ed("div",{className:`af-space-y-3 ${a??""}`,children:[r&&Cr("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r.message}),Cr($n,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:Cr(Pd,{site:s,updateSite:i,refetch:l})})]},e):Cr("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r?.message??"Could not load notification settings."})}import*as nr from"react";import{Fragment as Dd,jsx as ya,jsxs as Tr}from"react/jsx-runtime";function Ad({refreshKey:e,initialInvoiceId:t,onBackToWebsite:a,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,siteId:i,onSaveInvoiceSettings:l,className:u}){let{aggregates:d,isLoading:o,error:c,refetch:b}=js({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=Ys({refreshKey:e}),{api:m}=H(),p=g.filters,f=nr.useCallback(()=>m.exportRetainersCsv(p),[m,p]),[v,x]=nr.useState(!1),[R,P]=nr.useState(null),[h,S]=nr.useState(!1),N=ya("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:c||!o&&!d?Tr("div",{role:"alert",className:"sm:af-col-span-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't load invoice totals. ",ya(y,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):o||!d?Tr(Dd,{children:[ya(mt,{label:"Outstanding",children:ya(J,{className:"af-h-6 af-w-24"})}),ya(mt,{label:"Overdue",children:ya(J,{className:"af-h-6 af-w-24"})}),ya(mt,{label:"Paid this month",children:ya(J,{className:"af-h-6 af-w-24"})})]}):Tr(Dd,{children:[ya(mt,{label:"Outstanding",detail:`${d.outstanding.count} open`,children:Y(d.outstanding.amount,d.currency)}),ya(mt,{label:"Overdue",detail:d.overdue.count===0?"Nothing overdue":`${d.overdue.count} overdue`,valueClassName:d.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:Y(d.overdue.amount,d.currency)}),ya(mt,{label:"Paid this month",detail:`${d.paid_this_month.count} paid`,children:Y(d.paid_this_month.amount,d.currency)})]})});return Tr(Ft,{title:"Invoices",onBackToWebsite:a,hideBackButton:v,className:u,children:[N,i&&!v&&Tr("div",{className:"af-mb-6",children:[ya(y,{type:"button",variant:"outline",size:"sm","aria-expanded":h,"aria-controls":"af-invoice-settings",onClick:()=>S(C=>!C),children:"Invoice settings"}),h&&ya("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:ya(qi,{siteId:i,refreshKey:e,onSaveInvoiceSettings:l})})]}),!v&&ya(Gs,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:R?.id??null,onShowCycles:C=>P(w=>w?.id===C.id?null:C),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded,exportCsv:f}),ya(cs,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:x,onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:r,retainerFilter:R?{id:R.id,label:`${R.customer_name??R.customer_email??"Recurring invoices"} \u2014 ${R.description}`}:null,onClearRetainerFilter:()=>P(null)})]})}import*as ta from"react";import*as vn from"react";function Kt(e,t,a){let[s,n]=vn.useState(null),[r,i]=vn.useState(!0),[l,u]=vn.useState(null),d=vn.useRef(0),o=vn.useRef(e);o.current=e;let c=vn.useRef(a);c.current=a;let b=vn.useCallback(async()=>{let m=++d.current,p=c.current;i(!0),u(null);try{let f=await o.current();m===d.current&&n({scope:p,value:f})}catch(f){m===d.current&&u(f instanceof Error?f:new Error("Request failed"))}finally{m===d.current&&i(!1)}},[]);vn.useEffect(()=>{b()},[b,t]);let g=s!==null&&s.scope===a;return{data:g?s.value:null,isLoading:r||!g&&l===null,error:l,refetch:b}}var Qo={commitBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts"},cancelBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts/{sendId}/cancel",params:["sendId"]},createDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts"},updateDraft:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},deleteDraft:{method:"DELETE",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},testSendDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/test",params:["draftId"]},setDraftTemplate:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}/template",params:["draftId"]},duplicateDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/duplicate",params:["draftId"]},copyEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/copy",params:["templateId"]},publishEmailTemplate:{method:"POST",path:"/sites/{siteId}/marketing/templates/{templateId}/publish",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 Pg(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Qo,e)}function kg(e,t,a){let s=Qo[e],n="params"in s?s.params:[],r={...a};delete r.siteId;let i=s.path.replace("{siteId}",encodeURIComponent(t));for(let u of n){let d=r[u];if(typeof d!="string"&&typeof d!="number")throw new Error(`${e} needs ${u}`);i=i.replace(`{${u}}`,encodeURIComponent(String(d))),delete r[u]}let l=s.method==="GET"||s.method==="DELETE"?void 0:r;return{method:s.method,path:i,body:l}}var Ld={marketing_disabled:"Email marketing is not available yet.",site_deleted:"This site has been deleted.",sending_not_enabled:"Email isn't turned on for this site yet.",sending_paused:"Sending is paused while we review this site.",domain_not_verified:"Verify your sending domain before you can send.",dmarc_missing:"Your domain needs a DMARC record before you can send.",postal_address_missing:"Add your business postal address before you can send. Every email has to show it.",allowance_exhausted:"You've used this month's email allowance. Sending resumes next month or when you upgrade.",ramp_limit:"Today's sending limit for a new domain is used up. Sending continues tomorrow.",sample_failed:"Too many emails in the first batch bounced, so the rest of this send was stopped."},Er=new Set(["sending_not_enabled","domain_not_verified","dmarc_missing","postal_address_missing"]);function sr(e){return e?Ld[e]??"Sending is not available right now.":null}import*as Hn from"react";var rr=50;function ji({siteId:e,q:t="",offset:a=0,refreshKey:s=0}){let{api:n}=H(),r=Kt(()=>n.getMarketingContacts(e,{q:t||void 0,limit:rr,offset:a}),`${e}|${t}|${a}|${s}`,e),i=Kt(()=>n.getMarketingContactStats(e),`${e}|${s}`,e),l=Kt(()=>n.getMarketingTags(e),`${e}|${s}`,e);return{contacts:r,stats:i,tags:l,refetchAll:async()=>{await Promise.all([r.refetch(),i.refetch(),l.refetch()])}}}import*as lr from"react";import*as Pn from"react";import{Fragment as Cg,jsx as Ir,jsxs as Bd}from"react/jsx-runtime";var Dr=e=>`af-email-settings-${e}`,el=Pn.createContext(null);function nt(){let e=Pn.useContext(el);if(!e)throw new Error("Email panels render inside EmailView");return e}function Od(e){let{setInlineEditOpen:t}=nt();Pn.useEffect(()=>(t(e),()=>t(!1)),[e,t])}function tl(e){return e.status==="sending"||e.status==="sent"||(e.status==="cancelled"||e.status==="failed")&&e.recipients.consumed>0}function Wi(e,t){return new Set([...e.filter(a=>a.sent).map(a=>a.id),...t.filter(tl).flatMap(a=>a.draft_id?[a.draft_id]:[])])}function ks({onClick:e,children:t}){return Ir("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function ir({reason:e}){let{openSetup:t,onOpenStoreSettings:a}=nt(),s=e&&Er.has(e)?Ir(ks,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&a?Ir(ks,{onClick:a,children:"Open Store settings"}):null;return s&&Bd(Cg,{children:[" ",s]})}function Gi(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.code=="string"?t.code:typeof t.details?.code=="string"?t.details.code:null}function Ha(e,t){return Gi(e)===t?!0:e instanceof Error&&e.message.includes(t)}function or(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function Dt(){let{onOrgAction:e}=nt(),[t,a]=Pn.useState(!1),[s,n]=Pn.useState(null),r=Pn.useCallback(async(i,l={})=>{a(!0),n(null);try{return{ok:!0,result:await e(i,l)}}catch(u){return n(or(u)),{ok:!1,error:u}}finally{a(!1)}},[e]);return{busy:t,error:s,setError:n,run:r}}function Ne({tone:e="info",children:t,className:a}){return Ir("div",{role:e==="error"?"alert":"status",className:G("af-rounded-md af-border af-px-3 af-py-2 af-text-sm",e==="warning"&&"af-border-yellow-300 af-bg-yellow-50 af-text-yellow-900",e==="error"&&"af-border-destructive af-bg-destructive/10 af-text-destructive",e==="success"&&"af-border-green-300 af-bg-green-50 af-text-green-900",a),children:t})}function an({children:e,action:t,id:a}){return Bd("div",{id:a,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[Ir("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function Fe(e){return e.toLocaleString("en-US")}import{jsx as nn,jsxs as ms}from"react/jsx-runtime";var al="I confirm that everyone in this file agreed to receive marketing email from my business.",Tg={invalid_email:"not a valid email address",duplicate:"listed more than once",inactive_in_source:"inactive or unsubscribed in the file",previously_unsubscribed:"unsubscribed before, so they stay unsubscribed",suppressed:"bounced or marked email as spam before",pending:"still confirming their signup"};function Ki({onImported:e}){let{canWrite:t}=nt(),[a,s]=lr.useState(""),[n,r]=lr.useState(null),[i,l]=lr.useState(""),[u,d]=lr.useState(!1),[o,c]=lr.useState(null),b=Dt(),g=async()=>{if(!u||!a.trim())return;let m=i.split(",").map(f=>f.trim()).filter(Boolean),p=await b.run("importContacts",{csv:a,attested:!0,...m.length?{tags:m}:{}});if(p.ok){let f=p.result;c(f),e?.(f)}};if(o){let m=new Map;for(let p of o.skipped_rows)m.set(p.reason,(m.get(p.reason)??0)+1);return ms("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[nn("div",{className:"af-font-medium",children:"Import finished"}),ms("p",{className:"af-text-sm",children:[Fe(o.rows)," rows: ",Fe(o.created)," new, ",Fe(o.updated)," updated, ",Fe(o.skipped)," skipped."]}),m.size>0&&nn("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...m].map(([p,f])=>ms("li",{children:[Fe(f)," ",Tg[p]??p]},p))}),nn("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),nn(y,{type:"button",size:"sm",variant:"outline",onClick:()=>{c(null),s(""),r(null),d(!1)},children:"Import another file"})]})}return ms("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:m=>{m.preventDefault(),g()},children:[ms("label",{className:"af-block af-space-y-1",children:[nn("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),nn("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()))}}),nn("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&&nn("span",{className:"af-block af-text-xs",children:n})]}),ms("label",{className:"af-block af-space-y-1",children:[nn("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),nn(te,{"aria-label":"Tags for imported contacts",value:i,onChange:m=>l(m.target.value)})]}),ms("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[nn("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:u,onChange:m=>d(m.target.checked)}),ms("span",{children:[al," Importing people who didn't agree can get your sending paused."]})]}),b.error&&nn(Ne,{tone:"error",children:b.error}),nn(y,{type:"submit",size:"sm",disabled:!t||!u||!a.trim()||b.busy,children:b.busy?"Importing\u2026":"Import contacts"})]})}import{Fragment as Md,jsx as De,jsxs as Mt}from"react/jsx-runtime";var Eg={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function Fd(){let{siteId:e,canWrite:t,refreshKey:a}=nt(),[s,n]=Hn.useState(""),[r,i]=Hn.useState(""),[l,u]=Hn.useState(0),[d,o]=Hn.useState(0),[c,b]=Hn.useState(new Set),[g,m]=Hn.useState(!1),p=ji({siteId:e,q:r,offset:l,refreshKey:d+a}),f=Dt(),v=()=>o(N=>N+1),x=p.stats.data,R=p.contacts.data,P=p.tags.data??[],h=x?x.growth.slice(-4).reduce((N,C)=>N+C.new_subscribers,0):null,S=async()=>{let N=await f.run("exportContacts",{});if(!N.ok||typeof N.result!="string"||typeof document>"u")return;let C=URL.createObjectURL(new Blob([N.result],{type:"text/csv;charset=utf-8"})),w=document.createElement("a");w.href=C,w.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(C)};return Mt("div",{children:[Mt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[De(mt,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:x?Fe(x.total):De(J,{className:"af-h-6 af-w-16"})}),De(mt,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:x?Fe(x.mailable):De(J,{className:"af-h-6 af-w-16"})}),De(mt,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:h!==null?Fe(h):De(J,{className:"af-h-6 af-w-16"})})]}),Mt("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[Mt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:N=>{N.preventDefault(),u(0),i(s.trim())},children:[De(te,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:s,onChange:N=>n(N.target.value)}),De(y,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),De(y,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>m(N=>!N),children:g?"Close import":"Import"}),De(y,{type:"button",variant:"outline",size:"sm",disabled:!t||f.busy,onClick:()=>void S(),children:"Export"})]}),g&&De("div",{className:"af-mt-3",children:De(Ki,{onImported:v})}),f.error&&De(Ne,{tone:"error",className:"af-mt-2",children:f.error}),t&&c.size>0&&De(Dg,{tags:P.filter(N=>!N.system),count:c.size,busy:f.busy,onApply:async(N,C)=>{(await f.run("bulkTagContacts",{action:N,tag_id:C,contact_ids:[...c]})).ok&&(b(new Set),v())}}),De("div",{className:"af-mt-3",children:p.contacts.error?De(Nt,{message:"Couldn't load contacts.",onRetry:()=>void p.contacts.refetch()}):R?R.contacts.length===0?De(ba,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):Mt(Md,{children:[De("ul",{className:"af-divide-y af-rounded-md af-border",children:R.contacts.map(N=>De(Ig,{contact:N,canWrite:t,busy:f.busy,selected:c.has(N.id),onSelect:C=>b(w=>{let k=new Set(w);return C?k.add(N.id):k.delete(N.id),k}),onUnsubscribe:async()=>{(await f.run("unsubscribeContact",{contactId:N.id})).ok&&v()}},N.id))}),Mt("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[Mt("span",{children:[Fe(l+1),"\u2013",Fe(l+R.contacts.length)," of ",Fe(R.total)]}),Mt("div",{className:"af-flex af-gap-2",children:[De(y,{type:"button",variant:"ghost",size:"sm",disabled:l===0,onClick:()=>u(Math.max(0,l-rr)),children:"Previous"}),De(y,{type:"button",variant:"ghost",size:"sm",disabled:l+R.contacts.length>=R.total,onClick:()=>u(l+rr),children:"Next"})]})]})]}):De(J,{className:"af-h-24 af-w-full"})}),De(Ag,{tags:P,canWrite:t,onChanged:v})]})}function Ig({contact:e,canWrite:t,busy:a,selected:s,onSelect:n,onUnsubscribe:r}){return Mt("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&De("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:s,onChange:i=>n(i.target.checked)}),Mt("div",{className:"af-min-w-0 af-flex-1",children:[Mt("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?Mt("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),Mt("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[De(ee,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":Eg[e.status]}),e.tags.map(i=>De(ee,{variant:"outline",children:i.label},i.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&De(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:r,children:"Unsubscribe"})]})}function Dg({tags:e,count:t,busy:a,onApply:s}){let[n,r]=Hn.useState("");return Mt("div",{className:"af-mt-3 af-flex af-flex-wrap af-items-center af-gap-2 af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:[Mt("span",{children:[Fe(t)," selected"]}),Mt("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:n,onChange:i=>r(i.target.value),children:[De("option",{value:"",children:"Choose a tag\u2026"}),e.map(i=>De("option",{value:i.id,children:i.label},i.id))]}),De(y,{type:"button",size:"sm",variant:"outline",disabled:!n||a,onClick:()=>s("add",n),children:"Add tag"}),De(y,{type:"button",size:"sm",variant:"ghost",disabled:!n||a,onClick:()=>s("remove",n),children:"Remove tag"})]})}function Ag({tags:e,canWrite:t,onChanged:a}){let[s,n]=Hn.useState(""),[r,i]=Hn.useState(null),l=Dt();return Mt("div",{children:[De(an,{children:"Tags"}),e.length===0?De("p",{className:"af-text-sm af-text-muted-foreground",children:"No tags yet. Contacts are tagged automatically with where they signed up and what they bought."}):De("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(u=>De("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:r?.id===u.id?Mt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async d=>{d.preventDefault(),(await l.run("updateTag",{tagId:u.id,label:r.label.trim()})).ok&&(i(null),a())},children:[De(te,{"aria-label":`New name for ${u.label}`,value:r.label,onChange:d=>i({id:u.id,label:d.target.value})}),De(y,{type:"submit",size:"sm",disabled:!r.label.trim()||l.busy,children:"Save"})]}):Mt(Md,{children:[Mt("span",{children:[u.label," ",Mt("span",{className:"af-text-muted-foreground",children:["\xB7 ",Fe(u.total)," contacts, ",Fe(u.mailable)," can be emailed"]})]}),t&&!u.system&&De(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>i({id:u.id,label:u.label}),children:"Rename"})]})},u.id))}),t&&Mt("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async u=>{u.preventDefault(),(await l.run("createTag",{label:s.trim()})).ok&&(n(""),a())},children:[De(te,{"aria-label":"New tag",placeholder:"New tag",value:s,maxLength:100,onChange:u=>n(u.target.value)}),De(y,{type:"submit",size:"sm",variant:"outline",disabled:!s.trim()||l.busy,children:"Add tag"})]}),l.error&&De(Ne,{tone:"error",className:"af-mt-2",children:l.error})]})}import*as wt from"react";import{ArrowLeft as qg}from"lucide-react";function cr({siteId:e,refreshKey:t=0}){let{api:a}=H();return Kt(()=>a.getBroadcasts(e),`${e}|${t}`,e)}function dr({siteId:e,kind:t,refreshKey:a=0}){let{api:s}=H();return Kt(()=>s.getEmailDrafts(e,t),`${e}|${t??""}|${a}`,`${e}|${t??""}`)}import*as ze from"react";var Ar=e=>typeof e=="number"&&Number.isFinite(e);function nl(e){if(!e||typeof e!="object")return null;let t=e;return Ar(t.x)&&Ar(t.y)&&Ar(t.width)&&Ar(t.height)?{x:t.x,y:t.y,width:t.width,height:t.height}:null}var sl=(e,t)=>Number.isInteger(e)&&e>=0&&e<t;function Ud(e,t,a){if(!t||e.source!==t)return null;let s=e.data;if(!s||typeof s!="object"||s.af!=="email-editor")return null;switch(s.type){case"hover":{if(s.section===null)return{type:"hover",section:null,rect:null};let n=nl(s.rect);return sl(s.section,a)&&n?{type:"hover",section:s.section,rect:n}:null}case"focus":case"open":{let n=nl(s.rect);return sl(s.section,a)&&n?{type:s.type,section:s.section,rect:n}:null}case"layout":{if(!Ar(s.height)||!Array.isArray(s.sections))return null;let n=s.sections.flatMap(r=>{let i=r,l=i?nl(i.rect):null;return i&&sl(i.section,a)&&l?[{section:i.section,rect:l}]:[]});return{type:"layout",height:s.height,sections:n}}case"template":return s.region==="header"||s.region==="footer"?{type:"template",region:s.region}:null;default:return null}}var Lr=(e,t,a)=>Math.min(Math.max(e,t),Math.max(t,a));function rl(e,t){let a=Lr(e.x,0,t.width),s=Lr(e.y,0,t.height);return{x:a,y:s,width:Lr(e.width,0,t.width-a),height:Lr(e.height,0,t.height-s)}}var Or={min:240,max:6e3,initial:480},$d=e=>Lr(Math.ceil(e),Or.min,Or.max);import*as Cs from"react";import{jsx as xa,jsxs as kn}from"react/jsx-runtime";var il={heading:"Heading",text:"Text",button:"Button",image:"Image",cart:"Cart"};function Hd(e){switch(e){case"heading":case"text":return{type:e,text:""};case"button":return{type:e,label:"",url:"https://"};case"image":return{type:e,url:"",alt:""};case"cart":return{type:e,label:"Return to your cart"}}}function ol(e){switch(e.type){case"heading":case"text":return e.text;case"button":return`${e.label}
6
+ ${e.url}`;case"image":return[e.url,e.alt].filter(Boolean).join(`
7
+ `);case"cart":return e.label}}function Vd(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 Lg={...il,text:"Markdown: **bold**, *italic*, [link](https://\u2026), blank line = new paragraph"};function zd({block:e,isNew:t,busy:a,error:s,onPickImage:n,onDone:r,onRemove:i,onCancel:l,style:u,className:d}){let[o,c]=Cs.useState(e),[b,g]=Cs.useState(!1),m=v=>c(x=>({...x,...v})),p=Cs.useRef(null);Cs.useEffect(()=>p.current?.focus(),[]);let f=v=>{v&&!p.current&&(p.current=v)};return xa("form",{"data-testid":"section-editor",style:u,className:d,onSubmit:v=>{v.preventDefault(),Vd(o)&&r(o)},onKeyDown:v=>{v.key==="Escape"&&!a&&l()},children:kn("div",{className:"af-space-y-2",children:[o.type==="heading"&&xa(te,{ref:f,"aria-label":"Heading",value:o.text,maxLength:200,onChange:v=>m({text:v.target.value})}),o.type==="text"&&xa("textarea",{ref:f,"aria-label":"Text",className:"af-min-h-[120px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-font-mono af-text-sm",value:o.text,maxLength:5e3,onChange:v=>m({text:v.target.value})}),o.type==="button"&&kn("div",{className:"af-grid af-gap-2 sm:af-grid-cols-2",children:[kn("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",xa(te,{ref:f,"aria-label":"Button label",value:o.label,maxLength:80,onChange:v=>m({label:v.target.value})})]}),kn("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Opens",xa(te,{"aria-label":"Button link",type:"url",value:o.url,onChange:v=>m({url:v.target.value})})]})]}),o.type==="image"&&kn("div",{className:"af-space-y-2",children:[n?kn("div",{className:"af-flex af-items-center af-gap-2",children:[o.url&&xa("img",{src:o.url,alt:"",className:"af-h-12 af-w-12 af-rounded af-object-cover"}),xa(y,{ref:f,type:"button",variant:"outline",size:"sm",disabled:b,onClick:async()=>{g(!0);try{let v=await n();v&&c(x=>({...x,url:v.url,alt:v.alt??(x.type==="image"?x.alt:"")}))}finally{g(!1)}},children:"Choose from your site's images\u2026"})]}):kn("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Image address (https://\u2026)",xa(te,{ref:f,"aria-label":"Image URL",type:"url",value:o.url,onChange:v=>m({url:v.target.value})})]}),kn("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Describe the image (for people who can't see it)",xa(te,{"aria-label":"Image description",value:o.alt??"",maxLength:200,onChange:v=>m({alt:v.target.value})})]})]}),o.type==="cart"&&kn("div",{className:"af-space-y-2",children:[xa("p",{className:"af-text-sm af-text-muted-foreground",children:"Each shopper sees their own cart here. There's nothing to write but the button."}),kn("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Button text",xa(te,{ref:f,"aria-label":"Cart button label",value:o.label,maxLength:80,onChange:v=>m({label:v.target.value})})]})]}),s&&xa(Ne,{tone:"error",children:s}),kn("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[xa("span",{className:"af-grow af-text-xs af-text-muted-foreground",children:Lg[o.type]}),!t&&xa(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:i,children:"Remove"}),xa(y,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:l,children:"Cancel"}),xa(y,{type:"submit",size:"sm",disabled:a||!Vd(o),children:"Done"})]})]})})}import*as qd from"react";import{ArrowLeft as Og}from"lucide-react";import{Fragment as ll,jsx as je,jsxs as wa}from"react/jsx-runtime";var zn="standard",Zi={create:"Create an email template that ",copyStandard:"Create an email template based on Standard that ",update:e=>`Update the "${e}" template to be `};function cl({status:e}){return e==="draft"?je(ee,{variant:"warning",children:"Draft"}):e==="published"?je(ee,{variant:"success",children:"Published"}):je(ee,{variant:"secondary",children:e==="archived"?"Archived":"Built in"})}function jd(e,t){let{api:a}=H(),{siteId:s,refreshKey:n,settings:r}=nt(),i=JSON.stringify([r?.business_name,r?.postal_address,r?.brand]);return Kt(()=>a.previewEmailTemplate(s,e),`${s}|${e}|${t}|${n}|${i}`,`${s}|${e}|${t}`)}function Yi({templateId:e,version:t,className:a,frame:s}){let n=jd(e,t);return je("div",{"aria-hidden":!0,className:`af-pointer-events-none af-overflow-hidden af-bg-white ${a}`,children:n.data&&je("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 Wd({template:e,onBack:t,onOpenTemplate:a,onOpenDraft:s,onAskAssistant:n,reload:r,refreshKey:i}){let l=jd(e?.id??zn,e?.updated_at??"builtin");return wa("div",{className:"af-space-y-4",children:[wa(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[je(Og,{className:"af-mr-1 af-h-4 af-w-4"}),"All templates"]}),wa("div",{className:"af-grid af-gap-4 md:af-grid-cols-[minmax(0,1fr)_280px]",children:[wa("div",{children:[l.data?je("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?wa(Ne,{tone:"warning",children:[Gi(l.error)==="postal_address_missing"?"Add your business postal address to preview your emails.":"Couldn't load this preview.",je(ir,{reason:Gi(l.error)})]}):je(J,{className:"af-h-[520px] af-w-full"}),je("p",{className:"af-mt-2 af-text-center af-text-xs af-text-muted-foreground",children:"Shown with a sample email"})]}),wa("div",{className:"af-space-y-3",children:[je(Bg,{template:e,previewShown:l.data!==null,onOpenTemplate:a,onAskAssistant:n,reload:r}),je(Fg,{templateId:e?.id??null,onOpenDraft:s,refreshKey:i})]})]})]})}function Bg({template:e,previewShown:t,onOpenTemplate:a,onAskAssistant:s,reload:n}){let{canWrite:r}=nt(),i=Dt(),[l,u]=qd.useState(null),d=e?.name??"Standard",o=async(g,m)=>{let p=await i.run(g,m);u(null),p.ok&&g==="deleteEmailTemplate"&&a(null),p.ok||(Ha(p.error,"template_changed")?i.setError("The editor changed this template since you opened it. Check the latest version, then publish again."):Ha(p.error,"template_in_use")?i.setError("Emails use this template now."):Ha(p.error,"template_not_draft")&&i.setError("This template is already published.")),n()},c=async g=>{let m=await i.run("copyEmailTemplate",{templateId:g.id});m.ok&&(a(m.result.id),n())},b=null;if(!r)b=null;else if(l&&e){let[g,m,p]=l==="publish"?["Published templates can't be changed.","Publish",()=>o("publishEmailTemplate",{templateId:e.id,updated_at:e.updated_at})]:l==="delete"?["Delete this template?","Delete",()=>o("deleteEmailTemplate",{templateId:e.id})]:["Archive this template?","Archive",()=>o("archiveEmailTemplate",{templateId:e.id})];b=wa(ll,{children:[je("p",{className:"af-text-sm",children:g}),wa("div",{className:"af-flex af-gap-2",children:[je(y,{type:"button",variant:"outline",size:"sm",onClick:()=>u(null),children:"Cancel"}),je(y,{type:"button",size:"sm",variant:l==="delete"?"destructive":"default",className:"af-ml-auto",disabled:i.busy||l==="publish"&&!t,onClick:()=>void p(),children:m})]})]})}else if(!e)b=s&&je(y,{type:"button",size:"sm",onClick:()=>s(Zi.copyStandard),children:"Copy to edit"});else if(e.status==="draft")b=wa(ll,{children:[s&&je(y,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>s(Zi.update(e.name)),children:"\u2728 Change this template with the editor"}),wa("div",{className:"af-flex af-gap-2",children:[e.can_delete&&je(y,{type:"button",variant:"ghost",size:"sm",disabled:i.busy,onClick:()=>u("delete"),children:"Delete"}),je(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:i.busy||!t,onClick:()=>u("publish"),children:"Publish\u2026"})]})]});else{let g=e.status==="archived";b=wa("div",{className:"af-flex af-flex-wrap af-gap-2",children:[e.can_delete&&!g&&je(y,{type:"button",variant:"ghost",size:"sm",disabled:i.busy,onClick:()=>u("delete"),children:"Delete"}),e.can_archive&&!g&&je(y,{type:"button",variant:"outline",size:"sm",disabled:i.busy,onClick:()=>u("archive"),children:"Archive"}),g&&je(y,{type:"button",variant:"outline",size:"sm",disabled:i.busy,onClick:()=>void o("unarchiveEmailTemplate",{templateId:e.id}),children:"Unarchive"}),je(y,{type:"button",size:"sm",className:"af-ml-auto",disabled:i.busy,onClick:()=>void c(e),children:"Copy to edit"})]})}return wa("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[wa("div",{className:"af-flex af-items-center af-gap-2",children:[je("h3",{"data-testid":"template-title",className:"af-grow af-truncate af-text-sm af-font-semibold",children:d}),je(cl,{status:e?.status??"builtin"})]}),i.error&&je(Ne,{tone:"error",children:i.error}),b]})}function Fg({templateId:e,onOpenDraft:t,refreshKey:a}){let{siteId:s}=nt(),n=dr({siteId:s,kind:"broadcast",refreshKey:a}),r=cr({siteId:s,refreshKey:a}),i=n.data?.filter(c=>(c.template?.id??null)===e)??null,l=r.data??[],u=Wi(n.data??[],l),d=new Set(l.flatMap(c=>c.draft_id&&c.status==="scheduled"?[c.draft_id]:[])),o=c=>u.has(c)?"Sent":d.has(c)?"Scheduled":"Draft";return wa("div",{"data-testid":"template-usage",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[je("h3",{className:"af-text-sm af-font-semibold",children:"Emails using it"}),n.error||r.error?je(Nt,{message:"Couldn't load the emails.",onRetry:()=>{n.refetch(),r.refetch()}}):!i||!r.data?je(J,{className:"af-h-10 af-w-full"}):i.length===0?je("p",{className:"af-text-sm af-text-muted-foreground",children:"No emails use it."}):je("ul",{className:"af-space-y-1",children:i.map(c=>{let b=o(c.id),g=wa(ll,{children:[je("span",{className:"af-block af-truncate af-text-sm",children:c.subject||"(no subject)"}),wa("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["Broadcast \xB7 ",b]})]});return je("li",{children:b==="Sent"?je("div",{className:"af-rounded-md af-px-2 af-py-1",children:g}):je("button",{type:"button",onClick:()=>t(c.id),className:"af-w-full af-rounded-md af-px-2 af-py-1 af-text-left hover:af-bg-muted",children:g})},c.id)})})]})}import{jsx as Ts,jsxs as Ji}from"react/jsx-runtime";function Gd({draft:e,disabled:t,onChanged:a}){let{api:s}=H(),{siteId:n,refreshKey:r}=nt(),i=Kt(()=>s.getEmailTemplates(n),`${n}|${r}`,n),l=Dt(),u=e.template?.id??zn,d=u===zn,o=(i.data??[]).filter(p=>p.status==="published"),c=o.find(p=>p.id===u),b=d?"Standard":e.template?.name??c?.name??"",g=d?"builtin":c?.updated_at??"current",m=async p=>{if(p===u)return;let f=await l.run("setDraftTemplate",{draftId:e.id,template_id:p===zn?null:p,expected_version:e.version});f.ok?await a():Ha(f.error,"template_missing_cart")?l.setError("This email shows the shopper's cart, and that template has no cart section. Pick another template, or keep this one."):Ha(f.error,"version_conflict")?(l.setError("This email changed meanwhile. We've loaded the latest version; switch again if you still want to."),await a()):Ha(f.error,"template_not_published")&&(l.setError("That template isn't published any more."),await i.refetch())};return Ji("div",{"data-testid":"template-card",className:"af-space-y-2 af-rounded-md af-border af-p-3",children:[Ts("div",{className:"af-text-sm af-font-semibold",children:"Template"}),Ji("div",{className:"af-flex af-items-center af-gap-3",children:[Ts(Yi,{templateId:u,version:g,className:"af-h-20 af-w-[72px] af-shrink-0 af-rounded af-border",frame:{width:600,height:670,scale:.12}}),Ts("div",{className:"af-min-w-0 af-grow af-truncate af-text-sm af-font-medium",children:b})]}),Ji("label",{className:"af-grid af-gap-1 af-text-xs af-text-muted-foreground",children:["Switch to",Ji("select",{"aria-label":"Switch to",value:u,disabled:t||l.busy,onChange:p=>void m(p.target.value),className:"af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-text-sm af-text-foreground",children:[Ts("option",{value:zn,children:"Standard"}),o.map(p=>Ts("option",{value:p.id,children:p.name},p.id)),!d&&!c&&Ts("option",{value:u,disabled:!0,children:b})]})]}),l.error&&Ts(Ne,{tone:"error",children:l.error})]})}import{Fragment as dl,jsx as We,jsxs as Zt}from"react/jsx-runtime";var Mg={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"},Ug=320,$g=600,Vg=e=>({top:Math.max(0,e.y-24),left:e.x});function Hg(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 Zd({draftId:e,renderCommit:t,onSaved:a,scheduled:s,onAskAssistant:n,onPickImage:r}){let{api:i}=H(),{siteId:l,canWrite:u,refreshKey:d,openSettings:o}=nt(),c=u&&!s,b=ze.useRef(c);b.current=c;let[g,m]=ze.useState(null),[p,f]=ze.useState(null),[v,x]=ze.useState(null),[R,P]=ze.useState(null),[h,S]=ze.useState(null),[N,C]=ze.useState(null),[w,k]=ze.useState(null),[T,_]=ze.useState(null),[z,Z]=ze.useState(null),[U,ae]=ze.useState({}),[le,fe]=ze.useState(Or.initial),[M,W]=ze.useState(!1),A=Dt(),de=Dt(),ce=ze.useRef(null),Le=ze.useRef(null),ye=ze.useRef(0),Te=ze.useRef(!1),Oe=ze.useRef(!1),oe=ze.useCallback(xe=>{Te.current=xe!==null,C(xe)},[]);Od(N!==null);let st=ze.useRef(g);st.current=g;let E=ze.useRef(0),O=ze.useCallback(async(xe={})=>{let ot=++E.current,Ze=b.current,yt=()=>Ze?i.previewEmailDraft(l,e,{editable:!0}):i.previewEmailDraft(l,e),[$,Ge]=await Promise.allSettled([i.getEmailDraft(l,e),yt()]),ra=Ge,Ms=()=>$.status==="fulfilled"&&ra.status==="fulfilled"&&ra.value.version!==$.value.version;if(Ms()&&ot===E.current&&([ra]=await Promise.allSettled([yt()])),ot===E.current){if(xe.background&&Te.current){Oe.current=!0;return}if(P(null),x(null),$.status==="rejected"){P(or($.reason));return}m($.value),ra.status==="fulfilled"?f({...ra.value,editable:Ze&&!Ms()}):(f(null),x(Ha(ra.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:or(ra.reason),code:null}))}},[i,l,e]);ze.useEffect(()=>{m(null),f(null),O()},[O]);let B=ze.useRef(c);ze.useEffect(()=>{B.current!==c&&(B.current=c,c||oe(null),O())},[c,O,oe]);let we=ze.useRef(d);ze.useEffect(()=>{if(d!==we.current){if(we.current=d,Te.current){Oe.current=!0;return}O({background:!0})}},[d,O]);let X=()=>{oe(null),A.setError(null),Oe.current&&(Oe.current=!1,O())},ve=async(xe,ot,Ze)=>{let yt=await A.run("updateDraft",{draftId:e,expected_version:xe.version,...ot});yt.ok?(k(null),Le.current=null,Oe.current=!1,oe(null),await O(),a?.()):Ha(yt.error,"version_conflict")&&(A.setError(null),k(Ze),Oe.current=!1,oe(null),await O())},Me=ze.useRef({frame:null,html:null,count:0}),[ht,Ke]=ze.useState(null),Ct=(xe,ot)=>{let Ze=Me.current;Ze.frame!==xe.currentTarget||Ze.html!==ot?Me.current={frame:xe.currentTarget,html:ot,count:1}:++Ze.count>1&&Ke(ot)},pe=p!==null&&ht===p.html,ke=c&&p?.editable===!0&&!pe;if(ze.useEffect(()=>{if(!ke)return;let xe=ot=>{let Ze=st.current;if(!Ze)return;let yt=Ud(ot,ce.current?.contentWindow,Ze.blocks.length);if(yt)switch(yt.type){case"hover":Z(yt.section===null?null:{section:yt.section,rect:yt.rect});return;case"focus":Le.current=yt.section;return;case"open":if(Le.current=yt.section,Te.current)return;_(null),W(!1),oe({kind:"section",base:Ze,index:yt.section,block:Ze.blocks[yt.section],isNew:!1,anchor:yt.rect,key:++ye.current});return;case"layout":fe($d(yt.height));{let $=Object.fromEntries(yt.sections.map(Ge=>[Ge.section,Ge.rect]));ae(Ge=>Hg(Ge,$)?Ge:$)}return;case"template":Te.current||_(yt.region);return}};return window.addEventListener("message",xe),()=>window.removeEventListener("message",xe)},[ke,oe]),R)return Zt(Ne,{tone:"error",children:["Couldn't load this email. ",R]});if(!g)return We(J,{className:"af-h-40 af-w-full"});let rt={width:ce.current?.clientWidth||$g,height:ke?le:Or.initial},Je=N?.kind==="section"?N:null,zt=(()=>{if(!Je)return null;if(!Je.isNew)return U[Je.index]??Je.anchor;let xe=U[Je.index-1];return xe?{x:xe.x,y:xe.y+xe.height,width:xe.width,height:0}:null})(),Ot=zt?rl(zt,rt):null,sa=g.kind==="recovery",it=g.template?.name??"Standard",vt=Je&&We(zd,{block:Je.block,isNew:Je.isNew,busy:A.busy,error:A.error,onPickImage:r,onCancel:X,onRemove:()=>{let{base:xe}=Je;ve(xe,{subject:xe.subject,preheader:xe.preheader,blocks:xe.blocks.filter((ot,Ze)=>Ze!==Je.index)},ol(Je.block))},onDone:xe=>{let{base:ot}=Je,Ze=Je.isNew?[...ot.blocks.slice(0,Je.index),xe,...ot.blocks.slice(Je.index)]:ot.blocks.map((yt,$)=>$===Je.index?xe:yt);ve(ot,{subject:ot.subject,preheader:ot.preheader,blocks:Ze},ol(xe))},className:Ot?"af-absolute af-z-10 af-rounded-md af-border af-bg-background af-p-3 af-shadow-lg":"af-rounded-md af-border af-bg-background af-p-3 af-shadow-sm",style:Ot?{top:Ot.y,left:Ot.x,width:Math.min(Math.max(Ot.width,Ug),rt.width)}:void 0},Je.key);return Zt("div",{className:"af-grid af-gap-4 lg:af-grid-cols-[minmax(0,1fr)_300px]",children:[Zt("div",{className:"af-min-w-0 af-space-y-3",children:[N?.kind==="subject"?We(zg,{draft:N.base,busy:A.busy,error:A.error,onCancel:X,onDone:xe=>void ve(N.base,{...xe,blocks:N.base.blocks},[xe.subject,xe.preheader??""].join(`
8
+ `))}):ke?We("button",{type:"button","data-testid":"subject-line",onClick:()=>{Te.current||(_(null),oe({kind:"subject",base:g}))},className:"af-block af-w-full af-rounded-md af-border af-border-dashed af-px-3 af-py-2 af-text-left hover:af-border-primary",children:We(Kd,{draft:g})}):We("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:We(Kd,{draft:g})}),s&&Zt(Ne,{tone:"info",children:[Zt("p",{children:["This email is scheduled",s.sendsAt?` to send ${new Date(s.sendsAt).toLocaleString()}`:"",", so it can't change. Unschedule it to edit, then schedule it again."]}),We(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:!u||s.busy,onClick:()=>void s.onUnschedule(),children:"Unschedule to edit"}),s.error&&We("p",{className:"af-mt-1 af-text-destructive",children:s.error})]}),w!==null&&Zt(Ne,{tone:"warning",children:[We("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."}),We("textarea",{readOnly:!0,"aria-label":"Your unsaved text",value:w,className:"af-mt-2 af-min-h-[72px] af-w-full af-rounded-md af-border af-bg-background af-px-2 af-py-1 af-font-mono af-text-xs af-text-foreground"}),We(y,{type:"button",size:"sm",variant:"ghost",onClick:()=>k(null),children:"Dismiss"})]}),T&&We("div",{"data-testid":"template-hint",children:We(Ne,{children:T==="header"?Zt(dl,{children:['The header is part of the "',it,'" template. Switch templates on the right.']}):Zt(dl,{children:["Every email ends with this footer. Your business name and address come from"," ",We(ks,{onClick:()=>o("sender"),children:"Settings"}),"."]})})}),pe&&c&&We(Ne,{tone:"warning",children:"This template tried to open another page in the preview, so the preview can't be edited here."}),p?Zt("div",{className:"af-relative",children:[We("iframe",{ref:ce,title:"Email preview",sandbox:ke?"allow-scripts":"",srcDoc:p.html,onLoad:ke?xe=>Ct(xe,p.html):void 0,style:{height:rt.height},className:"af-block af-w-full af-rounded-md af-border af-bg-white"},ke?"editable":"read-only"),ke&&z&&!N&&We("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:Vg(rl(z.rect,rt)),children:Mg[g.blocks[z.section]?.type??"text"]}),Ot&&vt]}):v?Zt(Ne,{tone:"warning",children:[v.text,We(ir,{reason:v.code})]}):We(J,{className:"af-h-40 af-w-full"}),!Ot&&vt,ke&&!N&&Zt("div",{className:"af-space-y-2",children:[We(y,{type:"button",variant:"outline",size:"sm",onClick:()=>W(xe=>!xe),"aria-expanded":M,children:"+ Add a section"}),M&&We("div",{"data-testid":"add-section-menu",className:"af-flex af-flex-wrap af-gap-2",children:["text","heading","button","image",...sa?["cart"]:[]].map(xe=>We(y,{type:"button",size:"sm",variant:"secondary",onClick:()=>{let ot=Le.current!==null?Le.current+1:g.blocks.length;W(!1),_(null),oe({kind:"section",base:g,index:ot,block:Hd(xe),isNew:!0,anchor:null,key:++ye.current})},children:il[xe]},xe))})]}),We("p",{className:"af-text-center af-text-xs af-text-muted-foreground",children:"Header and footer come from your template."})]}),Zt("div",{className:"af-space-y-3",children:[Zt("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[We(y,{type:"button",variant:"outline",size:"sm",disabled:!u||de.busy,onClick:async()=>{S(null);let xe=await de.run("testSendDraft",{draftId:e});xe.ok&&S(xe.result?.sent_to??"your email")},children:"Send a test to me"}),h&&Zt(Ne,{tone:"success",children:["Test sent to ",h,"."]}),de.error&&We(Ne,{tone:"error",children:de.error}),p&&!s&&t?.({draft:g,preview:p,reload:()=>O()})]}),We(Gd,{draft:g,disabled:!c||N!==null,onChanged:async()=>{await O(),a?.()}}),n&&u&&We(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 Kd({draft:e}){return Zt(dl,{children:[We("span",{className:"af-text-xs af-text-muted-foreground",children:"Subject "}),We("span",{className:"af-font-medium",children:e.subject||"(no subject)"}),e.preheader&&Zt("span",{className:"af-text-sm af-text-muted-foreground",children:[" \u2014 ",e.preheader]})]})}function zg({draft:e,busy:t,error:a,onDone:s,onCancel:n}){let[r,i]=ze.useState(e.subject),[l,u]=ze.useState(e.preheader??"");return Zt("form",{className:"af-space-y-2 af-rounded-md af-border af-p-3",onSubmit:d=>{d.preventDefault(),s({subject:r,preheader:l.trim()||null})},children:[Zt("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Subject",We(te,{"aria-label":"Subject",value:r,maxLength:200,autoFocus:!0,onChange:d=>i(d.target.value)})]}),Zt("label",{className:"af-block af-space-y-1 af-text-xs af-text-muted-foreground",children:["Preview text (the grey line after the subject in the inbox)",We(te,{"aria-label":"Preview text",value:l,maxLength:200,onChange:d=>u(d.target.value)})]}),a&&We(Ne,{tone:"error",children:a}),Zt("div",{className:"af-flex af-justify-end af-gap-2",children:[We(y,{type:"button",variant:"outline",size:"sm",disabled:t,onClick:n,children:"Cancel"}),We(y,{type:"submit",size:"sm",disabled:t,children:"Done"})]})]})}import{jsx as Re,jsxs as At}from"react/jsx-runtime";var jg={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function Jd({openDraftId:e,onOpenDraft:t,onAskAssistant:a,onPickImage:s}){let{siteId:n,canWrite:r,refreshKey:i}=nt(),[l,u]=wt.useState(0),d=l+i,o=dr({siteId:n,kind:"broadcast",refreshKey:d}),c=cr({siteId:n,refreshKey:d}),b=Dt(),g=Dt(),m=Wi(o.data??[],c.data??[]),p=o.data?.filter(f=>!m.has(f.id))??null;if(e){let f=c.data?.find(v=>v.draft_id===e&&v.status==="scheduled");return At("div",{className:"af-space-y-4",children:[At(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>t(null),children:[Re(qg,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),!c.data&&!c.error||!o.data&&!o.error?Re(J,{className:"af-h-40 af-w-full"}):m.has(e)?Re(Ne,{children:"This email has been sent, so it can't change. Duplicate it from the list to send it again."}):Re(Zd,{draftId:e,onSaved:()=>u(v=>v+1),renderCommit:v=>Re(Zg,{...v,onCommitted:()=>u(x=>x+1)}),scheduled:f?{sendsAt:f.scheduled_at,busy:b.busy,error:b.error,onUnschedule:async()=>{(await b.run("cancelBroadcast",{sendId:f.id})).ok&&u(x=>x+1)}}:void 0,onAskAssistant:a,onPickImage:s})]})}return At("div",{children:[Re(an,{children:"Drafts"}),o.error?Re(Nt,{message:"Couldn't load drafts.",onRetry:()=>void o.refetch()}):p?p.length===0?Re(ba,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):Re("ul",{"data-testid":"drafts",className:"af-divide-y af-rounded-md af-border",children:p.map(f=>At("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[Re("span",{className:"af-truncate af-text-sm",children:f.subject||"(no subject)"}),Re(y,{type:"button",variant:"outline",size:"sm",onClick:()=>t(f.id),children:"Review"})]},f.id))}):Re(J,{className:"af-h-10 af-w-full"}),Re(an,{children:"Sent and scheduled"}),b.error&&Re(Ne,{tone:"error",children:b.error}),g.error&&Re(Ne,{tone:"error",children:g.error}),c.error?Re(Nt,{message:"Couldn't load broadcasts.",onRetry:()=>void c.refetch()}):c.data?c.data.length===0?Re(ba,{children:"Nothing sent yet."}):Re("ul",{className:"af-divide-y af-rounded-md af-border",children:c.data.map(f=>Re(Wg,{broadcast:f,canCancel:r&&(f.status==="scheduled"||f.status==="unscheduled"||f.status==="sending"),busy:b.busy||g.busy,onCancel:async()=>{(await b.run("cancelBroadcast",{sendId:f.id})).ok&&u(x=>x+1)},onDuplicate:r&&f.draft_id&&tl(f)?async()=>{let v=await g.run("duplicateDraft",{draftId:f.draft_id});v.ok&&(u(x=>x+1),t(v.result.id))}:void 0},f.id))}):Re(J,{className:"af-h-10 af-w-full"})]})}function Wg({broadcast:e,canCancel:t,busy:a,onCancel:s,onDuplicate:n}){return At("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[At("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[Re("span",{className:"af-truncate af-text-sm af-font-medium",children:e.subject}),At("div",{className:"af-flex af-items-center af-gap-2",children:[Re(ee,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:jg[e.status]}),t&&Re(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:s,children:"Cancel"}),n&&Re(y,{type:"button",variant:"ghost",size:"sm",disabled:a,onClick:n,children:"Duplicate"})]})]}),At("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",Fe(e.recipients.planned)," recipients \xB7 ",Fe(e.stats.delivered)," delivered \xB7 ",Fe(e.stats.opened)," opened \xB7"," ",Fe(e.stats.clicked)," clicked \xB7 ",Fe(e.stats.bounced)," bounced \xB7 ",Fe(e.stats.complained)," complaints \xB7"," ",Fe(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&Re("div",{className:"af-text-xs af-text-muted-foreground",children:sr(e.status_reason)})]})}var Xd=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function Yd(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:Xd(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:s?Gg(a):"",suggested:t!==null||a!==null,timePassed:a!==null&&!s}}function Gg(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 Kg=(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 Zg({draft:e,preview:t,reload:a,onCommitted:s}){let{api:n}=H(),{siteId:r,canWrite:i,settings:l,refreshKey:u}=nt(),[d,o]=wt.useState(null),[c,b]=wt.useState(!1),[g,m]=wt.useState(null),[p,f]=wt.useState(()=>Yd(e)),[v,x]=wt.useState(p.tagIds),[R,P]=wt.useState(p.match),[h,S]=wt.useState(p.scheduleAt),[N,C]=wt.useState(0),w=!Kg({tagIds:v,match:R,scheduleAt:h},p),k=Xd(e);wt.useEffect(()=>{if(k===p.key||e.id===p.draftId&&w)return;let X=Yd(e);f(X),x(X.tagIds),P(X.match),S(X.scheduleAt),C(0)},[k,e,p,w]);let T=wt.useMemo(()=>d?new Set(d.map(X=>X.id)):null,[d]),_=T!==null&&v.every(X=>T.has(X));wt.useEffect(()=>{if(!T||v.every(ve=>T.has(ve)))return;let X=ve=>ve.filter(Me=>T.has(Me));C(ve=>ve+v.length-X(v).length),x(X(v)),f(ve=>({...ve,tagIds:X(ve.tagIds)}))},[T,v]);let[z,Z]=wt.useState(null),[U,ae]=wt.useState(null),[le,fe]=wt.useState(null),M=Dt();wt.useEffect(()=>{n.getMarketingTags(r).then(X=>{o(X),b(!1)},()=>{o(null),b(!0)}),n.getMarketingContactStats(r).then(m,()=>m(null))},[n,r,u]);let W=h?new Date(h).toISOString():null,A=JSON.stringify([v,R,W]),de=z?.plan??null,ce=z!==null&&z.key===A,Le=wt.useRef(0),ye=wt.useCallback(async()=>{let X=++Le.current;ae(null);try{let ve=await n.estimateBroadcast(r,{targeting:{tag_ids:v,match:R},scheduled_at:W});X===Le.current&&Z({key:A,plan:ve})}catch(ve){if(X!==Le.current)return;Z(null),ae(or(ve))}},[n,r,v,R,W,A,u]),Te=wt.useRef(!1);wt.useEffect(()=>{if(!_&&v.length>0)return;if(!Te.current){Te.current=!0,ye();return}let X=setTimeout(()=>void ye(),300);return()=>clearTimeout(X)},[ye,_,v.length]);let Oe=l&&!l.readiness.can_send?sr(l.readiness.reason):null,oe=de!==null&&!de.fits,st=g?Math.max(0,g.by_status.subscribed-g.mailable):null,E=g&&de&&st!==null?Math.max(0,g.total-de.recipients-st):null,O=!i||M.busy||!de||!ce||oe||de.recipients===0||Oe!==null||c&&v.length>0,B=async()=>{fe(null);let X=await M.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:v,match:R},scheduled_at:W});if(X.ok){fe({tone:"success",text:W?"Scheduled.":"Sending now."}),s();return}Ha(X.error,"version_conflict")?(M.setError(null),await a(),fe({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):Ha(X.error,"over_allowance")&&await ye()},we=X=>x(ve=>ve.includes(X)?ve.filter(Me=>Me!==X):[...ve,X]);return At("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[p.suggested&&!w&&Re(Ne,{children:"Suggested by your assistant \u2014 review before sending."}),Re(an,{children:"Who gets it"}),c&&Re(Ne,{tone:"warning",children:v.length>0?"Couldn't load your tags, so this targeted send can't go out yet. Refresh to try again.":"Couldn't load your tags. Refresh to target by tag."}),N>0&&Re(Ne,{tone:"warning",children:N===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),d&&d.length>0?At("div",{className:"af-space-y-2",children:[Re("div",{className:"af-flex af-flex-wrap af-gap-2",children:d.map(X=>At("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[Re("input",{type:"checkbox",checked:v.includes(X.id),onChange:()=>we(X.id)}),X.label]},X.id))}),v.length>1&&At("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",At("select",{"aria-label":"Tag match",value:R,onChange:X=>P(X.target.value),className:"af-rounded-md af-border af-px-2 af-py-1",children:[Re("option",{value:"any",children:"any of these tags"}),Re("option",{value:"all",children:"all of these tags"})]})]}),v.length===0&&Re("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):Re("p",{className:"af-text-sm af-text-muted-foreground",children:"Everyone who can be emailed."}),At("label",{className:"af-block af-space-y-1",children:[Re("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),Re(te,{"aria-label":"Schedule time",type:"datetime-local",value:h,onChange:X=>S(X.target.value)})]}),p.timePassed&&!h&&Re(Ne,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),U?At(Ne,{tone:"error",children:["Couldn't work out the audience. ",U]}):de?At("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[At("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[Re(ul,{label:"Will receive it",value:de.recipients}),Re(ul,{label:"Suppressed (bounced or complained)",value:st}),Re(ul,{label:"Not included",value:E})]}),At("p",{className:"af-text-muted-foreground",children:[Fe(de.allowance.remaining)," of ",Fe(de.allowance.monthly)," emails left this month."]}),de.sample_size!==null&&At(Ne,{children:["We'll send to ",Fe(de.sample_size)," people first and check for bounces before sending the rest."]}),de.ramp_days.length>1&&At(Ne,{children:["Your domain is new, so this goes out over ",de.ramp_days.length," days:"," ",de.ramp_days.map(X=>`${Fe(X.recipients)} on ${X.date}`).join(", "),"."]})]}):Re(J,{className:"af-h-12 af-w-full"}),oe&&de&&At(Ne,{tone:"warning",children:["This send needs ",Fe(de.recipients)," emails, but only ",Fe(de.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),Oe&&At(Ne,{tone:"warning",children:[Oe,Re(ir,{reason:l?.readiness.reason})]}),le&&Re(Ne,{tone:le.tone,children:le.text}),M.error&&Re(Ne,{tone:"error",children:M.error}),Re(y,{type:"button",disabled:O,onClick:()=>void B(),children:W?"Schedule":"Send now"})]})}function ul({label:e,value:t}){return At("div",{className:"af-rounded-md af-border af-px-2 af-py-1",children:[Re("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Re("div",{className:"af-font-semibold",children:t===null?"\u2014":Fe(t)})]})}import*as ka from"react";import{Check as au,FileText as uv,ShieldCheck as fv}from"lucide-react";import*as Es from"react";import{ArrowRight as Yg,Check as Qd,ChevronDown as Jg,Globe as Xg,Lock as Qg,Mail as Qi,PenLine as ev,Sparkles as tv}from"lucide-react";import{Fragment as Xi,jsx as K,jsxs as ge}from"react/jsx-runtime";var av=[{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."}],nv="hello";function ml(e){return`${nv}@${e}`}function eu({onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a,onTurnOn:s,siteDomain:n,businessName:r}){let{api:i}=H(),{siteId:l,settings:u,canWrite:d,refreshKey:o,refetchSettings:c}=nt(),b=Kt(()=>i.getMarketingContactStats(l),`${l}|${o}`,l),[g,m]=Es.useState(!1),[p,f]=Es.useState(null);if(!u)return null;let v=b.data?.by_status.subscribed??0,x={siteDomain:n,businessName:r};return sv(u)?K(pl,{settings:u,site:x,waiting:v,children:d?s&&ge("div",{className:"af-space-y-2",children:[ge(y,{disabled:g,onClick:async()=>{m(!0),f(null);try{await s(),await c()}catch(R){f(R instanceof Error?R.message:"Couldn't turn on email. Try again.")}finally{m(!1)}},children:["Get started ",K(Yg,{className:"af-ml-2 af-h-4 af-w-4","aria-hidden":!0})]}),p&&K(Ne,{tone:"error",children:p})]}):K("p",{className:"af-text-sm af-text-muted-foreground",children:"Only the site owner can set up email."})}):K(rv,{settings:u,site:x,waiting:v,onStartDomainSetup:e,onConnectDomain:t,onAskAssistant:a})}function sv(e){return e.readiness.reason==="sending_not_enabled"}function pl({settings:e,site:t,waiting:a=0,children:s}){return K("div",{className:"af-mx-auto af-max-w-3xl af-px-2 af-py-8",children:ge("div",{className:"af-grid af-items-center af-gap-10 md:af-grid-cols-[1fr_18rem]",children:[ge("div",{children:[ge("div",{className:"af-mb-3 af-inline-flex af-items-center af-gap-1.5 af-rounded-full af-bg-muted af-px-2.5 af-py-1 af-text-xs af-font-medium",children:[K(Qi,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0})," Email marketing"]}),K("h3",{className:"af-text-2xl af-font-semibold af-tracking-tight",children:"Turn visitors into regulars"}),K("p",{className:"af-mt-2 af-text-muted-foreground",children:"Build an email list from your website and reach those people directly, whenever you have something worth telling them."}),K("ol",{className:"af-mt-6 af-space-y-3",children:av.map((n,r)=>ge("li",{className:"af-flex af-gap-3",children:[K("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-border af-text-xs af-font-semibold",children:r+1}),ge("p",{className:"af-text-sm",children:[ge("span",{className:"af-font-medium",children:[n.title,"."]})," ",K("span",{className:"af-text-muted-foreground",children:n.body})]})]},n.title))}),a>0&&ge("p",{className:"af-mt-5 af-rounded-md af-bg-amber-50 af-px-3 af-py-2 af-text-sm af-text-amber-900",children:[ge("span",{className:"af-font-semibold",children:[Fe(a)," ",a===1?"person has":"people have"]})," ","already signed up and ",a===1?"is":"are"," waiting for your first email."]}),K("div",{className:"af-mt-6",children:s})]}),K(eo,{settings:e,site:t,className:"af-rotate-1"})]})})}function tu({onUpgradePlan:e}){return ge("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-border-violet-200 af-bg-gradient-to-r af-from-violet-50 af-to-white af-p-4",children:[K(Qg,{className:"af-h-5 af-w-5 af-shrink-0 af-text-violet-700","aria-hidden":!0}),ge("div",{className:"af-flex-1",children:[K("div",{className:"af-text-sm af-font-semibold af-text-violet-900",children:"Email marketing is part of Pro"}),K("div",{className:"af-text-sm af-text-violet-900/80",children:"Collect subscribers and send newsletters from your own domain."})]}),e&&K(y,{size:"sm",onClick:e,children:"Upgrade to Pro"})]})}function rv({settings:e,site:t,waiting:a,onStartDomainSetup:s,onConnectDomain:n,onAskAssistant:r}){let{refetchSettings:i,canWrite:l}=nt(),[u,d]=Es.useState(null),o=p=>d(f=>f===p?null:p),{siteDomain:c}=t,b=Br(e),g=c===null&&!e.domain.sending_domain,m=!!e.postal_address;return ge("div",{className:"af-mx-auto af-max-w-4xl af-py-4",children:[ge("div",{className:"af-mb-6 af-flex af-items-start af-justify-between af-gap-6",children:[ge("div",{children:[K("h3",{className:"af-text-xl af-font-semibold",children:"Set up email"}),ge("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Newsletters to your subscribers, sent from ",c??"your own domain","."]})]}),a>0&&ge("div",{className:"af-text-right",children:[K("div",{className:"af-text-2xl af-font-semibold",children:Fe(a)}),ge("div",{className:"af-text-xs af-text-muted-foreground",children:[a===1?"subscriber":"subscribers"," waiting"]})]})]}),!l&&K(Ne,{className:"af-mb-4",children:"Only the site owner can finish setup."}),ge("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_16rem]",children:[ge("div",{className:"af-space-y-4",children:[ge(fl,{title:c??"Your domain",sub:"One domain for your website and your email.",children:[c&&K(Tn,{icon:Xg,label:"Website",value:c,status:K(Cn,{tone:"green",children:"Live"})}),g?K(Tn,{icon:Qi,label:"Email sending",value:"Needs a custom domain",status:K(Cn,{tone:"gray",children:"Not available"}),action:n&&l?{label:"Connect domain",onClick:n}:void 0}):ge(Tn,{icon:Qi,label:"Email sending",value:e.domain.sending_domain??(c?`news.${c}`:"news.yourdomain.com"),status:gl(e),action:!b&&l?{label:e.domain.sending_domain?"Details":"Set up",onClick:()=>o("sending")}:void 0,expanded:u==="sending",children:[!e.domain.sending_domain&&K("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:"Emails go out from a subdomain of your site's domain, so they reach inboxes and are clearly from you. If we manage your domain's DNS we add the records; otherwise you'll get a few to copy into your DNS provider."}),K(vl,{settings:e,canWrite:l,onStartDomainSetup:s,onChanged:i})]})]}),K(fl,{title:"Sender",sub:"Who your emails are from. The mailing address is legally required in every email.",children:K(Tn,{icon:ev,label:m?e.business_name??"Sender":"Not set",value:e.postal_address??"Name, mailing address and reply-to",status:m?K(Cn,{tone:"green",children:"Done"}):K(Cn,{tone:"gray",children:"Needed"}),action:l?{label:m?"Edit":"Add",onClick:()=>o("sender")}:void 0,expanded:u==="sender",children:K(iv,{settings:e,businessName:t.businessName,onSaved:async()=>{await i(),d(null)}})})}),K(fl,{title:"How people join your list",sub:"Only people who asked to hear from you get your emails.",children:K(dv,{onAskAssistant:l?r:void 0})})]}),ge("aside",{className:"af-space-y-3",children:[K("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails will look like"}),K(eo,{settings:e,site:t})]})]})]})}function fl({title:e,sub:t,children:a}){return ge("section",{className:"af-rounded-xl af-border af-bg-background",children:[ge("div",{className:"af-px-5 af-pb-3 af-pt-4",children:[K("h4",{className:"af-text-sm af-font-semibold",children:e}),K("p",{className:"af-text-xs af-text-muted-foreground",children:t})]}),K("div",{className:"af-space-y-2 af-px-3 af-pb-3",children:a})]})}function Tn({icon:e,marker:t,label:a,value:s,mono:n=!0,hint:r,status:i,action:l,expanded:u=!1,children:d}){return ge("div",{className:"af-rounded-lg af-border af-bg-muted/30",children:[ge("div",{className:"af-flex af-items-center af-gap-3 af-p-3",children:[t?ge("span",{className:"af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-xs af-font-semibold af-text-background",children:[K("span",{"aria-hidden":!0,children:t}),ge("span",{className:"af-sr-only",children:["Shown at ",t," in the preview"]})]}):e&&K("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-md af-border af-bg-background",children:K(e,{className:"af-h-4 af-w-4","aria-hidden":!0})}),ge("div",{className:"af-min-w-0 af-flex-1",children:[K("div",{className:"af-text-xs af-text-muted-foreground",children:a}),K("div",{className:G("af-truncate af-text-sm",n&&"af-font-mono"),children:s}),r&&K("div",{className:"af-text-xs af-text-muted-foreground",children:r})]}),i,l&&ge(y,{size:"sm",variant:u?"secondary":"outline","aria-expanded":d?u:void 0,onClick:l.onClick,children:[l.label,d&&K(Jg,{className:G("af-ml-1 af-h-3.5 af-w-3.5 af-transition-transform",u&&"af-rotate-180"),"aria-hidden":!0})]})]}),u&&d&&K("div",{className:"af-border-t af-bg-background af-p-4",children:d})]})}function Cn({tone:e,children:t}){return K("span",{className:G("af-inline-flex af-shrink-0 af-items-center af-rounded-full af-px-2 af-py-0.5 af-text-xs af-font-medium",e==="green"&&"af-bg-green-100 af-text-green-800",e==="amber"&&"af-bg-amber-100 af-text-amber-900",e==="gray"&&"af-bg-muted af-text-muted-foreground",e==="red"&&"af-bg-red-100 af-text-red-800"),children:t})}function Br(e){return e.domain.status==="verified"&&e.domain.dmarc_status==="ok"}function gl(e){let{sending_domain:t,status:a}=e.domain;return!t||a==="none"?K(Cn,{tone:"gray",children:"Not set up"}):a==="verified"?Br(e)?K(Cn,{tone:"green",children:"Live"}):K(Cn,{tone:"amber",children:"DMARC record missing"}):a==="failed"?K(Cn,{tone:"red",children:"Records not found"}):K(Cn,{tone:"amber",children:"Waiting for DNS"})}function iv({settings:e,businessName:t,onSaved:a}){let{canWrite:s}=nt(),[n,r]=Es.useState(e.business_name??t??""),[i,l]=Es.useState(e.postal_address??""),[u,d]=Es.useState(e.reply_to??""),o=Dt();return ge("form",{className:"af-space-y-3",onSubmit:async c=>{c.preventDefault(),(await o.run("updateSettings",{business_name:n.trim()||null,postal_address:i.trim()||null,reply_to:u.trim()||null,double_opt_in:e.double_opt_in})).ok&&await a()},children:[K(ov,{name:n,address:i}),ge("label",{className:"af-block af-space-y-1",children:[K("span",{className:"af-text-sm af-font-medium",children:"Sender name"}),K(te,{"aria-label":"Business name",value:n,disabled:!s,onChange:c=>r(c.target.value)})]}),ge("label",{className:"af-block af-space-y-1",children:[K("span",{className:"af-text-sm af-font-medium",children:"Mailing address"}),K("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:i,disabled:!s,onChange:c=>l(c.target.value)}),K("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Anti-spam law requires it at the bottom of every email. A PO box works."})]}),ge("label",{className:"af-block af-space-y-1",children:[K("span",{className:"af-text-sm af-font-medium",children:"Replies go to (optional)"}),K(te,{"aria-label":"Reply-to email",type:"email",value:u,disabled:!s,onChange:c=>d(c.target.value)}),K("span",{className:"af-block af-text-xs af-text-muted-foreground",children:"Your account email or an address on your domain."})]}),o.error&&K(Ne,{tone:"error",children:o.error}),s&&K(y,{type:"submit",size:"sm",disabled:o.busy||!i.trim(),children:"Save sender details"})]})}function ov({name:e,address:t}){return ge("div",{className:"af-rounded-lg af-bg-muted/50 af-px-4 af-py-4 af-text-center af-text-xs af-leading-relaxed af-text-muted-foreground",children:[K("div",{className:"af-mb-1 af-text-[10px] af-uppercase af-tracking-wide",children:"Footer of every email"}),ge("div",{children:["\xA9 ",new Date().getFullYear()," ",K("span",{className:"af-font-medium af-text-foreground",children:e.trim()||"Your business"})]}),K("div",{className:G(!t.trim()&&"af-italic af-text-amber-700"),children:t.trim()||"No mailing address yet"}),ge("div",{children:[K("span",{className:"af-underline",children:"Manage preferences"})," | ",K("span",{className:"af-underline",children:"Unsubscribe"})]})]})}var lv={1:"From",2:"Subject and body",3:"Footer"};function eo({settings:e,site:t,className:a,numbered:s=!1,highlight:n=null,postalAddress:r}){let i=e?.business_name||t.businessName||"Your business",l=e?.domain.sending_domain??(t.siteDomain?`news.${t.siteDomain}`:"news.yourdomain.com"),u={backgroundColor:e?.brand.color??"hsl(var(--primary))"},d=r!==void 0?r.trim()||null:e?.postal_address,o=(c,b,g)=>s?ge("div",{"data-preview-region":c,"data-highlighted":n===c,className:G("af-relative af-rounded-md af-transition-shadow",n===c&&"af-ring-2 af-ring-primary af-ring-offset-2",b),children:[ge("span",{className:"af-absolute -af-left-3 -af-top-2 af-flex af-h-5 af-w-5 af-items-center af-justify-center af-rounded-full af-bg-foreground af-text-[10px] af-font-semibold af-text-background",children:[K("span",{"aria-hidden":!0,children:c}),ge("span",{className:"af-sr-only",children:[c,". ",lv[c],":"]})]}),g]}):K("div",{className:b,children:g});return ge("div",{className:G("af-rounded-lg af-border af-bg-background af-p-4 af-shadow-sm",a),"aria-hidden":s?void 0:!0,"aria-label":s?"Email preview":void 0,role:s?"group":void 0,children:[o(1,"af-flex af-items-start af-gap-3",ge(Xi,{children:[K("div",{className:"af-flex af-h-9 af-w-9 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-sm af-font-semibold af-text-white",style:u,children:i.slice(0,1).toUpperCase()}),ge("div",{className:"af-min-w-0",children:[K("div",{className:"af-truncate af-text-sm af-font-semibold",children:i}),ge("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:["<",ml(l),">"]}),K("div",{className:"af-text-xs af-text-muted-foreground",children:"to me"})]})]})),o(2,"af-mt-4 af-space-y-2",ge(Xi,{children:[K("div",{className:"af-text-sm af-font-medium",children:"What's new this month"}),K("div",{className:"af-h-2 af-w-full af-rounded af-bg-muted"}),K("div",{className:"af-h-2 af-w-5/6 af-rounded af-bg-muted"}),K("div",{className:"af-h-2 af-w-2/3 af-rounded af-bg-muted"})]})),o(3,"af-mt-4 af-border-t af-pt-2 af-text-center af-text-[10px] af-leading-snug af-text-muted-foreground",ge(Xi,{children:[K("div",{children:d??K("span",{className:"af-italic af-text-amber-700",children:"Mailing address goes here"})}),K("div",{className:"af-underline",children:"Unsubscribe"})]}))]})}var cv="Add a newsletter signup to my footer";function dv({onAskAssistant:e}){let t=bl();if(!t.data)return null;let{signups:a,optIns:s,others:n}=hl(t.data);return ge("div",{className:"af-space-y-3",children:[a.length===0?ge("div",{className:"af-flex af-flex-col af-items-center af-gap-2 af-rounded-lg af-border af-border-dashed af-px-6 af-py-6 af-text-center",children:[K("div",{className:"af-flex af-h-10 af-w-10 af-items-center af-justify-center af-rounded-full af-bg-muted",children:K(Qi,{className:"af-h-5 af-w-5","aria-hidden":!0})}),K("div",{className:"af-text-sm af-font-medium",children:"Add a signup form to your site"}),K("p",{className:"af-max-w-sm af-text-xs af-text-muted-foreground",children:`A short "Get our news" form, usually in the footer. It's how most of your list will find you.`}),e&&ge(y,{type:"button",size:"sm",className:"af-mt-1",onClick:()=>e(cv),children:[K(tv,{className:"af-mr-1.5 af-h-3.5 af-w-3.5","aria-hidden":!0}),"Add signup form"]})]}):ge("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[K(Qd,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),ge("div",{className:"af-min-w-0 af-flex-1",children:[K("span",{className:"af-font-medium",children:"Signup form is live"}),ge("span",{className:"af-text-muted-foreground",children:[" \xB7 ",a.map(r=>r.name).join(", ")]})]})]}),s.length>0&&ge("div",{className:"af-flex af-items-center af-gap-3 af-rounded-lg af-border af-p-3 af-text-sm",children:[K(Qd,{className:"af-h-4 af-w-4 af-shrink-0 af-text-green-600","aria-hidden":!0}),ge("div",{className:"af-min-w-0 af-flex-1",children:[K("span",{className:"af-font-medium",children:"Opt-in checkbox"}),ge("span",{className:"af-text-muted-foreground",children:[" \xB7 ",s.map(r=>r.name).join(", ")]})]})]}),a.length===0&&n.length>0&&ge("p",{className:"af-px-2 af-text-xs af-text-muted-foreground",children:["Your ",n.length===1?"form":"forms"," ",n.map(r=>`"${r.name}"`).join(", "),' can also add people, with a "Send me news" checkbox.',e&&ge(Xi,{children:[" ",K("button",{type:"button",className:"af-font-medium af-text-foreground af-underline af-underline-offset-2",onClick:()=>e(yl(n)),children:"Add the checkbox"})]})]})]})}import{Fragment as wv,jsx as ue,jsxs as ea}from"react/jsx-runtime";var to="Subscribers confirm by email before they receive anything. Useful if many subscribers are in the EU (especially Germany), or if your forms attract fake or mistyped signups. Some signups need confirming even with this off: bursts of signups, and people re-subscribing after they unsubscribed.";function mv(e){let{status:t,dmarc_status:a,sending_domain:s}=e.domain;return!s||t==="none"?"No sending domain yet.":t==="verified"?a==="ok"?`Verified. Emails send from ${s}.`:`${s} is verified, but your domain still needs a DMARC record.`:t==="failed"?`${s} couldn't be verified. Check the DNS records below.`:`Waiting for the DNS records on ${s} to take effect. This can take a few hours.`}function xl({onStartDomainSetup:e,onAskAssistant:t}){let{settings:a,refetchSettings:s,canWrite:n,settingsSection:r}=nt(),[i,l]=ka.useState(null),[u,d]=ka.useState(null),[o,c]=ka.useState(""),b=a!==null;if(ka.useEffect(()=>{b&&r&&document.getElementById(Dr(r))?.scrollIntoView?.({block:"start"})},[b,r]),!a)return ue(J,{className:"af-h-40 af-w-full"});let g=h=>d(S=>S===h?null:h),m=()=>d(null),p=async()=>{await s(),m()},f=(h,S,N)=>({id:N,"data-settings-row":h,onMouseEnter:()=>l(S),onMouseLeave:()=>l(null),onFocus:()=>l(S),onBlur:()=>l(null)}),v=Br(a),{sending_domain:x,status:R}=a.domain,P=h=>n?{expanded:u===h}:{};return ue("div",{className:"af-@container",children:ea("div",{className:"af-grid af-items-start af-gap-6 @2xl:af-grid-cols-[minmax(0,17rem)_minmax(0,1fr)]",children:[ea("aside",{className:"af-space-y-3 af-pl-3",children:[ue("div",{className:"af-text-xs af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:"Your emails look like this"}),ue(eo,{settings:a,site:{},numbered:!0,highlight:i,postalAddress:u==="address"?o:void 0}),ue(yv,{settings:a})]}),ea("div",{children:[ue(an,{children:"From"}),ea("div",{className:"af-space-y-2",children:[ue("div",{...f("Sending domain",1,Dr("domain")),children:ue(Tn,{marker:1,label:"Sending from",value:x?ml(x):"No sending domain yet",status:gl(a),action:!v&&n?{label:x?R==="verified"||R==="failed"?"Fix":"Details":"Set up",onClick:()=>g("domain")}:void 0,...P("domain"),children:ue(vl,{settings:a,canWrite:n,onStartDomainSetup:e,onChanged:s})})}),ue("div",{...f("Sender name and replies",1),children:ue(Tn,{marker:1,label:"Sender name and replies",mono:!1,value:`${a.business_name??"No sender name"} \xB7 replies to ${a.reply_to??"your account email"}`,action:n?{label:"Edit",onClick:()=>g("sender")}:void 0,...P("sender"),children:ue(pv,{settings:a,onSaved:p,onCancel:m})})})]}),ue(an,{children:"Brand"}),ue("div",{...f("Brand color and logo",2),children:ue(Tn,{marker:2,label:"Brand color and logo",value:`${a.brand.color}, ${a.brand.logo_url?"with your logo":"no logo"}`,action:n?{label:"Edit",onClick:()=>g("brand")}:void 0,...P("brand"),children:ue(gv,{settings:a,onSaved:p,onCancel:m})})}),ue(an,{children:"Footer"}),ue("div",{...f("Mailing address",3,Dr("sender")),children:ue(Tn,{marker:3,label:"Mailing address",mono:!1,value:a.postal_address??"Not set",hint:"Anti-spam law requires it at the bottom of every email. A PO box works.",status:a.postal_address?void 0:ue(Cn,{tone:"amber",children:"Needed"}),action:n?{label:a.postal_address?"Edit":"Add",onClick:()=>{c(a.postal_address??""),g("address")}}:void 0,...P("address"),children:ue(vv,{settings:a,draft:o,onDraft:c,onSaved:p,onCancel:m})})}),ea("div",{id:Dr("signups"),children:[ue(an,{children:"Who gets it"}),ea("div",{className:"af-space-y-2",children:[ue("div",{...f("Double opt-in",null),children:ue(bv,{settings:a,canWrite:n,onSaved:s})}),ue(xv,{onAskAssistant:n?t:void 0})]})]})]})]})})}function no(e,t){return{business_name:e.business_name,postal_address:e.postal_address,reply_to:e.reply_to,double_opt_in:e.double_opt_in,...t}}function wl({busy:e,error:t,canSave:a=!0,onSave:s,onCancel:n,children:r}){return ea("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),await s()},children:[r,t&&ue(Ne,{tone:"error",children:t}),ea("div",{className:"af-flex af-gap-2",children:[ue(y,{type:"submit",size:"sm",disabled:e||!a,children:"Save"}),ue(y,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Cancel"})]})]})}function pv({settings:e,onSaved:t,onCancel:a}){let[s,n]=ka.useState(e.business_name??""),[r,i]=ka.useState(e.reply_to??""),l=Dt();return ea(wl,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",no(e,{business_name:s.trim()||null,reply_to:r.trim()||null}))).ok&&await t()},children:[ue(ao,{label:"Sender name",children:ue(te,{"aria-label":"Business name",value:s,onChange:u=>n(u.target.value)})}),ue(ao,{label:"Replies go to (your account email or an address on your domain)",children:ue(te,{"aria-label":"Reply-to email",type:"email",value:r,onChange:u=>i(u.target.value)})})]})}function gv({settings:e,onSaved:t,onCancel:a}){let[s,n]=ka.useState(e.brand.color),[r,i]=ka.useState(e.brand.logo_url??""),l=Dt();return ue(wl,{busy:l.busy,error:l.error,onCancel:a,onSave:async()=>{(await l.run("updateSettings",no(e,{brand:{color:s,logo_url:r.trim()||null}}))).ok&&await t()},children:ea("div",{className:"af-flex af-flex-wrap af-gap-3",children:[ue(ao,{label:"Brand color",children:ue(te,{"aria-label":"Brand color",type:"color",className:"af-h-9 af-w-16 af-p-1",value:s,onChange:u=>n(u.target.value)})}),ue(ao,{label:"Logo URL (https)",children:ue(te,{"aria-label":"Logo URL",value:r,onChange:u=>i(u.target.value)})})]})})}function vv({settings:e,draft:t,onDraft:a,onSaved:s,onCancel:n}){let r=Dt();return ue(wl,{busy:r.busy,error:r.error,canSave:!!t.trim(),onCancel:n,onSave:async()=>{(await r.run("updateSettings",no(e,{postal_address:t.trim()}))).ok&&await s()},children:ue("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",placeholder:"Street, city, state, ZIP",value:t,onChange:i=>a(i.target.value)})})}function bv({settings:e,canWrite:t,onSaved:a}){let[s,n]=ka.useState(null),[r,i]=ka.useState(!1),l=Dt(),u=s??e.double_opt_in;return ea("div",{className:"af-space-y-2",children:[ue(Tn,{icon:fv,label:"Double opt-in",mono:!1,value:u?"New subscribers confirm by email first":"New subscribers join straight away",status:ea("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[ue("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:to,className:"af-inline-flex af-h-4 af-w-4 af-cursor-help af-items-center af-justify-center af-rounded-full af-border af-text-[10px]",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:"?"}),ue("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!r,className:"af-absolute af-right-0 af-top-6 af-z-10 af-w-72 af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:to}),ue("input",{"aria-label":"Double opt-in",type:"checkbox",role:"switch",checked:u,disabled:!t||l.busy,onChange:async d=>{let o=d.target.checked;n(o),(await l.run("updateSettings",no(e,{double_opt_in:o}))).ok&&await a(),n(null)}})]})}),l.error&&ue(Ne,{tone:"error",children:l.error})]})}function vl({settings:e,canWrite:t,onStartDomainSetup:a,onChanged:s}){let[n,r]=ka.useState(null),[i,l]=ka.useState(!1),[u,d]=ka.useState(null),o=Br(e);return ea("div",{children:[ue("p",{className:"af-text-sm",children:mv(e)}),!o&&a&&ue(y,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||i,onClick:async()=>{l(!0),d(null);try{r(await a()),await s()}catch(c){d(c instanceof Error?c.message:"Couldn't start domain setup.")}finally{l(!1)}},children:e.domain.sending_domain?"Check domain setup":"Set up sending domain"}),u&&ue(Ne,{tone:"error",className:"af-mt-2",children:u}),n?.records&&n.records.length>0&&ea("div",{className:"af-mt-3 af-space-y-1",children:[ue("p",{className:"af-text-sm",children:"Add these records at your domain provider:"}),ea("table",{className:"af-w-full af-text-left af-text-xs",children:[ue("thead",{children:ea("tr",{children:[ue("th",{className:"af-py-1 af-pr-2",children:"Type"}),ue("th",{className:"af-py-1 af-pr-2",children:"Name"}),ue("th",{className:"af-py-1 af-pr-2",children:"Value"}),ue("th",{className:"af-py-1",children:"Priority"})]})}),ue("tbody",{children:n.records.map((c,b)=>ea("tr",{className:"af-border-t af-align-top",children:[ue("td",{className:"af-py-1 af-pr-2",children:c.type}),ue("td",{className:"af-break-all af-py-1 af-pr-2",children:c.name}),ue("td",{className:"af-break-all af-py-1 af-pr-2",children:c.value}),ue("td",{className:"af-py-1",children:c.priority??""})]},b))})]})]}),n&&ue(hv,{result:n})]})}function hv({result:e}){return e.status==="no_domain"?ue(Ne,{tone:"warning",className:"af-mt-2",children:"Emails send from your own domain, so this site needs a custom domain first. Connect one, then come back to finish here."}):e.status==="not_available"?ue(Ne,{tone:"warning",className:"af-mt-2",children:"Email sending isn't available for this site. It needs the Pro plan."}):e.records&&e.records.length>0?null:ue("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",children:"We added the DNS records for you. Verification usually finishes within a few hours."})}function yv({settings:e}){let{monthly:t,sent:a,reserved:s}=e.allowance,n=a+s;return ea("p",{className:"af-text-xs af-text-muted-foreground",children:[Fe(n)," of ",Fe(t)," emails used this month (",Fe(Math.max(0,t-n))," left). Receipts and form notifications don't count."]})}function bl(){let{api:e}=H(),{siteId:t,refreshKey:a}=nt();return Kt(async()=>Promise.all((await e.getForms()).map(s=>e.getForm(s.id))),`${t}|${a}`,t)}function hl(e){return{signups:e.filter(t=>t.purpose==="newsletter"),optIns:e.filter(t=>t.purpose==="opt_in"),others:e.filter(t=>t.purpose!=="newsletter"&&t.purpose!=="opt_in")}}function yl(e){let t=e.length===1;return`Add a "Send me news" opt-in checkbox to ${t?"the":"these"} ${e.map(a=>a.name).join(" and ")} form${t?"":"s"}`}function xv({onAskAssistant:e}){let t=bl();if(!t.data||t.data.length===0)return null;let{signups:a,optIns:s,others:n}=hl(t.data),r=[{id:"signup",label:"Signup forms",note:"Submitting one subscribes the visitor.",forms:a,icon:au},{id:"opt_in",label:'Forms with a "Send me news" checkbox',note:"Visitors who tick the box join your list.",forms:s,icon:au},{id:"other",label:"Other forms",note:"These don't add anyone to your list.",forms:n,icon:uv,action:a.length===0&&e?{label:"Add the checkbox",onClick:()=>e(yl(n))}:void 0}];return ue(wv,{children:r.filter(i=>i.forms.length>0).map(i=>ue("div",{"data-form-group":i.id,children:ue(Tn,{icon:i.icon,label:i.label,mono:!1,value:i.forms.map(l=>l.name).join(", "),hint:i.note,action:i.action})},i.id))})}function ao({label:e,children:t}){return ea("label",{className:"af-block af-space-y-1",children:[ue("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}import*as so from"react";import{jsx as la,jsxs as Is}from"react/jsx-runtime";function su({templateId:e,onOpenTemplate:t,onOpenDraft:a,onAskAssistant:s}){let{api:n}=H(),{siteId:r,canWrite:i,refreshKey:l}=nt(),[u,d]=so.useState(0),o=u+l,c=Kt(()=>n.getEmailTemplates(r),`${r}|${o}`,r),b=so.useCallback(()=>d(f=>f+1),[]),g=i?s:void 0;if(e){let f=e===zn?null:c.data?.find(v=>v.id===e);if(f!==void 0)return la(Wd,{template:f,onBack:()=>t(null),onOpenTemplate:t,onOpenDraft:a,onAskAssistant:g,reload:b,refreshKey:o},e);if(c.isLoading)return la(J,{className:"af-h-96 af-w-full"})}let m=c.data?.filter(f=>f.status!=="archived")??[],p=c.data?.filter(f=>f.status==="archived")??[];return Is("div",{children:[Is("div",{className:"af-mb-3 af-flex af-items-center af-justify-between af-gap-2",children:[la("h3",{className:"af-text-sm af-font-semibold",children:"Templates"}),g&&la(y,{type:"button",variant:"outline",size:"sm",onClick:()=>g(Zi.create),children:"\u2728 New template with the editor"})]}),Is(nu,{children:[la(Sl,{template:null,onOpen:()=>t(zn)}),m.map(f=>la(Sl,{template:f,onOpen:()=>t(f.id)},f.id))]}),c.error&&!c.data?la("div",{className:"af-mt-3",children:la(Nt,{message:"Couldn't load your templates.",onRetry:()=>void c.refetch()})}):!c.data&&la(J,{className:"af-mt-3 af-h-10 af-w-full"}),p.length>0&&Is("div",{"data-testid":"archived-templates",children:[la(an,{children:"Archived"}),la(nu,{children:p.map(f=>la(Sl,{template:f,onOpen:()=>t(f.id)},f.id))})]})]})}function nu({children:e}){return la("ul",{className:"af-grid af-gap-3 sm:af-grid-cols-2 lg:af-grid-cols-3",children:e})}function Sv(e){if(e.status==="draft")return null;let t=e.usage.drafts+e.usage.scheduled,a=[t>0&&`${t} email${t===1?"":"s"}`,e.usage.sent>0&&`${e.usage.sent} sent`].filter(Boolean);return a.length>0?a.join(" \xB7 "):"Not used yet"}function Sl({template:e,onOpen:t}){let a=e?.name??"Standard",s=e&&Sv(e);return Is("li",{"data-testid":"template-card",className:"af-relative af-overflow-hidden af-rounded-md af-border hover:af-border-primary",children:[la(Yi,{templateId:e?.id??zn,version:e?.updated_at??"builtin",className:"af-h-40 af-border-b",frame:{width:600,height:400,scale:.4}}),Is("div",{className:"af-space-y-1 af-p-2",children:[Is("div",{className:"af-flex af-items-center af-gap-2",children:[la("span",{"data-testid":"template-name",className:"af-grow af-truncate af-text-sm af-font-medium",children:a}),la(cl,{status:e?.status??"builtin"})]}),s&&la("p",{className:"af-text-xs af-text-muted-foreground",children:s})]}),la("button",{type:"button","aria-label":`Open ${a}`,onClick:t,className:"af-absolute af-inset-0 af-h-full af-w-full"})]})}import{Fragment as Ev,jsx as bt,jsxs as Fr}from"react/jsx-runtime";var Nv=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"templates",label:"Templates"},{id:"settings",label:"Settings"}];function ps(e,t={}){return{tab:e,draftId:null,templateId:null,...t}}var ru=e=>!!(e.tab||e.draftId||e.templateId);function iu(e){return e.draftId?ps("broadcasts"):e.templateId?ps("templates",{templateId:e.templateId}):ps(e.tab==="template"?"templates":e.tab==="automations"||!e.tab?"audience":e.tab)}var Rv={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function ou(e){return bt(_v,{...e},e.siteId)}function _v({siteId:e,isOwnerSide:t,needsPaidPlan:a,initialDraftId:s,initialTab:n,templateId:r,showViewNonce:i,onOrgAction:l,onRequestReview:u,onStartDomainSetup:d,onBackToWebsite:o,onUpgradePlan:c,onConnectDomain:b,onAskAssistant:g,onPickImage:m,onTurnOn:p,siteDomain:f,businessName:v,onOpenStoreSettings:x,refreshKey:R=0,className:P}){let{api:h}=H(),S=Kt(()=>h.getMarketingSettings(e),`${e}|${R}`,e),N={tab:n,draftId:s,templateId:r},[C,w]=ta.useState(()=>iu(N)),[k,T]=ta.useState(s??null),[_,z]=ta.useState(ru(N)),[Z,U]=ta.useState(null),[ae,le]=ta.useState(!1),fe=ta.useCallback(()=>z(!1),[]),M=ta.useCallback(oe=>{w(ps("settings")),U(oe??null)},[]),W=oe=>{w(ps(oe)),U(null)},A=ta.useCallback(oe=>w(ps("broadcasts",{draftId:oe})),[]),de=ta.useCallback(oe=>w(ps("templates",{templateId:oe})),[]),ce=!_&&S.data!==null&&Pv(S.data),Le=S.data&&!S.error?kv(S.data):null,ye=JSON.stringify([i??null,n??null,s??null,r??null]),Te=ta.useRef(ye);ta.useEffect(()=>{if(ye===Te.current||ae)return;Te.current=ye;let oe={tab:n,draftId:s,templateId:r};ru(oe)&&(w(iu(oe)),T(oe.draftId??null),U(null),z(!0))},[ye,ae,n,s,r]),ta.useEffect(()=>{if(!k||a)return;let oe=!0,st=E=>{oe&&(w(ps("broadcasts",{draftId:E})),T(null))};return h.getEmailDraft(e,k).then(E=>st(E.kind==="broadcast"?E.id:null),()=>st(null)),()=>{oe=!1}},[h,e,k,a]);let Oe=ta.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:l,settings:S.data,refetchSettings:S.refetch,refreshKey:R,openSetup:fe,openSettings:M,settingsSection:Z,onOpenStoreSettings:x,setInlineEditOpen:le}),[e,t,l,S.data,S.refetch,R,fe,M,Z,x]);return a?bt(Ft,{title:"Email Marketing",onBackToWebsite:o,className:P,children:bt(pl,{settings:S.data,site:{siteDomain:f,businessName:v},children:bt(tu,{onUpgradePlan:c})})}):bt(Ft,{title:"Email Marketing",onBackToWebsite:o,className:P,children:bt(el.Provider,{value:Oe,children:ce?bt(eu,{onStartDomainSetup:d,onConnectDomain:b,onAskAssistant:g,onTurnOn:p,siteDomain:f,businessName:v}):Fr(Ev,{children:[S.error&&!S.data&&bt(Nt,{message:"Couldn't load email settings.",onRetry:()=>void S.refetch()}),Le&&bt(Tv,{reason:Le,pauseReason:S.data?.paused.reason??null,onRequestReview:u}),!t&&bt(Ne,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),bt("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:Nv.map(oe=>Fr("button",{type:"button",role:"tab","aria-selected":C.tab===oe.id,onClick:()=>W(oe.id),className:G("af-border-b-2 af-px-3 af-py-2 af-text-sm",C.tab===oe.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:[oe.label,oe.id==="settings"&&Le&&bt("span",{"data-testid":"settings-dot",role:"img","aria-label":"Sending is on hold",className:"af-ml-1.5 af-inline-block af-h-1.5 af-w-1.5 af-rounded-full af-bg-amber-600 af-align-middle"})]},oe.id))}),bt("div",{role:"tabpanel",children:k?bt(J,{className:"af-h-24 af-w-full"}):C.tab==="audience"?bt(Fd,{}):C.tab==="broadcasts"?bt(Jd,{openDraftId:C.draftId,onOpenDraft:A,onAskAssistant:g,onPickImage:m}):C.tab==="templates"?bt(su,{templateId:C.templateId,onOpenTemplate:de,onOpenDraft:A,onAskAssistant:g}):bt(xl,{onStartDomainSetup:d,onAskAssistant:g})})]})})})}function Pv(e){return!e.paused.paused_at&&!e.readiness.can_send&&Er.has(e.readiness.reason??"")}function kv(e){if(e.paused.paused_at)return"paused";let t=e.readiness.reason;return!e.readiness.can_send&&t&&Er.has(t)?t:null}var Cv={domain_not_verified:"domain",dmarc_missing:"domain",postal_address_missing:"sender"};function Tv({reason:e,pauseReason:t,onRequestReview:a}){let{openSetup:s,openSettings:n}=nt(),[r,i]=ta.useState("idle");if(e==="paused")return bt("div",{"data-testid":"email-hold",className:"af-mb-3",children:Fr(Ne,{tone:"warning",children:[bt("div",{className:"af-font-medium",children:"Sending is paused."}),Fr("p",{children:[Rv[t??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),a&&(r==="sent"?bt("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):bt(y,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{i("sending");try{await a(),i("sent")}catch{i("failed")}},children:"Request review"})),r==="failed"&&bt("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]})});let l=Cv[e];return bt("div",{"data-testid":"email-hold",className:"af-mb-3",children:Fr(Ne,{tone:"warning",children:["Sending is on hold. ",sr(e)," ",l?bt(ks,{onClick:()=>n(l),children:"Fix in Settings"}):bt(ks,{onClick:s,children:"Finish setup"})]})})}import*as aa from"react";var Iv=2e3,ma=()=>({data:null,error:null,isLoading:!0});function ur(e,{refreshKey:t,breakdowns:a=[],filters:s=[]}={}){let{api:n}=H(),[r,i]=aa.useState(ma),[l,u]=aa.useState(ma),[d,o]=aa.useState(ma),[c,b]=aa.useState(ma),[g,m]=aa.useState(ma),p=M=>Object.fromEntries(M.map(W=>[W,ma()])),[f,v]=aa.useState(()=>p(a)),x=aa.useRef(0),R=aa.useRef(0),P=aa.useRef("idle"),h=a.join(","),S=ts()??"",N=JSON.stringify(s),C=`${e}:${h}:${N}:${S}`,[w,k]=aa.useState({api:n,fetchIdentity:C});(w.api!==n||w.fetchIdentity!==C)&&(k({api:n,fetchIdentity:C}),x.current+=1,i(ma),u(ma),o(ma),b(ma),v(p(h?h.split(","):[])));let T=`${e}:${String(t??"")}:${S}`,[_,z]=aa.useState({api:n,conversionsIdentity:T});(_.api!==n||_.conversionsIdentity!==T)&&(z({api:n,conversionsIdentity:T}),R.current+=1,P.current="idle",m(ma));let Z=aa.useCallback(async M=>{let W=++x.current,A=h?h.split(","):[];i(ma),u(ma),o(ma),b(ma),v(Object.fromEntries(A.map(E=>[E,ma()])));let de=P.current!=="pending"&&(M?.force===!0||P.current==="idle"),ce=(E,O)=>O.then(B=>{W===x.current&&E({data:B,error:null,isLoading:!1})},B=>{W===x.current&&E({data:null,error:B instanceof Error?B:new Error("Failed to fetch report"),isLoading:!1})}),Le=n.getAnalyticsStatus(),ye=ce(i,Le),Te=Symbol("status-timeout"),Oe,oe=await Promise.race([Le.then(E=>E,()=>null),new Promise(E=>{Oe=setTimeout(()=>E(Te),Iv)})]);if(clearTimeout(Oe),W!==x.current)return;if(oe===Te&&i({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),oe!==null&&oe!==Te&&(oe.collecting!==!0||oe.first_seen===null&&!oe.first_seen_unavailable||oe.first_seen!==null&&oe.first_seen_in_reports===!1)){let E={data:null,error:null,isLoading:!1};u(E),o(E),b(E),v(Object.fromEntries(A.map(O=>[O,{...E}]))),de&&(m(E),P.current="done"),await ye;return}await Promise.all([oe===Te?Promise.resolve():ye,ce(u,n.getAnalyticsSummary(e,s)),ce(o,n.getAnalyticsTimeseries(e,s)),ce(b,n.getAnalyticsChannels(e,s)),de?(()=>{P.current="pending";let E=++R.current;return m(ma),n.getAnalyticsConversions(e).then(O=>{E===R.current&&(m({data:O,error:null,isLoading:!1}),P.current="done")},O=>{E===R.current&&(m({data:null,error:O instanceof Error?O:new Error("Failed to fetch report"),isLoading:!1}),P.current="done")})})():Promise.resolve(),...A.map(E=>n.getAnalyticsBreakdown(E,e,s).then(O=>{W===x.current&&v(B=>({...B,[E]:{data:O,error:null,isLoading:!1}}))},O=>{W===x.current&&v(B=>({...B,[E]:{data:null,error:O instanceof Error?O:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,N,T,S]),U=aa.useCallback(async()=>{let M=x.current;try{let W=await n.getAnalyticsStatus();if(M!==x.current)return;i({data:W,error:null,isLoading:!1})}catch(W){if(M!==x.current)return;i(A=>({data:A.data,error:W instanceof Error?W:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),ae=aa.useCallback(()=>Z({force:!0}),[Z]);aa.useEffect(()=>{Z()},[Z,t]);let le=r.isLoading||l.isLoading||d.isLoading||c.isLoading||g.isLoading||Object.values(f).some(M=>M.isLoading),fe=[d,l,c,g,...Object.values(f)].map(M=>M.data?.status==="ok"?M.data.timezone:void 0).find(M=>M!==void 0);return{status:r,summary:l,timeseries:d,channels:c,conversions:g,breakdowns:f,reportedZone:fe,isLoading:le,refetch:ae,refetchStatus:U}}import*as na from"react";var Nl=3e4,Rl=3;function ro(e={}){let t="collecting"in e,{collecting:a,statusFailed:s=!1,identity:n}=e,{api:r}=H(),[i,l]=na.useState(null),[u,d]=na.useState(null),[o,c]=na.useState(!1),[b,g]=na.useState(null),[m,p]=na.useState(!1),[f,v]=na.useState(!0),[x,R]=na.useState(0),P=na.useRef(0),h=na.useRef(0),S=na.useRef(void 0);a!==void 0&&(S.current=a);let N=t?S.current===!0||S.current===void 0&&s:!0,[C,w]=na.useState({api:r,identity:n}),k=n!==void 0&&n!==C.identity;(C.api!==r||k)&&(S.current=void 0,w({api:r,identity:n}),h.current+=1,P.current=0,l(null),d(null),c(!1),g(null),p(!1),v(!0),R(0));let T=na.useRef(()=>{}),_=na.useRef(null),z=na.useCallback(async()=>{if(_.current!==null&&_.current===h.current)return;let Z=++h.current;_.current=Z;try{let U=await r.getAnalyticsRealtime();if(Z!==h.current)return;if(U.status==="unreachable"){p(!0),c(!0),v(!1),R(ae=>ae+1);return}P.current=0,p(!1),l(U.data.current_visitors),d(U.as_of),c(!1),g(null),v(!1),R(ae=>ae+1)}catch(U){if(Z!==h.current)return;P.current+=1,v(!1),R(ae=>ae+1),c(!0),P.current>=Rl&&g(U instanceof Error?U:new Error("Realtime unavailable"))}finally{_.current===Z&&(_.current=null)}},[r]);return T.current=()=>void z(),na.useEffect(()=>{let Z,U=()=>{Z===void 0&&(Z=setInterval(()=>T.current(),Nl))},ae=()=>{Z!==void 0&&(clearInterval(Z),Z=void 0)},le=()=>{typeof document<"u"&&document.hidden?ae():(T.current(),U())};return N?((typeof document>"u"||!document.hidden)&&(T.current(),U()),document?.addEventListener("visibilitychange",le),()=>{ae(),document?.removeEventListener("visibilitychange",le),h.current+=1}):()=>{document?.removeEventListener("visibilitychange",le)}},[C.api,C.identity,N]),{currentVisitors:i,asOf:u,isStale:o,error:b,isUnreachable:m,isInitialLoad:f,polls:x}}import*as Lt from"react";import*as cu from"react";import{jsx as _l,jsxs as lu}from"react/jsx-runtime";function Dv(){try{let e=Intl.supportedValuesOf?.("timeZone");if(e&&e.length>0)return e.includes("UTC")?e:["UTC",...e]}catch{}return["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Madrid","Africa/Johannesburg","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Tokyo","Australia/Sydney"]}function Pl({value:e,chosen:t,onChange:a}){let s=pr(),n=t===null&&s!==null&&e===s,r=cu.useMemo(()=>{let i=Dv();return i.includes(e)?i:[e,...i]},[e]);return lu("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[_l("span",{className:"af-sr-only",children:"Reporting timezone"}),lu("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:[_l("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(i=>_l("option",{value:i,children:i.replace(/_/g," ")},i))]})]})}var io=(e,{published:t}={})=>{let a=t===!1,s=e!=null&&(!e.collecting||a&&e.first_seen===null&&!e.first_seen_unavailable),n=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,i=n||r;return{notCollecting:s,awaitingFirstVisit:n,firstVisitTooRecent:r,holdingForFirstData:i,nothingToReport:s||i}};import*as Mr from"react";var Av=3e4;function oo({status:e,holdingForFirstData:t,refetchStatus:a,refetch:s}){Mr.useEffect(()=>{if(!t)return;let r,i=()=>{r===void 0&&(r=setInterval(()=>void a(),Av))},l=()=>{r!==void 0&&(clearInterval(r),r=void 0)},u=()=>{typeof document<"u"&&document.hidden?l():(a(),i())};return(typeof document>"u"||!document.hidden)&&i(),document?.addEventListener("visibilitychange",u),()=>{l(),document?.removeEventListener("visibilitychange",u)}},[t,a]);let n=Mr.useRef(void 0);Mr.useEffect(()=>{if(!e){n.current=void 0;return}let r=n.current;n.current=t,r===!0&&!t&&s()},[e,t,s])}import*as As from"react";var Lv=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ca(e){let t=Math.abs(e);if(t<1e3)return String(e);let a=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[s,n]of a)if(t>=s){let r=e/s,i=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(i)>=1e3&&s!==1e9?Ca(i*s):`${i}${n}`}return String(e)}function fr(e){return`${(e*100).toFixed(1)}%`}function Ur(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let a=Math.floor(t/60);return a<60?`${a}m ${t%60}s`:`${Math.floor(a/60)}h ${a%60}m`}function uu(e){let t=Math.max(0,Math.round(e));return t>=3600&&t%3600===0?`${t/3600}h`:t>=60&&t%60===0?`${t/60}m`:Ur(t)}function fu(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function mu(e,t){if(!(!Number.isFinite(e)||e<=0))for(let a of t){let s=Math.ceil(e/a);if(s<=5)return Array.from({length:s+1},(n,r)=>Number((r*a).toPrecision(12)))}}function $r(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function pu(e){let t=new Date(e);return Number.isNaN(t.getTime())?"as of an unknown time":`as of ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function kl(e){let t=Number(e.slice(5,7)),a=Number(e.slice(8,10));return`${Lv[t-1]} ${a}`}function du(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Ov(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function gu(e,t,a="UTC"){let s=new Map(t.map(i=>[i.date,i])),n=[],r=du(e.to,a);for(let i=du(e.from,a);i<r;i=Ov(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 vu(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=new Date(`${e}T00:00:00Z`);if(Number.isNaN(s.getTime()))return e;let n=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${n} ${a[s.getUTCMonth()]}`}import{Fragment as Fv,jsx as gs,jsxs as Bv}from"react/jsx-runtime";function bu({what:e="This report",onRetry:t,collecting:a}){return Bv("div",{role:"status",className:"af-flex af-flex-col af-items-center af-gap-1 af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-8 af-text-center",children:[gs("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),gs("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:a===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),t?gs("button",{type:"button",onClick:t,className:"af-mt-2 af-rounded-md af-border af-border-border af-px-3 af-py-1 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Try again"}):null]})}function lo({what:e="No data"}){return gs("div",{className:"af-flex af-items-center af-justify-center af-rounded-md af-px-4 af-py-8 af-text-center af-text-xs af-text-muted-foreground",children:e})}function es({sourced:e,error:t,isLoading:a,what:s,onRetry:n,collecting:r,children:i}){return a?gs("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?gs(bu,{what:s,onRetry:n,collecting:r}):!e||e.status==="unreachable"?gs(bu,{what:s,onRetry:n,collecting:r}):gs(Fv,{children:i(e.data)})}import{Fragment as Mv,jsx as za,jsxs as Ds}from"react/jsx-runtime";function Cl({rows:e,dimension:t,metric:a,metricLabel:s,secondary:n,emptyCopy:r="No data for this period",onFilter:i,canFilter:l,maxRows:u=9}){let[d,o]=As.useState(!1);if(e.length===0)return za(lo,{what:r});let c=e.reduce((m,p)=>Math.max(m,Number(p[a]??0)),0)||1,b=Math.max(0,e.length-u),g=d?e:e.slice(0,u);return Ds(Mv,{children:[Ds("table",{className:"af-w-full af-text-sm",children:[za("thead",{children:Ds("tr",{className:"af-text-xs af-text-muted-foreground",children:[za("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),za("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),za("tbody",{children:g.map((m,p)=>{let f=Number(m[a]??0),v=m[t]??null,x=$r(v),R=n?m[n]:null,P=v!==null&&(l?l(v,R):!0);return Ds("tr",{className:"af-border-t af-border-border",children:[Ds("td",{className:"af-relative af-py-1.5 af-pr-2",children:[za("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,f/c*100)}%`}}),v!==null&&i&&P?za("button",{type:"button",onClick:()=>i(v,R),title:`Filter by ${x}`,"aria-label":`Filter by ${x}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:x}):za("span",{className:"af-relative af-break-words af-text-foreground",children:x}),R?za("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:R}):null]}),za("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Ca(f)})]},`${x}-${R??""}-${p}`)})})]}),b>0?za("button",{type:"button",onClick:()=>o(m=>!m),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:d?"Show fewer":`Show all ${e.length}`}):null]})}function Vr({title:e,tabs:t,defaultTabId:a,headerRight:s}){let[n,r]=As.useState(a),i=t.find(g=>g.id===n)??t[0],l=As.useId(),u=g=>`${l}-tab-${g}`,d=g=>`${l}-panel-${g}`,o=As.useRef(null),c=(g,m)=>{g.preventDefault();let p=(m+t.length)%t.length;r(t[p].id),o.current?.querySelectorAll('[role="tab"]')?.[p]?.focus()};return Ds("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[Ds("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:[za("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=>za("button",{id:u(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?za("div",{id:d(i.id),role:"tabpanel","aria-labelledby":u(i.id),tabIndex:0,className:"af-px-3 af-py-2",children:i.render()},i.id):null]})}import*as qa from"react";import*as vs from"@radix-ui/react-popover";var Ls=3,Os=100;import{jsx as Ht,jsxs as qn}from"react/jsx-runtime";var Hr={channel:"Channel",source:"Source",campaign:"Campaign",utm_source:"UTM source",utm_medium:"UTM medium",utm_content:"UTM content",utm_term:"UTM term",page:"Page",entry_page:"Entry page",exit_page:"Exit page",country:"Country",region:"Region",city:"City",browser:"Browser",os:"Operating system",device:"Device"},Uv=Object.keys(Hr);function hu(e){let t=Hr[e.dimension],a=e.operator==="is_not"?"is not":"is",s=e.values.map(n=>$r(n)).join(" or ");return`${t} ${a} ${s}`}function Tl(e,t){let a=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));if(a>=0){let s=[...new Set([...e[a].values,...t.values])];return s.length>Os||s.length===e[a].values.length?e:e.map((n,r)=>r===a?{...n,values:s}:n)}return t.values.length>Os||e.length>=Ls?e:[...e,t]}function $v(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 yu(e,t){let a=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));return a>=0?e.map((s,n)=>n===a?t:s):t.values.length>Os||e.length>=Ls?e:[...e,t]}function Vv(e){return{dimension:e,operator:"is",search:"",picked:[]}}function xu(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=$v(e.byDimension,a);for(let[r,i]of Object.entries(s)){let l=e.foldsByLabel.get(r)??new Set;for(let u of i)l.add(u);e.foldsByLabel.set(r,l)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([r,i])=>[r,[...i]]))}}function wu(e){let{filters:t,onChange:a}=e,s=t.length>=Ls;return qa.useEffect(()=>{if(t.length===0)return;let n=r=>{let i=r.target;i&&(i.tagName==="INPUT"||i.closest('[role="dialog"]'))||r.key==="Escape"&&a([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[t.length,a]),qn("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,r)=>qn("span",{className:"af-inline-flex af-items-center af-gap-1 af-rounded-full af-border af-border-border af-bg-muted af-py-1 af-pl-3 af-pr-1 af-text-xs",children:[Ht("span",{className:"af-text-foreground",children:hu(n)}),Ht("button",{type:"button","aria-label":`Remove filter ${hu(n)}`,onClick:()=>a(t.filter((i,l)=>l!==r)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),Ht(Hv,{...e,disabled:s}),t.length>0?Ht("button",{type:"button",onClick:()=>a([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Hv({filters:e,onChange:t,suggestions:a,resetKey:s,disabled:n,expandValues:r}){let[i,l]=qa.useState(!1),u=qa.useRef(null),[d,o]=qa.useState(null);qa.useEffect(()=>{o(u.current?.closest(".aifeatures-admin")??null)},[]);let[c,b]=qa.useState(null),[g,m]=qa.useState("is"),[p,f]=qa.useState(""),[v,x]=qa.useState([]);qa.useEffect(()=>{i||(b(null),m("is"),f(""),x([]))},[i]);let R=qa.useRef(s);R.current!==s&&(R.current=s,i&&l(!1),c!==null&&b(null),v.length>0&&x([]),p!==""&&f(""),g!=="is"&&m("is"));let P=k=>{let T=Vv(k);b(T.dimension),x(T.picked),f(T.search),m(T.operator)},S=(c?a[c]??[]:[]).filter(k=>k.toLowerCase().includes(p.trim().toLowerCase())),N=c===null||v.length===0?null:Tl(e,{dimension:c,operator:g,values:r?r(c,v):v}),C=N!==null&&N!==e,w=()=>{let k=N;!k||k===e||(t(k),l(!1))};return qn(vs.Root,{open:i,onOpenChange:l,children:[Ht(vs.Trigger,{asChild:!0,children:Ht("button",{ref:u,type:"button",disabled:!1,title:n?`At most ${Ls} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),Ht(vs.Portal,{container:d,children:Ht(vs.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:c===null?qn("div",{children:[Ht("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),Ht("div",{className:"af-max-h-96 af-overflow-y-auto",children:Uv.filter(k=>a[k]!==void 0).map(k=>{let T=a[k]?.length??0,_=!e.some(z=>z.dimension===k)&&e.length>=Ls;return qn("button",{type:"button",onClick:()=>P(k),disabled:T===0||_,className:"af-flex af-w-full af-items-center af-justify-between af-rounded-md af-px-2 af-py-1.5 af-text-left af-text-xs af-text-foreground hover:af-bg-muted disabled:af-text-muted-foreground disabled:hover:af-bg-transparent",children:[Ht("span",{children:Hr[k]}),Ht("span",{className:"af-text-muted-foreground",children:T===0?"no data":_?"no room":T})]},k)})})]}):qn("div",{children:[qn("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Ht("button",{type:"button",onClick:()=>P(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),Ht("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Hr[c]}),qn("select",{"aria-label":"Operator",value:g,onChange:k=>m(k.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[Ht("option",{value:"is",children:"is"}),Ht("option",{value:"is_not",children:"is not"})]})]}),Ht("input",{type:"text",value:p,onChange:k=>f(k.target.value),placeholder:"Search\u2026","aria-label":`Search ${Hr[c]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),Ht("div",{className:"af-max-h-48 af-overflow-y-auto",children:S.length===0?qn("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",p,"\u201D."]}):S.map(k=>qn("label",{className:"af-flex af-cursor-pointer af-items-center af-gap-2 af-rounded-md af-px-2 af-py-1.5 af-text-xs af-text-foreground hover:af-bg-muted",children:[Ht("input",{type:"checkbox",checked:v.includes(k),disabled:!v.includes(k)&&v.length>=Os,onChange:T=>x(_=>T.target.checked?[..._,k]:_.filter(z=>z!==k))}),Ht("span",{className:"af-break-all",children:$r(k)})]},k))}),Ht("button",{type:"button",onClick:w,disabled:!C,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:v.length<=1?"Apply filter":v.length>=Os?`Apply filter (${v.length} values \u2014 the maximum)`:`Apply filter (${v.length} values)`})]})})})]})}import{Fragment as jv,jsx as Ta,jsxs as co}from"react/jsx-runtime";var zv=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Ca,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Ca,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Ca,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:fr,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Ur,chart:"visit_duration_seconds"}];function qv({current:e,previous:t,downIsGood:a}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let n=s>0,r=a?!n:n,i=`${n?"+":""}${(s*100).toFixed(1)}%`;return Ta("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:i})}function Su({summary:e,selected:t,onSelect:a}){return Ta("div",{className:"af-@container",children:Ta("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:zv.map(s=>{let n=s.chart===t,r=a!==void 0,i=co(jv,{children:[Ta("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),co("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Ta("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?Ta(qv,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?Ta("button",{type:"button","aria-pressed":n,onClick:()=>a(s.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:i},s.key):Ta("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:i},s.key)})})})}function El({currentVisitors:e,asOf:t,isStale:a,isUnreachable:s,isInitialLoad:n=!1,scopeIsSiteWide:r=!1}){if(n&&!s)return co("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1","aria-hidden":"true",children:[Ta("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Ta("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return Ta("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let i=t?pu(t):"freshness unknown",l=r?" across the whole site, not the current filter,":"",u=a?`${e} current visitors${l} ${i} (not updating)`:`${e} current visitors${l} ${i}`;return co("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:u,children:[Ta("span",{"aria-hidden":"true",className:a?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),Ta("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Ta("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),Ta("span",{className:"af-sr-only",children:u})]})}import*as Ru from"react";import{Star as Wv}from"lucide-react";import{Fragment as Nu,jsx as ca,jsxs as Bs}from"react/jsx-runtime";function uo(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function fo({rows:e,denominator:t,windowPrecedesCollection:a=!1,coverageUnknown:s=!1,emptyCopy:n="No conversions in this period",maxRows:r=9,primaryConversion:i}){let[l,u]=Ru.useState(!1),d=e.filter(f=>!f.implicit||f.visitors>0||f.events>0||uo(f,i)),o=a?ca("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This period starts before we began collecting for this site, so these counts cover less time than the dates suggest."}):s?ca("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null;if(d.length===0)return Bs(Nu,{children:[ca(lo,{what:n}),o]});let c=d.slice(0,r),b=i?d.find(f=>uo(f,i)):void 0,g=b&&!c.includes(b)?d.filter(f=>c.includes(f)||f===b).slice(0,Math.max(0,r-1)).concat(b):c,m=l?e:g,p=Math.max(0,e.length-g.length);return Bs(Nu,{children:[Bs("table",{className:"af-w-full af-text-sm",children:[ca("thead",{children:Bs("tr",{className:"af-text-xs af-text-muted-foreground",children:[ca("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),ca("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),ca("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),ca("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),ca("tbody",{children:m.map((f,v)=>Bs("tr",{className:"af-border-t af-border-border","aria-current":uo(f,i)?"true":void 0,children:[ca("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:uo(f,i)?Bs("span",{className:"af-flex af-items-center af-gap-1.5",children:[ca(Wv,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),ca("span",{className:"af-font-medium af-text-foreground",children:f.goal}),ca("span",{className:"af-sr-only",children:"(your main conversion)"})]}):f.goal}),ca("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ca(f.visitors)}),ca("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ca(f.events)}),ca("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:f.conversion_rate===null?ca("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):fr(f.conversion_rate)})]},`${f.goal}-${v}`))})]}),p>0?ca("button",{type:"button",onClick:()=>u(f=>!f),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length} goals`}):null,Bs("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Ca(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),o]})}import{Area as Gv,AreaChart as Kv,CartesianGrid as Zv,ResponsiveContainer as Yv,Tooltip as Jv,XAxis as Xv,YAxis as Qv}from"recharts";import{jsx as Ea,jsxs as zr}from"react/jsx-runtime";var mo={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Dl={visitors:Ca,visits:Ca,pageviews:Ca,views_per_visit:e=>e.toFixed(2),bounce_rate:fr,visit_duration_seconds:Ur},eb=31,tb=new Set(["visitors","visits","pageviews"]),ab={...Dl,bounce_rate:fu,visit_duration_seconds:uu},Il=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],nb=[5,10,15,30,60,120,300,600,900,1800,3600,7200],sb=[.01,.02,.05,.1,.2,.25,.5,1],rb=[.25,.5,1,2,5,10,25,50],ib={visitors:Il,visits:Il,pageviews:Il,views_per_visit:rb,bounce_rate:sb,visit_duration_seconds:nb};function ob({active:e,payload:t,label:a,metric:s}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return zr("div",{className:"af-rounded-lg af-border af-border-border af-bg-popover af-px-3 af-py-2 af-text-popover-foreground af-shadow-md",children:[Ea("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:mo[s]}),zr("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[Ea("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),Ea("span",{className:"af-text-muted-foreground",children:vu(String(a))}),Ea("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Dl[s](Number(n[s]??0))})]})]})}function po({rows:e,window:t,metric:a,timeZone:s="UTC",height:n=260}){let r=gu(t,e,s),i=Dl[a],l=ab[a],u=mu(r.reduce((o,c)=>Math.max(o,Number(c[a]??0)),0),ib[a]),d=`${mo[a]} by day: ${r.map(o=>`${kl(o.date)}: ${i(Number(o[a]??0))}`).join("; ")}.`;return zr("figure",{"aria-label":`${mo[a]} over time`,className:"af-m-0",children:[Ea(Yv,{width:"100%",height:n,children:zr(Kv,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[Ea("defs",{children:zr("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[Ea("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),Ea("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),Ea(Zv,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Ea(Xv,{dataKey:"date",tickFormatter:kl,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Ea(Qv,{allowDecimals:!tb.has(a),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...u?{ticks:u,domain:[0,u[u.length-1]]}:{},tickFormatter:o=>l(o),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Ea(Jv,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Ea(ob,{metric:a})}),Ea(Gv,{type:"linear",dataKey:a,name:mo[a],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=eb?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),Ea("figcaption",{className:"af-sr-only",children:d})]})}import{Fragment as Al,jsx as Ae,jsxs as Sa}from"react/jsx-runtime";var lb="2026-08-13",cb=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],db=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function ub({filters:e,onFiltersChange:t,refreshKey:a,onBackToWebsite:s,primaryConversion:n,className:r,published:i,lastPublishedAt:l}){let[u,d]=Lt.useState(30),[o,c]=Lt.useState(()=>yo()),b=e!==void 0&&t!==void 0,[g,m]=Lt.useState(e??[]),{api:p}=H(),[f,v]=Lt.useState(p);f!==p&&(v(p),!b&&g.length>0&&m([]));let x=b?e:g,R=Lt.useCallback(B=>{t&&t(B),b||m(B)},[t,b]),P=Lt.useCallback((B,we,X)=>{let ve=Array.isArray(we)?we:[we];if(ve.length===0)return null;let Me=Tl(x,{dimension:B,operator:"is",values:ve});if(X&&(!X.value||(Me=yu(Me,{dimension:X.dimension,operator:"is",values:[X.value]}),!Me.find(Ct=>Ct.dimension===X.dimension&&Ct.operator!=="is_not")?.values.includes(X.value))))return null;let ht=Me.find(Ke=>Ke.dimension===B&&Ke.operator!=="is_not");return ve.every(Ke=>ht?.values.includes(Ke))?JSON.stringify(Me)===JSON.stringify(x)?null:Me:null},[x]),h=Lt.useCallback((B,we,X)=>P(B,we,X)!==null,[P]),S=Lt.useCallback((B,we,X)=>{let ve=P(B,we,X);ve&&R(ve)},[P,R]),[N,C]=Lt.useState("visitors"),w=ur(u,{refreshKey:a,breakdowns:db,filters:x}),k=w.status.data,T=w.reportedZone??k?.timezone,_=T??o??pr()??"UTC",{notCollecting:z,awaitingFirstVisit:Z,firstVisitTooRecent:U,holdingForFirstData:ae}=io(k,{published:i}),le=i===!1,fe=ro({collecting:Z||z?!1:k?.collecting,statusFailed:w.status.error!=null,identity:k?.analytics_id}),M=Lt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),W=Lt.useMemo(()=>{let B=w.breakdowns.sources?.data,we={};if(!B||B.status!=="ok")return we;for(let X of B.data){let ve=X.source,Me=X.sources;typeof ve=="string"&&Array.isArray(Me)&&Me.length>0&&(we[ve]=Me)}return we},[w.breakdowns.sources?.data]),A=Lt.useMemo(()=>{let B=(ve,Me)=>{let ht=w.breakdowns[ve]?.data;return!ht||ht.status!=="ok"?[]:[...new Set(ht.data.map(Ke=>Ke[Me]).filter(Ke=>typeof Ke=="string"&&Ke!==""))]};return{channel:w.channels.data?.status==="ok"?[...new Set(w.channels.data.data.map(ve=>ve.channel))]:[],source:B("sources","source"),campaign:B("utm/campaign","campaign"),page:B("pages","pathname"),entry_page:B("entry-pages","pathname"),exit_page:B("exit-pages","pathname"),country:B("countries","country"),browser:B("browsers","browser"),os:B("operating-systems","os"),device:B("devices","device")}},[w.breakdowns,w.channels.data]),[de,ce]=Lt.useState({}),Le=JSON.stringify(A),[ye,Te]=Lt.useState(new Map),Oe=JSON.stringify(W);Lt.useEffect(()=>{let{suggestions:B,folds:we}=xu(M.current,{api:p,period:u},JSON.parse(Le),JSON.parse(Oe));ce(B),Te(we)},[Le,Oe,p,u]);let oe=Lt.useCallback((B,we)=>B!=="source"?we:[...new Set(we.flatMap(X=>{let ve=[...ye.get(X)??[],...W[X]??[]];return ve.length>0?ve:[X]}))],[ye,W]),st=Lt.useMemo(()=>{let B=w.conversions.error;return B instanceof Yt&&B.details?.code==="goals_exceed_report_budget"?B.message:null},[w.conversions.error]),E=Lt.useMemo(()=>{let B=[w.summary,w.timeseries,w.channels,...Object.values(w.breakdowns)];for(let we of B){let X=we?.error;if(X instanceof Yt&&X.details?.code==="filter_unsupported")return X.message}return null},[w.summary,w.timeseries,w.channels,w.breakdowns]),O=(B,we,X,ve,Me,ht,Ke,Ct,pe)=>()=>{let ke=w.breakdowns[B];return Ae(es,{sourced:ke?.data??null,error:ke?.error,isLoading:ke?.isLoading,what:we,collecting:k?.collecting,onRetry:w.refetch,children:rt=>{let Je=zt=>Ct?oe(Ct,[zt]):zt;return Ae(Cl,{rows:rt,dimension:X,metric:ve,metricLabel:Me,secondary:ht,emptyCopy:x.length>0?"No data for this filter":Ke,canFilter:Ct?(zt,Ot)=>h(Ct,Je(zt),pe?{dimension:pe,value:Ot}:void 0):()=>!1,onFilter:Ct?(zt,Ot)=>S(Ct,Je(zt),pe?{dimension:pe,value:Ot}:void 0):void 0})}})};if(oo({status:k,holdingForFirstData:ae,refetchStatus:w.refetchStatus,refetch:w.refetch}),z){let B=!!l&&String(l).slice(0,10)<lb;return Ae(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:Sa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),Ae("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:le?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":B?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return Z?Ae(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:Sa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),Ae("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:"Your site is set up and analytics is running. The first visit shows up here shortly after someone lands on a published page."})]})}):U?Sa(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:[Ae("div",{className:"af-mb-3 af-flex af-justify-end",children:Ae(Pl,{value:_,chosen:o,onChange:B=>{xo(B),c(B)}})}),Sa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),Sa("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",k?.timezone?` ${k.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),Ae("div",{className:"af-mt-4 af-flex af-justify-center",children:Ae(El,{currentVisitors:fe.currentVisitors,asOf:fe.asOf,isStale:fe.isStale,isUnreachable:fe.isUnreachable||fe.error!==null,isInitialLoad:fe.isInitialLoad})})]})]}):Ae(Ft,{title:"Analytics",onBackToWebsite:s,className:r,children:Sa("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Sa("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Ae("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:cb.map(B=>Ae("button",{type:"button","aria-pressed":B.value===u,onClick:()=>d(B.value),className:B.value===u?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:B.label},B.value))}),Ae(Pl,{value:_,chosen:o,onChange:B=>{xo(B),c(B)}}),Ae(El,{currentVisitors:fe.currentVisitors,asOf:fe.asOf,isStale:fe.isStale,isUnreachable:fe.isUnreachable||fe.error!==null,isInitialLoad:fe.isInitialLoad,scopeIsSiteWide:x.length>0})]}),Ae(wu,{filters:x,onChange:R,suggestions:de,expandValues:oe,resetKey:p}),E?Sa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),Ae("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:E}),Ae("button",{type:"button",onClick:()=>R([]),className:"af-mt-4 af-rounded-md af-border af-border-border af-px-3 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Clear filters"})]}):null,!E&&k?.timezone_defaulted?Ae("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,E?null:Sa(Al,{children:[Ae(es,{sourced:w.summary.data,error:w.summary.error,isLoading:w.summary.isLoading,what:"The traffic summary",collecting:k?.collecting,onRetry:w.refetch,children:B=>Sa(Al,{children:[Ae(Su,{summary:B,selected:N,onSelect:C}),B.previous_unavailable?Sa("p",{className:"af-text-xs af-text-muted-foreground",children:[B.previous_unavailable_reason==="filter"?"No comparison for this filter \u2014 the previous period has too many distinct traffic sources to resolve it. Try a shorter period, or filter by source instead.":"No comparison available right now \u2014 we couldn\u2019t check how far back this site\u2019s history goes. It should return on its own."," ","The numbers above are still for the period you selected."]}):null]})}),Ae("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:Ae(es,{sourced:w.timeseries.data,error:w.timeseries.error,isLoading:w.timeseries.isLoading,what:"The visitors chart",collecting:k?.collecting,onRetry:w.refetch,children:B=>{let we=w.timeseries.data?.status==="ok"?w.timeseries.data.window:{from:"",to:""};return Ae(po,{rows:B,window:we,metric:N,timeZone:T??"UTC"})}})}),Sa("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[Ae(Vr,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>Ae(es,{sourced:w.channels.data,error:w.channels.error,isLoading:w.channels.isLoading,what:"Channels",collecting:k?.collecting,onRetry:w.refetch,children:B=>Ae(Cl,{rows:B,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:we=>h("channel",we),onFilter:we=>S("channel",we)})})},{id:"sources",label:"Sources",render:O("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:O("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),Ae(Vr,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:O("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:O("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:O("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),Ae(Vr,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:O("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:O("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:O("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),Ae(Vr,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:O("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:O("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:O("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),Sa("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[Ae("header",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-border-b af-border-border af-px-3 af-py-2",children:Ae("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),Sa("div",{className:"af-px-3 af-py-2",children:[x.length>0?Sa("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",x.length===1?"filter":"filters"," above."]}):null,st!==null?Sa("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[Ae("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),Ae("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:st})]}):Ae(es,{sourced:w.conversions.data,error:w.conversions.error,isLoading:w.conversions.isLoading,what:"Conversions",collecting:k?.collecting,onRetry:w.refetch,children:B=>{let we=w.conversions.data?.status==="ok"?w.conversions.data:null;return Ae(Al,{children:Ae(fo,{rows:B,primaryConversion:n,denominator:we?.denominator??0,windowPrecedesCollection:we?.window_precedes_collection??!1,coverageUnknown:we?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import*as Au from"react";import{Phone as Eu,Mail as Ol,ShoppingBag as gb,ExternalLink as vb,MessageCircle as bb,Download as hb,Target as Lu}from"lucide-react";import*as bn from"react";import{Check as Ll,ChevronLeft as fb,Loader2 as _u}from"lucide-react";import{jsx as gt,jsxs as da}from"react/jsx-runtime";var Pu=90,ku=100;function mb(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Cu(e){return!!e.label&&e.label!==e.target}function pb(e,t,a){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:s,with_a_value:n}=t;return s===0?e===0?"Nothing specific has converted here yet.":null:n===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":n<s?a?`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${n.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function qr(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Tu({current:e,onChange:t,onClose:a}){let{api:s}=H(),[n,r]=bn.useState(null),[i,l]=bn.useState(!1),[u,d]=bn.useState({at:"goals"}),[o,c]=bn.useState(null),[b,g]=bn.useState(null),[m,p]=bn.useState(!1),[f,v]=bn.useState(null),x=bn.useRef(0);bn.useEffect(()=>{let S=!0;return r(null),l(!1),d({at:"goals"}),c(null),g(null),p(!1),v(null),x.current+=1,s.getAnalyticsConversions(Pu).then(N=>{if(S){if(N.status!=="ok"){l(!0);return}r(N.data)}}).catch(()=>{S&&l(!0)}),()=>{S=!1}},[s]);let R=S=>{d({at:"targets",row:S}),c(null),g(null),p(!1),v(null);let N=++x.current;s.getAnalyticsGoalTargets(S.goal,Pu,ku).then(C=>{if(N===x.current){if(C.status!=="ok"){g("failed");return}c(C.data),p(C.truncated===!0),v(C.coverage??null)}}).catch(C=>{if(N!==x.current)return;let w=C instanceof Yt?C.details?.code:void 0;g(w==="goal_has_no_targets"?"no-values":"failed")})},P=S=>{t(S),a()};if(i)return gt("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return da("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[gt(_u,{className:"af-h-4 af-w-4 af-animate-spin"}),gt("span",{children:"Loading your conversions\u2026"})]});if(u.at==="targets"){let S=u.row,N=new Map;for(let C of o??[])N.set(C.label,(N.get(C.label)??0)+1);return da("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[gt("header",{className:"af-flex af-items-center af-gap-1",children:da(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>d({at:"goals"}),children:[gt(fb,{className:"af-h-4 af-w-4"}),gt("span",{children:"All conversions"})]})}),da("button",{type:"button","aria-current":e&&qr(S,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>P({goal:S.goal,implicit:S.implicit}),children:[e&&qr(S,e)&&!e.target&&gt(Ll,{className:"af-h-4 af-w-4 af-shrink-0"}),da("span",{children:["Any ",S.goal.toLowerCase()]})]}),b==="no-values"&&gt("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),b==="failed"&&da("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[gt("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),gt(y,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(S),children:"Try again"})]}),!o&&b===null&&da("div",{className:"af-flex af-items-center af-gap-2 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[gt(_u,{className:"af-h-4 af-w-4 af-animate-spin"}),gt("span",{children:"Loading\u2026"})]}),o&&gt("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:pb(o.length,f,m)}),m&&da("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",ku,". If what you want isn\u2019t here, pick the conversion itself instead."]}),o?.some(Cu)&&gt("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),o?.map(C=>{let w=!!(e&&qr(S,e)&&e.target===C.target),k=N.get(C.label)>1;return Cu(C)?da("div",{className:"af-flex af-items-center af-justify-between af-gap-3 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[da("span",{className:"af-min-w-0",children:[gt("span",{className:"af-block af-truncate",children:C.label}),k&&gt("span",{className:"af-block af-truncate af-text-xs",children:C.target})]}),gt("span",{className:"af-shrink-0 af-text-xs",children:C.visitors.toLocaleString()})]},C.target):da("button",{type:"button","aria-current":w?"true":void 0,className:"af-flex af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>P({goal:S.goal,implicit:S.implicit,target:C.target,...C.label&&C.label!==C.target?{label:C.label}:{}}),children:[da("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[w&&gt(Ll,{className:"af-h-4 af-w-4 af-shrink-0"}),da("span",{className:"af-min-w-0",children:[gt("span",{className:"af-block af-truncate",children:C.label}),k&&gt("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:C.target})]})]}),gt("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:C.visitors.toLocaleString()})]},C.target)})]})}let h=e?.goal&&!n.some(S=>qr(S,e));return da("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[h&&da("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&gt("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(S=>{let N=e?qr(S,e):!1;return da("div",{className:"af-flex af-items-center af-gap-1",children:[da("button",{type:"button","aria-current":N?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>P({goal:S.goal,implicit:S.implicit}),children:[da("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[N&&gt(Ll,{className:"af-h-4 af-w-4 af-shrink-0"}),gt("span",{className:"af-truncate",children:S.goal})]}),gt("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:S.visitors.toLocaleString()})]}),mb(S)&&gt(y,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${S.goal}`,onClick:()=>R(S),children:"Narrow"})]},S.goal)}),e?.goal&&gt("button",{type:"button",className:"af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm af-text-muted-foreground hover:af-bg-accent",onClick:()=>P(null),children:"No main conversion"})]})}import{Fragment as Sb,jsx as Fs,jsxs as Du}from"react/jsx-runtime";function yb(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 xb(e){if(Bl(e,"whatsapp"))return!0;let t=yb(e);return t===null?!1:["wa.me","whatsapp.com"].some(a=>t===a||t.endsWith(`.${a}`))}function Bl(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var Iu=[{goal:"Contact",target:e=>Bl(e,"tel"),icon:Eu,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Bl(e,"mailto"),icon:Ol,line:"This site is set up to get you emails."},{goal:"Contact",icon:Eu,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>xb(e),icon:bb,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:vb,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Ol,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Ol,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:gb,line:"This site is set up to sell."},{goal:"File Download",icon:hb,line:"This site is set up to get your file downloaded."}];function Ou(e){let{goal:t,target:a}=e;return e.implicit!==!0?null:(a?Iu.find(n=>n.goal===t&&n.target?.(a)):void 0)??Iu.find(n=>n.goal===t&&!n.target)??null}function wb(e){return Ou(e)?.icon??Lu}function Bu({primaryConversion:e,onChange:t}){let[a,s]=Au.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?Ou(e):null,i=e?.label?.trim(),l=e?wb(e):Lu,u=e?.goal?i?`Your main conversion is ${i}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",d=Du(Sb,{children:[Fs(l,{className:"af-h-4 af-w-4 af-shrink-0"}),Fs("span",{children:u})]});return t?Du(vi,{open:a,onOpenChange:s,children:[Fs(bi,{asChild:!0,children:Fs("button",{type:"button",className:"af-flex af-items-center af-gap-2 af-rounded af-text-left af-text-sm af-text-muted-foreground hover:af-text-foreground focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:d})}),Fs(Nr,{align:"start",className:"af-w-80 af-p-1",children:a&&Fs(Tu,{current:e,onChange:t,onClose:()=>s(!1)})})]}):Fs("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:d})}import{Fragment as Nb,jsx as bs,jsxs as go}from"react/jsx-runtime";function Fu({refreshKey:e,onViewAll:t,primaryConversion:a}){let s=ur(7,{refreshKey:e,breakdowns:[]}),n=s.status.data??void 0,{nothingToReport:r,notCollecting:i,holdingForFirstData:l}=io(n);return oo({status:n,holdingForFirstData:l,refetchStatus:s.refetchStatus,refetch:s.refetch}),go("section",{className:"af-rounded-md af-border af-p-3",children:[go("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[bs("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&bs(y,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?bs("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:i?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):go(Nb,{children:[bs(es,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let d=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return bs(po,{rows:u,window:d?.window??{from:"",to:""},metric:"visitors",timeZone:d?.timezone,height:140})}}),go("div",{className:"af-mt-3",children:[bs("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),bs(es,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:s.refetch,children:u=>{let d=s.conversions.data?.status==="ok"?s.conversions.data:null;return bs(fo,{rows:u,primaryConversion:a,denominator:d?.denominator??0,windowPrecedesCollection:d?.window_precedes_collection??!1,coverageUnknown:d?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as En,jsxs as jr}from"react/jsx-runtime";var Fl=5;function Ml({title:e,viewAllLabel:t,onViewAll:a}){return jr("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[En("h3",{className:"af-text-sm af-font-medium",children:e}),a&&En(y,{type:"button",variant:"ghost",size:"sm",onClick:a,children:t})]})}function Rb({refreshKey:e,onBackToWebsite:t,primaryConversion:a,onChangePrimaryConversion:s,onOpenSurface:n,needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l}){let u=Xs({refreshKey:e}),d=(u.summary?.products.count??0)>0||(u.summary?.commerce?.storefront_orders??!1),o=d||(u.summary?.commerce?.invoicing??!1);return En(Ft,{title:"Dashboard",onBackToWebsite:t,children:jr("div",{className:"af-flex af-flex-col af-gap-4",children:[En(Bu,{primaryConversion:a,onChange:s}),En(Fu,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:a}),jr("section",{className:"af-rounded-md af-border af-p-3",children:[En(Ml,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),En(Mi,{refreshKey:e,maxRows:Fl,onViewAll:n&&(()=>n("leads"))})]}),d&&jr("section",{className:"af-rounded-md af-border af-p-3",children:[En(Ml,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),En(os,{refreshKey:e,maxRows:Fl,onViewAll:n&&(()=>n("orders"))})]}),o&&jr("section",{className:"af-rounded-md af-border af-p-3",children:[En(Ml,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),En(cs,{refreshKey:e,maxRows:Fl,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:r,onUpgradePlan:i,onConnectStripe:l})]})]})})}export{rr as AUDIENCE_PAGE_SIZE,Yt as AifeaturesApiError,$u as AifeaturesProvider,ub as AnalyticsView,Ki as ContactImport,_i as CustomerDetail,Pi as CustomersList,to as DOUBLE_OPT_IN_HELP,Rb as DashboardView,Qo as EMAIL_ORG_ACTIONS,Ld as EMAIL_READINESS_TEXT,ou as EmailView,ga as ExportCsvButton,ci as FormSettings,ri as FormSubmissions,lc as FormsDashboard,Yr as FormsList,al as IMPORT_ATTESTATION,Uo as InvoiceDetail,Rr as InvoiceLabelBadge,qi as InvoiceSettingsPanel,cs as InvoicesList,Ad as InvoicesView,Mi as LeadsView,Ls as MAX_ANALYTICS_FILTERS,Os as MAX_ANALYTICS_FILTER_VALUES,Id as NotificationRecipientsSettings,wi as OrderDetail,Ss as OrderStatusBadge,os as OrdersList,Hc as OrdersView,Uc as PaymentsDashboard,Ks as PaymentsSetup,pi as ProductSettings,fi as ProductsList,Yc as ProductsView,Vs as PromosPanel,Rl as REALTIME_FAILURES_BEFORE_ERROR,Nl as REALTIME_POLL_MS,$o as RetainerStatusBadge,Gs as RetainersPanel,Cd as StoreSettings,ti as SubmissionDetail,dd as SubscriptionsView,mi as VariantsEditor,Ft as ViewShell,oi as WebhookDeliveries,li as WebhookSettings,kg as buildEmailOrgRequest,Jn as chargedTotal,wo as createApiClient,sr as emailReadinessText,Y as formatPrice,Pg as isEmailOrgAction,dn as isZeroDecimalCurrency,Et as toMajorUnits,ua as toMinorUnits,H as useAifeatures,H as useAifeaturesContext,ur as useAnalytics,ji as useAudience,cr as useBroadcasts,Xs as useBusinessSummary,si as useCsvExport,Ri as useCustomers,dr as useEmailDrafts,ii as useEventDestinations,Us as useForms,js as useInvoices,gi as useOrders,rs as usePaymentsStatus,Bi as usePeople,Fi as usePerson,Zs as useProducts,ro as useRealtimeVisitors,Ys as useRetainers,fs as useSiteSettings,Qr as useSubmissions,Ui as useSubscriptions};