@aifeatures/admin-react 0.21.0 → 0.23.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,5 @@
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 Ws from"react";var Wi="aifeatures:analytics:timezone",ji;function Jn(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function sl(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function qs(){return Gi()??Jn()}function Gi(){if(ji!==void 0)return ji;try{let e=window.localStorage.getItem(Wi);return sl(e)?e:null}catch{return null}}function Ki(e){if(!(e!==null&&!sl(e))){ji=e;try{e===null?window.localStorage.removeItem(Wi):window.localStorage.setItem(Wi,e)}catch{}}}function Rr(e,t){let s=new URLSearchParams({period:String(e)}),n=qs();return n&&s.set("timezone",n),t&&t.length>0&&s.set("filters",JSON.stringify(t)),s.toString()}var Ft=class extends Error{constructor(s,n,a){super(s);this.status=n;this.details=a;this.name="AifeaturesApiError"}};function _r(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 Xn(e,t){let s=t.toString();return s?`${e}?${s}`:e}function nl(e){let t=new URLSearchParams;return e.status&&t.set("status",e.status),e.source&&t.set("source",e.source),e.excludeStatus?.length&&t.set("exclude_status",e.excludeStatus.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),e.from&&t.set("from",e.from),e.to&&t.set("to",e.to),e.unfulfilledOnly&&t.set("unfulfilled_only","true"),t}function rl(e){let t=new URLSearchParams;return e.statuses?.length&&t.set("status",e.statuses.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),t}function Zi(e,t="https://aifeatures.dev"){async function s(a,r={}){let o=`${t}${a}`,c=await fetch(o,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!c.ok){let d;try{d=await c.json()}catch{}throw new Ft(_r(d?.error,c.status),c.status,d)}if(c.status!==204)return c.json()}async function n(a){let r=await fetch(`${t}${a}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let o;try{o=await r.json()}catch{}throw new Ft(_r(o?.error,r.status),r.status,o)}return r.blob()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(a){return s(`/api/v1/forms/${a}`)},async createForm(a){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,r){return s(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(a){await s(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,r={}){let o=new URLSearchParams;r.limit!==void 0&&o.set("limit",String(r.limit)),r.offset!==void 0&&o.set("offset",String(r.offset));let c=o.toString(),d=`/api/v1/forms/${a}/submissions${c?`?${c}`:""}`;return s(d)},async getSubmission(a){return s(`/api/v1/submissions/${a}`)},async exportSubmissionsCsv(a,r={}){let o=new URLSearchParams;return r.includeSpam&&o.set("include_spam","true"),n(Xn(`/api/v1/forms/${encodeURIComponent(a)}/submissions/export`,o))},async deleteSubmission(a){await s(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,r){let o=typeof r=="string"?{name:r}:r,c=o.name,d=o.id??o.name,l=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(d)}`,i=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){let u;try{u=await i.json()}catch{}throw new Ft(_r(u?.error,i.status),i.status,u)}let m=await i.blob(),v=URL.createObjectURL(m),g=document.createElement("a");g.href=v,g.download=c,document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(v)},async getSite(a){return s(`/api/v1/sites/${encodeURIComponent(a)}`)},async updateSite(a,r){return s(`/api/v1/sites/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return s("/api/v1/payments/status")},getPromos(a){let r=new URLSearchParams({limit:"10"});return a&&r.set("cursor",a),s(`/api/v1/promos?${r}`)},getPromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return s("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,r){return s(`/api/v1/promos/${encodeURIComponent(a)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(a={}){let r=new URLSearchParams;a.include&&r.set("include",a.include);let o=r.toString();return(await s(`/api/v1/products${o?`?${o}`:""}`)).products},async getProduct(a){return s(`/api/v1/products/${a}`)},async createProduct(a){return s("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,r){return s(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(a){await s(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,r){let o=new FormData;o.append("file",r);let c=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:o});if(!c.ok){let d;try{d=await c.json()}catch{}throw new Ft(_r(d?.error,c.status),c.status,d)}return c.json()},async attachProductFileFromUrl(a,r){return s(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(a,r){return s(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(a,r){return s(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(a){await s(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,r){return s(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(a,r){return s(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(a){await s(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,r){return s(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(a,r){return s(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(a={}){let r=new URLSearchParams;a.email?r.set("email",a.email):a.q&&r.set("q",a.q),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/customers${o?`?${o}`:""}`)},async getCustomer(a){return s(`/api/v1/customers/${a}`)},async exportProductsCsv(){return n("/api/v1/products/export")},async exportCustomersCsv(){return n("/api/v1/customers/export")},async getOrders(a={}){let r=nl(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/orders${o?`?${o}`:""}`)},async exportOrdersCsv(a={}){return n(Xn("/api/v1/orders/export",nl(a)))},async getOrder(a){return s(`/api/v1/orders/${a}`)},async getInvoices(a={}){let r=new URLSearchParams;a.labels?.length&&r.set("label",a.labels.join(",")),a.customerEmail&&r.set("customer_email",a.customerEmail),a.customerId&&r.set("customer_id",a.customerId),a.q&&r.set("q",a.q),a.from&&r.set("from",a.from),a.to&&r.set("to",a.to),a.includeAggregates&&r.set("include","aggregates"),a.retainerId&&r.set("retainer_id",a.retainerId),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/invoices${o?`?${o}`:""}`)},async getInvoice(a){return s(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return s(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(a={}){let r=rl(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/retainers${o?`?${o}`:""}`)},async exportRetainersCsv(a={}){return n(Xn("/api/v1/retainers/export",rl(a)))},async getRetainer(a){return s(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await s(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return s(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,r){return s(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(a={}){let r=new URLSearchParams;a.status&&r.set("status",a.status),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/subscriptions${o?`?${o}`:""}`)},async exportSubscriptionsCsv(a={}){let r=new URLSearchParams;return a.status&&r.set("status",a.status),n(Xn("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let a=new URLSearchParams,r=qs();r&&a.set("timezone",r);let o=a.toString();return s(`/api/v1/analytics/status${o?`?${o}`:""}`)},async getAnalyticsSummary(a,r){return s(`/api/v1/analytics/summary?${Rr(a,r)}`)},async getAnalyticsTimeseries(a,r){return s(`/api/v1/analytics/timeseries?${Rr(a,r)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,r){return s(`/api/v1/analytics/channels?${Rr(a,r)}`)},async getAnalyticsConversions(a){return s((()=>{let r=new URLSearchParams({period:String(a)}),o=qs();return o&&r.set("timezone",o),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(a,r,o){let c=new URLSearchParams({goal:a,period:String(r)}),d=qs();return d&&c.set("timezone",d),o!==void 0&&c.set("limit",String(o)),s(`/api/v1/analytics/conversions/targets?${c.toString()}`)},async getAnalyticsBreakdown(a,r,o){let c=a.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${c}?${Rr(r,o)}`)},async getBusinessSummary(a){let r=new URLSearchParams;r.set("tz_offset_minutes",String(a.tzOffsetMinutes));let o=qs();return o&&r.set("timezone",o),s(`/api/v1/summary?${r.toString()}`)},async getPeople(a={}){let r=new URLSearchParams;a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return s(`/api/v1/people${o?`?${o}`:""}`)},async exportPeopleCsv(a={}){let r=new URLSearchParams;return a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),n(Xn("/api/v1/people/export",r))},async getPerson(a){return s(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(a){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,r){return s(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(a){await s(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return s(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await s(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,r){let o=r===void 0?"":`?limit=${r}`;return(await s(`/api/v1/event-destinations/${a}/deliveries${o}`)).deliveries},async retryEventDelivery(a,r){return s(`/api/v1/event-destinations/${a}/deliveries/${r}/retry`,{method:"POST"})},async getMarketingSettings(a){return s(`${ls(a)}/marketing`)},async getMarketingContacts(a,r={}){let o=new URLSearchParams;r.q&&o.set("q",r.q),r.limit&&o.set("limit",String(r.limit)),r.offset&&o.set("offset",String(r.offset));let c=o.toString();return s(`${ls(a)}/contacts${c?`?${c}`:""}`)},async getMarketingContactStats(a){return s(`${ls(a)}/contacts/stats`)},async getMarketingTags(a){return(await s(`${ls(a)}/contact-tags`)).tags},async getEmailDrafts(a,r){let o=r?`?kind=${r}`:"";return(await s(`${ls(a)}/marketing/drafts${o}`)).drafts},async getEmailDraft(a,r){return s(`${ls(a)}/marketing/drafts/${encodeURIComponent(r)}`)},async previewEmailDraft(a,r){return s(`${ls(a)}/marketing/drafts/${encodeURIComponent(r)}/preview`)},async getBroadcasts(a){return(await s(`${ls(a)}/marketing/broadcasts`)).broadcasts},async estimateBroadcast(a,r){return s(`${ls(a)}/marketing/broadcasts/estimate`,{method:"POST",body:JSON.stringify(r)})},async getWelcomeSequence(a){return s(`${ls(a)}/marketing/welcome`)},async getRecoveryFlow(a){return s(`${ls(a)}/marketing/recovery`)}}}function ls(e){return`/api/v1/sites/${encodeURIComponent(e)}`}import{jsx as Qn,jsxs as $u}from"react/jsx-runtime";var il=Ws.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 Mu({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:s=!1,className:n,children:a}){let r=Ws.useMemo(()=>Uu(e),[e]),o=Ws.useMemo(()=>Zi(e,t),[e,t]),c=Ws.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return r?Qn("div",{className:`aifeatures-admin ${s?"dark":""} ${n||""}`,children:$u("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[Qn("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),Qn("p",{className:"af-text-sm af-text-destructive",children:r})]})}):Qn(il.Provider,{value:c,children:Qn("div",{className:`aifeatures-admin ${s?"dark":""} ${n||""}`,children:a})})}function q(){let e=Ws.useContext(il);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as Fs from"react";import{ArrowLeft as Gd,Settings as Kd,Inbox as Zd}from"lucide-react";import*as Pr from"react";import*as cs from"@radix-ui/react-tabs";import{clsx as Vu}from"clsx";import{extendTailwindMerge as Hu}from"tailwind-merge";var zu=Hu({prefix:"af-"});function G(...e){return zu(Vu(e))}import{jsx as Yi}from"react/jsx-runtime";var Cr=cs.Root,er=Pr.forwardRef(({className:e,...t},s)=>Yi(cs.List,{ref:s,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}));er.displayName=cs.List.displayName;var us=Pr.forwardRef(({className:e,...t},s)=>Yi(cs.Trigger,{ref:s,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}));us.displayName=cs.Trigger.displayName;var ds=Pr.forwardRef(({className:e,...t},s)=>Yi(cs.Content,{ref:s,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}));ds.displayName=cs.Content.displayName;import*as ol from"react";import{Slot as qu}from"@radix-ui/react-slot";import{cva as Wu}from"class-variance-authority";import{jsx as Gu}from"react/jsx-runtime";var ju=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"}}),h=ol.forwardRef(({className:e,variant:t,size:s,asChild:n=!1,...a},r)=>Gu(n?qu:"button",{className:G(ju({variant:t,size:s,className:e})),ref:r,...a}));h.displayName="Button";import{Inbox as ll,Settings as Yu}from"lucide-react";import*as As from"react";import{jsx as Ds}from"react/jsx-runtime";var Ze=As.forwardRef(({className:e,...t},s)=>Ds("div",{className:"af-relative af-w-full af-overflow-auto",children:Ds("table",{ref:s,className:G("af-w-full af-caption-bottom af-text-sm",e),...t})}));Ze.displayName="Table";var Ye=As.forwardRef(({className:e,...t},s)=>Ds("thead",{ref:s,className:G("[&_tr]:af-border-b",e),...t}));Ye.displayName="TableHeader";var Je=As.forwardRef(({className:e,...t},s)=>Ds("tbody",{ref:s,className:G("[&_tr:last-child]:af-border-0",e),...t}));Je.displayName="TableBody";var Ku=As.forwardRef(({className:e,...t},s)=>Ds("tfoot",{ref:s,className:G("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Ku.displayName="TableFooter";var Se=As.forwardRef(({className:e,...t},s)=>Ds("tr",{ref:s,className:G("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Se.displayName="TableRow";var V=As.forwardRef(({className:e,...t},s)=>Ds("th",{ref:s,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}));V.displayName="TableHead";var H=As.forwardRef(({className:e,...t},s)=>Ds("td",{ref:s,className:G("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));H.displayName="TableCell";var Zu=As.forwardRef(({className:e,...t},s)=>Ds("caption",{ref:s,className:G("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Zu.displayName="TableCaption";import*as fs from"react";function Rn(){let{api:e}=q(),[t,s]=fs.useState([]),[n,a]=fs.useState(!0),[r,o]=fs.useState(null),c=fs.useCallback(async()=>{try{a(!0),o(null);let m=await e.getForms();s(m)}catch(m){o(m instanceof Error?m:new Error("Failed to fetch forms"))}finally{a(!1)}},[e]);fs.useEffect(()=>{c()},[c]);let d=fs.useCallback(async m=>{let v=await e.createForm(m);return s(g=>[...g,v]),v},[e]),l=fs.useCallback(async(m,v)=>{let g=await e.updateForm(m,v);return s(u=>u.map(f=>f.id===m?g:f)),g},[e]),i=fs.useCallback(async m=>{await e.deleteForm(m),s(v=>v.filter(g=>g.id!==m))},[e]);return{forms:t,isLoading:n,error:r,refetch:c,createForm:d,updateForm:l,deleteForm:i}}import{jsx as ha,jsxs as Ls}from"react/jsx-runtime";function kr({onSelectForm:e,className:t}){let{forms:s,isLoading:n,error:a}=Rn();return n?ha("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:ha("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):a?ha("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ls("div",{className:"af-text-destructive",children:["Error: ",a.message]})}):s.length===0?Ls("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[ha(ll,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ls("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",ha("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):ha("div",{className:t,children:Ls(Ze,{children:[ha(Ye,{children:Ls(Se,{children:[ha(V,{children:"Name"}),ha(V,{className:"af-text-right",children:"Actions"})]})}),ha(Je,{children:s.map(r=>Ls(Se,{children:[ha(H,{className:"af-font-medium",children:r.name}),ha(H,{className:"af-text-right",children:Ls("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Ls(h,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[ha(ll,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Ls(h,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[ha(Yu,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}import{AlertTriangle as ed}from"lucide-react";import{cva as Ju}from"class-variance-authority";import{jsx as Qu}from"react/jsx-runtime";var Xu=Ju("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,...s}){return Qu("div",{className:G(Xu({variant:t}),e),...s})}import{jsx as cn,jsxs as Tr}from"react/jsx-runtime";var td={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 Er(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 Ji(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function ad(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 tr({deliveries:e,label:t="Email needs attention"}){return Ji(e)?Tr("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:[cn(ed,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function hs({deliveries:e,problemsOnly:t=!1,className:s=""}){let n=(e??[]).filter(a=>!t||Ji([a]));return n.length?cn("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:n.map(a=>{let r=Er(a),o=ad(a);return Tr("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[Tr("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[cn("span",{className:"af-font-medium",children:td[a.kind]??"Email notification"}),cn(te,{variant:r.variant,children:r.label})]}),Tr("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",a.recipients.join(", ")]}),a.recipients.length>1&&Ji([a])&&cn("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&&cn("p",{className:"af-mt-1",children:r.detail}),o&&cn("p",{className:"af-mt-1",children:o})]},a.id)})}):null}import*as Gs from"react";import{ArrowLeft as wd,ChevronLeft as Nd,ChevronRight as Rd,Eye as _d,Inbox as Pd,Paperclip as Cd}from"lucide-react";import*as js from"react";import*as Le from"@radix-ui/react-select";import{Check as sd,ChevronDown as cl,ChevronUp as nd}from"lucide-react";import{jsx as ea,jsxs as Xi}from"react/jsx-runtime";var Ga=Le.Root;var Ka=Le.Value,Oa=js.forwardRef(({className:e,children:t,...s},n)=>Xi(Le.Trigger,{ref:n,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),...s,children:[t,ea(Le.Icon,{asChild:!0,children:ea(cl,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Oa.displayName=Le.Trigger.displayName;var ul=js.forwardRef(({className:e,...t},s)=>ea(Le.ScrollUpButton,{ref:s,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:ea(nd,{className:"af-h-4 af-w-4"})}));ul.displayName=Le.ScrollUpButton.displayName;var dl=js.forwardRef(({className:e,...t},s)=>ea(Le.ScrollDownButton,{ref:s,className:G("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:ea(cl,{className:"af-h-4 af-w-4"})}));dl.displayName=Le.ScrollDownButton.displayName;var Ba=js.forwardRef(({className:e,children:t,position:s="popper",...n},a)=>ea(Le.Portal,{children:Xi(Le.Content,{ref:a,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",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...n,children:[ea(ul,{}),ea(Le.Viewport,{className:G("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),ea(dl,{})]})}));Ba.displayName=Le.Content.displayName;var rd=js.forwardRef(({className:e,...t},s)=>ea(Le.Label,{ref:s,className:G("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));rd.displayName=Le.Label.displayName;var ot=js.forwardRef(({className:e,children:t,...s},n)=>Xi(Le.Item,{ref:n,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),...s,children:[ea("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:ea(Le.ItemIndicator,{children:ea(sd,{className:"af-h-4 af-w-4"})})}),ea(Le.ItemText,{children:t})]}));ot.displayName=Le.Item.displayName;var id=js.forwardRef(({className:e,...t},s)=>ea(Le.Separator,{ref:s,className:G("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));id.displayName=Le.Separator.displayName;import*as ca from"react";function Ir({formId:e,initialPageSize:t=25}){let{api:s}=q(),[n,a]=ca.useState([]),[r,o]=ca.useState(0),[c,d]=ca.useState(!0),[l,i]=ca.useState(null),[m,v]=ca.useState(0),[g,u]=ca.useState(t),f=ca.useRef(0),p=ca.useCallback(async()=>{if(!e)return;let P=++f.current;try{d(!0),i(null);let y={limit:g,offset:m*g},R=await s.getSubmissions(e,y);if(P!==f.current)return;if(R.submissions.length===0&&m>0){v(Math.max(0,Math.ceil(R.total/g)-1));return}a(R.submissions),o(R.total)}catch(y){if(P!==f.current)return;i(y instanceof Error?y:new Error("Failed to fetch submissions"))}finally{P===f.current&&d(!1)}},[s,e,m,g]);ca.useEffect(()=>{p()},[p]);let b=ca.useRef(p);b.current=p;let x=ca.useCallback(async P=>{await s.deleteSubmission(P),b.current()},[s]),N=Math.ceil(r/g);return{submissions:n,total:r,isLoading:c,error:l,page:m,pageSize:g,hasNextPage:m<N-1,hasPreviousPage:m>0,setPage:v,setPageSize:P=>{u(P),v(0)},refetch:p,deleteSubmission:x}}import*as Dr from"react";import{Trash2 as cd}from"lucide-react";import*as ar from"react";import*as Ut from"@radix-ui/react-dialog";import{X as od}from"lucide-react";import{jsx as Os,jsxs as Qi}from"react/jsx-runtime";var Za=Ut.Root;var ld=Ut.Portal;var fl=ar.forwardRef(({className:e,...t},s)=>Os(Ut.Overlay,{ref:s,className:G("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));fl.displayName=Ut.Overlay.displayName;var Fa=ar.forwardRef(({className:e,children:t,...s},n)=>Os(ld,{children:Qi("div",{className:"aifeatures-admin",children:[Os(fl,{}),Qi(Ut.Content,{ref:n,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),...s,children:[t,Qi(Ut.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:[Os(od,{className:"af-h-4 af-w-4"}),Os("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Fa.displayName=Ut.Content.displayName;var Ua=({className:e,...t})=>Os("div",{className:G("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Ua.displayName="DialogHeader";var Ma=({className:e,...t})=>Os("div",{className:G("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ma.displayName="DialogFooter";var $a=ar.forwardRef(({className:e,...t},s)=>Os(Ut.Title,{ref:s,className:G("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));$a.displayName=Ut.Title.displayName;var Va=ar.forwardRef(({className:e,...t},s)=>Os(Ut.Description,{ref:s,className:G("af-text-sm af-text-muted-foreground",e),...t}));Va.displayName=Ut.Description.displayName;import{Fragment as ud,jsx as un,jsxs as sr}from"react/jsx-runtime";function _n({onDelete:e,iconOnly:t}){let[s,n]=Dr.useState(!1),[a,r]=Dr.useState(!1),[o,c]=Dr.useState(null);return sr(ud,{children:[sr(h,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{c(null),n(!0)},children:[un(cd,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),un(Za,{open:s,onOpenChange:l=>{!l&&!a&&n(!1)},children:sr(Fa,{children:[sr(Ua,{children:[un($a,{children:"Delete this submission?"}),un(Va,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),o&&un("p",{className:"af-text-sm af-text-destructive",children:o}),sr(Ma,{children:[un(h,{variant:"outline",onClick:()=>n(!1),disabled:a,children:"Cancel"}),un(h,{variant:"destructive",onClick:async()=>{r(!0),c(null);try{await e(),n(!1)}catch(l){c(l instanceof Error?l.message:"Failed to delete submission")}finally{r(!1)}},disabled:a,children:a?"Deleting...":"Delete"})]})]})})]})}import*as pl from"react";import{ArrowLeft as dd,Download as fd,Globe as md,Clock as pd,FileText as gd,Loader2 as vd,Monitor as bd,Mail as yd}from"lucide-react";import{jsx as wt,jsxs as vt}from"react/jsx-runtime";function ml(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function hd(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,n)).toFixed(1))} ${s[n]}`}function Ar({submission:e,onBack:t,onDelete:s}){let{api:n}=q(),[a,r]=pl.useState(null),o=l=>l.id??l.name,c=async l=>{r(o(l));try{await n.downloadAttachment(e.id,l)}catch(i){console.error("Download failed:",i)}finally{r(null)}},d=Object.entries(e.data).filter(([l])=>!l.startsWith("_"));return vt("div",{children:[vt("div",{className:"af-mb-6",children:[vt(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[wt(dd,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),vt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[vt("div",{children:[wt("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),vt("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",ml(e.metadata.submitted_at)]})]}),s&&wt(_n,{onDelete:s})]})]}),vt("div",{className:"af-space-y-6",children:[wt(hs,{deliveries:e.email_deliveries}),vt("div",{children:[wt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),vt("div",{className:"af-space-y-3",children:[d.map(([l,i])=>vt("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[wt("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:l.replace(/_/g," ")}),wt("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof i=="string"&&i.includes(`
3
+ `)?wt("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:i}):String(i)})]},l)),d.length===0&&wt("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&vt("div",{children:[wt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),wt("div",{className:"af-space-y-2",children:e.attachments.map((l,i)=>vt("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[vt("div",{className:"af-flex af-items-center af-gap-2",children:[wt(gd,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),wt("span",{className:"af-text-sm",children:l.name}),vt("span",{className:"af-text-xs af-text-muted-foreground",children:["(",hd(l.size),")"]})]}),vt(h,{variant:"ghost",size:"sm",onClick:()=>c(l),disabled:a===o(l),children:[a===o(l)?wt(vd,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):wt(fd,{className:"af-h-4 af-w-4 af-mr-1"}),a===o(l)?"Downloading...":"Download"]})]},i))})]}),vt("div",{children:[wt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),vt("div",{className:"af-space-y-2 af-text-sm",children:[vt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[wt(pd,{className:"af-h-4 af-w-4"}),wt("span",{children:ml(e.metadata.submitted_at)})]}),e.metadata.ip_address&&vt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[wt(md,{className:"af-h-4 af-w-4"}),vt("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&vt("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[wt(bd,{className:"af-h-4 af-w-4 af-mt-0.5"}),wt("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&vt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[wt(yd,{className:"af-h-4 af-w-4"}),vt("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{Download as Sd}from"lucide-react";import*as dn from"react";var xd=/^\+[1-9]\d{1,14}$/;function gl(e){let t=e==null?"":String(e),s=!xd.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),n=s?`'${t}`:t;return s||/[",;\r\n]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function Lr(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function Or(e,t){if(typeof document>"u")return;let s=URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}function Br({fetchCsv:e,filename:t}){let[s,n]=dn.useState(!1),[a,r]=dn.useState(null),o=dn.useRef(!1);return{exportCsv:dn.useCallback(async()=>{if(!o.current){o.current=!0,n(!0),r(null);try{let d=await e();Or(d,Lr(t))}catch(d){r(d instanceof Error?d:new Error("Export failed"))}finally{o.current=!1,n(!1)}}},[e,t]),exporting:s,error:a}}import{jsx as vl,jsxs as bl}from"react/jsx-runtime";function ta({fetchCsv:e,filename:t,label:s="Export CSV",disabled:n,className:a}){let{exportCsv:r,exporting:o,error:c}=Br({fetchCsv:e,filename:t});return bl("span",{className:a,children:[bl(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:n||o,"aria-busy":o,children:[vl(Sd,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Exporting\u2026":s]}),c&&vl("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}import{jsx as Te,jsxs as Ct}from"react/jsx-runtime";function kd(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Td(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let s of t)if(typeof e[s]=="string")return e[s];return null}var Ed=["message","comments","comment","inquiry","question","details","body","notes"];function Id(e){let t=Object.entries(e).filter(([r,o])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),s=new Map(t.map(([r,o])=>[r.toLowerCase(),o])),a=(Ed.map(r=>s.get(r)).find(Boolean)??t.reduce((r,[,o])=>o.length>r.length?o:r,"")).trim().replace(/\s+/g," ");return a.length>80?a.slice(0,80)+"\u2026":a}function Fr({formId:e,className:t,defaultSubmissionId:s,submissionId:n,onSelectSubmission:a}){let{api:r}=q(),{submissions:o,total:c,isLoading:d,error:l,page:i,pageSize:m,hasNextPage:v,hasPreviousPage:g,setPage:u,setPageSize:f,deleteSubmission:p}=Ir({formId:e}),b=Gs.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[x,N]=Gs.useState(s??null),P=a?n??null:x,y=a??N,R=$=>!!$&&$.id===P&&$.form_id===e,_=o.find(R),[k,S]=Gs.useState(null),C=R(k)?k:null,[T,w]=Gs.useState(null);if(Gs.useEffect(()=>{if(w(null),!P||_||C)return;let $=!1;return r.getSubmission(P).then(ne=>{if(!$){if(ne.form_id!==e){w("This submission could not be found.");return}S(ne)}}).catch(()=>{$||w("This submission could not be found.")}),()=>{$=!0}},[r,e,P,_,C]),P){let $=_??C;return $?Te("div",{className:t,children:Te(Ar,{submission:$,onBack:()=>y(null),onDelete:async()=>{await p($.id),y(null)}})}):T?Ct("div",{className:t,children:[Ct(h,{variant:"ghost",size:"sm",onClick:()=>y(null),className:"af-mb-2 af--ml-2",children:[Te(wd,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Te("p",{className:"af-text-sm af-text-destructive",children:T})]}):Te("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Te("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(d)return Te("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Te("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(l)return Te("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ct("div",{className:"af-text-destructive",children:["Error: ",l.message]})});if(o.length===0&&i===0)return Ct("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Te(Pd,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ct("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",Te("br",{}),"Submissions will appear here when visitors use your form."]})]});let W=i*m+1,K=Math.min((i+1)*m,c);return Ct("div",{className:t,children:[Te("div",{className:"af-mb-2 af-flex af-justify-end",children:Te(ta,{fetchCsv:b,filename:"submissions"})}),Ct(Ze,{children:[Te(Ye,{children:Ct(Se,{children:[Te(V,{children:"Email"}),Te(V,{children:"Preview"}),Te(V,{children:"Date"}),Te(V,{className:"af-text-right",children:"Actions"})]})}),Te(Je,{children:o.map($=>{let ne=Td($.data),ie=Id($.data);return Ct(Se,{children:[Ct(H,{className:"af-font-medium",children:[Ct("div",{className:"af-flex af-items-center af-gap-2",children:[ne||Te("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),$.attachments.length>0&&Ct("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${$.attachments.length} attachment(s)`,children:[Te(Cd,{className:"af-h-3 af-w-3"}),Te("span",{className:"af-text-xs",children:$.attachments.length})]})]}),Te(tr,{deliveries:$.email_deliveries,label:"Notification email needs attention"})]}),Te(H,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:ie||Te("span",{className:"af-italic",children:"No preview available"})}),Te(H,{className:"af-text-muted-foreground",children:kd($.metadata.submitted_at)}),Ct(H,{className:"af-text-right",children:[Te(h,{variant:"ghost",size:"icon",onClick:()=>y($.id),title:"View details",children:Te(_d,{className:"af-h-4 af-w-4"})}),Te(_n,{iconOnly:!0,onDelete:()=>p($.id)})]})]},$.id)})})]}),Ct("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Ct("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ct("span",{children:["Showing ",W,"-",K," of ",c]}),Ct(Ga,{value:String(m),onValueChange:$=>f(Number($)),children:[Te(Oa,{className:"af-w-[70px] af-h-8",children:Te(Ka,{})}),Ct(Ba,{children:[Te(ot,{value:"10",children:"10"}),Te(ot,{value:"25",children:"25"}),Te(ot,{value:"50",children:"50"}),Te(ot,{value:"100",children:"100"})]})]}),Te("span",{children:"per page"})]}),Ct("div",{className:"af-flex af-items-center af-gap-2",children:[Ct(h,{variant:"outline",size:"sm",onClick:()=>u(i-1),disabled:!g,children:[Te(Nd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ct(h,{variant:"outline",size:"sm",onClick:()=>u(i+1),disabled:!v,children:["Next",Te(Rd,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as za from"react";import{Plus as zd,X as qd,Loader2 as Wd,Check as jd}from"lucide-react";import*as yl from"react";import{jsx as Dd}from"react/jsx-runtime";var Q=yl.forwardRef(({className:e,type:t,...s},n)=>Dd("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:n,...s}));Q.displayName="Input";import*as hl from"react";import{cva as Ad}from"class-variance-authority";import{jsx as Od}from"react/jsx-runtime";var Ld=Ad("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Re=hl.forwardRef(({className:e,...t},s)=>Od("label",{ref:s,className:G(Ld(),e),...t}));Re.displayName="Label";import*as Ja from"react";import{Plus as Fd,Loader2 as eo,Copy as Ud,Check as Md,Trash2 as $d,RefreshCw as Vd,AlertTriangle as Hd}from"lucide-react";import*as Ha from"react";function Ur(){let{api:e}=q(),[t,s]=Ha.useState([]),[n,a]=Ha.useState(!0),[r,o]=Ha.useState(null),c=Ha.useCallback(async()=>{try{a(!0),o(null),s(await e.getEventDestinations())}catch(g){o(g instanceof Error?g:new Error("Failed to fetch webhooks"))}finally{a(!1)}},[e]);Ha.useEffect(()=>{c()},[c]);let d=Ha.useCallback(async g=>{let u=await e.createEventDestination(g);return s(f=>[u,...f]),u},[e]),l=Ha.useCallback(async(g,u)=>{let f=await e.updateEventDestination(g,u);return s(p=>p.map(b=>b.id===g?f:b)),f},[e]),i=Ha.useCallback(async g=>{await e.deleteEventDestination(g),s(u=>u.filter(f=>f.id!==g))},[e]),m=Ha.useCallback(async g=>{let u=await e.rotateEventDestinationSecret(g);return s(f=>f.map(p=>p.id===g?u:p)),u},[e]),v=Ha.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:t,isLoading:n,error:r,refetch:c,createDestination:d,updateDestination:l,deleteDestination:i,rotateSecret:m,getSecret:v}}import*as Bs from"react";import{Loader2 as xl,RotateCw as Bd}from"lucide-react";import{jsx as Ya,jsxs as nr}from"react/jsx-runtime";function Mr({destinationId:e,limit:t=25,className:s}){let{api:n}=q(),[a,r]=Bs.useState([]),[o,c]=Bs.useState(!0),[d,l]=Bs.useState(null),[i,m]=Bs.useState(null),v=Bs.useCallback(async()=>{try{c(!0),l(null),r(await n.getEventDeliveries(e,t))}catch(u){l(u instanceof Error?u.message:"Failed to load deliveries")}finally{c(!1)}},[n,e,t]);Bs.useEffect(()=>{v()},[v]);let g=async u=>{try{m(u.id),l(null);let f=await n.retryEventDelivery(e,u.id);r(p=>p.map(b=>b.id===u.id?f:b))}catch(f){l(f instanceof Error?f.message:"Retry failed")}finally{m(null)}};return o?nr("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[Ya(xl,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):d?Ya("div",{className:"af-text-sm af-text-destructive af-py-2",children:d}):a.length===0?Ya("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):Ya("div",{className:s,children:Ya("div",{className:"af-divide-y af-border af-rounded",children:a.map(u=>{let f=u.delivered_at!==null;return nr("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[nr("div",{className:"af-min-w-0",children:[nr("div",{className:"af-flex af-items-center af-gap-2",children:[f?Ya(te,{variant:"secondary",children:u.last_status??200}):Ya(te,{variant:"destructive",children:u.last_status??"failed"}),Ya("span",{className:"af-text-sm af-truncate",children:u.type})]}),nr("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[u.event_id," \xB7 ",u.created_at,u.attempts>0&&` \xB7 ${u.attempts} failed ${u.attempts===1?"attempt":"attempts"}`]}),!f&&u.last_error&&Ya("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),Ya(h,{variant:"ghost",size:"sm",title:"Send this event again",disabled:i===u.id,onClick:()=>g(u),children:i===u.id?Ya(xl,{className:"af-h-4 af-w-4 af-animate-spin"}):Ya(Bd,{className:"af-h-4 af-w-4"})})]},u.id)})})})}import{jsx as $e,jsxs as Dt}from"react/jsx-runtime";function $r({formId:e,topics:t,description:s,className:n}){let{destinations:a,isLoading:r,error:o,createDestination:c,updateDestination:d,deleteDestination:l,rotateSecret:i,getSecret:m}=Ur(),[v,g]=Ja.useState(""),[u,f]=Ja.useState(!1),[p,b]=Ja.useState(null),[x,N]=Ja.useState(null),[P,y]=Ja.useState(null),[R,_]=Ja.useState(!1),[k,S]=Ja.useState(null),[C,T]=Ja.useState(null),[w,W]=Ja.useState(null),K=Ja.useMemo(()=>a.filter(B=>B.form_id===e),[a,e]),$=async()=>{let B=v.trim();if(B){if(!B.startsWith("https://")){b("Webhook URLs must start with https://");return}try{f(!0),b(null),await c({url:B,form_id:e,...t&&t.length>0?{topics:t}:{}}),g("")}catch(le){b(le instanceof Error?le.message:"Failed to add webhook")}finally{f(!1)}}},ne=async B=>{try{T(B.id),b(null),await i(B.id),_(!1),y(await m(B.id))}catch(le){b(le instanceof Error?le.message:"Failed to rotate secret")}finally{T(null)}},ie=async B=>{try{T(B.id),b(null),await d(B.id,{status:"active"})}catch(le){b(le instanceof Error?le.message:"Failed to re-enable")}finally{T(null)}},ue=async()=>{if(k)try{T(k.id),await l(k.id),S(null)}catch(B){b(B instanceof Error?B.message:"Failed to delete")}finally{T(null)}},F=async B=>{if(x===B.id){N(null),y(null);return}try{T(B.id),b(null),_(!1),N(B.id),y(await m(B.id))}catch(le){N(null),b(le instanceof Error?le.message:"Failed to read secret")}finally{T(null)}},Z=async()=>{if(P)try{await navigator.clipboard.writeText(P),_(!0)}catch{}};return Dt("div",{className:n,children:[Dt("div",{className:"af-space-y-1",children:[$e(Re,{children:"Webhooks"}),$e("p",{className:"af-text-sm af-text-muted-foreground",children:s??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),Dt("div",{className:"af-flex af-gap-2 af-mt-4",children:[$e(Q,{value:v,placeholder:"https://hooks.zapier.com/...",onChange:B=>g(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),$())},disabled:u}),Dt(h,{onClick:$,disabled:u||!v.trim(),children:[u?$e(eo,{className:"af-h-4 af-w-4 af-animate-spin"}):$e(Fd,{className:"af-h-4 af-w-4"}),$e("span",{className:"af-ml-1",children:"Add"})]})]}),(p||o)&&$e("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:p||o?.message}),Dt("div",{className:"af-mt-4 af-space-y-2",children:[r&&Dt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[$e(eo,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&K.length===0&&$e("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),K.map(B=>Dt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[Dt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[Dt("div",{className:"af-min-w-0",children:[Dt("div",{className:"af-flex af-items-center af-gap-2",children:[$e("span",{className:"af-font-mono af-text-sm af-truncate",children:B.url}),B.status==="disabled"?$e(te,{variant:"destructive",children:"Disabled"}):$e(te,{variant:"secondary",children:"Active"})]}),$e("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:B.topics.includes("*")?"All events":B.topics.join(", ")})]}),Dt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[$e(h,{variant:"ghost",size:"sm",onClick:()=>W(w===B.id?null:B.id),children:w===B.id?"Hide log":"Deliveries"}),$e(h,{variant:"ghost",size:"sm",onClick:()=>F(B),disabled:C===B.id,children:x===B.id?"Hide secret":"Show secret"}),$e(h,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:C===B.id,onClick:()=>S(B),children:$e($d,{className:"af-h-4 af-w-4"})})]})]}),B.status==="disabled"&&Dt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[$e(Hd,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),Dt("div",{className:"af-text-sm",children:[Dt("p",{children:["We stopped sending after repeated failures."," ",B.disabled_reason]}),$e(h,{variant:"outline",size:"sm",className:"af-mt-2",disabled:C===B.id,onClick:()=>ie(B),children:"Re-enable"})]})]}),x===B.id&&P&&Dt("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[$e("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."}),Dt("div",{className:"af-flex af-gap-2",children:[$e(Q,{readOnly:!0,value:P,className:"af-font-mono"}),$e(h,{variant:"outline",title:"Copy signing secret",onClick:Z,children:R?$e(Md,{className:"af-h-4 af-w-4"}):$e(Ud,{className:"af-h-4 af-w-4"})}),$e(h,{variant:"outline",title:"Rotate signing secret",disabled:C===B.id,onClick:()=>ne(B),children:C===B.id?$e(eo,{className:"af-h-4 af-w-4 af-animate-spin"}):$e(Vd,{className:"af-h-4 af-w-4"})})]})]}),w===B.id&&$e(Mr,{destinationId:B.id})]},B.id))]}),$e(Za,{open:!!k,onOpenChange:B=>{!B&&!C&&S(null)},children:Dt(Fa,{children:[Dt(Ua,{children:[$e($a,{children:"Delete this webhook?"}),Dt(Va,{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."]})]}),Dt(Ma,{children:[$e(h,{variant:"outline",onClick:()=>S(null),disabled:!!C,children:"Cancel"}),$e(h,{variant:"destructive",onClick:ue,disabled:!!C,children:C?"Deleting...":"Delete"})]})]})})]})}import{jsx as je,jsxs as ms}from"react/jsx-runtime";function Vr({form:e,onSaved:t,className:s}){let{updateForm:n}=Rn(),[a,r]=za.useState(!1),[o,c]=za.useState(null),[d,l]=za.useState(null),[i,m]=za.useState(e.name),[v,g]=za.useState(e.redirect_url||""),[u,f]=za.useState(e.email_recipients),[p,b]=za.useState("");za.useEffect(()=>{m(e.name),g(e.redirect_url||""),f(e.email_recipients),l(null)},[e]);let x=za.useCallback(async _=>{try{r(!0),l(null);let k=await n(e.id,_);c(new Date),t?.(k)}catch(k){l(k instanceof Error?k.message:"Failed to save")}finally{r(!1)}},[e.id,n,t]);za.useEffect(()=>{if(o){let _=setTimeout(()=>c(null),2e3);return()=>clearTimeout(_)}},[o]);let N=async()=>{let _=p.trim().toLowerCase();if(!_)return;if(!_.includes("@")){l("Please enter a valid email address");return}if(u.includes(_)){l("This email is already added");return}let k=[...u,_];f(k),b(""),l(null),await x({email_recipients:k})},P=async _=>{let k=u.filter(S=>S!==_);f(k),await x({email_recipients:k})},y=async()=>{i!==e.name&&await x({name:i})},R=async()=>{let _=v||null;_!==e.redirect_url&&await x({redirect_url:_})};return ms("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(a||o)&&je("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:a?ms("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:[je(Wd,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),je("span",{className:"af-text-sm",children:"Saving..."})]}):ms("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:[je(jd,{className:"af-h-4 af-w-4 af-text-green-600"}),je("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),ms("div",{className:"af-space-y-2",children:[je(Re,{htmlFor:"form-name",children:"Form Name"}),je(Q,{id:"form-name",value:i,onChange:_=>m(_.target.value),onBlur:y,placeholder:"Contact Form"}),je("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),ms("div",{className:"af-space-y-2",children:[je(Re,{children:"Email Recipients"}),je("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),ms("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(_=>ms(te,{variant:"secondary",className:"af-gap-1",children:[_,je("button",{type:"button",onClick:()=>P(_),className:"af-ml-1 hover:af-text-destructive",disabled:a,children:je(qd,{className:"af-h-3 af-w-3"})})]},_)),u.length===0&&je("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),ms("div",{className:"af-flex af-gap-2",children:[je(Q,{type:"email",value:p,onChange:_=>b(_.target.value),placeholder:"Add email address",onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),N())},disabled:a}),je(h,{type:"button",variant:"outline",onClick:N,disabled:!p.trim()||a,children:je(zd,{className:"af-h-4 af-w-4"})})]})]}),ms("div",{className:"af-space-y-2",children:[je(Re,{htmlFor:"redirect-url",children:"Redirect URL"}),je(Q,{id:"redirect-url",value:v,onChange:_=>g(_.target.value),onBlur:R,placeholder:"/thank-you"}),je("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."})]}),ms("div",{className:"af-space-y-2",children:[je(Re,{children:"Form Endpoint"}),je("div",{className:"af-flex af-items-center af-gap-2",children:je("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})}),je("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),ms("div",{className:"af-space-y-2",children:[je(Re,{children:"Captcha Protection"}),je("div",{className:"af-flex af-items-center af-gap-2",children:je(te,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),je("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),je($r,{formId:e.id}),d&&je("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})]})}import{jsx as xa,jsxs as xs}from"react/jsx-runtime";function Sl({className:e,location:t,onNavigate:s,submissionId:n}){let{api:a}=q(),[r,o]=Fs.useState({submissionId:n});Fs.useEffect(()=>{n&&o({submissionId:n})},[n]);let c=s?t??{}:r,d=s??o,[l,i]=Fs.useState(null),m=`${c.formId??""}|${c.submissionId??""}`,[v,g]=Fs.useState(null),u=v?.key===m?v.message:null,f=c.formId??(l&&l.submissionId===c.submissionId?l.formId:void 0);Fs.useEffect(()=>{let _=c.submissionId;if(!_||c.formId)return;let k=!1;return a.getSubmission(_).then(S=>{k||(g(null),i({submissionId:_,formId:S.form_id}))}).catch(()=>{k||g({key:m,message:"This submission could not be found."})}),()=>{k=!0}},[a,c.submissionId,c.formId,m]);let[p,b]=Fs.useState(null);Fs.useEffect(()=>{if(!f||p?.id===f)return;let _=!1;return a.getForm(f).then(k=>{_||(g(null),b(k))}).catch(()=>{_||g({key:m,message:"This form could not be found."})}),()=>{_=!0}},[a,f,p?.id,m]);let x=(_,k)=>{b(_),d({formId:_.id,tab:k})},N=()=>d({});if(!c.formId&&!c.submissionId)return xs("div",{className:e,children:[xs("div",{className:"af-mb-6",children:[xa("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),xa("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),xa(kr,{onSelectForm:x})]});let y=xs(h,{variant:"ghost",size:"sm",onClick:N,className:"af-mb-2 af--ml-2",children:[xa(Gd,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(u)return xs("div",{className:e,children:[y,xa("p",{className:"af-text-sm af-text-destructive",children:u})]});if(!f||p?.id!==f)return xa("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:xa("div",{className:"af-text-muted-foreground",children:"Loading..."})});let R=c.submissionId?"submissions":c.tab??"submissions";return xs("div",{className:e,children:[xs("div",{className:"af-mb-6",children:[y,xa("h2",{className:"af-text-lg af-font-semibold",children:p.name})]}),xs(Cr,{value:R,onValueChange:_=>d({formId:f,tab:_}),children:[xs(er,{className:"af-mb-4",children:[xs(us,{value:"submissions",className:"af-gap-2",children:[xa(Zd,{className:"af-h-4 af-w-4"}),"Submissions"]}),xs(us,{value:"settings",className:"af-gap-2",children:[xa(Kd,{className:"af-h-4 af-w-4"}),"Settings"]})]}),xa(ds,{value:"submissions",children:xa(Fr,{formId:f,submissionId:c.submissionId,onSelectSubmission:_=>d({formId:f,tab:"submissions",submissionId:_??void 0})})}),xa(ds,{value:"settings",children:xa(Vr,{form:p,onSaved:b})})]})]})}import*as Ge from"react";import*as Ss from"react";function Ks(){let{api:e}=q(),[t,s]=Ss.useState(null),[n,a]=Ss.useState(!0),[r,o]=Ss.useState(null),c=Ss.useRef(0),d=Ss.useCallback(async()=>{let l=++c.current;try{a(!0),o(null);let i=await e.getPaymentsStatus();if(l!==c.current)return;s(i)}catch(i){if(l!==c.current)return;o(i instanceof Error?i:new Error("Failed to fetch payments status"))}finally{l===c.current&&a(!1)}},[e]);return Ss.useEffect(()=>{d()},[d]),{status:t,isLoading:n,error:r,refetch:d}}var Yd=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Xa(e){return Yd.has(e.toLowerCase())}function j(e,t,s){let n=Xa(t)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:t.toUpperCase()}).format(n)}catch{return`${n} ${t.toUpperCase()}`}}function Us(e){let t=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+t}function Zt(e,t){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let n=Xa(t)?s:s*100;return Math.round(n)}function bt(e,t){return Xa(t)?e:e/100}function Hr(e){return e.amount_paid??Math.max(0,Us(e)-(e.credit_applied??0))}import{Fragment as Qd,jsx as He,jsxs as Qe}from"react/jsx-runtime";function rr(e){return e instanceof Ft&&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 wl(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${j(e.amount_off,e.currency)} off`:"Discount unavailable"}function Pn(){let{api:e,siteToken:t}=q();return He(Jd,{api:e},t)}function Jd({api:e}){let{status:t,error:s}=Ks(),[n,a]=Ge.useState([]),[r,o]=Ge.useState(null),[c,d]=Ge.useState(null),[l,i]=Ge.useState(!1),[m,v]=Ge.useState(!1),[g,u]=Ge.useState(""),[f,p]=Ge.useState(null),[b,x]=Ge.useState(null),[N,P]=Ge.useState(!1),y=Ge.useRef(0),R=Ge.useCallback(async S=>{let C=++y.current;i(!0),u("");try{let T=await e.getPromos(S);if(C!==y.current)return;a(w=>S?[...w,...T.promos.filter(W=>!w.some(K=>K.id===W.id))]:T.promos),o(T.next_cursor),d(T.checkout_enabled)}catch(T){C===y.current&&u(rr(T))}finally{C===y.current&&i(!1)}},[e]);Ge.useEffect(()=>(R(),()=>{y.current++}),[R]);async function _(S){let C=++y.current;i(!0),u(""),P(!1);try{let T=await e.getPromo(S);C===y.current&&p(T)}catch(T){C===y.current&&u(rr(T))}finally{C===y.current&&i(!1)}}async function k(){if(f){v(!0),i(!0),u("");try{let S=await e.disablePromo(f.id);if(p(S),!["inactive","expired","exhausted"].includes(S.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");P(!1),await R()}catch(S){u(rr(S))}finally{v(!1),i(!1)}}}return b?He(Xd,{currency:t?.currency??void 0,replaces:b.replaces,onCancel:()=>x(null),onSave:async S=>{let C=b.replaces?await e.replacePromo(b.replaces.id,S):await e.createPromo(S),T=await e.getPromo(C.id);if(T.status==="pending"||T.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(T),x(null),await R()}}):Qe("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[Qe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[He("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),He(h,{disabled:l||!t?.currency,onClick:()=>{u(""),x({})},children:"Create promo code"})]}),He("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),c===!1&&He("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&&He("p",{className:"af-text-sm",children:s?rr(s):"Connect Stripe and set the payment currency before creating codes."}),g&&Qe("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",He(h,{variant:"outline",disabled:l,onClick:()=>f?void _(f.id):void R(),children:"Refresh"})]}),f?Qe("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[He(h,{variant:"ghost",disabled:m,onClick:()=>{p(null),P(!1),R()},children:"Back to codes"}),Qe("h4",{className:"af-font-semibold af-break-all",children:[f.code," \xB7 ",f.name]}),Qe("p",{children:[wl(f)," \xB7 ",f.status]}),Qe("p",{className:"af-text-sm",children:[f.times_redeemed==null?"Usage unavailable":`${f.times_redeemed} redemptions`,f.max_redemptions!=null?` / ${f.max_redemptions} maximum`:""]}),Qe("p",{className:"af-text-sm",children:[f.minimum_amount!=null&&f.currency?`Minimum order: ${j(f.minimum_amount,f.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),Qe("p",{className:"af-text-sm",children:["Subscription discount:"," ",f.duration==="repeating"?`${f.duration_in_months} months`:f.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),He("p",{className:"af-text-sm",children:f.expires_at?`Expires ${new Date(f.expires_at).toLocaleString()}`:"No expiry"}),Qe("div",{className:"af-flex af-flex-wrap af-gap-2",children:[He(h,{variant:"outline",disabled:l,onClick:()=>void _(f.id),children:"Refresh details"}),He(h,{variant:"outline",disabled:l||f.status==="pending"||f.status==="unavailable"||!t?.currency,onClick:()=>x({replaces:f}),children:"Replace with new code"}),He(h,{variant:"outline",disabled:l||!["active","pending","unavailable"].includes(f.status),onClick:()=>P(!0),children:f.status==="pending"?"Cancel pending offer":"Disable code"})]}),N&&Qe("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[Qe("p",{className:"af-text-sm",children:[f.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${f.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),He(h,{disabled:l,onClick:()=>void k(),children:f.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",He(h,{variant:"ghost",disabled:l,onClick:()=>P(!1),children:"Cancel"})]})]}):Qe(Qd,{children:[n.map(S=>Qe("button",{type:"button",disabled:l,onClick:()=>void _(S.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:[Qe("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[He("span",{className:"af-font-semibold af-break-all",children:S.code}),He("span",{className:"af-text-sm",children:S.status})]}),Qe("div",{className:"af-text-sm",children:[wl(S)," \xB7"," ",S.times_redeemed==null?"Usage unavailable":`${S.times_redeemed} redemptions`]})]},S.id)),!l&&!g&&n.length===0&&He("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&&He("p",{role:"status",children:"Loading promo codes\u2026"}),r&&He(h,{variant:"outline",disabled:l,onClick:()=>void R(r),children:"Load more"})]})]})}function Xd({currency:e,replaces:t,onCancel:s,onSave:n}){let[a,r]=Ge.useState(""),[o,c]=Ge.useState(t?.name??""),[d,l]=Ge.useState(t?.amount_off!=null?"fixed":"percent"),[i,m]=Ge.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(bt(t.amount_off,e)):"")),[v,g]=Ge.useState(t?.minimum_amount!=null&&e?String(bt(t.minimum_amount,e)):""),[u,f]=Ge.useState(()=>{if(!t?.expires_at)return"";let ie=new Date(t.expires_at);return Number.isFinite(ie.getTime())?new Date(ie.getTime()-ie.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,b]=Ge.useState(t?.max_redemptions?.toString()??""),[x,N]=Ge.useState(t?.duration??"once"),[P,y]=Ge.useState(t?.duration_in_months?.toString()??"3"),[R,_]=Ge.useState(null),[k,S]=Ge.useState(!1),[C,T]=Ge.useState(""),w=Ge.useRef(!1),W=e&&Xa(e)?"1":"0.01";async function K(ie){if(ie.preventDefault(),w.current)return;T("");let ue=R;if(!ue){if(!e){T("Payment currency is not available.");return}if(t&&a.trim().toUpperCase()===t.code.toUpperCase()){T("Choose a different code for the replacement.");return}let F=Zt(i,e),Z=v?Zt(v,e):null;if(d==="fixed"&&(!F||F>999999999999)||v&&(!Z||Z>999999999999)){T("Enter a positive amount within the supported range.");return}if(u&&new Date(u).getTime()<=Date.now()){T("Choose a future expiry.");return}ue={request_id:crypto.randomUUID(),code:a.trim().toUpperCase(),name:o.trim(),duration:x,...d==="percent"?{percent_off:Number(i)}:{amount_off:F,currency:e},...v?{minimum_amount:Z,currency:e}:{},...u?{expires_at:new Date(u).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...x==="repeating"?{duration_in_months:Number(P)}:{}},_(ue)}w.current=!0,S(!0);try{await n(ue)}catch(F){T(rr(F)),F instanceof Ft&&F.status>=400&&F.status<500&&F.details?.retryable!==!0&&_(null)}finally{w.current=!1,S(!1)}}let $=(ie,ue,F,Z={})=>Qe("label",{className:"af-grid af-gap-1 af-text-sm",children:[ie,He(Q,{"aria-label":ie,value:ue,onChange:B=>F(B.target.value),...Z})]}),ne="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return Qe("form",{onSubmit:K,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[He("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&He("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."}),Qe("fieldset",{disabled:k||!!R,className:"af-grid af-gap-4",children:[$("Code",a,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),$("Name",o,c,{required:!0,maxLength:40}),Qe("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",Qe("select",{"aria-label":"Discount type",className:ne,value:d,onChange:ie=>l(ie.target.value),children:[He("option",{value:"percent",children:"Percentage"}),Qe("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),$("Discount",i,m,{type:"number",required:!0,min:d==="percent"?"0.01":W,max:d==="percent"?"100":void 0,step:d==="percent"?"0.01":W}),$("Minimum order amount",v,g,{type:"number",min:W,step:W,placeholder:e?.toUpperCase()}),Qe("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)",u,f,{type:"datetime-local",step:1}),$("Maximum redemptions",p,b,{type:"number",min:1,max:1e6,step:1}),Qe("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",Qe("select",{"aria-label":"Subscription duration",className:ne,value:x,onChange:ie=>N(ie.target.value),children:[He("option",{value:"once",children:"First invoice only"}),He("option",{value:"forever",children:"Every invoice"}),He("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&$("Months",P,y,{type:"number",required:!0,min:1,max:36,step:1})]}),C&&He("p",{role:"alert",className:"af-text-sm af-text-destructive",children:C}),R&&!k&&Qe("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",He("span",{className:"af-break-all",children:R.request_id})]}),Qe("div",{className:"af-flex af-flex-wrap af-gap-2",children:[He(h,{type:"submit",disabled:k,children:k?"Saving\u2026":R?"Retry same request":t?"Create replacement":"Create code"}),He(h,{type:"button",variant:"ghost",disabled:k||!!R,onClick:s,children:"Cancel"})]})]})}import*as On from"react";import{ArrowLeft as Rm,FileText as _m,Package as Pm,Receipt as Cm,Settings as km,Users as Tm}from"lucide-react";import*as zr from"react";import{Package as ef,Pencil as tf,Plus as Nl,Trash2 as af}from"lucide-react";import{jsx as Xe,jsxs as aa}from"react/jsx-runtime";function sf(e){if(e.allow_custom_amount){let t=e.min_amount!==null?j(e.min_amount,e.currency):"?",s=e.max_amount!==null?j(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${s})`}return e.unit_amount===null?"Varies by variant":j(e.unit_amount,e.currency)}function nf(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function qr({productsState:e,onSelectProduct:t,onCreateProduct:s,className:n}){let{products:a,isLoading:r,error:o,deleteProduct:c}=e,[d,l]=zr.useState(null),[i,m]=zr.useState(!1),[v,g]=zr.useState(null),u=async()=>{if(d)try{m(!0),g(null),await c(d.id),l(null)}catch(f){g(f instanceof Error?f.message:"Failed to delete product")}finally{m(!1)}};return r?Xe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:Xe("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?Xe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:aa("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):a.length===0?aa("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${n||""}`,children:[Xe(ef,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),aa("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",Xe("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),aa(h,{variant:"outline",onClick:()=>s?.(),children:[Xe(Nl,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):aa("div",{className:n,children:[Xe("div",{className:"af-flex af-justify-end af-mb-4",children:aa(h,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[Xe(Nl,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),aa(Ze,{children:[Xe(Ye,{children:aa(Se,{children:[Xe(V,{children:"Name"}),Xe(V,{children:"Price"}),Xe(V,{children:"Fulfillment"}),Xe(V,{children:"Status"}),Xe(V,{className:"af-text-right",children:"Actions"})]})}),Xe(Je,{children:a.map(f=>aa(Se,{children:[Xe(H,{className:"af-font-medium",children:f.name}),Xe(H,{children:sf(f)}),Xe(H,{className:"af-text-muted-foreground",children:nf(f)}),Xe(H,{children:Xe(te,{variant:f.active?"success":"secondary",children:f.active?"Active":"Inactive"})}),Xe(H,{className:"af-text-right",children:aa("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[aa(h,{variant:"ghost",size:"sm",onClick:()=>t?.(f),children:[Xe(tf,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),aa(h,{variant:"ghost",size:"sm",onClick:()=>{g(null),l(f)},children:[Xe(af,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},f.id))})]}),Xe(Za,{open:!!d,onOpenChange:f=>{!f&&!i&&l(null)},children:aa(Fa,{children:[aa(Ua,{children:[Xe($a,{children:"Delete product?"}),aa(Va,{children:['"',d?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),v&&Xe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),aa(Ma,{children:[Xe(h,{variant:"outline",onClick:()=>l(null),disabled:i,children:"Cancel"}),Xe(h,{variant:"destructive",onClick:u,disabled:i,children:i?"Deleting...":"Delete"})]})]})})]})}import*as lt from"react";import{FileText as of,Link2 as lf,Loader2 as Pl,Plus as cf,Upload as uf,X as df}from"lucide-react";import*as At from"react";import{Loader2 as Rl,Plus as to,Trash2 as _l,X as rf}from"lucide-react";import{jsx as ee,jsxs as ye}from"react/jsx-runtime";function ao(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Wr({productId:e,currency:t,className:s}){let{api:n}=q(),a=Xa(t)?"1":"0.01",[r,o]=At.useState(null),[c,d]=At.useState(!0),[l,i]=At.useState(null),[m,v]=At.useState(null),[g,u]=At.useState(!1),f=At.useRef(!0);At.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]);let p=At.useCallback(async()=>{try{let I=await n.getProduct(e);if(!f.current)return;o(I)}catch(I){if(!f.current)return;i(I instanceof Error?I.message:"Failed to load product")}finally{f.current&&d(!1)}},[n,e]);At.useEffect(()=>{p()},[p]);let b=async I=>{v(null),u(!0);try{await I(),await p()}catch(U){f.current&&v(U instanceof Error?U.message:"Something went wrong")}finally{f.current&&u(!1)}},[x,N]=At.useState(""),[P,y]=At.useState(""),[R,_]=At.useState({}),k=()=>b(async()=>{let I=x.trim(),U=P.split(",").map(O=>O.trim()).filter(Boolean);if(!I)throw new Error("Option name is required");if(U.length===0)throw new Error("Add at least one value");await n.createOption(e,{title:I,values:U}),f.current&&(N(""),y(""))}),S=I=>b(async()=>{let U=(R[I.id]??"").trim();if(!U)throw new Error("Enter a value");await n.updateOption(I.id,{add_values:[U]}),f.current&&_(O=>({...O,[I.id]:""}))}),C=(I,U)=>b(()=>n.updateOption(I.id,{remove_values:[U]})),T=I=>b(()=>n.deleteOption(I.id)),[w,W]=At.useState(null),[K,$]=At.useState(null),[ne,ie]=At.useState(!1),[ue,F]=At.useState(null),Z=r?.options??[],B=r?.variants??[],le=()=>{$(null),W({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(Z.map(I=>[I.id,I.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},oe=I=>{$(null);let U=I.inventory?.on_hand??0,O=U<0?"":String(U);W({variant:I,title:I.title??"",sku:I.sku??"",unitAmount:I.unit_amount!=null?String(bt(I.unit_amount,t)):"",compareAt:I.compare_at_amount!=null?String(bt(I.compare_at_amount,t)):"",active:I.active,optionValues:{},tracked:I.inventory?.tracked??!1,onHand:O,initialOnHand:O,allowBackorder:I.inventory?.allow_backorder??!1})},Ke=async()=>{if(!w)return;$(null);let I=w.variant?.allow_custom_amount??!1,U=null,O=null;if(!I){if(U=Zt(w.unitAmount,t),U===null||U<=0){$("Enter a valid price");return}if(w.compareAt.trim()&&(O=Zt(w.compareAt,t),O===null||O<=U)){$("Compare-at price must be greater than the price");return}}let be=w.onHand.trim()!==w.initialOnHand.trim(),Y=parseInt(w.onHand,10);if(w.tracked&&be&&(!Number.isFinite(Y)||Y<0)){$("On-hand quantity must be zero or more");return}try{if(ie(!0),w.variant)await n.updateVariant(w.variant.id,{title:w.title.trim()||null,sku:w.sku.trim()||null,...I?{}:{unit_amount:U,compare_at_amount:O},active:w.active}),await n.setVariantInventory(w.variant.id,{tracked:w.tracked,on_hand:w.tracked&&be?Y:void 0,allow_backorder:w.allowBackorder});else{let pe={};for(let Fe of Z){let mt=w.optionValues[Fe.id];if(!mt){$(`Choose a ${Fe.title}`),ie(!1);return}pe[Fe.title]=mt}await n.createVariant(e,{title:w.title.trim()||null,sku:w.sku.trim()||null,unit_amount:U,compare_at_amount:O,active:w.active,option_values:Z.length>0?pe:void 0,inventory:w.tracked?{tracked:!0,on_hand:Y,allow_backorder:w.allowBackorder}:{tracked:!1,allow_backorder:w.allowBackorder}})}await p(),f.current&&W(null)}catch(pe){if(f.current&&$(pe instanceof Error?pe.message:"Failed to save variant"),w.variant)try{let Fe=await n.getProduct(e);f.current&&o(Fe)}catch{}}finally{f.current&&ie(!1)}},xe=()=>b(async()=>{ue&&(await n.deleteVariant(ue.id),f.current&&F(null))}),Me=w?.variant?.allow_custom_amount??!1,We=w?.variant!=null&&w.variant.option_values.length===0&&Z.length>0&&!w.variant.active,ke=w?.variant?.inventory!=null&&w.variant.inventory.on_hand<0?-w.variant.inventory.on_hand:null;function St(I){let U=I.inventory;if(!U||!U.tracked)return ee("span",{className:"af-text-muted-foreground",children:"Unlimited"});let O=U.available??U.on_hand;return O<0?ye("span",{children:[-O," backordered"]}):ye("span",{children:[O," in stock",U.allow_backorder&&ee("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return c?ee("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:ee(Rl,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):l?ee("div",{className:s,children:ee("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l})}):ye("div",{className:`af-space-y-6 ${s||""}`,children:[ye("div",{className:"af-space-y-3",children:[ye("div",{children:[ee(Re,{children:"Options"}),ee("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&&ee("div",{className:"af-space-y-3",children:Z.map(I=>ye("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[ye("div",{className:"af-flex af-items-center af-justify-between",children:[ee("span",{className:"af-text-sm af-font-medium",children:I.title}),ee(h,{variant:"ghost",size:"sm",onClick:()=>T(I),disabled:g,children:ee(_l,{className:"af-h-4 af-w-4"})})]}),ee("div",{className:"af-flex af-flex-wrap af-gap-2",children:I.values.map(U=>ye(te,{variant:"secondary",className:"af-gap-1",children:[U.value,ee("button",{type:"button",onClick:()=>C(I,U.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:ee(rf,{className:"af-h-3 af-w-3"})})]},U.id))}),ye("div",{className:"af-flex af-gap-2",children:[ee(Q,{value:R[I.id]??"",onChange:U=>_(O=>({...O,[I.id]:U.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),S(I))},disabled:g}),ee(h,{type:"button",variant:"outline",size:"sm",onClick:()=>S(I),disabled:g||!(R[I.id]??"").trim(),children:ee(to,{className:"af-h-4 af-w-4"})})]})]},I.id))}),ye("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[ye("div",{className:"af-space-y-1",children:[ee(Re,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),ee(Q,{id:"new-option-title",value:x,onChange:I=>N(I.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),ye("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[ee(Re,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),ee(Q,{id:"new-option-values",value:P,onChange:I=>y(I.target.value),placeholder:"S, M, L",disabled:g})]}),ye(h,{type:"button",variant:"outline",onClick:k,disabled:g||!x.trim()||!P.trim(),children:[ee(to,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),ye("div",{className:"af-space-y-3",children:[ye("div",{className:"af-flex af-items-center af-justify-between",children:[ee(Re,{children:"Variants"}),ye(h,{type:"button",variant:"outline",size:"sm",onClick:le,disabled:g||Z.length===0,children:[ee(to,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),Z.length===0&&ee("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),B.length===0?ee("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):ye(Ze,{children:[ee(Ye,{children:ye(Se,{children:[ee(V,{children:"Variant"}),ee(V,{children:"SKU"}),ee(V,{children:"Price"}),ee(V,{children:"Stock"}),ee(V,{children:"Status"}),ee(V,{className:"af-text-right",children:"Actions"})]})}),ee(Je,{children:B.map(I=>ye(Se,{children:[ee(H,{className:"af-font-medium",children:ao(I)}),ee(H,{className:"af-text-muted-foreground",children:I.sku||"-"}),ee(H,{children:I.unit_amount!=null?ye("span",{children:[I.compare_at_amount!=null&&ee("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:j(I.compare_at_amount,I.currency)}),j(I.unit_amount,I.currency)]}):I.allow_custom_amount?ee("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),ee(H,{children:St(I)}),ee(H,{children:ee(te,{variant:I.active?"success":"secondary",children:I.active?"Active":"Inactive"})}),ee(H,{className:"af-text-right",children:ye("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[ee(h,{variant:"ghost",size:"sm",onClick:()=>oe(I),disabled:g,children:"Edit"}),ee(h,{variant:"ghost",size:"icon",onClick:()=>F(I),disabled:g,title:"Delete variant",children:ee(_l,{className:"af-h-4 af-w-4"})})]})})]},I.id))})]})]}),m&&ee("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m}),ee(Za,{open:w!==null,onOpenChange:I=>{!I&&!ne&&W(null)},children:ye(Fa,{children:[ye(Ua,{children:[ee($a,{children:w?.variant?"Edit variant":"Add variant"}),ee(Va,{children:"Price, markdown, and stock live on the variant."})]}),w&&ye("div",{className:"af-space-y-3",children:[w.variant?w.variant.option_values.length>0&&ye("div",{className:"af-text-sm",children:[ee("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),ao(w.variant)]}):Z.map(I=>ye("div",{className:"af-space-y-1",children:[ee(Re,{className:"af-text-xs af-text-muted-foreground",children:I.title}),ye(Ga,{value:w.optionValues[I.id]??"",onValueChange:U=>W(O=>O&&{...O,optionValues:{...O.optionValues,[I.id]:U}}),children:[ee(Oa,{children:ee(Ka,{placeholder:`Choose ${I.title}`})}),ee(Ba,{children:I.values.map(U=>ee(ot,{value:U.value,children:U.value},U.id))})]})]},I.id)),Me?ye("div",{className:"af-space-y-1",children:[ee(Re,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),ee("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):ye("div",{className:"af-flex af-gap-3",children:[ye("div",{className:"af-space-y-1",children:[ye(Re,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),ee(Q,{id:"variant-price",type:"number",min:"0",step:a,value:w.unitAmount,onChange:I=>W(U=>U&&{...U,unitAmount:I.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),ye("div",{className:"af-space-y-1",children:[ee(Re,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),ee(Q,{id:"variant-compare",type:"number",min:"0",step:a,value:w.compareAt,onChange:I=>W(U=>U&&{...U,compareAt:I.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),ye("div",{className:"af-space-y-1",children:[ee(Re,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),ee(Q,{id:"variant-sku",value:w.sku,onChange:I=>W(U=>U&&{...U,sku:I.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),ye("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[ye("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ee("input",{type:"checkbox",checked:w.tracked,onChange:I=>W(U=>U&&{...U,tracked:I.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),w.tracked&&ye("div",{className:"af-space-y-1 af-pl-6",children:[ye("div",{className:"af-flex af-items-end af-gap-3",children:[ye("div",{className:"af-space-y-1",children:[ee(Re,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),ee(Q,{id:"variant-onhand",type:"number",min:"0",step:"1",value:w.onHand,onChange:I=>W(U=>U&&{...U,onHand:I.target.value}),placeholder:ke!=null?"0":void 0,className:"af-w-[100px]"})]}),ye("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[ee("input",{type:"checkbox",checked:w.allowBackorder,onChange:I=>W(U=>U&&{...U,allowBackorder:I.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),ke!=null&&ye("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",ke," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),ye("div",{className:"af-space-y-1",children:[ye("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ee("input",{type:"checkbox",checked:w.active,onChange:I=>W(U=>U&&{...U,active:I.target.checked}),className:"af-h-4 af-w-4",disabled:We}),"Active (buyers can purchase this variant)"]}),We&&ee("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."})]}),K&&ee("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:K})]}),ye(Ma,{children:[ee(h,{variant:"outline",onClick:()=>W(null),disabled:ne,children:"Cancel"}),ye(h,{onClick:Ke,disabled:ne,children:[ne?ee(Rl,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,w?.variant?"Save":"Add variant"]})]})]})}),ee(Za,{open:ue!==null,onOpenChange:I=>{!I&&!g&&F(null)},children:ye(Fa,{children:[ye(Ua,{children:[ee($a,{children:"Delete variant?"}),ee(Va,{children:ue&&`"${ao(ue)}" will no longer be purchasable. Past orders are unaffected.`})]}),ye(Ma,{children:[ee(h,{variant:"outline",onClick:()=>F(null),disabled:g,children:"Cancel"}),ee(h,{variant:"destructive",onClick:xe,disabled:g,children:"Delete"})]})]})})]})}import{Fragment as mf,jsx as he,jsxs as Be}from"react/jsx-runtime";function ff(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,n)).toFixed(1))} ${s[n]}`}function jr({productsState:e,product:t,currency:s,onSaved:n,className:a}){let{createProduct:r,updateProduct:o,attachProductFile:c,attachProductFileFromUrl:d}=e,l=!!t,i=t?.currency??s,m=Xa(i)?"1":"0.01",v=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[g,u]=lt.useState(!1),[f,p]=lt.useState(null),b=lt.useRef(!0);lt.useEffect(()=>(b.current=!0,()=>{b.current=!1}),[]);let[x,N]=lt.useState(t?.name??""),[P,y]=lt.useState(t?.description??""),[R,_]=lt.useState(t?.allow_custom_amount?"custom":"fixed"),[k,S]=lt.useState(t?.unit_amount!=null?String(bt(t.unit_amount,i)):""),[C,T]=lt.useState(t?.min_amount!=null?String(bt(t.min_amount,i)):""),[w,W]=lt.useState(t?.max_amount!=null?String(bt(t.max_amount,i)):""),[K,$]=lt.useState(String(t?.max_quantity??10)),ne=lt.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(bt(t.unit_amount,i)):"",minAmount:t?.min_amount!=null?String(bt(t.min_amount,i)):"",maxAmount:t?.max_amount!=null?String(bt(t.max_amount,i)):"",maxQuantity:String(t?.max_quantity??10)}).current,[ie,ue]=lt.useState(t?.collect_shipping_address??!1),[F,Z]=lt.useState(t?.active??!0),[B,le]=lt.useState(t?.images??[]),[oe,Ke]=lt.useState(""),[xe,Me]=lt.useState(t?.fulfillment??null),[We,ke]=lt.useState(!1),[St,I]=lt.useState(""),[U,O]=lt.useState(null),be=lt.useRef(null),Y=g||We,pe=()=>{let de=oe.trim();if(de){if(B.includes(de)){p("This image URL is already added");return}le(Ae=>[...Ae,de]),Ke(""),p(null)}},Fe=de=>{le(Ae=>Ae.filter(pt=>pt!==de))},mt=async()=>{if(p(null),!x.trim()){p("Product name is required");return}let de=null,Ae=null,pt=null,La=!l||R!==ne.pricingMode||(R==="fixed"?k!==ne.unitAmount:C!==ne.minAmount||w!==ne.maxAmount),Kt=!l||K!==ne.maxQuantity,va=v||R==="fixed";if(!(v||!La))if(R==="fixed"){if(de=Zt(k,i),de===null||de<=0){p("Enter a valid price");return}}else{if(Ae=Zt(C,i),pt=Zt(w,i),Ae===null||pt===null){p("Enter valid minimum and maximum amounts");return}if(pt<Ae){p("Maximum amount must be at least the minimum amount");return}}let Qt=parseInt(K,10);if(va&&Kt&&(!Number.isFinite(Qt)||Qt<1)){p("Max quantity must be at least 1");return}try{u(!0);let nt;if(l&&t){let gt={name:x.trim(),description:P.trim()||null,images:B,collect_shipping_address:ie,active:F};!v&&La&&(gt.allow_custom_amount=R==="custom",R==="fixed"?gt.unit_amount=de:(gt.min_amount=Ae,gt.max_amount=pt)),va&&Kt&&(gt.max_quantity=Qt),nt=await o(t.id,gt),ne.pricingMode=nt.allow_custom_amount?"custom":"fixed",ne.unitAmount=nt.unit_amount!=null?String(bt(nt.unit_amount,i)):"",ne.minAmount=nt.min_amount!=null?String(bt(nt.min_amount,i)):"",ne.maxAmount=nt.max_amount!=null?String(bt(nt.max_amount,i)):"",ne.maxQuantity=String(nt.max_quantity)}else{let gt={name:x.trim(),allow_custom_amount:R==="custom",collect_shipping_address:ie,active:F};P.trim()&&(gt.description=P.trim()),B.length>0&&(gt.images=B),R==="fixed"?(gt.unit_amount=de,gt.max_quantity=Qt):(gt.min_amount=Ae,gt.max_amount=pt),nt=await r(gt)}if(!b.current)return;Me(nt.fulfillment),n?.(nt)}catch(nt){if(!b.current)return;p(nt instanceof Error?nt.message:"Failed to save product")}finally{b.current&&u(!1)}},ze=async de=>{let Ae=de.target.files?.[0];if(!(!Ae||!t))try{ke(!0),O(null);let pt=await c(t.id,Ae);if(!b.current)return;Me(pt.fulfillment),n?.(pt)}catch(pt){if(!b.current)return;O(pt instanceof Error?pt.message:"Failed to upload file")}finally{b.current&&(ke(!1),be.current&&(be.current.value=""))}},Pt=async()=>{let de=St.trim();if(!(!de||!t))try{ke(!0),O(null);let Ae=await d(t.id,de);if(!b.current)return;Me(Ae.fulfillment),I(""),n?.(Ae)}catch(Ae){if(!b.current)return;O(Ae instanceof Error?Ae.message:"Failed to fetch file")}finally{b.current&&ke(!1)}};return Be("div",{className:`af-space-y-6 ${a||""}`,children:[Be("div",{className:"af-space-y-2",children:[he(Re,{htmlFor:"product-name",children:"Name"}),he(Q,{id:"product-name",value:x,onChange:de=>N(de.target.value),placeholder:"My product"})]}),Be("div",{className:"af-space-y-2",children:[he(Re,{htmlFor:"product-description",children:"Description"}),he("textarea",{id:"product-description",value:P,onChange:de=>y(de.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"})]}),Be("div",{className:"af-space-y-2",children:[he(Re,{children:"Pricing"}),v?he("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):Be(mf,{children:[Be(Ga,{value:R,onValueChange:de=>_(de),children:[he(Oa,{className:"af-w-[260px]",children:he(Ka,{})}),Be(Ba,{children:[he(ot,{value:"fixed",children:"Fixed price"}),he(ot,{value:"custom",children:"Buyer chooses the amount"})]})]}),R==="fixed"?he("div",{className:"af-flex af-items-end af-gap-3",children:Be("div",{className:"af-space-y-1",children:[Be(Re,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",i.toUpperCase(),")"]}),he(Q,{id:"product-price",type:"number",min:"0",step:m,value:k,onChange:de=>S(de.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):Be("div",{className:"af-space-y-1",children:[Be("div",{className:"af-flex af-items-end af-gap-3",children:[Be("div",{className:"af-space-y-1",children:[Be(Re,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",i.toUpperCase(),")"]}),he(Q,{id:"product-min-amount",type:"number",min:"0",step:m,value:C,onChange:de=>T(de.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),Be("div",{className:"af-space-y-1",children:[Be(Re,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",i.toUpperCase(),")"]}),he(Q,{id:"product-max-amount",type:"number",min:"0",step:m,value:w,onChange:de=>W(de.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),he("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."})]}),Be("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",i.toUpperCase(),"), which follows the country of your payment account."]})]}),(v||R==="fixed")&&Be("div",{className:"af-space-y-1",children:[he(Re,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),he(Q,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:K,onChange:de=>$(de.target.value),className:"af-w-[140px]"})]})]}),Be("div",{className:"af-space-y-2",children:[he(Re,{children:"Images"}),he("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),Be("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[B.map(de=>Be(te,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[he("span",{className:"af-truncate",children:de}),he("button",{type:"button",onClick:()=>Fe(de),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:he(df,{className:"af-h-3 af-w-3"})})]},de)),B.length===0&&he("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),Be("div",{className:"af-flex af-gap-2",children:[he(Q,{type:"url",value:oe,onChange:de=>Ke(de.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:de=>{de.key==="Enter"&&(de.preventDefault(),pe())},disabled:g}),he(h,{type:"button",variant:"outline",onClick:pe,disabled:!oe.trim()||g,children:he(cf,{className:"af-h-4 af-w-4"})})]})]}),Be("div",{className:"af-space-y-2",children:[he(Re,{children:"Digital File"}),he("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?Be("div",{className:"af-space-y-3",children:[xe?.type==="download"&&Be("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[he(of,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),he("span",{className:"af-text-sm",children:xe.filename}),xe.size!=null&&Be("span",{className:"af-text-xs af-text-muted-foreground",children:["(",ff(xe.size),")"]})]}),xe?.type==="redirect"&&xe.url&&Be("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[he(lf,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Be("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",xe.url]})]}),Be("div",{className:"af-flex af-items-center af-gap-2",children:[he("input",{ref:be,type:"file",onChange:ze,className:"af-hidden",disabled:Y}),Be(h,{type:"button",variant:"outline",size:"sm",onClick:()=>be.current?.click(),disabled:Y,children:[We?he(Pl,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):he(uf,{className:"af-h-4 af-w-4 af-mr-1"}),xe?.type==="download"?"Replace file":"Upload file"]}),he("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),he(Q,{type:"url",value:St,onChange:de=>I(de.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:We}),he(h,{type:"button",variant:"outline",size:"sm",onClick:Pt,disabled:!St.trim()||Y,children:"Fetch from URL"})]}),U&&he("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:U})]}):he("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),Be("div",{className:"af-space-y-2",children:[he(Re,{children:"Settings"}),Be("div",{className:"af-space-y-2",children:[Be("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[he("input",{type:"checkbox",checked:ie,onChange:de=>ue(de.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),Be("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[he("input",{type:"checkbox",checked:F,onChange:de=>Z(de.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),l&&t&&Be("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[he(Re,{children:"Options & Variants"}),he(Wr,{productId:t.id,currency:i})]}),f&&he("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f}),he("div",{className:"af-flex af-items-center af-gap-2",children:Be(h,{type:"button",onClick:mt,disabled:Y,children:[g?he(Pl,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,l?"Save changes":"Create product"]})})]})}import*as Mt from"react";import{ChevronLeft as Ff,ChevronRight as Fl,Loader2 as Uf,Receipt as Mf,Search as $f,SlidersHorizontal as Vf}from"lucide-react";import*as yt from"react";var pf=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Gr({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=q(),[n,a]=yt.useState([]),[r,o]=yt.useState(0),[c,d]=yt.useState(!0),[l,i]=yt.useState(null),[m,v]=yt.useState(0),[g,u]=yt.useState(e),[f,p]=yt.useState(void 0),[b,x]=yt.useState(""),[N,P]=yt.useState(""),[y,R]=yt.useState(""),[_,k]=yt.useState(!1),[S,C]=yt.useState(!1),[T,w]=yt.useState(void 0),W=T?T.join(","):"",K=yt.useMemo(()=>{if(!W)return;let F=new Set(W.split(","));return pf.filter(Z=>!F.has(Z))},[W]),$=yt.useMemo(()=>{let F={};return f?F.status=f:K?F.excludeStatus=K:_||(F.excludeStatus=["pending","expired"]),b.trim()&&(F.customerEmail=b.trim()),N.trim()&&(F.from=N.trim()),y.trim()&&(F.to=y.trim()),S&&(F.unfulfilledOnly=!0),F},[f,K,_,b,N,y,S]),ne=yt.useRef(0),ie=yt.useCallback(async()=>{let F=++ne.current;try{d(!0),i(null);let Z={...$,limit:g,offset:m*g},B=await s.getOrders(Z);if(F!==ne.current)return;a(B.orders),o(B.total)}catch(Z){if(F!==ne.current)return;i(Z instanceof Error?Z:new Error("Failed to fetch orders"))}finally{F===ne.current&&d(!1)}},[s,m,g,$,t]);yt.useEffect(()=>{ie()},[ie]);let ue=Math.ceil(r/g);return{orders:n,total:r,isLoading:c,error:l,page:m,pageSize:g,hasNextPage:m<ue-1,hasPreviousPage:m>0,setPage:v,setPageSize:F=>{u(F),v(0)},status:f,setStatus:F=>{p(F),v(0)},statusIn:T,setStatusIn:F=>{w(F&&F.length>0?F:void 0),v(0)},customerEmail:b,setCustomerEmail:F=>{x(F),v(0)},from:N,setFrom:F=>{P(F),v(0)},to:y,setTo:F=>{R(F),v(0)},showAbandoned:_,setShowAbandoned:F=>{k(F),v(0)},unfulfilledOnly:S,setUnfulfilledOnly:F=>{C(F),v(0)},clearFilters:()=>{p(void 0),w(void 0),k(!1),C(!1),x(""),P(""),R(""),v(0)},filters:$,refetch:ie}}import*as kt from"react";import{ArrowLeft as bf,Check as Tl,ChevronLeft as yf,ChevronRight as hf,ClipboardCopy as xf,Copy as Sf,Download as wf,Loader2 as Jr,Mail as El,MoreHorizontal as Nf,Package as Rf,RotateCcw as _f,Truck as Pf,Undo2 as Il}from"lucide-react";import*as Cl from"react";import*as ws from"@radix-ui/react-popover";import{jsx as so}from"react/jsx-runtime";var Kr=ws.Root,Zr=ws.Trigger;var ir=Cl.forwardRef(({className:e,align:t="end",sideOffset:s=4,...n},a)=>so(ws.Portal,{children:so("div",{className:"aifeatures-admin",children:so(ws.Content,{ref:a,align:t,sideOffset:s,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),...n})})}));ir.displayName=ws.Content.displayName;import{jsx as Yr}from"react/jsx-runtime";var gf={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function vf(e){return gf[e]??e}function kl(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 Yr(te,{variant:kl(e),className:t,children:vf(e)})}function mn({status:e}){return Yr(fn,{status:e})}function Cn({order:e,className:t}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?Yr(te,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?Yr(te,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Ms(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as Lf,jsx as D,jsxs as se}from"react/jsx-runtime";var Ol="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",pn="af-text-xs af-text-muted-foreground";function no(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 Cf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bl(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 Xr=24,kf=["paid","partially_refunded"],Tf=["paid","partially_refunded","disputed"],Ef=/^[A-Za-z0-9 _-]*$/,Dl=100;function oo(e,t,s,n,a){let r=kf.includes(n);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${Xr} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${Xr} tries used). Nothing is being retried while the order is ${n.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?s<Xr&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:s<Xr&&e==="buyer"&&!a?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${s} attempt${s===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${n==="refunded"?"because the order was refunded":n==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function Al({title:e,recipient:t,status:s,attempts:n,side:a,orderStatus:r,action:o,delivery:c}){if(c)return se("div",{children:[D(hs,{deliveries:[c]}),o&&D("div",{className:"af-mt-2",children:o})]});let d=oo(a,s,n,r,t);return se("div",{children:[se("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[se("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(te,{variant:d.variant,className:"af-shrink-0",children:d.label})]}),d.detail&&D("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:d.detail}),o&&D("div",{className:"af-mt-2",children:o})]})}function Ll(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let s=Cf(e.address)?e.address:null;if(s){for(let a of["line1","line2"]){let r=s[a];typeof r=="string"&&r&&t.push(r)}let n=["city","state","postal_code"].map(a=>s[a]).filter(a=>typeof a=="string"&&!!a).join(", ");n&&t.push(n),typeof s.country=="string"&&s.country&&t.push(s.country)}return t.length>0?t:Object.entries(e).map(([n,a])=>`${n}: ${Bl(a)}`)}function If(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function lo({value:e,label:t,children:s,className:n,size:a="icon"}){let[r,o]=kt.useState(!1);if(!If())return null;let c=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},d=r?D(Tl,{className:"af-h-3 af-w-3"}):D(Sf,{className:"af-h-3 af-w-3"});return a==="icon"?D(h,{variant:"ghost",size:"icon",className:G("af-h-6 af-w-6 af-shrink-0",n),onClick:c,title:t,"aria-label":t,children:d}):se(h,{variant:"outline",size:"sm",className:n,onClick:c,"aria-label":t,children:[r?D(Tl,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):D(xf,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":s]})}function ro({label:e,value:t}){return se("div",{children:[D("div",{className:pn,children:e}),se("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 Df({src:e}){let[t,s]=kt.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(Rf,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):D("img",{src:e,alt:"","aria-hidden":"true",onError:()=>s(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Ns({title:e,action:t,children:s,className:n}){return se("section",{className:G("af-rounded-lg af-border af-p-4",n),children:[se("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[D("h4",{className:Ol,children:e}),t]}),D("div",{className:"af-mt-3",children:s})]})}function Sa({label:e,emphasis:t,divider:s,children:n}){return se("div",{className:G("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[D("span",{className:t?"af-text-base af-font-semibold":pn,children:e}),D("span",{className:G("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:n})]})}function io({onSelect:e,disabled:t,icon:s,children:n}){return se(h,{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:s}),n]})}function Af(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 ${j(Hr(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(a=>a.kind==="purchase_receipt"),n=s?Er(s):oo("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(a=>a.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${n.label.toLowerCase()}`,at:null,tone:n.variant==="destructive"?"destructive":n.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(a=>a.kind==="merchant_sale"),n=s?Er(s):oo("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(a=>a.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${n.label.toLowerCase()}`,at:null,tone:n.variant==="destructive"?"destructive":n.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${j(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 Qr({order:e,onBack:t,onRefund:s,onOrderUpdated:n,allowFulfillment:a=!1,onPrevOrder:r,onNextOrder:o,hasPrevOrder:c=!1,hasNextOrder:d=!1}){let{api:l}=q(),[i,m]=kt.useState(e),[v,g]=kt.useState(null),[u,f]=kt.useState(null),[p,b]=kt.useState(!1),[x,N]=kt.useState(!1),[P,y]=kt.useState(!1),[R,_]=kt.useState(!1),[k,S]=kt.useState(""),[C,T]=kt.useState(!1),[w,W]=kt.useState(null),[K,$]=kt.useState(!1),[ne,ie]=kt.useState(""),[ue,F]=kt.useState([]),[Z,B]=kt.useState(!1),[le,oe]=kt.useState(!1),[Ke,xe]=kt.useState(null);kt.useEffect(()=>{m(e)},[e]);let Me=L=>{let Ve=L.id===i.id&&L.email_deliveries===void 0?{...L,email_deliveries:i.email_deliveries}:L;m(Ve),n?.(Ve)},We=Object.entries(i.metadata??{}),ke=Math.max(0,Hr(i)-i.amount_refunded),St=(i.status==="paid"||i.status==="partially_refunded")&&ke>0,I=i.exclusive_tax_total!=null,U=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)),be=ue.reduce((L,Ve)=>L+U(i.line_items[Ve]??{}),0)+(Z?O:0),Y=i.tax_total??0,pe=Math.max(0,(i.exclusive_tax_total??0)-i.line_items.reduce((L,Ve)=>L+(Ve.exclusiveTax??0),0)),Fe=I?Z&&O>0?pe:0:i.automatic_tax&&i.tax_behavior==="exclusive"&&Y>0&&i.amount_total+(i.shipping_total??0)>0?Math.min(Math.max(0,Y-(i.tax_refunded??0)),Math.round(Y*be/(i.amount_total+(i.shipping_total??0)))):0,mt=i.source==="subscription"&&(i.credit_applied??0)>0&&i.line_items.length===1?Math.min(be+Fe,ke):be+Fe,ze=ue.length>0||Z,Pt=ze?mt:Zt(ne,i.currency),de=Xa(i.currency)?"1":"0.01",Ae=async()=>{try{b(!0),g(null),f(null),await l.resendOrderReceipt(i.id);let L=await l.getOrder(i.id);Me(L),f("Receipt email queued.")}catch(L){g(L instanceof Error?L.message:"Failed to resend receipt")}finally{b(!1)}},pt=async()=>{try{N(!0),g(null),f(null);let L=await l.resetOrderDownloads(i.id);Me(L),y(!1),f("Download count reset.")}catch(L){g(L instanceof Error?L.message:"Failed to reset downloads")}finally{N(!1)}},La=i.line_items.some(L=>L.collectShippingAddress===!0&&!L.refunded&&!L.unavailableReason),Kt=typeof i.merchant_fulfilled_at=="string",va=Tf.includes(i.status)||i.status==="refunded"&&i.line_items.some(L=>L.collectShippingAddress===!0&&L.amountNet===0&&!L.refunded&&!L.unavailableReason),Qt=k.trim(),nt=Ef.test(Qt)&&Qt.length<=Dl,gt=async L=>{try{T(!0),W(null),f(null);let Ve=await l.setOrderFulfillment(i.id,{fulfilled:L,...L&&Qt?{trackingNumber:Qt}:{}});Me(Ve),S(""),f(L?"Marked as shipped.":"Marked as not shipped.")}catch(Ve){Ve instanceof Ft&&Ve.status===409?W(`This order is ${i.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):W(Ve instanceof Error?Ve.message:"Failed to update the order")}finally{T(!1)}},os=()=>{xe(null),ie(String(bt(ke,i.currency))),F([]),B(!1),$(!0)},ln=L=>F(Ve=>Ve.includes(L)?Ve.filter(ya=>ya!==L):[...Ve,L]),ba=async(L,Ve)=>{if(s)try{oe(!0),xe(null),await s(i,L,Ve);let ya=await l.getOrder(i.id);Me(ya),$(!1),f("Refund issued.")}catch(ya){xe(ya instanceof Error?ya.message:"Refund failed")}finally{oe(!1)}},Hi=async()=>{if(ze){if(mt<=0){xe("The lines you picked were charged nothing");return}if(mt>ke){xe(`That selection exceeds the refundable remainder (${j(ke,i.currency)})`);return}await ba(mt,{...ue.length>0?{line_items:[...ue].sort((Ve,ya)=>Ve-ya)}:{},...Z?{shipping:!0}:{}});return}let L=Zt(ne,i.currency);if(L===null||L<=0){xe("Enter a valid refund amount");return}if(L>ke){xe(`Amount exceeds the refundable remainder (${j(ke,i.currency)})`);return}await ba(L,{amount:L})},z=()=>ba(ke,{full:!0}),it=!i.subscription_history_only&&i.fulfillment_type==="download",ys=!i.subscription_history_only&&a&&La,zi=Af(i),X=i.shipping_address?Ll(i.shipping_address).join(`
4
+ `):"",la=i.shipping_total!=null,qi=i.exclusive_tax_total??(i.automatic_tax&&i.tax_behavior==="exclusive"?i.tax_total??0:0),Xo=i.exclusive_tax_total!=null?Math.max(0,(i.tax_total??0)-qi):i.automatic_tax&&i.tax_behavior==="exclusive"?0:i.tax_total??0,Qo=qi>0,Fu=Xo>0,el=i.amount_subtotal!=null||la||Qo||(i.discount_total??0)>0,Yn=[];return i.subscription_history_only||Yn.push(D(io,{icon:p?D(Jr,{className:"af-h-4 af-w-4 af-animate-spin"}):D(El,{className:"af-h-4 af-w-4"}),disabled:p||i.fulfillment_status!=="fulfilled",onSelect:()=>{_(!1),Ae()},children:"Resend receipt"},"resend")),it&&Yn.push(D(io,{icon:D(_f,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{_(!1),y(!0)},children:"Reset download count"},"reset")),St&&Yn.push(se("div",{children:[D(io,{icon:D(Il,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{_(!1),os()},children:"Refund\u2026"}),!s&&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")),se("div",{children:[se("div",{className:"af-mb-6",children:[se(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[D(bf,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),se("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[se("div",{className:"af-min-w-0",children:[se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[D("h3",{className:"af-text-xl af-font-semibold",children:Ms(i)}),D(fn,{status:i.status}),a&&!i.subscription_history_only&&D(Cn,{order:i}),i.is_test&&D(te,{variant:"outline",children:"Test"})]}),se("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",no(i.created_at)]}),i.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."})]}),se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||o)&&se("div",{className:"af-flex af-items-center",children:[D(h,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!c,"aria-label":"Previous order",children:D(yf,{className:"af-h-4 af-w-4"})}),D(h,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!d,"aria-label":"Next order",children:D(hf,{className:"af-h-4 af-w-4"})})]}),ys&&(Kt?se("div",{className:"af-flex af-items-center af-gap-1",children:[se("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",i.merchant_fulfilled_at?` \xB7 ${no(i.merchant_fulfilled_at)}`:""]}),va&&se(h,{variant:"ghost",size:"sm",onClick:()=>gt(!1),disabled:C,children:[C?D(Jr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(Il,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):va?se("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[D(Q,{value:k,onChange:L=>S(L.target.value),placeholder:"Tracking number (optional)",maxLength:Dl,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:C}),se(h,{variant:"default",className:"af-shrink-0",onClick:()=>gt(!0),disabled:C||!nt,children:[C?D(Jr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(Pf,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Yn.length>0&&se(Kr,{open:R,onOpenChange:_,children:[D(Zr,{asChild:!0,children:D(h,{variant:"outline",size:"icon","aria-label":"More actions",children:D(Nf,{className:"af-h-4 af-w-4"})})}),D(ir,{children:D("div",{className:"af-space-y-0.5",children:Yn})})]})]})]}),ys&&!Kt&&!nt&&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."}),w&&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:w}),u&&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:u}),v&&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:v})]}),se("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[se("div",{className:"af-space-y-6",children:[i.line_items.length>0&&D(Ns,{title:"Items",children:D("ul",{className:"af-space-y-3",children:i.line_items.map((L,Ve)=>{let ya=typeof L.name=="string"&&L.name?L.name:"Item",tl=typeof L.quantity=="number"&&L.quantity>0?L.quantity:1,al=typeof L.unitAmount=="number";return se("li",{className:"af-flex af-items-start af-gap-3",children:[D(Df,{src:typeof L.imageUrl=="string"&&L.imageUrl?L.imageUrl:void 0}),se("div",{className:"af-min-w-0 af-flex-1",children:[se("div",{className:"af-text-sm af-font-medium",children:[ya,typeof L.variantTitle=="string"&&L.variantTitle&&se("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",L.variantTitle]})]}),se("div",{className:pn,children:[tl," \xD7"," ",al?j(L.unitAmount,i.currency):"\u2014"]}),L.unavailableReason==="oversold"&&!L.refunded&&D(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&&D(te,{variant:"secondary",className:"af-mt-1",children:L.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),D("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof L.amountNet=="number"||al?j(L.amountNet??L.unitAmount*tl,i.currency):"\u2014"})]},Ve)})})}),We.length>0&&D(Ns,{title:"Order details",children:D("dl",{className:"af-space-y-2",children:We.map(([L,Ve])=>se("div",{children:[D("dt",{className:G(pn,"af-capitalize"),children:L.replace(/_/g," ")}),D("dd",{className:"af-text-sm af-break-words",children:Bl(Ve)})]},L))})}),D(Ns,{title:"Totals",children:se("div",{className:"af-w-full",children:[el&&D(Sa,{label:"Subtotal",children:j(i.amount_subtotal??i.amount_total+(i.discount_total??0),i.currency)}),(i.discount_total??0)>0&&se(Sa,{label:"Discount",children:["\u2212",j(i.discount_total,i.currency)]}),la&&D(Sa,{label:"Shipping",children:i.shipping_total===0?"Free":j(i.shipping_total??0,i.currency)}),Qo&&D(Sa,{label:"Tax",children:j(qi,i.currency)}),D(Sa,{label:"Total",emphasis:!0,divider:el,children:j(Us(i),i.currency)}),(i.credit_applied??0)>0&&se(Sa,{label:"Credit applied",children:["\u2212",j(i.credit_applied,i.currency)]}),i.amount_paid!=null&&D(Sa,{label:"Amount paid",children:j(i.amount_paid,i.currency)}),Fu&&D(Sa,{label:"incl. tax",children:j(Xo,i.currency)}),i.base_currency!=null&&i.base_amount_total!=null&&se(Sa,{label:"Your price",children:[j(i.base_amount_total,i.base_currency),se("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",i.currency.toUpperCase()]})]}),i.amount_refunded>0&&se(Lf,{children:[se(Sa,{label:"Refunded",children:["\u2212",j(i.amount_refunded,i.currency),(i.shipping_refunded??0)>0&&se("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",j(i.shipping_refunded??0,i.currency)," ","shipping"]})]}),D(Sa,{label:"Net",children:D("span",{className:"af-font-medium",children:j(Math.max(0,Hr(i)-i.amount_refunded),i.currency)})})]})]})}),i.application_fee_state&&se(Ns,{title:"Platform fee",children:[i.application_fee_original!=null&&D(Sa,{label:"Collected",children:j(i.application_fee_original,i.application_fee_currency??i.currency)}),i.application_fee_returned!=null&&D(Sa,{label:"Returned",children:j(i.application_fee_returned,i.application_fee_currency??i.currency)}),i.application_fee_retained!=null&&D(Sa,{label:"Retained",children:j(i.application_fee_retained,i.application_fee_currency??i.currency)}),i.application_fee_state!=="complete"&&D("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"})]}),D(Ns,{title:"Timeline",children:D("ol",{className:"af-space-y-3",children:zi.map(L=>se("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",L.tone==="destructive"?"af-bg-destructive":L.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),se("div",{className:"af-min-w-0",children:[D("div",{className:"af-text-sm af-break-words",children:L.text}),L.at&&D("div",{className:"af-text-xs af-text-muted-foreground",children:no(L.at)})]})]},L.key))})})]}),se("div",{className:"af-space-y-6",children:[D(Ns,{title:"Customer",children:se("div",{className:"af-space-y-2",children:[se("div",{children:[D("div",{className:pn,children:"Email"}),se("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:i.customer_email||D("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),i.customer_email&&D(lo,{value:i.customer_email,label:"Copy email"})]})]}),i.customer_name&&se("div",{children:[D("div",{className:pn,children:"Name"}),D("div",{className:"af-text-sm",children:i.customer_name})]}),i.customer&&se("div",{children:[D("div",{className:pn,children:"Customer record"}),se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[D("span",{className:"af-break-all af-text-sm",children:i.customer.name||i.customer.email}),D(te,{variant:"secondary",children:"Linked"})]})]})]})}),i.shipping_address&&D(Ns,{title:"Ship to",action:D(lo,{value:X,label:"Copy address",size:"sm",children:"Copy address"}),children:D("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Ll(i.shipping_address).map((L,Ve)=>D("div",{children:L},Ve))})}),i.subscription_history_only?D(Ns,{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."})}):se(Ns,{title:"Emails",children:[D(hs,{deliveries:i.email_deliveries?.filter(L=>!["purchase_receipt","merchant_sale"].includes(L.kind)),problemsOnly:!0,className:"af-mb-4"}),se("div",{className:"af-space-y-4",children:[D(Al,{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:se(h,{variant:"outline",size:"sm",onClick:Ae,disabled:p||i.fulfillment_status!=="fulfilled",children:[p?D(Jr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(El,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),D(Al,{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})]})]}),it&&D(Ns,{title:"Download",children:se("div",{className:"af-space-y-2",children:[se("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[D(wf,{className:"af-h-4 af-w-4"}),se("span",{children:["Downloaded ",i.download_count," time",i.download_count===1?"":"s"]})]}),i.download_url&&D("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"})]})}),se("details",{className:"af-rounded-lg af-border af-p-4",children:[D("summary",{className:G(Ol,"af-cursor-pointer af-select-none"),children:"Technical details"}),se("div",{className:"af-mt-3 af-space-y-2",children:[D(ro,{label:"Order ID",value:i.id}),i.stripe_checkout_session_id&&D(ro,{label:"Checkout session",value:i.stripe_checkout_session_id}),i.stripe_payment_intent_id&&D(ro,{label:"Payment",value:i.stripe_payment_intent_id})]})]})]})]}),D(Za,{open:P,onOpenChange:L=>{!L&&!x&&y(!1)},children:se(Fa,{children:[se(Ua,{children:[D($a,{children:"Reset download count?"}),D(Va,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),se(Ma,{children:[D(h,{variant:"outline",onClick:()=>y(!1),disabled:x,children:"Cancel"}),D(h,{onClick:pt,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),D(Za,{open:K,onOpenChange:L=>{!L&&!le&&$(!1)},children:se(Fa,{children:[se(Ua,{children:[D($a,{children:"Refund order"}),se(Va,{children:["Refund up to ",j(ke,i.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),se("div",{className:"af-space-y-4",children:[(i.line_items.length>0||O>0)&&se("div",{className:"af-space-y-2",children:[D(Re,{children:"Items"}),se("div",{className:"af-space-y-2",children:[i.line_items.map((L,Ve)=>{let ya=L.refunded===!0;return se("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[D("input",{type:"checkbox",checked:ue.includes(Ve),onChange:()=>ln(Ve),disabled:le||ya||!!L.unavailableReason||U(L)<=0,className:"af-h-4 af-w-4"}),se("span",{className:ya?"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}`:""]}),D("span",{className:"af-ml-auto af-text-muted-foreground",children:ya?"Refunded":j(U(L),i.currency)})]},Ve)}),O>0&&se("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[D("input",{type:"checkbox",checked:Z,onChange:L=>B(L.target.checked),disabled:le,className:"af-h-4 af-w-4"}),D("span",{children:"Shipping"}),D("span",{className:"af-ml-auto af-text-muted-foreground",children:j(O,i.currency)})]})]})]}),se("div",{className:"af-space-y-2",children:[se(Re,{htmlFor:"refund-amount",children:["Amount (",i.currency.toUpperCase(),")"]}),D(Q,{id:"refund-amount",type:"number",min:"0",step:de,value:ze?String(bt(mt,i.currency)):ne,onChange:L=>ie(L.target.value),disabled:le||ze}),ze&&D("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Ke&&D("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Ke}),se(Ma,{children:[D(h,{variant:"outline",onClick:()=>$(!1),disabled:le,children:"Cancel"}),D(h,{variant:"outline",onClick:z,disabled:le,children:"Refund everything"}),D(h,{variant:"destructive",onClick:Hi,disabled:le,children:le?"Refunding...":Pt!==null&&Pt>0?`Refund ${j(Pt,i.currency)}`:"Refund"})]})]})})]})}import*as ei from"react";import{ArrowLeft as Of,RefreshCw as Bf}from"lucide-react";import{jsx as wa,jsxs as Zs}from"react/jsx-runtime";function Nt({title:e,onBackToWebsite:t,hideBackButton:s=!1,children:n,className:a}){let r=ei.useRef(null);return ei.useEffect(()=>{r.current?.focus()},[]),Zs("div",{className:G("af-bg-background",a),children:[Zs("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:[wa("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!s&&Zs(h,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[wa(Of,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),wa("div",{className:"af-p-4",children:n})]})}function J({className:e}){return wa("div",{"aria-hidden":"true",className:G("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function et({label:e,children:t,detail:s,valueClassName:n}){return Zs("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[wa("div",{className:"af-text-xs af-text-muted-foreground",children:e}),wa("div",{className:G("af-mt-1 af-text-lg af-font-semibold",n),children:t}),s&&wa("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function Lt({message:e,onRetry:t}){return Zs("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[wa("span",{children:e}),Zs(h,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[wa(Bf,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function sa({icon:e,children:t}){return Zs("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,wa("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function Ys({icon:e,heading:t,body:s,action:n,className:a,children:r}){return Zs("div",{className:G("af-px-6 af-py-10 af-text-center",a),children:[wa(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),wa("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),wa("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:s}),n&&wa(h,{type:"button",className:"af-mt-4",onClick:n.onClick,children:n.label}),r]})}import{jsx as M,jsxs as Ee}from"react/jsx-runtime";var Hf={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Ul={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Ml(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function $l(e){let t=Array.isArray(e.line_items)?e.line_items:[],s=t[0];if(!s)return"\u2014";let n=typeof s.name=="string"&&s.name?s.name:"Item",a=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,r=a>1?`${n} \xD7${a}`:n;return t.length>1?`${r} +${t.length-1} more`:r}function ti(e){return e.customer?.name||e.customer_name||null}function zf({onRefund:e,className:t,refreshKey:s,initialOrderId:n,showFulfillment:a=!1,emptyMessage:r,onDetailOpenChange:o,maxRows:c,onViewAll:d}){let l=typeof c=="number",{api:i}=q(),m=Gr({refreshKey:s}),{orders:v,total:g,isLoading:u,error:f,page:p,pageSize:b,hasNextPage:x,hasPreviousPage:N,setPage:P,setPageSize:y,customerEmail:R,setCustomerEmail:_,setStatusIn:k,from:S,setFrom:C,to:T,setTo:w,showAbandoned:W,setShowAbandoned:K,setUnfulfilledOnly:$,filters:ne,refetch:ie}=m,ue=Mt.useCallback(()=>i.exportOrdersCsv(ne),[i,ne]),[F,Z]=Mt.useState("list"),[B,le]=Mt.useState(null),[oe,Ke]=Mt.useState(""),[xe,Me]=Mt.useState(""),[We,ke]=Mt.useState(!l&&a?"needs_shipping":"all"),[St,I]=Mt.useState(!1),[U,O]=Mt.useState(!!n&&!l),[be,Y]=Mt.useState(null);Mt.useEffect(()=>{if(!n||l)return;let X=!1;return O(!0),Y(null),i.getOrder(n).then(la=>{X||(le(la),Z("detail"))}).catch(()=>{X||Y("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{X||O(!1)}),()=>{X=!0}},[i,n,l]);let pe=Mt.useCallback(X=>{ke(X);let la=Ul[X];k(la.statusIn),$(la.unfulfilledOnly)},[k,$]);Mt.useEffect(()=>{a&&!l&&$(!0)},[]);let Fe=Mt.useRef(!a);Mt.useEffect(()=>{Fe.current||u||(Fe.current=!0,v.length===0&&pe("all"))},[u,v.length,pe]);let mt=F==="detail"&&!!B;Mt.useEffect(()=>{o?.(mt)},[mt,o]);let ze=(S?1:0)+(T?1:0)+(W?1:0),Pt=ze>0||!!R||!!xe,de=!!S&&!!T&&S>T,Ae=!l||!!d,pt=X=>{if(l){d?.();return}le(X),Z("detail")},La=()=>{Z("list"),le(null),ie()},Kt=X=>{let la=X.trim();if(!la){Me(""),R&&_("");return}if(la.startsWith("#")||/^\d+$/.test(la)){Me(la),R&&_("");return}Me(""),_(la)},va=()=>{Ke(""),Me(""),_(""),C(""),w(""),K(!1),I(!1)},Qt=xe.replace(/^#/,"").toLowerCase(),nt=Qt?v.filter(X=>String(X.order_number??"")===Qt||X.id.toLowerCase().startsWith(Qt)):v,gt=l?nt.slice(0,c):nt,os=B?v.findIndex(X=>X.id===B.id):-1,ln=os>0,ba=os>=0&&os<v.length-1;if(U)return M("div",{className:t,children:M("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:M(Uf,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(F==="detail"&&B)return M("div",{className:t,children:M(Qr,{order:B,onBack:La,onRefund:e,onOrderUpdated:X=>le(X),allowFulfillment:a,onPrevOrder:ln?()=>le(v[os-1]):void 0,onNextOrder:ba?()=>le(v[os+1]):void 0,hasPrevOrder:ln,hasNextOrder:ba},B.id)});let z=Ee("div",{className:"af-mb-4 af-space-y-3",children:[be&&M("p",{className:"af-text-xs af-text-muted-foreground",children:be}),Ee("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(X=>M("button",{type:"button","aria-pressed":We===X,onClick:()=>pe(X),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",We===X?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Hf[X]},X))}),Ee("div",{className:"af-relative af-w-full af-max-w-xs",children:[M($f,{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(Q,{type:"text",value:oe,onChange:X=>Ke(X.target.value),onBlur:()=>Kt(oe),onKeyDown:X=>{X.key==="Enter"&&(X.preventDefault(),Kt(oe))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),Ee(h,{type:"button",variant:ze>0?"secondary":"ghost",size:"sm",onClick:()=>I(X=>!X),"aria-expanded":St,children:[M(Vf,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",ze>0&&M(te,{variant:"secondary",className:"af-ml-2",children:ze})]}),Pt&&M(h,{type:"button",variant:"ghost",size:"sm",onClick:va,children:"Clear filters"}),M(ta,{fetchCsv:ue,filename:"orders",disabled:!!xe,className:"af-ml-auto"})]}),(St||!!S||!!T)&&Ee("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(Re,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),M(Q,{id:"orders-from",type:"date",value:S,max:T||void 0,onChange:X=>C(X.target.value),className:"af-w-[170px]"}),M(Re,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),M(Q,{id:"orders-to",type:"date",value:T,min:S||void 0,onChange:X=>w(X.target.value),className:"af-w-[170px]"}),!Ul[We].statusIn&&M(h,{type:"button",variant:W?"secondary":"ghost",size:"sm",onClick:()=>K(!W),"aria-pressed":W,children:W?"Hide abandoned":"Show abandoned"})]}),de&&M("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(u)return Ee("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(X=>Ee("div",{className:"af-rounded-md af-border af-p-3",children:[Ee("div",{className:"af-flex af-items-center af-justify-between",children:[M(J,{className:"af-h-4 af-w-16"}),M(J,{className:"af-h-4 af-w-14"})]}),M(J,{className:"af-mt-2 af-h-3 af-w-40"}),M(J,{className:"af-mt-2 af-h-3 af-w-24"})]},X))}),M("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ee(Ze,{children:[M(Ye,{children:Ee(Se,{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(Je,{"aria-hidden":"true",children:[0,1,2,3,4].map(X=>Ee(Se,{children:[M(H,{children:M(J,{className:"af-h-4 af-w-14"})}),M(H,{children:M(J,{className:"af-h-4 af-w-24"})}),M(H,{children:M(J,{className:"af-h-4 af-w-40"})}),M(H,{children:M(J,{className:"af-h-4 af-w-32"})}),M(H,{children:M(J,{className:"af-ml-auto af-h-4 af-w-16"})}),M(H,{children:M(J,{className:"af-h-5 af-w-16"})}),M(H,{})]},X))})]})}),M("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(f)return Ee("div",{className:t,children:[l?null:z,Ee("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(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>ie(),children:"Try again"})]})]});let it=We!=="all";if(nt.length===0&&p===0)return Pt||it?Ee("div",{className:t,children:[!l&&z,M(sa,{children:"No orders match these filters."})]}):M("div",{className:t,children:M(Ys,{icon:Mf,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!l&&M(h,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>K(!0),children:"Show abandoned checkouts"})})});let ys=p*b+1,zi=Math.min((p+1)*b,g);return Ee("div",{className:t,children:[l?null:z,M("div",{className:"af-space-y-3 lg:af-hidden",children:gt.map(X=>Ee("button",{type:"button",onClick:()=>pt(X),disabled:!Ae,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ae?" hover:af-bg-muted/50":""}`,children:[Ee("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[M("span",{className:"af-font-medium",children:Ms(X)}),M("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:j(Us(X),X.currency)})]}),Ee("div",{className:"af-mt-1 af-min-w-0",children:[Ee("div",{className:"af-truncate af-text-sm",children:[X.customer_email||M("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),ti(X)&&Ee("span",{className:"af-text-muted-foreground",children:[" \xB7 ",ti(X)]})]}),M("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:$l(X)}),X.amount_refunded>0&&Ee("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(X.amount_refunded,X.currency)," refunded"]})]}),Ee("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[M(fn,{status:X.status}),M(tr,{deliveries:X.email_deliveries}),X.is_test&&M(te,{variant:"outline",children:"Test"}),a&&M(Cn,{order:X}),M("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Ml(X.created_at)})]})]},X.id))}),M("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ee(Ze,{children:[M(Ye,{children:Ee(Se,{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(Je,{children:gt.map(X=>Ee(Se,{onClick:Ae?()=>pt(X):void 0,className:Ae?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[Ee(H,{className:"af-whitespace-nowrap af-font-medium",children:[M("button",{type:"button",onClick:la=>{la.stopPropagation(),pt(X)},disabled:!Ae,"aria-label":`Open order ${Ms(X)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ae?" hover:af-underline":""}`,children:Ms(X)}),X.is_test&&M(te,{variant:"outline",className:"af-ml-2",children:"Test"})]}),M(H,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ml(X.created_at)}),Ee(H,{className:"af-max-w-[220px]",children:[M("div",{className:"af-truncate",children:X.customer_email||M("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),ti(X)&&M("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ti(X)})]}),M(H,{className:"af-max-w-[220px]",children:M("div",{className:"af-truncate af-text-muted-foreground",children:$l(X)})}),Ee(H,{className:"af-whitespace-nowrap af-text-right",children:[M("div",{className:"af-font-medium af-tabular-nums",children:j(Us(X),X.currency)}),X.amount_refunded>0&&Ee("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(X.amount_refunded,X.currency)," ","refunded"]})]}),M(H,{children:Ee("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[M(fn,{status:X.status}),M(tr,{deliveries:X.email_deliveries}),a&&M(Cn,{order:X})]})}),M(H,{className:"af-w-8 af-text-right",children:M(Fl,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},X.id))})]})}),l?null:Ee("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Ee("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[M("span",{children:Qt?`${nt.length} matching this page`:`Showing ${ys}-${zi} of ${g}`}),Ee(Ga,{value:String(b),onValueChange:X=>y(Number(X)),children:[M(Oa,{className:"af-w-[70px] af-h-8",children:M(Ka,{})}),Ee(Ba,{children:[M(ot,{value:"10",children:"10"}),M(ot,{value:"25",children:"25"}),M(ot,{value:"50",children:"50"}),M(ot,{value:"100",children:"100"})]})]}),M("span",{children:"per page"})]}),Ee("div",{className:"af-flex af-items-center af-gap-2",children:[Ee(h,{variant:"outline",size:"sm",onClick:()=>P(p-1),disabled:!N,children:[M(Ff,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ee(h,{variant:"outline",size:"sm",onClick:()=>P(p+1),disabled:!x,children:["Next",M(Fl,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function Js(e){return M(zf,{...e},e.maxRows==null?"full":"compact")}import*as kn from"react";import{ChevronLeft as Gf,ChevronRight as Kf,Eye as Zf,Search as Yf,Users as Jf}from"lucide-react";import*as Na from"react";function ai({initialPageSize:e=25}={}){let{api:t}=q(),[s,n]=Na.useState([]),[a,r]=Na.useState(0),[o,c]=Na.useState(!0),[d,l]=Na.useState(null),[i,m]=Na.useState(0),[v,g]=Na.useState(e),[u,f]=Na.useState(""),p=Na.useRef(0),b=Na.useCallback(async()=>{let N=++p.current;try{c(!0),l(null);let P={limit:v,offset:i*v};u.trim()&&(P.email=u.trim());let y=await t.getCustomers(P);if(N!==p.current)return;n(y.customers),r(y.total)}catch(P){if(N!==p.current)return;l(P instanceof Error?P:new Error("Failed to fetch customers"))}finally{N===p.current&&c(!1)}},[t,i,v,u]);Na.useEffect(()=>{b()},[b]);let x=Math.ceil(a/v);return{customers:s,total:a,isLoading:o,error:d,page:i,pageSize:v,hasNextPage:i<x-1,hasPreviousPage:i>0,setPage:m,setPageSize:N=>{g(N),m(0)},email:u,setEmail:N=>{f(N),m(0)},refetch:b}}import*as gn from"react";import{ArrowLeft as qf,Loader2 as Wf}from"lucide-react";import{jsx as qe,jsxs as Yt}from"react/jsx-runtime";function Vl(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 jf(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&t.push(s),e.country&&t.push(e.country),t}function si({customer:e,onBack:t,className:s}){let{api:n}=q(),[a,r]=gn.useState(null),[o,c]=gn.useState([]),[d,l]=gn.useState(!0),[i,m]=gn.useState(null);gn.useEffect(()=>{let u=!1;return l(!0),m(null),Promise.all([n.getCustomer(e.id),n.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([f,p])=>{u||(r(f),c(p.orders))}).catch(f=>{u||m(f instanceof Error?f.message:"Failed to load customer")}).finally(()=>{u||l(!1)}),()=>{u=!0}},[n,e.id,e.email]);let v=a?.addresses??[],g=a?.order_count??o.length;return Yt("div",{className:s,children:[Yt("div",{className:"af-mb-6",children:[Yt(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[qe(qf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),qe("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),Yt("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Vl(e.created_at)]})]}),d?qe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:qe(Wf,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):i?qe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i}):Yt("div",{className:"af-space-y-6",children:[qe(hs,{deliveries:a?.email_deliveries}),Yt("div",{children:[qe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),Yt("div",{className:"af-space-y-1 af-text-sm",children:[Yt("div",{className:"af-flex af-gap-2",children:[qe("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),qe("span",{children:e.email})]}),e.name&&Yt("div",{className:"af-flex af-gap-2",children:[qe("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),qe("span",{children:e.name})]}),e.phone&&Yt("div",{className:"af-flex af-gap-2",children:[qe("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),qe("span",{children:e.phone})]}),Yt("div",{className:"af-flex af-gap-2",children:[qe("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),qe("span",{children:g})]})]})]}),v.length>0&&Yt("div",{children:[qe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),qe("div",{className:"af-flex af-flex-wrap af-gap-3",children:v.map(u=>Yt("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&qe(te,{variant:"secondary",className:"af-mb-1",children:"Default"}),jf(u).map((f,p)=>qe("div",{children:f},p))]},u.id))})]}),Yt("div",{children:[qe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?qe("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):Yt(Ze,{children:[qe(Ye,{children:Yt(Se,{children:[qe(V,{children:"Date"}),qe(V,{children:"Amount"}),qe(V,{children:"Status"})]})}),qe(Je,{children:o.map(u=>Yt(Se,{children:[qe(H,{className:"af-text-muted-foreground",children:Vl(u.created_at)}),qe(H,{children:j(Us(u),u.currency)}),qe(H,{children:qe(mn,{status:u.status})})]},u.id))})]})]})]})]})}import{Fragment as Qf,jsx as Ie,jsxs as Ot}from"react/jsx-runtime";function Xf(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 ni({className:e}){let{customers:t,total:s,isLoading:n,error:a,page:r,pageSize:o,hasNextPage:c,hasPreviousPage:d,setPage:l,setPageSize:i,email:m,setEmail:v,refetch:g}=ai(),{api:u}=q(),f=kn.useCallback(()=>u.exportCustomersCsv(),[u]),[p,b]=kn.useState("list"),[x,N]=kn.useState(null),[P,y]=kn.useState(""),R=T=>{N(T),b("detail")},_=()=>{b("list"),N(null),g()};if(p==="detail"&&x)return Ie("div",{className:e,children:Ie(si,{customer:x,onBack:_})});let k=Ot("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Ie(Q,{type:"email",value:P,onChange:T=>y(T.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),v(P.trim()))}}),Ot(h,{type:"button",variant:"outline",size:"sm",onClick:()=>v(P.trim()),children:[Ie(Yf,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),m&&Ie(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>{y(""),v("")},children:"Clear"}),Ie(ta,{fetchCsv:f,filename:"customers",className:"af-ml-auto"})]});if(n)return Ot("div",{className:e,children:[k,Ie("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ie("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(a)return Ot("div",{className:e,children:[k,Ie("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ot("div",{className:"af-text-destructive",children:["Error: ",a.message]})})]});if(t.length===0&&r===0)return Ot("div",{className:e,children:[m&&k,Ot("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[Ie(Jf,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ie("p",{className:"af-text-muted-foreground af-text-center",children:m?"No customers match that email.":Ot(Qf,{children:["No customers yet.",Ie("br",{}),"Customers appear here after their first purchase."]})})]})]});let S=r*o+1,C=Math.min((r+1)*o,s);return Ot("div",{className:e,children:[k,Ot(Ze,{children:[Ie(Ye,{children:Ot(Se,{children:[Ie(V,{children:"Email"}),Ie(V,{children:"Name"}),Ie(V,{children:"Phone"}),Ie(V,{children:"Customer since"}),Ie(V,{className:"af-text-right",children:"Actions"})]})}),Ie(Je,{children:t.map(T=>Ot(Se,{children:[Ie(H,{className:"af-font-medium",children:T.email}),Ie(H,{children:T.name||Ie("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Ie(H,{children:T.phone||Ie("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Ie(H,{className:"af-text-muted-foreground",children:Xf(T.created_at)}),Ie(H,{className:"af-text-right",children:Ie(h,{variant:"ghost",size:"icon",onClick:()=>R(T),title:"View customer",children:Ie(Zf,{className:"af-h-4 af-w-4"})})})]},T.id))})]}),Ot("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[Ot("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ot("span",{children:["Showing ",S,"-",C," of ",s]}),Ot(Ga,{value:String(o),onValueChange:T=>i(Number(T)),children:[Ie(Oa,{className:"af-w-[70px] af-h-8",children:Ie(Ka,{})}),Ot(Ba,{children:[Ie(ot,{value:"10",children:"10"}),Ie(ot,{value:"25",children:"25"}),Ie(ot,{value:"50",children:"50"}),Ie(ot,{value:"100",children:"100"})]})]}),Ie("span",{children:"per page"})]}),Ot("div",{className:"af-flex af-items-center af-gap-2",children:[Ot(h,{variant:"outline",size:"sm",onClick:()=>l(r-1),disabled:!d,children:[Ie(Gf,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ot(h,{variant:"outline",size:"sm",onClick:()=>l(r+1),disabled:!c,children:["Next",Ie(Kf,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Oe from"react";import{ArrowLeft as em,ChevronLeft as tm,ChevronRight as Hl,Copy as am,Download as sm,ExternalLink as nm,FileText as Wl,Loader2 as rm,Search as im}from"lucide-react";import*as Bt from"react";function Tn({initialPageSize:e=25,refreshKey:t,includeAggregates:s=!1}={}){let{api:n}=q(),[a,r]=Bt.useState([]),[o,c]=Bt.useState(0),[d,l]=Bt.useState(null),[i,m]=Bt.useState(!0),[v,g]=Bt.useState(null),[u,f]=Bt.useState(0),[p,b]=Bt.useState(e),[x,N]=Bt.useState(void 0),[P,y]=Bt.useState(""),[R,_]=Bt.useState(""),[k,S]=Bt.useState(""),[C,T]=Bt.useState(""),[w,W]=Bt.useState(""),K=x?x.join(","):"",$=Bt.useRef(0),ne=Bt.useCallback(async()=>{let ue=++$.current;m(!0),g(null);try{let F={labels:K?K.split(","):void 0,customerEmail:P||void 0,q:R||void 0,from:k||void 0,to:C||void 0,retainerId:w||void 0,includeAggregates:s,limit:p,offset:u*p},Z=await n.getInvoices(F);if(ue!==$.current)return;if(u>0&&u*p>=Z.total){f(Math.max(0,Math.ceil(Z.total/p)-1));return}r(Z.invoices),c(Z.total),s&&l(Z.aggregates??null)}catch(F){if(ue!==$.current)return;g(F instanceof Error?F:new Error("Failed to fetch invoices"))}finally{ue===$.current&&m(!1)}},[n,K,P,R,k,C,w,u,p,s]);Bt.useEffect(()=>{ne()},[ne,t]);let ie=ue=>F=>{f(0),ue(F)};return{invoices:a,total:o,aggregates:d,isLoading:i,error:v,page:u,pageSize:p,hasNextPage:(u+1)*p<o,hasPreviousPage:u>0,setPage:f,setPageSize:ie(b),labels:x,setLabels:ie(N),customerEmail:P,setCustomerEmail:ie(y),q:R,setQ:ie(_),from:k,setFrom:ie(S),to:C,setTo:ie(T),retainerId:w,setRetainerId:ie(W),clearFilters:()=>{f(0),N(void 0),y(""),_(""),S(""),T(""),W("")},refetch:ne}}import{Fragment as mm,jsx as A,jsxs as ae}from"react/jsx-runtime";var om={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`:om[e.label]??e.label}function lm(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"},cm={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function or({invoice:e,className:t}){return ae("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[A(te,{variant:lm(e.label),className:t,children:mo(e)}),e.collection_method==="charge_automatically"&&A(te,{variant:"secondary",children:"Managed in Stripe"})]})}function oi({delivery:e,className:t}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return A(te,{variant:s,className:t,children:fo[e.state]??e.state})}function En(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function es(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var zl={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},ri={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},co=100,uo=5e3;async function um(e,t){let s=[],n=0;for(let a=0;a<uo;a+=co){let r=await e.getInvoices({...t,limit:co,offset:a});if(n=r.total,s.push(...r.invoices),r.invoices.length<co||s.length>=n)break}return{invoices:s.slice(0,uo),total:n,truncated:n>s.length||n>uo}}function jl(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],s=e.map(n=>[n.id,En(n),mo(n),n.customer_name??"",n.customer_email??"",n.created_at,n.due_at??"",n.paid_at??"",n.currency.toUpperCase(),j(n.amount_subtotal,n.currency),j(n.tax_total,n.currency),j(n.amount_total,n.currency),n.amount_due===null?"":j(n.amount_due,n.currency),n.amount_paid===null?"":j(n.amount_paid,n.currency),j(n.amount_refunded,n.currency),n.payment_method??"",n.pay_url??"",n.retainer_id??"",n.replaces_order_id??"",n.replaced_by_order_id??"",n.tax_behavior??"",n.discount_total===void 0?"":j(n.discount_total,n.currency),n.collection_method??""]);return[t,...s].map(n=>n.map(gl).join(",")).join(`
5
+ `)}function dm(e){Or(new Blob([jl(e)],{type:"text/csv;charset=utf-8"}),Lr("invoices"))}function fm({className:e,refreshKey:t,initialInvoiceId:s,onDetailOpenChange:n,onConnectStripe:a,onUpgradePlan:r,needsPaidPlan:o=!1,retainerFilter:c=null,onClearRetainerFilter:d,maxRows:l,onViewAll:i}){let m=typeof l=="number",{api:v}=q(),{invoices:g,total:u,isLoading:f,error:p,page:b,pageSize:x,hasNextPage:N,hasPreviousPage:P,setPage:y,labels:R,setLabels:_,customerEmail:k,setCustomerEmail:S,q:C,setQ:T,from:w,setFrom:W,to:K,setTo:$,retainerId:ne,setRetainerId:ie,refetch:ue}=Tn({refreshKey:t}),[F,Z]=Oe.useState(typeof l=="number"?"all":"open"),[B,le]=Oe.useState(""),[oe,Ke]=Oe.useState(null),xe=Oe.useRef(0),Me=!m||!!i,We=Oe.useCallback(z=>{if(m){i?.();return}xe.current++,St(!1),Ke(z)},[m,i]),[ke,St]=Oe.useState(!1),[I,U]=Oe.useState(0),[O,be]=Oe.useState(null),[Y,pe]=Oe.useState(!1),[Fe,mt]=Oe.useState(0);Oe.useEffect(()=>{Ke(z=>{if(!z)return z;let it=g.find(ys=>ys.id===z.id);return it&&it!==z?it:z})},[g]);let[ze,Pt]=Oe.useState(!1),[de,Ae]=Oe.useState(null),pt=async()=>{if(!ze){Pt(!0),Ae(null);try{let{invoices:z,total:it,truncated:ys}=await um(v,{labels:R,customerEmail:k,q:C,from:w,to:K,retainerId:ne});dm(z),Ae(ys?`Exported the first ${z.length.toLocaleString()} of ${it.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ae("Couldn't export \u2014 try again.")}finally{Pt(!1)}}},La=!k&&!C&&!w&&!K&&!ne,[Kt,va]=Oe.useState(null);Oe.useEffect(()=>{if(f||u>0||!La||F!=="open")return;let z=!1;return v.getInvoices({limit:1}).then(it=>{z||va(it.total>0)}).catch(()=>{z||va(!0)}),()=>{z=!0}},[v,f,u,La,F,t]),Oe.useEffect(()=>{_(m?ri.all:ri.open)},[]),Oe.useEffect(()=>{let z=c?.id??"";z!==ne&&(ie(z),z&&(Z("all"),_(ri.all),S(""),T(""),le(""),W(""),$("")))},[c?.id]),Oe.useEffect(()=>{let z=!1;return pe(!1),v.getInvoiceSettings().then(it=>{z||be({payments_active:it.payments_active,blocked:it.blocked})}).catch(()=>{z||pe(!0)}),()=>{z=!0}},[v,t,Fe]),Oe.useEffect(()=>{if(!s||m)return;let z=!1,it=xe.current;return St(!1),v.getInvoice(s).then(ys=>{!z&&it===xe.current&&Ke(ys)}).catch(()=>{!z&&it===xe.current&&St(!0)}),()=>{z=!0}},[v,s,I,m]),Oe.useEffect(()=>{n?.(oe!==null)},[oe,n]);let Qt=z=>{Z(z),_(ri[z])},nt=z=>{let it=z.trim();if(!it){C&&T(""),k&&S("");return}if(it.includes("@")){C&&T(""),S(it);return}k&&S(""),T(it.replace(/^#/,""))},gt=g,os=m?gt.slice(0,l):gt,ln=ke&&ae("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. ",A(h,{type:"button",variant:"link",size:"sm",onClick:()=>U(z=>z+1),children:"Retry opening invoice"})]});if(oe)return ae("div",{className:e,children:[ln,A(po,{invoice:oe,refreshKey:t,onBack:()=>{We(null),ue()}},oe.id)]});let ba=ae("div",{className:"af-mb-4 af-space-y-3",children:[Y&&ae("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",A(h,{type:"button",variant:"link",size:"sm",onClick:()=>mt(z=>z+1),children:"Retry setup check"})]}),ln,O?.blocked&&ae("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."]}),c&&ae("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[ae(te,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",c.label]}),d&&A(h,{type:"button",variant:"link",size:"sm",onClick:d,children:"Clear schedule filter"})]}),ae("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[A("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(zl).map(z=>A("button",{type:"button","aria-pressed":F===z,onClick:()=>Qt(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",F===z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:zl[z]},z))}),ae("div",{className:"af-relative af-w-full af-max-w-xs",children:[A(im,{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"}),A(Q,{type:"text",value:B,onChange:z=>le(z.target.value),onBlur:()=>nt(B),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),nt(B))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),ae("div",{className:"af-flex af-items-center af-gap-2",children:[A(Re,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),A(Q,{id:"invoices-from",type:"date",value:w,max:K||void 0,onChange:z=>W(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),ae("div",{className:"af-flex af-items-center af-gap-2",children:[A(Re,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),A(Q,{id:"invoices-to",type:"date",value:K,min:w||void 0,onChange:z=>$(z.target.value),className:"af-invoice-date af-w-[150px]"})]}),ae(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>void pt(),disabled:ze||f||!!p||u===0,"aria-busy":ze,children:[A(sm,{className:"af-h-4 af-w-4 af-mr-1"}),ze?"Exporting\u2026":"Export CSV (all matching)"]})]}),de&&A("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:de})]});return f?ae("div",{className:e,children:[m?null:ba,A("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(z=>ae("div",{className:"af-rounded-md af-border af-p-3",children:[ae("div",{className:"af-flex af-items-center af-justify-between",children:[A(J,{className:"af-h-4 af-w-20"}),A(J,{className:"af-h-4 af-w-16"})]}),A(J,{className:"af-mt-2 af-h-3 af-w-40"})]},z))})]}):p?ae("div",{className:e,children:[m?null:ba,ae("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",A(h,{type:"button",variant:"link",size:"sm",onClick:()=>void ue(),children:"Retry"})]})]}):u===0&&La&&(F==="all"||Kt===!1)&&(F==="open"||F==="all")?O?.blocked?ae("div",{className:e,children:[m?null:ba,A(ii,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?ae("div",{className:e,children:[m?null:ba,A(ii,{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?ae("div",{className:e,children:[m?null:ba,A(ii,{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})]}):ae("div",{className:e,children:[m?null:ba,A(ii,{heading:"No invoices yet",body:!O||Y?"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."})]}):ae("div",{className:e,children:[m?null:ba,os.length===0?A("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."}):ae(mm,{children:[A("div",{className:"af-space-y-3 lg:af-hidden",children:os.map(z=>ae("button",{type:"button",onClick:()=>We(z),disabled:!Me,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Me?" hover:af-bg-muted/50":""}`,children:[ae("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[A("span",{className:"af-font-medium",children:En(z)}),A(or,{invoice:z})]}),A("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&&A("div",{className:"af-mt-1",children:A(oi,{delivery:z.delivery})}),ae("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[A("span",{children:z.collection_method==="charge_automatically"?"Automatic collection":z.due_at?`Due ${es(z.due_at)}`:"Due on receipt"}),A("span",{className:"af-font-medium af-tabular-nums",children:j(z.amount_due??z.amount_total,z.currency)})]})]},z.id))}),A("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ae(Ze,{children:[A(Ye,{children:ae(Se,{children:[A(V,{children:"Invoice"}),A(V,{children:"Created"}),A(V,{children:"Customer"}),A(V,{children:"Due"}),A(V,{className:"af-text-right",children:"Amount"}),A(V,{children:"Status"}),A(V,{children:"Delivery"}),A(V,{className:"af-w-8"})]})}),A(Je,{children:os.map(z=>ae(Se,{className:Me?"af-cursor-pointer":void 0,onClick:Me?()=>We(z):void 0,children:[A(H,{className:"af-font-medium",children:A("button",{type:"button",disabled:!Me,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Me?" hover:af-underline":""}`,onClick:it=>{it.stopPropagation(),We(z)},"aria-label":`Open invoice ${En(z)}`,children:En(z)})}),A(H,{children:es(z.created_at)}),ae(H,{children:[A("div",{children:z.customer_name??"\u2014"}),A("div",{className:"af-text-xs af-text-muted-foreground",children:z.customer_email})]}),A(H,{children:z.collection_method==="charge_automatically"?"Automatic":z.due_at?es(z.due_at):"On receipt"}),A(H,{className:"af-text-right af-tabular-nums",children:j(z.amount_due??z.amount_total,z.currency)}),A(H,{children:A(or,{invoice:z})}),A(H,{children:A(oi,{delivery:z.delivery})}),A(H,{children:A(Hl,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},z.id))})]})}),m?null:ae("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[ae("span",{children:[u," invoice",u===1?"":"s"]}),ae("div",{className:"af-flex af-items-center af-gap-1",children:[A(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b-1),disabled:!P,"aria-label":"Previous page",children:A(tm,{className:"af-h-4 af-w-4"})}),ae("span",{className:"af-tabular-nums",children:[b*x+1,"\u2013",Math.min((b+1)*x,u)]}),A(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b+1),disabled:!N,"aria-label":"Next page",children:A(Hl,{className:"af-h-4 af-w-4"})})]})]})]})]})}function ii({heading:e,body:t,action:s}){return A(Ys,{icon:Wl,heading:e,body:t,action:s})}function Qs(e){return A(fm,{...e},e.maxRows==null?"full":"compact")}var $s="af-text-xs af-text-muted-foreground";function ql(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function po({invoice:e,onBack:t,refreshKey:s,className:n}){let{api:a}=q(),r=Oe.useRef(null);Oe.useEffect(()=>{r.current?.focus()},[e.id]);let[o,c]=Oe.useState(!1),[d,l]=Oe.useState(null),[i,m]=Oe.useState(!1),[v,g]=Oe.useState(!1),u=Oe.useRef(0),[f,p]=Oe.useState(null),[b,x]=Oe.useState(!1),[N,P]=Oe.useState(0);Oe.useEffect(()=>{let w=!1;return x(!1),a.getInvoice(e.id).then(W=>{w||p({source:e,value:W})}).catch(()=>{w||x(!0)}),()=>{w=!0}},[a,e,s,N]);let y=f?.source===e?f.value:e,R=y.collection_method==="charge_automatically";Oe.useEffect(()=>(u.current++,l(null),m(!1),g(!1),c(!1),()=>{u.current++}),[a,y,s]);let _=w=>w==null?"\u2014":j(w,y.currency),k=async()=>{if(!(!y.pay_url||!ql()))try{await navigator.clipboard.writeText(y.pay_url),c(!0),setTimeout(()=>c(!1),1500)}catch{}},S=async()=>{if(d){l(null);return}let w=++u.current;g(!1),m(!0);try{let W=await a.getInvoicePreview(y.id);w===u.current&&l(W)}catch{w===u.current&&g(!0)}finally{w===u.current&&m(!1)}},C=y.bill_to,T=C?[C.company,C.name,C.address?.line1,C.address?.line2,[C.address?.city,C.address?.state,C.address?.postal_code].filter(Boolean).join(", "),C.address?.country,C.tax_id?`${C.tax_id.value}`:null,C.po_number?`PO ${C.po_number}`:null,C.service_period?`Service period: ${C.service_period}`:null].filter(w=>!!w&&w.length>0):[];return ae("div",{className:n,children:[ae("div",{className:"af-mb-4",children:[ae(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[A(em,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),ae("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ae("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",En(y)]}),A(or,{invoice:y}),A(oi,{delivery:y.delivery})]}),ae("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[y.customer_name??y.customer_email,y.customer_name&&y.customer_email?` \xB7 ${y.customer_email}`:""]})]}),b&&ae("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. ",A(h,{type:"button",variant:"link",size:"sm",onClick:()=>P(w=>w+1),children:"Retry details"})]}),y.label==="failed"&&A("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),y.label==="creating"&&A("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."}),ae("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[ae("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[ae("section",{className:"af-rounded-md af-border af-p-4",children:[ae(Ze,{children:[A(Ye,{children:ae(Se,{children:[A(V,{children:"Description"}),A(V,{className:"af-text-right",children:"Qty"}),A(V,{className:"af-text-right",children:"Amount"})]})}),A(Je,{children:y.line_items.map((w,W)=>ae(Se,{children:[A(H,{style:{overflowWrap:"anywhere"},children:w.description}),A(H,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:w.quantity}),A(H,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_(w.amount)})]},W))})]}),ae("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[A(Xs,{label:"Subtotal",value:_(y.amount_subtotal)}),(y.discount_total??0)>0&&A(Xs,{label:"Discount",value:`-${_(y.discount_total)}`}),y.tax_total>0&&A(Xs,{label:y.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:_(y.tax_total)}),A(Xs,{label:"Total",value:_(y.amount_total),strong:!0}),y.credit_applied>0&&A(Xs,{label:"Credit applied",value:`-${_(y.credit_applied)}`}),y.amount_due!==null&&y.amount_due!==y.amount_total&&A(Xs,{label:"Amount due",value:_(y.amount_due),strong:!0}),y.amount_paid!==null&&y.amount_paid>0&&A(Xs,{label:"Amount paid",value:_(y.amount_paid)}),y.amount_refunded>0&&A(Xs,{label:"Refunded",value:_(y.amount_refunded)})]}),y.credit_notes?.length>0&&ae("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[A("div",{className:$s,children:"Credit notes"}),y.credit_notes.map(w=>ae("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[ae("span",{className:"af-text-muted-foreground",children:[es(w.created_at)," \xB7 ",w.origin==="dashboard"?"issued in Stripe":"refund",w.stripe_credit_note_id?"":" \xB7 being created"]}),ae("span",{className:"af-tabular-nums",children:["-",j(w.amount,w.currency)]})]},w.id))]})]}),(y.note||y.footer)&&ae("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[y.note&&ae("div",{children:[A("div",{className:$s,children:"Note"}),A("div",{className:"af-whitespace-pre-wrap af-break-words",children:y.note})]}),y.footer&&ae("div",{children:[A("div",{className:$s,children:"Footer"}),A("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:y.footer})]})]}),d&&!R&&ae("section",{className:"af-rounded-md af-border af-p-4",children:[ae("div",{className:G($s,"af-break-words"),children:["Email preview \u2014 ",d.subject]}),A("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),A("iframe",{title:"Invoice email preview",srcDoc:d.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),ae("div",{className:"af-min-w-0 af-space-y-4",children:[ae("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[A(Qa,{label:"Created",value:es(y.created_at)}),A(Qa,{label:"Due",value:y.collection_method==="charge_automatically"?"Managed in Stripe":y.due_at?es(y.due_at):"On receipt"}),y.paid_at&&A(Qa,{label:"Paid",value:es(y.paid_at)}),y.payment_method&&A(Qa,{label:"Paid by",value:y.paid_out_of_band?`${y.payment_method} (recorded outside Stripe)`:y.payment_method}),y.payment_state!=="none"&&A(Qa,{label:"Payment",value:y.payment_state==="processing"?"Processing":y.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),y.delivery&&A(Qa,{label:"Delivery",value:`${fo[y.delivery.state]} \xB7 ${y.delivery.recipient}`}),y.marked_uncollectible_at&&A(Qa,{label:"Written off",value:es(y.marked_uncollectible_at)}),y.correction_reason&&A(Qa,{label:"Correction",value:y.correction_reason}),y.replaced_by_order_id&&A(Qa,{label:"Replaced by",value:y.replaced_by_order_id}),y.collection_method==="charge_automatically"?A(Qa,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):y.retainer_id&&A(Qa,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),y.replaces_order_id&&A(Qa,{label:"Replaces",value:y.replaces_order_id})]}),ae("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[A("div",{className:$s,children:"Reminders"}),R?A("div",{children:"View automatic payment reminders in Stripe."}):y.reminders.disabled?A("div",{children:"Off for this invoice."}):y.reminders.paused_until?ae("div",{children:["Paused until ",es(y.reminders.paused_until),"."]}):y.reminders.next_at?ae("div",{children:["Next on ",es(y.reminders.next_at),"."]}):y.reminders.final_sent_at?ae("div",{children:["Final reminder sent ",es(y.reminders.final_sent_at),"."]}):A("div",{children:"None scheduled."}),!R&&ae("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",y.reminders.schedule.length===0?"none":y.reminders.schedule.map(w=>w<0?`${-w}d before`:w===0?"due day":`${w}d after`).join(", ")]})]}),y.communications&&y.communications.length>0&&ae("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[A("div",{className:$s,children:"Email delivery history"}),y.communications.map(w=>ae("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[ae("span",{className:"af-min-w-0 af-break-words",children:[cm[w.kind]??w.kind,w.kind==="reminder"&&w.slot!==null?` #${w.slot}`:"",ae("span",{className:"af-text-muted-foreground",children:[" \xB7 ",w.recipient]})]}),ae("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[fo[w.state]??w.state," \xB7 ",es(w.state_at??w.created_at)]})]},w.id))]}),T.length>0&&ae("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[A("div",{className:$s,children:"Bill to"}),T.map((w,W)=>A("div",{className:"af-break-words",children:w},W))]}),ae("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[y.pay_url&&ae(h,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void k(),disabled:!ql(),children:[A(am,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":R?"Copy invoice link":"Copy pay link"]}),y.pdf_url&&A(h,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:ae("a",{href:y.pdf_url,target:"_blank",rel:"noreferrer",children:[A(nm,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!R&&ae(h,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void S(),disabled:i,children:[i?A(rm,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):A(Wl,{className:"af-h-4 af-w-4 af-mr-1"}),d?"Hide email preview":v?"Retry email preview":"Show email preview"]}),v&&!R&&A("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),y.pay_url&&A("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:y.pay_url}),A("p",{className:"af-text-xs af-text-muted-foreground",children:R?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function Qa({label:e,value:t}){return ae("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[A("span",{className:G($s,"af-shrink-0"),children:e}),A("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function Xs({label:e,value:t,strong:s}){return ae("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[A("dt",{className:G($s,s&&"af-font-medium af-text-foreground"),children:e}),A("dd",{className:G("af-tabular-nums",s&&"af-font-semibold"),children:t})]})}import{Repeat as pm}from"lucide-react";import{jsx as Tt,jsxs as ps}from"react/jsx-runtime";var gm={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Gl={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function vm(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 Kl(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>Gl[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>Gl[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":gm[e.status]}function Zl(e){let t=e.interval==="year"?"every year":"every month";return`${j(e.amount,e.currency)} ${t}`}function bm(e){return e.status==="canceled"?`Ended ${li(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${li(e.next_cycle_at)}`:"Ends this period":e.collection_method==="charge_automatically"?"Billing schedule managed in Stripe":e.status==="paused"?"Future invoices paused":e.status==="failed"||e.status==="creating"?"Next invoice not scheduled yet":e.skip_next_cycle?e.next_cycle_at?`Skipping ${li(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${li(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function li(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(t);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function go({retainer:e,className:t}){return Tt(te,{variant:vm(e.status),className:G("af-max-w-full af-whitespace-normal af-break-words",t),children:Kl(e)})}function In({retainers:e,isLoading:t,error:s,onRetry:n,onShowCycles:a,activeRetainerId:r,total:o,endedTotal:c=0,isLoadingMore:d=!1,onLoadMore:l,includeEnded:i=!1,onIncludeEndedChange:m,exportCsv:v,className:g}){let u=!!m;if(!t&&!s&&e.length===0&&!(u&&(i||c>0)))return null;let f=o!==void 0?Math.max(0,o-e.length):0;return ps("section",{className:G("af-mb-6",g),"aria-label":"Recurring invoices",children:[ps("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[Tt(pm,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),Tt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),Tt("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),u&&Tt(h,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":i,onClick:()=>m?.(!i),children:i?"Hide ended recurring invoices":c>0&&e.length===0?`Show ended recurring invoices (${c})`:"Show ended recurring invoices"}),v&&Tt(ta,{fetchCsv:v,filename:"retainers",className:u?void 0:"af-ml-auto"})]}),s?ps("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",Tt(h,{type:"button",variant:"link",size:"sm",onClick:n,children:"Retry"})]}):t?Tt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(p=>ps("div",{className:"af-rounded-md af-border af-p-3",children:[Tt(J,{className:"af-h-4 af-w-48"}),Tt(J,{className:"af-mt-2 af-h-3 af-w-32"})]},p))}):e.length===0?Tt("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."}):Tt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(p=>{let b=r===p.id;return ps("li",{className:G("af-rounded-md af-border af-p-3",b&&"af-border-primary af-bg-muted/40"),children:[ps("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[ps("div",{className:"af-min-w-0",children:[Tt("div",{className:"af-truncate af-font-medium",children:p.customer_name??p.customer_email??"\u2014"}),Tt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:p.description})]}),Tt(go,{retainer:p})]}),p.collection_method==="charge_automatically"?ps("div",{className:"af-mt-2 af-space-y-1",children:[Tt(te,{variant:"secondary",children:"Managed in Stripe"}),Tt("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."})]}):Tt("div",{className:"af-mt-2 af-text-sm",children:Zl(p)}),ps("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:[ps("span",{children:[bm(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&&Tt(h,{type:"button",variant:b?"secondary":"ghost",size:"sm",onClick:()=>a(p),"aria-pressed":b,children:b?"Showing invoices":"View invoices"})]}),p.status==="failed"&&p.operation?.last_error&&ps("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",p.operation.last_error,". Ask in the chat to try again."]})]},p.id)})}),!t&&!s&&f>0&&l&&Tt("div",{className:"af-mt-2",children:Tt(h,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:d,children:d?"Loading\u2026":`Load more (${f} more)`})})]})}import*as Jl from"react";import{AlertTriangle as Yl,CheckCircle2 as ym,CreditCard as vo,Loader2 as hm,RefreshCw as xm}from"lucide-react";import{jsx as ct,jsxs as zt}from"react/jsx-runtime";function Dn({onConnectStripe:e,onUpgradePlan:t,whenActive:s,className:n}){let{status:a,isLoading:r,error:o,refetch:c}=Ks(),[d,l]=Jl.useState(!1),i=async()=>{l(!0);try{await c()}finally{l(!1)}};return r&&!a?ct("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:ct("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):o||!a?ct("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${n||""}`,children:zt("div",{className:"af-text-destructive",children:["Error: ",o?.message||"Failed to load payment status"]})}):a.status==="active"?s!==void 0?ct("div",{className:n,children:s}):ct("div",{className:n,children:zt("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:[ct(ym,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),zt("div",{children:[ct("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),zt("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."]})]})]})}):zt("div",{className:`af-space-y-4 ${n||""}`,children:[a.reason==="needs_stripe"&&zt("div",{className:"af-space-y-3",children:[zt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[ct(vo,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),zt("div",{children:[ct("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),ct("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?zt(h,{onClick:e,children:[ct(vo,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):ct("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"&&zt("div",{className:"af-space-y-3",children:[zt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[ct(Yl,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),zt("div",{children:[ct("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),ct("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?ct(h,{onClick:t,children:"Upgrade plan"}):ct("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),a.reason==="account_disabled"&&zt("div",{className:"af-space-y-3",children:[zt("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:[ct(Yl,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),zt("div",{children:[ct("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?ct("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."}):ct("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."})]})]}),zt("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&zt(h,{onClick:e,children:[ct(vo,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),zt(h,{variant:"outline",onClick:i,disabled:d,children:[d?ct(hm,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):ct(xm,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as ua from"react";function bo(e,t,s){return e.map(n=>n.id===t?{...n,...s}:n)}function An({includeStats:e=!1,refreshKey:t}={}){let{api:s}=q(),[n,a]=ua.useState([]),[r,o]=ua.useState(!0),[c,d]=ua.useState(null),l=ua.useRef(0),i=ua.useCallback(async()=>{let p=++l.current;try{o(!0),d(null);let b=await s.getProducts(e?{include:"stats"}:{});if(p!==l.current)return;a(b)}catch(b){if(p!==l.current)return;d(b instanceof Error?b:new Error("Failed to fetch products"))}finally{p===l.current&&o(!1)}},[s,e,t]);ua.useEffect(()=>{i()},[i]);let m=ua.useCallback(async p=>{let b=await s.createProduct(p);return a(x=>[b,...x]),b},[s]),v=ua.useCallback(async(p,b)=>{let x=await s.updateProduct(p,b);return a(N=>bo(N,p,x)),x},[s]),g=ua.useCallback(async p=>{await s.deleteProduct(p),a(b=>b.filter(x=>x.id!==p))},[s]),u=ua.useCallback(async(p,b)=>{let x=await s.attachProductFile(p,b);return a(N=>bo(N,p,x)),x},[s]),f=ua.useCallback(async(p,b)=>{let x=await s.attachProductFileFromUrl(p,b);return a(N=>bo(N,p,x)),x},[s]);return{products:n,isLoading:r,error:c,refetch:i,createProduct:m,updateProduct:v,deleteProduct:g,attachProductFile:u,attachProductFileFromUrl:f}}import*as da from"react";var yo=["creating","active","paused","canceling"],Sm=["canceled","failed"],wm={statuses:yo},Nm={};function Ln({refreshKey:e,includeEnded:t=!1,limit:s=50}={}){let{api:n}=q(),[a,r]=da.useState([]),[o,c]=da.useState(0),[d,l]=da.useState(0),[i,m]=da.useState(!0),[v,g]=da.useState(!1),[u,f]=da.useState(null),[p,b]=da.useState(t),x=da.useRef(0),N=da.useCallback(async()=>{let y=++x.current;m(!0),g(!1),f(null);try{let R=await n.getRetainers({statuses:p?void 0:yo,limit:s,offset:0});if(y!==x.current)return;if(r(R.retainers),c(R.total),!p&&R.total===0){let _=await n.getRetainers({statuses:Sm,limit:1,offset:0});if(y!==x.current)return;l(_.total)}else l(0)}catch(R){if(y!==x.current)return;f(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{y===x.current&&m(!1)}},[n,p,s]);da.useEffect(()=>{N()},[N,e]);let P=da.useCallback(async()=>{if(i||v||a.length>=o)return;let y=x.current;g(!0);try{let R=await n.getRetainers({statuses:p?void 0:yo,limit:s,offset:a.length});if(y!==x.current)return;r(_=>{let k=new Set(_.map(S=>S.id));return[..._,...R.retainers.filter(S=>!k.has(S.id))]}),c(R.total)}catch(R){if(y!==x.current)return;f(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{y===x.current&&g(!1)}},[n,p,s,i,v,a.length,o]);return{retainers:a,total:o,endedTotal:d,hasMore:a.length<o,isLoading:i,isLoadingMore:v,error:u,includeEnded:p,setIncludeEnded:b,loadMore:P,refetch:N,filters:p?Nm:wm}}import{Fragment as Im,jsx as tt,jsxs as Ra}from"react/jsx-runtime";function Xl({className:e,defaultTab:t="products",onConnectStripe:s,onRefund:n,onUpgradePlan:a}){let[r,o]=On.useState(t),[c,d]=On.useState("list"),[l,i]=On.useState(null),m=An(),{status:v,error:g}=Ks(),u=v?.currency,f=N=>{i(N),d("edit")},p=()=>{i(null),d("create")},b=()=>{d("list"),i(null)},x=N=>{i(N),d("edit")};return Ra("div",{className:e,children:[Ra("div",{className:"af-mb-6",children:[tt("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),tt("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Ra(Cr,{value:r,onValueChange:N=>o(N),children:[Ra(er,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Ra(us,{value:"products",className:"af-gap-2",children:[tt(Pm,{className:"af-h-4 af-w-4"}),"Products"]}),Ra(us,{value:"orders",className:"af-gap-2",children:[tt(Cm,{className:"af-h-4 af-w-4"}),"Orders"]}),Ra(us,{value:"invoices",className:"af-gap-2",children:[tt(_m,{className:"af-h-4 af-w-4"}),"Invoices"]}),Ra(us,{value:"customers",className:"af-gap-2",children:[tt(Tm,{className:"af-h-4 af-w-4"}),"Customers"]}),tt(us,{value:"promos",children:"Promo codes"}),Ra(us,{value:"setup",className:"af-gap-2",children:[tt(km,{className:"af-h-4 af-w-4"}),"Setup"]})]}),tt(ds,{value:"products",children:c==="list"?tt(qr,{productsState:m,onSelectProduct:f,onCreateProduct:p}):Ra("div",{children:[Ra("div",{className:"af-mb-6",children:[Ra(h,{variant:"ghost",size:"sm",onClick:b,className:"af-mb-2 af--ml-2",children:[tt(Rm,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),tt("h3",{className:"af-text-lg af-font-semibold",children:c==="create"?"New Product":l?.name})]}),c==="create"&&!u?tt("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?Ra("div",{className:"af-text-destructive",children:["Error: ",g.message]}):tt("div",{className:"af-text-muted-foreground",children:"Loading..."})}):tt(jr,{productsState:m,product:c==="edit"?l:null,currency:u??"usd",onSaved:x},c==="edit"?l?.id??"edit":"new")]})}),tt(ds,{value:"orders",children:tt(Js,{onRefund:n})}),tt(ds,{value:"invoices",children:tt(Em,{onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:v?.reason==="needs_paid_plan"})}),tt(ds,{value:"customers",children:tt(ni,{})}),tt(ds,{value:"promos",children:tt(Pn,{})}),tt(ds,{value:"setup",children:tt(Dn,{onConnectStripe:s,onUpgradePlan:a})})]})]})}function Em({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s}){let n=Ln(),[a,r]=On.useState(null),[o,c]=On.useState(!1);return Ra(Im,{children:[!o&&tt(In,{retainers:n.retainers,isLoading:n.isLoading,error:n.error,onRetry:()=>void n.refetch(),activeRetainerId:a?.id??null,onShowCycles:d=>r(l=>l?.id===d.id?null:d),total:n.total,endedTotal:n.endedTotal,isLoadingMore:n.isLoadingMore,onLoadMore:()=>void n.loadMore(),includeEnded:n.includeEnded,onIncludeEndedChange:n.setIncludeEnded}),tt(Qs,{onDetailOpenChange:c,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s,retainerFilter:a?{id:a.id,label:`${a.customer_name??a.customer_email??"Recurring invoices"} \u2014 ${a.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}import*as ec from"react";import*as Rs from"react";function Bn({refreshKey:e}={}){let{api:t}=q(),[s,n]=Rs.useState(null),[a,r]=Rs.useState(!0),[o,c]=Rs.useState(null),d=Rs.useRef(0),l=Rs.useCallback(async()=>{let i=++d.current;try{r(!0),c(null);let m=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(i!==d.current)return;n(m)}catch(m){if(i!==d.current)return;c(m instanceof Error?m:new Error("Failed to fetch summary"))}finally{i===d.current&&r(!1)}},[t,e]);return Rs.useEffect(()=>{l()},[l]),{summary:s,isLoading:a,error:o,refetch:l}}import{Fragment as ho,jsx as qt,jsxs as xo}from"react/jsx-runtime";function Ql(e,t){if(e.settled.complete)return{headline:j(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:j(s.gross,s.currency),extra:e.totals.slice(1).map(n=>`+ ${j(n.gross,n.currency)} in ${n.currency.toUpperCase()}`)}:{headline:j(0,t),extra:[]}}function tc({refreshKey:e,initialOrderId:t,isOwner:s=!1,onRefund:n,onBackToWebsite:a,className:r}){let{summary:o,isLoading:c,error:d,refetch:l}=Bn({refreshKey:e}),[i,m]=ec.useState(!1),v=qt("div",{className:"af-mb-6",children:d&&!o?qt(Lt,{message:"Couldn't load your revenue summary.",onRetry:()=>l()}):qt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:c||!o?xo(ho,{children:[qt(et,{label:"This week",children:qt(J,{className:"af-h-6 af-w-24"})}),qt(et,{label:"Today",children:qt(J,{className:"af-h-6 af-w-24"})}),qt(et,{label:"Needs attention",children:qt(J,{className:"af-h-6 af-w-10"})})]}):qt(ho,{children:(()=>{let g=Ql(o.revenue.d7,o.currency),u=Ql(o.revenue.today,o.currency);return xo(ho,{children:[qt(et,{label:"This week",detail:g.extra.length>0?qt("div",{children:g.extra.map(f=>qt("div",{children:f},f))}):void 0,children:g.headline}),qt(et,{label:"Today",detail:u.extra.length>0?qt("div",{children:u.extra.map(f=>qt("div",{children:f},f))}):void 0,children:u.headline}),qt(et,{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 xo(Nt,{title:"Orders",onBackToWebsite:a,hideBackButton:i,className:r,children:[v,qt(Js,{refreshKey:e,initialOrderId:t,onDetailOpenChange:m,showFulfillment:!0,onRefund:s?n:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as ts from"react";import{ImageOff as Bm,Package as Fm,Search as Um}from"lucide-react";import*as _s from"react";import{ArrowLeft as Lm,ImageOff as Om}from"lucide-react";import{jsx as gs,jsxs as lr}from"react/jsx-runtime";var ac="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",en="af-text-xs af-text-muted-foreground",ci="af-text-sm af-font-medium af-tabular-nums",Dm=3;function Am(e){let t=e.pricing,s=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let d=e.min_amount??t?.min_amount??null,l=e.max_amount??t?.max_amount??null;return d!==null&&l!==null?{text:`Buyer chooses (${j(d,s)} \u2013 ${j(l,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let a=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(a===null||r===null)return{text:"Varies by variant",compareAt:null};let o=a===r?j(a,s):`${j(a,s)} \u2013 ${j(r,s)}`,c=t?.compare_at_amount??null;return{text:o,compareAt:c!==null&&c>r?j(c,s):null}}function ui({product:e,className:t}){let s=Am(e);return lr("div",{className:t,children:[gs("span",{className:ci,children:s.text}),s.compareAt&&gs("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function di({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?gs(te,{variant:"destructive",children:"Out of stock"}):t.low_stock?lr(te,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?gs(te,{variant:"secondary",children:"Backorder"}):t.available===null?null:lr(te,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?gs(te,{variant:"warning",children:"Low stock"}):null}function fi(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function mi(e){return e.map(t=>j(t.amount,t.currency)).join(" + ")}function sc(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${j(e.min_amount,e.currency)} \u2013 ${j(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":j(e.unit_amount,e.currency)}function nc({variant:e}){let t=e.inventory;if(!t||!t.tracked)return gs("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=t.available??0;return t.allow_backorder?lr("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[gs("span",{className:"af-tabular-nums",children:Math.max(0,s)}),gs(te,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?gs(te,{variant:"destructive",children:"Out of stock"}):lr("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[gs("span",{className:"af-tabular-nums",children:s}),s<=Dm&&gs(te,{variant:"warning",children:"Low"})]})}import{jsx as me,jsxs as ut}from"react/jsx-runtime";function cr({title:e,children:t,className:s}){return ut("section",{className:G("af-rounded-lg af-border af-p-4",s),children:[me("h4",{className:ac,children:e}),me("div",{className:"af-mt-3",children:t})]})}function rc({src:e,className:t}){let[s,n]=_s.useState(!1);return _s.useEffect(()=>n(!1),[e]),!e||s?me("div",{"aria-hidden":"true",className:G("af-flex af-items-center af-justify-center af-bg-muted",t),children:me(Om,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):me("img",{src:e,alt:"",loading:"lazy",onError:()=>n(!0),className:G("af-object-cover",t)})}function ic({product:e,showStats:t=!1,onBack:s}){let{api:n}=q(),[a,r]=_s.useState(null),[o,c]=_s.useState(!0),[d,l]=_s.useState(null),[i,m]=_s.useState(0),[v,g]=_s.useState(0);_s.useEffect(()=>{let y=!1;return c(!0),l(null),n.getProduct(e.id).then(R=>{y||r(R)}).catch(R=>{y||l(R instanceof Error?R:new Error("Failed to load product"))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[n,e.id,i]);let u=a?{...e,...a}:e,f=u.images.length>0?u.images:e.images,p=f[v]??f[0],b=fi(u),x=t?u.stats:void 0,N=a?.variants??[],P=N.length>1;return ut("div",{children:[ut("div",{className:"af-mb-6",children:[ut(h,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[me(Lm,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),ut("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[me("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),me(te,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),me(di,{product:u})]}),me(ui,{product:u,className:"af-mt-1"}),!u.active&&me("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),ut("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[ut("div",{className:"af-space-y-2",children:[me(rc,{src:p,className:"af-h-48 af-w-full af-rounded-md af-border"}),f.length>1&&me("div",{className:"af-flex af-flex-wrap af-gap-2",children:f.map((y,R)=>me("button",{type:"button",onClick:()=>g(R),"aria-label":`Show photo ${R+1} of ${f.length}`,"aria-pressed":R===v,className:G("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",R===v?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:me(rc,{src:y,className:"af-h-12 af-w-12 af-rounded-md"})},`${y}-${R}`))})]}),ut("div",{className:"af-space-y-6",children:[u.description&&me(cr,{title:"Description",children:me("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?ut(cr,{title:"Variants",children:[me("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(y=>ut("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[me(J,{className:"af-h-4 af-w-28"}),me(J,{className:"af-h-4 af-w-20"}),me(J,{className:"af-h-4 af-w-16"})]},y))}),me("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):d?me(Lt,{message:"Couldn't load this product's variants.",onRetry:()=>m(y=>y+1)}):P?me(cr,{title:`Variants \xB7 ${N.length}`,children:me("div",{className:"af-overflow-x-auto",children:ut(Ze,{children:[me(Ye,{children:ut(Se,{children:[me(V,{children:"Variant"}),me(V,{children:"SKU"}),me(V,{className:"af-text-right",children:"Price"}),me(V,{children:"Stock"})]})}),me(Je,{children:N.map(y=>ut(Se,{children:[ut(H,{className:"af-font-medium",children:[y.title||y.option_values.map(R=>R.value).join(" / ")||"\u2014",!y.active&&me(te,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),me(H,{className:"af-text-muted-foreground",children:y.sku?me("code",{className:"af-font-mono af-text-xs af-break-all",children:y.sku}):"\u2014"}),ut(H,{className:"af-whitespace-nowrap af-text-right",children:[me("div",{className:ci,children:sc(y)}),y.compare_at_amount!==null&&y.unit_amount!==null&&y.compare_at_amount>y.unit_amount&&me("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:j(y.compare_at_amount,y.currency)})]}),me(H,{className:"af-text-sm",children:me(nc,{variant:y})})]},y.id))})]})})}):null,me(cr,{title:"Details",children:ut("dl",{className:"af-space-y-2",children:[ut("div",{children:[me("dt",{className:en,children:"Delivery"}),me("dd",{className:"af-text-sm",children:b==="Digital download"?u.fulfillment.filename??"Digital download":b??"Nothing to deliver"})]}),u.fulfillment.type==="redirect"&&u.fulfillment.url&&ut("div",{children:[me("dt",{className:en,children:"Sends buyers to"}),me("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),ut("div",{children:[me("dt",{className:en,children:"Shipping address"}),me("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),ut("div",{children:[me("dt",{className:en,children:"Most one buyer can order"}),me("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),x&&me(cr,{title:"Last 30 days",children:ut("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[ut("div",{children:[me("dt",{className:en,children:"Units sold"}),me("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),ut("div",{children:[me("dt",{className:en,children:"Orders"}),me("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),ut("div",{children:[me("dt",{className:en,children:"Gross"}),me("dd",{className:ci,children:x.gross.length>0?mi(x.gross):"\u2014"})]})]})}),me("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 ce,jsxs as dt}from"react/jsx-runtime";var Mm={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},$m=["all","active","draft","low_stock","out_of_stock"];function oc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t).getTime();return Number.isNaN(s)?0:s}function lc(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Vm(e){return e.inventory?.out_of_stock??!1}function Hm(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return lc(e);case"out_of_stock":return Vm(e);default:return!0}}function zm({product:e,showStats:t,onOpen:s}){let n=e.images[0],a=t?e.stats:void 0,r=fi(e),o=e.variant_count??0;return dt("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[n?ce("img",{src:n,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):ce("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:ce(Bm,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),dt("div",{className:"af-space-y-2 af-p-3",children:[dt("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[dt("div",{className:"af-min-w-0",children:[ce("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),ce(ui,{product:e,className:"af-mt-0.5"})]}),!e.active&&ce(te,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),dt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ce(di,{product:e}),o>1&&dt(te,{variant:"outline",children:[o," variants"]}),r&&ce(te,{variant:"outline",children:r})]}),a&&dt("div",{className:"af-text-xs af-text-muted-foreground",children:[a.units_sold," sold",a.gross.length>0?` \xB7 ${mi(a.gross)}`:""," ",ce("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function qm(){return ce("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=>dt("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[ce("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),dt("div",{className:"af-space-y-2 af-p-3",children:[ce(J,{className:"af-w-32"}),ce(J,{className:"af-w-16"}),ce(J,{className:"af-h-5 af-w-24"})]})]},e))})}function cc({refreshKey:e,showStats:t=!1,onBackToWebsite:s,className:n}){let{products:a,isLoading:r,error:o,refetch:c}=An({includeStats:t,refreshKey:e}),[d,l]=ts.useState(!1),[i,m]=ts.useState(null),[v,g]=ts.useState("all"),{api:u}=q(),f=ts.useCallback(()=>u.exportProductsCsv(),[u]),[p,b]=ts.useState(""),[x,N]=ts.useState("newest"),P=ts.useMemo(()=>{if(!t)return null;let K=null;for(let $ of a)!$.stats||$.stats.units_sold===0||(!K||$.stats.units_sold>(K.stats?.units_sold??0))&&(K=$);return K},[a,t]),y=ts.useMemo(()=>a.filter(lc).length,[a]),R=p.trim().toLowerCase(),_=ts.useMemo(()=>{let $=[...a.filter(ne=>Hm(ne,v)&&(!R||ne.name.toLowerCase().includes(R)))];return x==="name"?$.sort((ne,ie)=>ne.name.localeCompare(ie.name)):x==="best_selling"?$.sort((ne,ie)=>(ie.stats?.units_sold??0)-(ne.stats?.units_sold??0)):$.sort((ne,ie)=>oc(ie.created_at)-oc(ne.created_at)),$},[a,v,R,x]),k=v!=="all"||!!R,S=()=>{g("all"),b("")},C=r||o!==null&&a.length===0,T=ce("div",{className:"af-mb-6",children:ce("div",{className:G("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:C?dt(tn,{children:[ce(et,{label:"Products",children:ce(J,{className:"af-h-6 af-w-10"})}),t?dt(tn,{children:[ce(et,{label:"Best seller",children:ce(J,{className:"af-h-6 af-w-28"})}),ce(et,{label:"Low stock",children:ce(J,{className:"af-h-6 af-w-10"})})]}):ce(et,{label:"Active",children:ce(J,{className:"af-h-6 af-w-10"})})]}):dt(tn,{children:[ce(et,{label:"Products",children:a.length}),t?dt(tn,{children:[ce(et,{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?ce("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:P.name}):ce("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),ce(et,{label:"Low stock",children:y})]}):ce(et,{label:"Active",children:a.filter(K=>K.active).length})]})})}),w=dt("div",{className:"af-mb-4 af-space-y-3",children:[dt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ce("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:$m.map(K=>ce("button",{type:"button","aria-pressed":v===K,onClick:()=>g(K),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",v===K?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Mm[K]},K))}),dt("div",{className:"af-relative af-w-full af-max-w-xs",children:[ce(Um,{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"}),ce(Q,{type:"text",value:p,onChange:K=>b(K.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),dt(Ga,{value:x,onValueChange:K=>N(K),children:[ce(Oa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:ce(Ka,{})}),dt(Ba,{children:[ce(ot,{value:"newest",children:"Newest"}),ce(ot,{value:"name",children:"Name A\u2013Z"}),t&&ce(ot,{value:"best_selling",children:"Best selling"})]})]}),k&&ce(h,{type:"button",variant:"ghost",size:"sm",onClick:S,children:"Clear filters"}),ce(ta,{fetchCsv:f,filename:"products",label:k?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&a.length===0?ce(J,{className:"af-h-4 af-w-28"}):ce("p",{className:"af-text-sm af-text-muted-foreground",children:k?`${_.length} of ${a.length} products`:`${a.length} ${a.length===1?"product":"products"}${y>0?` \xB7 ${y} low stock`:""}`})]}),W;return i?W=ce(ic,{product:i,showStats:t,onBack:()=>{m(null),c()}},i.id):r&&a.length===0?W=dt(tn,{children:[w,ce(qm,{}),ce("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&a.length===0?W=ce("div",{className:"af-flex af-justify-center af-py-8",children:ce(Lt,{message:"Couldn't load your products.",onRetry:()=>c()})}):a.length===0?W=dt(sa,{icon:ce(Fm,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",ce("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):W=dt(tn,{children:[w,o&&ce("div",{className:"af-mb-4",children:ce(Lt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>c()})}),_.length===0?dt(sa,{children:["No products match these filters.",ce("br",{}),ce(h,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:S,children:"Show all products"})]}):ce("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:_.map(K=>ce(zm,{product:K,showStats:t,onOpen:()=>m(K)},K.id))})]}),ce(Nt,{title:"Products",onBackToWebsite:s,hideBackButton:!!i,className:n,children:d?dt(tn,{children:[ce(h,{variant:"ghost",onClick:()=>l(!1),children:"Back to products"}),ce(Pn,{})]}):dt(tn,{children:[!i&&ce("div",{className:"af-mb-4 af-flex af-justify-end",children:ce(h,{variant:"outline",onClick:()=>l(!0),children:"Promo codes"})}),!i&&T,W]})})}import*as Pa from"react";import{ArrowLeft as gc,Check as Wm,ChevronLeft as uc,ChevronRight as dc,ClipboardCopy as jm,Mail as wo,Search as Gm,Users as Km}from"lucide-react";import*as _a from"react";function pi({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=q(),[n,a]=_a.useState([]),[r,o]=_a.useState(!0),[c,d]=_a.useState(null),[l,i]=_a.useState(0),[m]=_a.useState(e),[v,g]=_a.useState(""),[u,f]=_a.useState(void 0),p=_a.useRef(0),b=_a.useCallback(async({afterRemoval:x=!1}={})=>{let N=++p.current;try{o(!0),d(null);let P={limit:m,offset:l*m};v.trim()&&(P.q=v.trim()),u&&(P.source=u);let y=await s.getPeople(P);if(N!==p.current)return;if(x&&y.people.length===0&&l>0){i(l-1);return}a(y.people)}catch(P){if(N!==p.current)return;d(P instanceof Error?P:new Error("Failed to fetch people"))}finally{N===p.current&&o(!1)}},[s,l,m,v,u,t]);return _a.useEffect(()=>{b()},[b]),{people:n,isLoading:r,error:c,page:l,pageSize:m,hasNextPage:n.length===m,hasPreviousPage:l>0,setPage:i,q:v,setQ:x=>{g(x),i(0)},source:u,setSource:x=>{f(x),i(0)},refetch:()=>b(),refetchAfterRemoval:()=>b({afterRemoval:!0})}}import*as Ps from"react";function gi(e,{refreshKey:t}={}){let{api:s}=q(),[n,a]=Ps.useState(null),[r,o]=Ps.useState(e!==null),[c,d]=Ps.useState(null),l=Ps.useRef(0),i=Ps.useCallback(async()=>{if(e===null){a(null),o(!1),d(null);return}let m=++l.current;try{o(!0),d(null);let v=await s.getPerson(e);if(m!==l.current)return;a(v)}catch(v){if(m!==l.current)return;d(v instanceof Error?v:new Error("Failed to fetch person"))}finally{m===l.current&&o(!1)}},[s,e,t]);return Ps.useEffect(()=>{i()},[i]),{person:n,isLoading:r,error:c,refetch:i}}import{jsx as E,jsxs as fe}from"react/jsx-runtime";var So="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Zm="af-text-xs af-text-muted-foreground";function Fn(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 No(e,t){let s=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function Ym(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Jm({value:e,label:t}){let[s,n]=Pa.useState(!1);return Ym()?fe(h,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[s?E(Wm,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):E(jm,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function fc(e){return fe("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&fe(te,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&E(te,{variant:"secondary",children:"Contact form"})]})}function mc(e){return e.name?e.name:e.email?e.email:E("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Xm=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Qm=40;function ep(e){let t=Object.entries(e).filter(([a])=>!a.startsWith("_")),n=t.find(([a,r])=>Xm.test(a)&&typeof r=="string"&&r.trim())??t.filter(([,a])=>typeof a=="string"&&a.trim().length>=Qm).sort((a,r)=>String(r[1]).trim().length-String(a[1]).trim().length)[0];return n?{message:String(n[1]),rest:t.filter(([a])=>a!==n[0])}:{message:null,rest:t}}function tp(e){return e.replace(/_/g," ")}function ap(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function sp({data:e}){let{message:t,rest:s}=ep(e);return t===null&&s.length===0?E("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):fe("div",{className:"af-space-y-3",children:[t!==null&&E("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),s.length>0&&E("dl",{className:"af-space-y-1",children:s.map(([n,a])=>fe("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[E("dt",{className:G(Zm,"af-w-28 af-shrink-0 af-capitalize"),children:tp(n)}),E("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:ap(a)})]},n))})]})}function vc({formName:e,createdAt:t,data:s,onDelete:n}){return fe("div",{className:"af-rounded-md af-border af-p-3",children:[fe("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[E(te,{variant:"outline",children:"Form submission (unverified)"}),e&&E("span",{className:"af-text-xs af-text-muted-foreground",children:e}),E("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Fn(t)}),E(_n,{iconOnly:!0,onDelete:n})]}),E(sp,{data:s})]})}function np(e){return e.charged_total??e.amount_total}function rp({email:e,refreshKey:t,onBack:s,onRemoved:n}){let{api:a}=q(),{person:r,isLoading:o,error:c,refetch:d}=gi(e,{refreshKey:t}),l=async m=>{await a.deleteSubmission(m),n(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?d():s()},i=No(e,r?.submissions[0]?.form_name);return fe("div",{children:[fe("div",{className:"af-mb-6",children:[fe(h,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[E(gc,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),fe("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[fe("div",{className:"af-min-w-0",children:[o?E(J,{className:"af-h-7 af-w-48"}):E("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),fe("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[E("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),E(Jm,{value:e,label:"Copy email address"})]})]}),E(h,{asChild:!0,children:fe("a",{href:i,children:[E(wo,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),o?fe("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(m=>fe("div",{className:"af-rounded-md af-border af-p-3",children:[E(J,{className:"af-w-40"}),E(J,{className:"af-mt-2 af-w-64"})]},m)),E("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):c||!r?E("div",{className:"af-flex af-justify-center af-py-8",children:E(Lt,{message:"Couldn't load this person.",onRetry:()=>d()})}):fe("div",{className:"af-space-y-6",children:[r.customer&&fe("div",{children:[E("h4",{className:G(So,"af-mb-3"),children:"Customer"}),fe("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&fe("div",{className:"af-flex af-gap-2",children:[E("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),E("dd",{children:r.customer.name})]}),r.customer.phone&&fe("div",{className:"af-flex af-gap-2",children:[E("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),E("dd",{children:r.customer.phone})]}),fe("div",{className:"af-flex af-gap-2",children:[E("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),E("dd",{children:Fn(r.customer.created_at)})]})]})]}),r.orders.length>0&&fe("div",{children:[E("h4",{className:G(So,"af-mb-3"),children:"Purchases"}),E("div",{className:"af-overflow-x-auto",children:fe(Ze,{children:[E(Ye,{children:fe(Se,{children:[E(V,{children:"Order"}),E(V,{children:"Date"}),E(V,{className:"af-text-right",children:"Total"}),E(V,{children:"Status"})]})}),E(Je,{children:r.orders.map(m=>fe(Se,{children:[E(H,{className:"af-whitespace-nowrap af-font-medium",children:Ms(m)}),E(H,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Fn(m.created_at)}),E(H,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:j(np(m),m.currency)}),E(H,{children:E(mn,{status:m.status})})]},m.id))})]})}),E("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&&fe("div",{children:[E("h4",{className:G(So,"af-mb-3"),children:"Messages"}),E("div",{className:"af-space-y-3",children:r.submissions.map(m=>E(vc,{formName:m.form_name,createdAt:m.created_at,data:m.data,onDelete:()=>l(m.id)},m.id))})]})]})]})}function ip({submissionId:e,onBack:t,onRemoved:s}){let{api:n}=q(),[a,r]=Pa.useState(null),[o,c]=Pa.useState(!0),[d,l]=Pa.useState(null),[i,m]=Pa.useState(0);return Pa.useEffect(()=>{let v=!1;return c(!0),l(null),n.getSubmission(e).then(g=>{v||r(g)}).catch(g=>{v||l(g instanceof Error?g:new Error("Failed to load submission"))}).finally(()=>{v||c(!1)}),()=>{v=!0}},[n,e,i]),fe("div",{children:[fe("div",{className:"af-mb-6",children:[fe(h,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[E(gc,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),E("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),o?E(J,{className:"af-mt-1 af-h-4 af-w-32"}):a&&E("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Fn(a.metadata.submitted_at)})]}),o?fe("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[E(J,{className:"af-w-40"}),E(J,{className:"af-mt-2 af-w-64"}),E(J,{className:"af-mt-2 af-w-52"}),E("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):d||!a?E("div",{className:"af-flex af-justify-center af-py-8",children:E(Lt,{message:"Couldn't load this submission.",onRetry:()=>m(v=>v+1)})}):fe("div",{className:"af-space-y-3",children:[E(vc,{formName:null,createdAt:a.metadata.submitted_at,data:a.data,onDelete:async()=>{await n.deleteSubmission(e),s(),t()}}),E("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 op={all:"All",customers:"Customers",leads:"Leads"},lp=["all","customers","leads"],pc={all:void 0,customers:"customer",leads:"lead"};function cp({refreshKey:e,onBackToWebsite:t,className:s,maxRows:n,onViewAll:a}){let r=typeof n=="number",{people:o,isLoading:c,error:d,page:l,pageSize:i,hasNextPage:m,hasPreviousPage:v,setPage:g,q:u,setQ:f,source:p,setSource:b,refetch:x,refetchAfterRemoval:N}=pi({refreshKey:e}),[P,y]=Pa.useState({kind:"list"}),[R,_]=Pa.useState(""),k=p==="customer"?"customers":p==="lead"?"leads":"all",S=Z=>{pc[Z]!==p&&b(pc[Z])},{api:C}=q(),T=Pa.useCallback(()=>C.exportPeopleCsv({...u?{q:u}:{},...p?{source:p}:{}}),[C,u,p]),w=!r||!!a,W=Z=>{if(r){a?.();return}Z.email?y({kind:"person",email:Z.email}):Z.submission_id&&y({kind:"submission",submissionId:Z.submission_id})},K=Pa.useRef(!1),$=()=>{K.current=!0},ne=()=>{y({kind:"list"}),K.current?(K.current=!1,N()):x()},ie=Z=>{let B=Z.trim();B!==u&&f(B)},ue=r?o.slice(0,n):o,F;if(P.kind==="person")F=E(rp,{email:P.email,refreshKey:e,onBack:ne,onRemoved:$});else if(P.kind==="submission")F=E(ip,{submissionId:P.submissionId,onBack:ne,onRemoved:$});else{let Z=fe("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[E("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:lp.map(B=>E("button",{type:"button","aria-pressed":k===B,onClick:()=>S(B),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",k===B?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:op[B]},B))}),fe("div",{className:"af-relative af-w-full af-max-w-xs",children:[E(Gm,{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"}),E(Q,{type:"text",value:R,onChange:B=>_(B.target.value),onBlur:()=>ie(R),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),ie(R))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),u&&E(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>{_(""),f("")},children:"Clear search"}),E(ta,{fetchCsv:T,filename:"people",className:"af-ml-auto"})]});if(c)F=fe("div",{children:[r?null:Z,E("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(B=>fe("div",{className:"af-rounded-md af-border af-p-3",children:[fe("div",{className:"af-flex af-items-center af-justify-between",children:[E(J,{className:"af-h-4 af-w-32"}),E(J,{className:"af-h-4 af-w-16"})]}),E(J,{className:"af-mt-2 af-h-5 af-w-28"}),E(J,{className:"af-mt-2 af-h-3 af-w-56"})]},B))}),E("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:fe(Ze,{children:[E(Ye,{children:fe(Se,{children:[E(V,{children:"Person"}),E(V,{children:"Came from"}),E(V,{children:"Latest message"}),E(V,{children:"Last activity"}),E(V,{className:"af-w-8"}),E(V,{className:"af-w-8"})]})}),E(Je,{"aria-hidden":"true",children:[0,1,2,3,4].map(B=>fe(Se,{children:[E(H,{children:E(J,{className:"af-h-4 af-w-40"})}),E(H,{children:E(J,{className:"af-h-5 af-w-24"})}),E(H,{children:E(J,{className:"af-h-4 af-w-56"})}),E(H,{children:E(J,{className:"af-h-4 af-w-24"})}),E(H,{}),E(H,{})]},B))})]})}),E("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(d)F=fe("div",{children:[r?null:Z,E("div",{className:"af-flex af-justify-center af-py-8",children:E(Lt,{message:"Couldn't load your leads.",onRetry:()=>x()})})]});else if(ue.length===0&&l===0){let B=!!u||k!=="all";F=fe("div",{children:[B&&Z,B?E(sa,{children:u?"Nobody matches that search.":k==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):E(Ys,{icon:Km,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)F=fe("div",{children:[r?null:Z,E(sa,{children:"No more results."}),E("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:fe(h,{variant:"outline",size:"sm",onClick:()=>g(l-1),children:[E(uc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let B=l*i+1,le=l*i+o.length;F=fe("div",{children:[r?null:Z,E("div",{className:"af-space-y-3 lg:af-hidden",children:ue.map((oe,Ke)=>fe("div",{onClick:w?()=>W(oe):void 0,className:`af-rounded-md af-border af-p-3${w?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[fe("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[fe("div",{className:"af-min-w-0",children:[E("button",{type:"button",onClick:xe=>{xe.stopPropagation(),W(oe)},disabled:!w,"aria-label":`Open ${oe.name||oe.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${w?" hover:af-underline":""}`,children:mc(oe)}),oe.name&&oe.email&&E("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:oe.email})]}),fe("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[E("span",{className:"af-text-xs af-text-muted-foreground",children:Fn(oe.last_activity_at)}),oe.email&&E(h,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:E("a",{href:No(oe.email),onClick:xe=>xe.stopPropagation(),"aria-label":`Email ${oe.email}`,children:E(wo,{className:"af-h-4 af-w-4"})})})]})]}),E("div",{className:"af-mt-2",children:fc(oe)}),oe.latest_message_excerpt&&E("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:oe.latest_message_excerpt})]},oe.email??oe.submission_id??Ke))}),E("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:fe(Ze,{children:[E(Ye,{children:fe(Se,{children:[E(V,{children:"Person"}),E(V,{children:"Came from"}),E(V,{children:"Latest message"}),E(V,{children:"Last activity"}),E(V,{className:"af-w-8",children:E("span",{className:"af-sr-only",children:"Reply"})}),E(V,{className:"af-w-8"})]})}),E(Je,{children:ue.map((oe,Ke)=>fe(Se,{onClick:w?()=>W(oe):void 0,className:w?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[fe(H,{className:"af-max-w-[260px] af-font-medium",children:[E("button",{type:"button",onClick:xe=>{xe.stopPropagation(),W(oe)},disabled:!w,"aria-label":`Open ${oe.name||oe.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${w?" hover:af-underline":""}`,children:mc(oe)}),oe.name&&oe.email&&E("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:oe.email})]}),E(H,{children:fc(oe)}),E(H,{className:"af-max-w-[320px]",children:oe.latest_message_excerpt?E("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:oe.latest_message_excerpt}):E("span",{className:"af-text-muted-foreground",children:"\u2014"})}),E(H,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Fn(oe.last_activity_at)}),E(H,{className:"af-w-8",children:oe.email&&E(h,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:E("a",{href:No(oe.email),onClick:xe=>xe.stopPropagation(),"aria-label":`Email ${oe.email}`,children:E(wo,{className:"af-h-4 af-w-4"})})})}),E(H,{className:"af-w-8 af-text-right",children:E(dc,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},oe.email??oe.submission_id??Ke))})]})}),!r&&fe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[E("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${B}-${le}`}),fe("div",{className:"af-flex af-items-center af-gap-2",children:[fe(h,{variant:"outline",size:"sm",onClick:()=>g(l-1),disabled:!v,children:[E(uc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),fe(h,{variant:"outline",size:"sm",onClick:()=>g(l+1),disabled:!m,children:["Next",E(dc,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?E("div",{className:s,children:F}):E(Nt,{title:"Leads",onBackToWebsite:t,hideBackButton:P.kind!=="list",className:s,children:F})}function vi(e){return E(cp,{...e},e.maxRows==null?"full":"compact")}import*as wc from"react";import{ChevronLeft as bc,ChevronRight as up,Repeat as dp}from"lucide-react";import*as Ca from"react";function bi({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=q(),[n,a]=Ca.useState([]),[r,o]=Ca.useState(0),[c,d]=Ca.useState(!0),[l,i]=Ca.useState(null),[m,v]=Ca.useState(0),[g,u]=Ca.useState(e),[f,p]=Ca.useState(void 0),b=Ca.useRef(0),x=Ca.useCallback(async()=>{let P=++b.current;try{d(!0),i(null);let y={limit:g,offset:m*g};f&&(y.status=f);let R=await s.getSubscriptions(y);if(P!==b.current)return;a(R.subscriptions),o(R.total)}catch(y){if(P!==b.current)return;i(y instanceof Error?y:new Error("Failed to fetch subscriptions"))}finally{P===b.current&&d(!1)}},[s,m,g,f,t]);Ca.useEffect(()=>{x()},[x]);let N=Math.ceil(r/g);return{subscriptions:n,total:r,isLoading:c,error:l,page:m,pageSize:g,hasNextPage:m<N-1,hasPreviousPage:m>0,setPage:v,setPageSize:P=>{u(P),v(0)},status:f,setStatus:P=>{p(P),v(0)},refetch:x}}import{jsx as re,jsxs as ft}from"react/jsx-runtime";function yc(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function hc({sub:e}){return e.status==="canceled"?re(te,{variant:"outline",children:"Canceled"}):e.status==="past_due"?re(te,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?re(te,{variant:"warning",children:"Scheduled to cancel"}):re(te,{variant:"success",children:"Active"}):re(te,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function fp(e,t){let s=j(t,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function xc({sub:e}){let t=e.current_amount!==e.plan_amount;return ft("div",{children:[re("div",{className:"af-font-medium af-tabular-nums",children:fp(e,e.current_amount)}),t&&ft("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",j(e.plan_amount,e.currency)]})]})}function Sc(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${yc(e.current_period_end)}`:"Ends at period end":e.current_period_end?yc(e.current_period_end):"\u2014"}function Nc({refreshKey:e,onBackToWebsite:t,className:s}){let{subscriptions:n,total:a,isLoading:r,error:o,page:c,pageSize:d,hasNextPage:l,hasPreviousPage:i,setPage:m,status:v,refetch:g}=bi({refreshKey:e}),{api:u}=q(),f=wc.useCallback(()=>u.exportSubscriptionsCsv(v?{status:v}:{}),[u,v]),p;if(r)p=ft("div",{children:[re("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(b=>ft("div",{className:"af-rounded-md af-border af-p-3",children:[ft("div",{className:"af-flex af-items-center af-justify-between",children:[re(J,{className:"af-h-4 af-w-40"}),re(J,{className:"af-h-4 af-w-20"})]}),re(J,{className:"af-mt-2 af-h-3 af-w-32"}),re(J,{className:"af-mt-2 af-h-5 af-w-24"})]},b))}),re("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ft(Ze,{children:[re(Ye,{children:ft(Se,{children:[re(V,{children:"Subscriber"}),re(V,{children:"Plan"}),re(V,{className:"af-text-right",children:"Amount"}),re(V,{children:"Renews"}),re(V,{children:"Status"})]})}),re(Je,{"aria-hidden":"true",children:[0,1,2,3,4].map(b=>ft(Se,{children:[re(H,{children:re(J,{className:"af-h-4 af-w-44"})}),re(H,{children:re(J,{className:"af-h-4 af-w-32"})}),re(H,{className:"af-text-right",children:re(J,{className:"af-ml-auto af-h-4 af-w-24"})}),re(H,{children:re(J,{className:"af-h-4 af-w-24"})}),re(H,{children:re(J,{className:"af-h-5 af-w-20"})})]},b))})]})}),re("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=re("div",{className:"af-flex af-justify-center af-py-8",children:re(Lt,{message:"Couldn't load your subscriptions.",onRetry:()=>g()})});else if(n.length===0&&c===0)p=re(sa,{icon:re(dp,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Subscriptions appear here when a customer subscribes to one of your products."});else if(n.length===0)p=ft("div",{children:[re(sa,{children:"No more results."}),re("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:ft(h,{variant:"outline",size:"sm",onClick:()=>m(c-1),children:[re(bc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let b=c*d+1,x=c*d+n.length;p=ft("div",{children:[re("div",{className:"af-mb-3 af-flex af-justify-end",children:re(ta,{fetchCsv:f,filename:"subscriptions"})}),re("div",{className:"af-space-y-3 lg:af-hidden",children:n.map(N=>ft("div",{className:"af-rounded-md af-border af-p-3",children:[ft("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[ft("div",{className:"af-min-w-0",children:[re("div",{className:"af-truncate af-text-sm af-font-medium",children:N.customer_email||re("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),re("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:N.plan_title||"Untitled plan"})]}),re("div",{className:"af-shrink-0 af-text-right",children:re(xc,{sub:N})})]}),ft("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[re(hc,{sub:N}),N.is_test&&re(te,{variant:"outline",children:"Test"}),re("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Sc(N)})]}),re(hs,{deliveries:N.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},N.id))}),re("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ft(Ze,{children:[re(Ye,{children:ft(Se,{children:[re(V,{children:"Subscriber"}),re(V,{children:"Plan"}),re(V,{className:"af-text-right",children:"Amount"}),re(V,{children:"Renews"}),re(V,{children:"Status"})]})}),re(Je,{children:n.map(N=>ft(Se,{children:[re(H,{className:"af-max-w-[240px]",children:re("div",{className:"af-truncate af-font-medium",children:N.customer_email||re("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),re(H,{className:"af-max-w-[220px]",children:re("div",{className:"af-truncate",children:N.plan_title||re("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),re(H,{className:"af-whitespace-nowrap af-text-right",children:re(xc,{sub:N})}),re(H,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Sc(N)}),ft(H,{children:[ft("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[re(hc,{sub:N}),N.is_test&&re(te,{variant:"outline",children:"Test"})]}),re(hs,{deliveries:N.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},N.id))})]})}),ft("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[re("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${b}-${x} of ${a}`}),ft("div",{className:"af-flex af-items-center af-gap-2",children:[ft(h,{variant:"outline",size:"sm",onClick:()=>m(c-1),disabled:!i,children:[re(bc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ft(h,{variant:"outline",size:"sm",onClick:()=>m(c+1),disabled:!l,children:["Next",re(up,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return re(Nt,{title:"Subscriptions",onBackToWebsite:t,className:s,children:p})}import*as Ts from"react";import{Loader2 as wp}from"lucide-react";import*as na from"react";import*as yi from"react";var vn=typeof window>"u"?yi.useEffect:yi.useLayoutEffect;var hi=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},mp=(e,t)=>e instanceof Error?e:new Error(t);function pp(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 Rc(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function an({siteId:e,refreshKey:t,onSaveInvoiceSettings:s}){let{api:n}=q(),[a,r]=na.useState(null),[o,c]=na.useState(!0),[d,l]=na.useState(null),i=na.useRef(null),[m,v]=na.useState(()=>Rc(n,e)),g=m.api!==n||m.siteId!==e,u=m;g&&(u=Rc(n,e),v(u),r(null),c(!0),l(null));let f=na.useRef(u);vn(()=>{f.current!==u&&(f.current=u,i.current=null)},[u]);let p=(S,C)=>f.current===S&&C>S.applied,b=(S,C,T)=>p(S,C)?(S.applied=C,i.current=T,r(T),c(!1),!0):!1,x=async S=>{for(;S.writing;)await S.idle;let C=++S.seq;try{let T=await S.api.getSite(S.siteId);return b(S,C,T)&&l(null),{seq:C,error:null}}catch(T){return{seq:C,error:mp(T,"Failed to load store settings")}}},N=(S,C)=>{let T=async()=>{if(f.current!==S)throw new Error("Not saved: the store switched to another site first.");S.writing=!0,S.idle=new Promise(W=>{S.markIdle=W});try{return await C(++S.seq)}finally{S.writing=!1,S.markIdle()}},w=S.queue.then(T,T);return S.queue=w.catch(()=>{}),w},P=na.useCallback(async()=>{let S=await x(u);S.error&&p(u,S.seq)&&(l(S.error),c(!1))},[u]);na.useEffect(()=>{P()},[P,t]);let y=na.useCallback(S=>N(u,async C=>{let T=await u.api.updateSite(u.siteId,S),{currency_restatement:w,...W}=T;return b(u,C,W)&&l(K=>K instanceof hi?K:null),T}),[u]),R=na.useRef(s);vn(()=>{R.current=s});let _=na.useCallback(async(S,C)=>{await N(u,()=>S());let T=await x(u);return T.error&&p(u,T.seq)&&i.current&&(b(u,T.seq,{...i.current,...C}),l(new hi(`Saved, but couldn't refresh settings: ${T.error.message}`))),f.current===u?i.current:null},[u]),k=na.useCallback(S=>{let C=R.current;return _(()=>C(S),pp(S))},[_]);return{site:g?null:a,isLoading:g||o,error:g?null:d,refetch:P,updateSite:y,saveInvoiceSettings:s?k:null}}import*as $t from"react";import{Loader2 as _c}from"lucide-react";import{jsx as as,jsxs as Cs}from"react/jsx-runtime";function xi(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var vs="af-grid af-gap-1 af-text-sm",Pc="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",Cc="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 ka({children:e}){return as("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function ur({children:e}){return as("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var ks=$t.forwardRef(function({id:t,title:s,description:n,children:a},r){let o=`af-store-${t}-title`;return Cs("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:[Cs("div",{className:"af-space-y-1",children:[as("h3",{id:o,className:"af-text-sm af-font-semibold",children:s}),n&&as(ka,{children:n})]}),a]})});function Si({label:e,description:t,checked:s,onSave:n,disabled:a=!1,disabledReason:r}){let[o,c]=$t.useState(null),[d,l]=$t.useState(null),i=o??s,m=async v=>{c(v),l(null);try{await n(v)}catch(g){l(xi(g))}finally{c(null)}};return Cs("div",{className:"af-space-y-1",children:[Cs("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[as("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":i,checked:i,disabled:a||o!==null,onChange:v=>void m(v.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),Cs("span",{className:"af-space-y-0.5",children:[Cs("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,o!==null&&as(_c,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&as(ka,{children:t})]})]}),(a&&r||d)&&Cs("div",{className:"af-space-y-1 af-pl-6",children:[a&&r&&as(ka,{children:r}),d&&as(ur,{children:d})]})]})}var _o=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ro=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function gp(e,t,s,n=[]){if(!Ro(e)||!Ro(t)||!Ro(s))return{draft:_o(e,t)?s:e,dropped:[]};let a=[],r={...s};for(let o of Object.keys(s))_o(e[o],t[o])||(n.includes(o)?a.push(o):r[o]=e[o]);return{draft:r,dropped:a}}function Un(e,t){let s=JSON.stringify(e),[n,a]=$t.useState(e),[r,o]=$t.useState([]),c=$t.useRef(e),d=$t.useRef(e),l=$t.useRef(n);vn(()=>{d.current=e,l.current=n});let i=$t.useRef(t?.when);$t.useEffect(()=>{let v=Object.is(i.current,t?.when)?[]:t?.fields??[];if(i.current=t?.when,_o(c.current,d.current)&&v.length===0)return;let g=gp(l.current,c.current,d.current,v);c.current=d.current,a(g.draft),g.dropped.length&&o(g.dropped)},[s,t?.when]);let m=$t.useCallback(v=>{a(v??d.current),o([])},[]);return{draft:n,setDraft:a,dirty:JSON.stringify(n)!==s,reset:m,dropped:r}}function Mn({dirty:e,saving:t,error:s,onSave:n,onDiscard:a}){return e?Cs("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[Cs(h,{type:"button",size:"sm",disabled:t,onClick:n,children:[t&&as(_c,{className:"af-animate-spin"}),"Save"]}),as(h,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:a,children:"Discard"}),s&&as("p",{role:"alert",className:G("af-text-sm af-text-destructive"),children:s})]}):null}function $n(){let[e,t]=$t.useState(!1),[s,n]=$t.useState(null),a=$t.useCallback(async r=>{t(!0),n(null);try{await r()}catch(o){n(xi(o))}finally{t(!1)}},[]);return{saving:e,error:s,setError:n,run:a}}function kc({what:e}){return Cs(ka,{children:["Only the site owner can change ",e,"."]})}import*as ss from"react";import{ExternalLink as vp,Plus as bp,X as Dc}from"lucide-react";import{Fragment as Sp,jsx as ge,jsxs as Ne}from"react/jsx-runtime";var Co=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Ac({site:e,updateSite:t}){return Ne("div",{className:"af-space-y-4",children:[ge(Si,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:s=>t({collect_phone_at_checkout:s})}),e.checkout_marketing_consent!==void 0&&ge(Si,{label:"Ask buyers for marketing consent at checkout",description:"Adds Stripe's consent checkbox to your checkout. Buyers who tick it join your email list, and buyers who leave without paying can get your abandoned-cart recovery emails.",checked:e.checkout_marketing_consent&&e.stripe_account_country==="US",disabled:e.stripe_account_country!=="US",disabledReason:e.stripe_account_country?'Only available for US stores: Stripe offers its consent checkbox to US businesses only. Your checkout shows an "Email me" box instead.':"Available once your Stripe account is connected and its country has synced.",onSave:s=>t({checkout_marketing_consent:s})})]})}function Tc(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(bt(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(bt(e.free_shipping_over,e.currency))}}function Lc({site:e,updateSite:t,refetch:s,providerSlot:n,currencyChanging:a=!1}){let{draft:r,setDraft:o,dirty:c,reset:d,dropped:l}=Un(Tc(e),{when:e.currency,fields:["rates","threshold"]}),{saving:i,error:m,setError:v,run:g}=$n(),u=e.currency.toUpperCase(),f=()=>g(async()=>{let b={},x=[...new Set(r.countries.split(/[\s,]+/).map(S=>S.trim().toUpperCase()).filter(Boolean))],N=x.find(S=>!/^[A-Z]{2}$/.test(S));if(N)throw new Error(`"${N}" isn't a two-letter country code (e.g. US, CA).`);let P=x.length?x:null;Co(P,e.shipping_countries)||(b.shipping_countries=P);let y=[];for(let S of r.rates){let C=S.label.trim(),T=Zt(S.amount,e.currency);if(!C)throw new Error("Every rate needs a name.");if(S.amount.trim()===""||T===null)throw new Error(`Enter a price for "${C}" (0 for free).`);y.push({label:C,amount:T})}let R=y.length?y:null;Co(R,e.shipping_rates)||(b.shipping_rates=R);let _=null;if(r.threshold.trim()!==""&&(_=Zt(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&&(b.free_shipping_over=_),Object.keys(b).length===0){d();return}("shipping_rates"in b||"free_shipping_over"in b)&&(b.expected_currency=e.currency);let k;try{k=await t(b)}catch(S){throw S instanceof Ft&&S.details?.code==="currency_changed"&&await s?.(),S}d(Tc(k))}),p=(b,x)=>o({...r,rates:r.rates.map((N,P)=>P===b?{...N,...x}:N)});return Ne("fieldset",{disabled:i||a,className:"af-space-y-4",children:[Ne("label",{className:vs,children:["Countries you ship to",ge(Q,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:b=>o({...r,countries:b.target.value})}),ge(ka,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),Ne("div",{className:"af-space-y-2",children:[Ne("p",{className:"af-text-sm",children:["Flat shipping rates (",u,")"]}),r.rates.length===0&&ge(ka,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((b,x)=>Ne("div",{className:"af-flex af-items-center af-gap-2",children:[ge(Q,{"aria-label":`Rate ${x+1} name`,value:b.label,placeholder:"Standard",onChange:N=>p(x,{label:N.target.value})}),ge(Q,{"aria-label":`Rate ${x+1} price`,type:"number",min:"0",step:"any",value:b.amount,placeholder:"0",className:"af-w-32",onChange:N=>p(x,{amount:N.target.value})}),ge(h,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${x+1}`,onClick:()=>o({...r,rates:r.rates.filter((N,P)=>P!==x)}),children:ge(Dc,{})})]},x)),Ne(h,{type:"button",variant:"outline",size:"sm",onClick:()=>o({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[ge(bp,{})," Add rate"]}),ge(ka,{children:"Buyers pick one at checkout. The first is preselected."})]}),Ne("label",{className:vs,children:["Free shipping over (",u,")",ge(Q,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:b=>o({...r,threshold:b.target.value})}),ge(ka,{children:"Orders at or above this get the cheapest rate free."})]}),l.length>0&&Ne("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",u,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),ge(Mn,{dirty:c,saving:i,error:m,onSave:()=>void f(),onDiscard:()=>{v(null),d()}}),n]})}var Po="exclusive",yp=[{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 hp({href:e,children:t}){return Ne("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,ge(vp,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function Oc({site:e,updateSite:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=Un(e.tax_behavior??Po),{saving:o,error:c,setError:d,run:l}=$n(),[i,m]=ss.useState(!1),v=e.stripe_tax_enabled,g=v||i,u=()=>l(async()=>{let b=s;if(b===e.tax_behavior){r();return}let x={tax_behavior:b};b!=="inclusive"&&e.tax_rate_bps!=null&&(x.tax_rate_bps=null);let N=await t(x);r(N.tax_behavior??Po)}),f=()=>l(async()=>{let b={stripe_tax_enabled:!0,tax_behavior:s};s!=="inclusive"&&e.tax_rate_bps!=null&&(b.tax_rate_bps=null);let x=await t(b);r(x.tax_behavior??Po),m(!1)}),p=(a||i)&&s!=="inclusive"&&e.tax_rate_bps!=null;return Ne("div",{className:"af-space-y-5",children:[Ne("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[ge("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."}),ge("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."}),ge("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:yp.map(b=>ge("li",{children:ge(hp,{href:b.href,children:b.label})},b.href))})]}),ge(Si,{label:"Stripe automatic tax",description:v?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:g,onSave:async b=>{if(i){m(!1),d(null),r();return}if(b&&!e.tax_behavior){m(!0);return}return t({stripe_tax_enabled:b})}}),g&&Ne("fieldset",{disabled:o,className:"af-space-y-4 af-pl-6",children:[Ne("label",{className:vs,children:["Do your prices already include tax?",Ne("select",{"aria-label":"Your prices",className:Pc,value:s,onChange:b=>n(b.target.value),children:[ge("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),ge("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),ge(ka,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),p&&Ne(ka,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),i?Ne("div",{className:"af-space-y-2",children:[Ne("div",{className:"af-flex af-gap-2",children:[ge(h,{type:"button",size:"sm",disabled:o,onClick:()=>void f(),children:"Turn on"}),ge(h,{type:"button",size:"sm",variant:"outline",disabled:o,onClick:()=>{m(!1),d(null),r()},children:"Cancel"})]}),c&&ge(ur,{children:c})]}):ge(Mn,{dirty:a,saving:o,error:c,onSave:()=>void u(),onDiscard:()=>{d(null),r()}})]})]})}function Ec(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function Bc({site:e,updateSite:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=Un(Ec(e)),{saving:o,error:c,setError:d,run:l}=$n(),i=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),m=()=>l(async()=>{let v={},g=null;if(i&&s.rate.trim()!==""){let b=Number(s.rate);if(!Number.isFinite(b)||b<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");g=Math.round(b*100)}i&&g!==e.tax_rate_bps&&(v.tax_rate_bps=g),g!=null&&e.tax_behavior!=="inclusive"&&(v.tax_behavior="inclusive");let u=s.taxId.trim()||null;u!==e.tax_id&&(v.tax_id=u);let f=s.label.trim()||null;if(f!==e.tax_label&&(v.tax_label=f),Object.keys(v).length===0){r();return}let p=await t(v);r(Ec(p))});return Ne("fieldset",{disabled:o,className:"af-space-y-4",children:[Ne("label",{className:vs,children:["Tax rate (%)",ge(Q,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!i,value:i?s.rate:"",onChange:v=>n({...s,rate:v.target.value})}),ge(ka,{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."})]}),Ne("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[Ne("label",{className:vs,children:["Tax ID",ge(Q,{"aria-label":"Tax ID",value:s.taxId,maxLength:64,placeholder:"DE123456789",onChange:v=>n({...s,taxId:v.target.value})})]}),Ne("label",{className:vs,children:["Tax label",ge(Q,{"aria-label":"Tax label",value:s.label,maxLength:24,placeholder:"Tax",onChange:v=>n({...s,label:v.target.value})})]})]}),ge(Mn,{dirty:a,saving:o,error:c,onSave:()=>void m(),onDiscard:()=>{d(null),r()}})]})}function Fc({site:e,updateSite:t,onChangeStart:s}){let[n,a]=ss.useState(e.currency.toUpperCase()),[r,o]=ss.useState(!1),[c,d]=ss.useState(!1),[l,i]=ss.useState(null),m=e.currency.toUpperCase(),v=ss.useRef(m);ss.useEffect(()=>{v.current!==m&&(a(b=>b===v.current?m:b),v.current=m)},[m]);let g=n.trim().toUpperCase(),u=g!==m,f=/^[A-Z]{3}$/.test(g),p=async()=>{d(!0);let b=s?.(),x=!1;i(null);try{let N=await t({currency:g.toLowerCase()});x=!0;let P=N.currency_restatement;P&&!P.applied?i(P.reason?`Not changed: ${P.reason}.`:"The currency was not changed."):(a(N.currency.toUpperCase()),v.current=N.currency.toUpperCase()),o(!1)}catch(N){i(xi(N))}finally{d(!1),b?.(x)}};return Ne("div",{className:"af-space-y-3",children:[Ne("div",{className:"af-flex af-items-end af-gap-2",children:[Ne("label",{className:vs,children:["Store currency",ge(Q,{"aria-label":"Store currency",value:n,maxLength:3,className:"af-w-24 af-uppercase",disabled:c||r,onChange:b=>{a(b.target.value),i(null)}})]}),u&&!r&&Ne(Sp,{children:[ge(h,{type:"button",size:"sm",disabled:!f,onClick:()=>o(!0),children:"Change currency"}),ge(h,{type:"button",size:"sm",variant:"ghost",onClick:()=>{a(m),i(null)},children:"Discard"})]})]}),ge(ka,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&Ne("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[Ne("p",{className:"af-text-sm",children:["Change the store currency from ",m," to ",g,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",g,":"," ",j(2e3,m)," becomes ",j(2e3,g),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),Ne("div",{className:"af-flex af-gap-2",children:[ge(h,{type:"button",size:"sm",disabled:c,onClick:()=>void p(),children:"Confirm change"}),ge(h,{type:"button",size:"sm",variant:"ghost",disabled:c,onClick:()=>o(!1),children:"Cancel"})]})]}),l&&ge(ur,{children:l})]})}function Ic(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function xp(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 Uc({site:e,save:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=Un(Ic(e)),{saving:o,error:c,setError:d,run:l}=$n();if(!t)return Ne("div",{className:"af-space-y-2 af-text-sm",children:[Ne("p",{children:["Due ",e.invoice_due_days," days after sending"]}),Ne("p",{children:["Reminders: ",xp(e.invoice_reminder_schedule)]}),Ne("p",{children:["Footer: ",e.invoice_footer||"None"]}),ge(kc,{what:"invoice defaults"})]});let i=()=>l(async()=>{let m={},v=Number(s.dueDays);if(s.dueDays.trim()===""||!Number.isInteger(v)||v<0||v>90)throw new Error("Due days must be a whole number from 0 to 90.");v!==e.invoice_due_days&&(m.due_days=v);let u=s.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(u.some(x=>!Number.isInteger(x)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let f=[...new Set(u)].sort((x,N)=>x-N);Co(f,e.invoice_reminder_schedule)||(m.reminder_schedule=f);let p=s.footer.trim()||null;if(p!==e.invoice_footer&&(m.footer=p),Object.keys(m).length===0){r();return}let b=await t(m);r(b?Ic(b):void 0)});return Ne("fieldset",{disabled:o,className:"af-space-y-4",children:[Ne("label",{className:vs,children:["Days until due",ge(Q,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:s.dueDays,onChange:m=>n({...s,dueDays:m.target.value})})]}),Ne("label",{className:vs,children:["Reminder schedule",ge(Q,{"aria-label":"Reminder schedule",value:s.reminders,placeholder:"Off",onChange:m=>n({...s,reminders:m.target.value})}),ge(ka,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),Ne("label",{className:vs,children:["Invoice footer",ge("textarea",{"aria-label":"Invoice footer",className:Cc,maxLength:300,value:s.footer,onChange:m=>n({...s,footer:m.target.value})})]}),ge(Mn,{dirty:a,saving:o,error:c,onSave:()=>void i(),onDiscard:()=>{d(null),r()}})]})}function Mc({site:e,updateSite:t}){let{draft:s,setDraft:n,dirty:a,reset:r}=Un(e.default_email_recipients),{saving:o,error:c,setError:d,run:l}=$n(),[i,m]=ss.useState(""),[v,g]=ss.useState(null),u=()=>{let p=i.trim().toLowerCase();if(p){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p)){g("Enter a valid email address.");return}if(s.some(b=>b.toLowerCase()===p)){g("Already added.");return}n([...s,p]),m(""),g(null)}},f=()=>l(async()=>{let p=await t({default_email_recipients:s});r(p.default_email_recipients)});return Ne("fieldset",{disabled:o,className:"af-space-y-3",children:[Ne("div",{className:"af-flex af-flex-wrap af-gap-2",children:[s.map(p=>Ne(te,{variant:"secondary",className:"af-gap-1",children:[p,ge("button",{type:"button","aria-label":`Remove ${p}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>n(s.filter(b=>b!==p)),children:ge(Dc,{className:"af-h-3 af-w-3"})})]},p)),s.length===0&&ge("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),Ne("div",{className:"af-flex af-gap-2",children:[ge(Q,{"aria-label":"Add notification email",type:"email",value:i,placeholder:"Add email address",onChange:p=>{m(p.target.value),g(null)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),u())}}),ge(h,{type:"button",variant:"outline",disabled:!i.trim(),onClick:u,children:"Add"})]}),v&&ge(ur,{children:v}),ge(Mn,{dirty:a,saving:o,error:c,onSave:()=>void f(),onDiscard:()=>{d(null),r()}})]})}import{jsx as qa,jsxs as $c}from"react/jsx-runtime";function Vc({siteId:e,refreshKey:t,section:s,shippingProviderSlot:n,onConnectStripe:a,onUpgradePlan:r,className:o}){let{site:c,isLoading:d,error:l,refetch:i,updateSite:m}=an({siteId:e,refreshKey:t}),v=Ts.useRef(i),g=Ts.useRef(e);vn(()=>{v.current=i,g.current=e});let u=Ts.useRef({}),[f,p]=Ts.useState([]),b=f.some(R=>R.siteId===e),x=Ts.useCallback(()=>{let R={siteId:e},_=v.current;return p(k=>[...k,R]),k=>{let S=()=>p(T=>T.filter(w=>w!==R));!(g.current===R.siteId)||k&&v.current===_?S():v.current().finally(S)}},[e]),N=R=>_=>{u.current[R]=_},P=c!==null&&c.payments_active;if(Ts.useEffect(()=>{if(!P||!s)return;let R=u.current[s];R&&(R.scrollIntoView?.({behavior:"smooth",block:"start"}),R.focus({preventScroll:!0}))},[P,s]),d)return $c("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[qa(wp,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!c)return qa("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l?.message??"Could not load store settings."});if(!c.payments_active)return qa(Dn,{className:o,onConnectStripe:a,onUpgradePlan:r,whenActive:qa("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let y={site:c,updateSite:m,refetch:i};return $c("div",{className:`af-space-y-6 ${o??""}`,children:[l&&qa("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}),qa(ks,{ref:N("checkout"),id:"checkout",title:"Checkout",children:qa(Ac,{...y})}),qa(ks,{ref:N("shipping"),id:"shipping",title:"Shipping",children:qa(Lc,{...y,providerSlot:n,currencyChanging:b})}),qa(ks,{ref:N("tax"),id:"tax",title:"Tax",children:qa(Oc,{...y})}),qa(ks,{ref:N("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:qa(Fc,{...y,onChangeStart:x})})]},e)}import{Loader2 as Np}from"lucide-react";import{jsx as bn,jsxs as Hc}from"react/jsx-runtime";function wi({siteId:e,refreshKey:t,onSaveInvoiceSettings:s,className:n}){let{site:a,isLoading:r,error:o,updateSite:c,refetch:d,saveInvoiceSettings:l}=an({siteId:e,refreshKey:t,onSaveInvoiceSettings:s});return r?Hc("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[bn(Np,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):a?Hc("div",{className:`af-space-y-6 ${n??""}`,children:[o&&bn("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}),bn(ks,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:bn(Uc,{site:a,save:l})}),bn(ks,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:bn(Bc,{site:a,updateSite:c,refetch:d})})]},e):bn("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 Rp}from"lucide-react";import{jsx as dr,jsxs as zc}from"react/jsx-runtime";function qc({siteId:e,refreshKey:t,className:s}){let{site:n,isLoading:a,error:r,updateSite:o,refetch:c}=an({siteId:e,refreshKey:t});return a?zc("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[dr(Rp,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):n?zc("div",{className:`af-space-y-3 ${s??""}`,children:[r&&dr("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}),dr(ks,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:dr(Mc,{site:n,updateSite:o,refetch:c})})]},e):dr("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 Vn from"react";import{Fragment as Wc,jsx as ra,jsxs as fr}from"react/jsx-runtime";function jc({refreshKey:e,initialInvoiceId:t,onBackToWebsite:s,onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:r,siteId:o,onSaveInvoiceSettings:c,className:d}){let{aggregates:l,isLoading:i,error:m,refetch:v}=Tn({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=Ln({refreshKey:e}),{api:u}=q(),f=g.filters,p=Vn.useCallback(()=>u.exportRetainersCsv(f),[u,f]),[b,x]=Vn.useState(!1),[N,P]=Vn.useState(null),[y,R]=Vn.useState(!1),_=ra("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:m||!i&&!l?fr("div",{role:"alert",className:"sm:af-col-span-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't load invoice totals. ",ra(h,{type:"button",variant:"link",size:"sm",onClick:()=>void v(),children:"Retry totals"})]}):i||!l?fr(Wc,{children:[ra(et,{label:"Outstanding",children:ra(J,{className:"af-h-6 af-w-24"})}),ra(et,{label:"Overdue",children:ra(J,{className:"af-h-6 af-w-24"})}),ra(et,{label:"Paid this month",children:ra(J,{className:"af-h-6 af-w-24"})})]}):fr(Wc,{children:[ra(et,{label:"Outstanding",detail:`${l.outstanding.count} open`,children:j(l.outstanding.amount,l.currency)}),ra(et,{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:j(l.overdue.amount,l.currency)}),ra(et,{label:"Paid this month",detail:`${l.paid_this_month.count} paid`,children:j(l.paid_this_month.amount,l.currency)})]})});return fr(Nt,{title:"Invoices",onBackToWebsite:s,hideBackButton:b,className:d,children:[_,o&&!b&&fr("div",{className:"af-mb-6",children:[ra(h,{type:"button",variant:"outline",size:"sm","aria-expanded":y,"aria-controls":"af-invoice-settings",onClick:()=>R(k=>!k),children:"Invoice settings"}),y&&ra("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:ra(wi,{siteId:o,refreshKey:e,onSaveInvoiceSettings:c})})]}),!b&&ra(In,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:N?.id??null,onShowCycles:k=>P(S=>S?.id===k.id?null:k),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded,exportCsv:p}),ra(Qs,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:x,onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:r,retainerFilter:N?{id:N.id,label:`${N.customer_name??N.customer_email??"Recurring invoices"} \u2014 ${N.description}`}:null,onClearRetainerFilter:()=>P(null)})]})}import*as Ia from"react";import{Mail as Zp}from"lucide-react";import*as ns from"react";function Ta(e,t,s){let[n,a]=ns.useState(null),[r,o]=ns.useState(!0),[c,d]=ns.useState(null),l=ns.useRef(0),i=ns.useRef(e);i.current=e;let m=ns.useRef(s);m.current=s;let v=ns.useCallback(async()=>{let u=++l.current,f=m.current;o(!0),d(null);try{let p=await i.current();u===l.current&&a({scope:f,value:p})}catch(p){u===l.current&&d(p instanceof Error?p:new Error("Request failed"))}finally{u===l.current&&o(!1)}},[]);ns.useEffect(()=>{v()},[v,t]);let g=n!==null&&n.scope===s;return{data:g?n.value:null,isLoading:r||!g&&c===null,error:c,refetch:v}}var ko={commitBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts"},cancelBroadcast:{method:"POST",path:"/sites/{siteId}/marketing/broadcasts/{sendId}/cancel",params:["sendId"]},createDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts"},updateDraft:{method:"PUT",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},deleteDraft:{method:"DELETE",path:"/sites/{siteId}/marketing/drafts/{draftId}",params:["draftId"]},testSendDraft:{method:"POST",path:"/sites/{siteId}/marketing/drafts/{draftId}/test",params:["draftId"]},importContacts:{method:"POST",path:"/sites/{siteId}/contacts/import"},exportContacts:{method:"GET",path:"/sites/{siteId}/contacts/export"},createTag:{method:"POST",path:"/sites/{siteId}/contact-tags"},updateTag:{method:"PATCH",path:"/sites/{siteId}/contact-tags/{tagId}",params:["tagId"]},bulkTagContacts:{method:"POST",path:"/sites/{siteId}/contacts/tags"},unsubscribeContact:{method:"POST",path:"/sites/{siteId}/contacts/{contactId}/unsubscribe",params:["contactId"]},updateSettings:{method:"PUT",path:"/sites/{siteId}/marketing"},setFormPurpose:{method:"PATCH",path:"/forms/{formId}",params:["formId"]},createWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps"},updateWelcomeStep:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},deleteWelcomeStep:{method:"DELETE",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}",params:["stepId"]},publishWelcomeStep:{method:"POST",path:"/sites/{siteId}/marketing/welcome/steps/{stepId}/publish",params:["stepId"]},activateWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/activate"},pauseWelcome:{method:"POST",path:"/sites/{siteId}/marketing/welcome/pause"},updateWelcome:{method:"PATCH",path:"/sites/{siteId}/marketing/welcome"},setRecoveryStep:{method:"PUT",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},publishRecoveryStep:{method:"POST",path:"/sites/{siteId}/marketing/recovery/steps/{step}/publish",params:["step"]},deleteRecoveryStep:{method:"DELETE",path:"/sites/{siteId}/marketing/recovery/steps/{step}",params:["step"]},activateRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/activate"},pauseRecovery:{method:"POST",path:"/sites/{siteId}/marketing/recovery/pause"}};function _p(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(ko,e)}function Pp(e,t,s){let n=ko[e],a="params"in n?n.params:[],r={...s};delete r.siteId;let o=n.path.replace("{siteId}",encodeURIComponent(t));for(let d of a){let l=r[d];if(typeof l!="string"&&typeof l!="number")throw new Error(`${e} needs ${d}`);o=o.replace(`{${d}}`,encodeURIComponent(String(l))),delete r[d]}let c=n.method==="GET"||n.method==="DELETE"?void 0:r;return{method:n.method,path:o,body:c}}var Gc={marketing_disabled:"Email marketing is not available yet.",site_deleted:"This site has been deleted.",sending_not_enabled:"Email sending is not turned on for this site. It needs the Pro plan.",sending_paused:"Sending is paused while we review this site.",domain_not_verified:"Verify your sending domain before you can send.",dmarc_missing:"Your domain needs a DMARC record before you can send.",postal_address_missing:"Add your business postal address before you can send. Every email has to show it.",allowance_exhausted:"You've used this month's email allowance. Sending resumes next month or when you upgrade.",ramp_limit:"Today's sending limit for a new domain is used up. Sending continues tomorrow.",sample_failed:"Too many emails in the first batch bounced, so the rest of this send was stopped."},Ni=new Set(["domain_not_verified","dmarc_missing","postal_address_missing"]);function Hn(e){return e?Gc[e]??"Sending is not available right now.":null}import*as Es from"react";var zn=50;function Ri({siteId:e,q:t="",offset:s=0,refreshKey:n=0}){let{api:a}=q(),r=Ta(()=>a.getMarketingContacts(e,{q:t||void 0,limit:zn,offset:s}),`${e}|${t}|${s}|${n}`,e),o=Ta(()=>a.getMarketingContactStats(e),`${e}|${n}`,e),c=Ta(()=>a.getMarketingTags(e),`${e}|${n}`,e);return{contacts:r,stats:o,tags:c,refetchAll:async()=>{await Promise.all([r.refetch(),o.refetch(),c.refetch()])}}}import*as jn from"react";import*as Vs from"react";import{Fragment as kp,jsx as mr,jsxs as Kc}from"react/jsx-runtime";var pr=e=>`af-email-settings-${e}`,To=Vs.createContext(null);function Wt(){let e=Vs.useContext(To);if(!e)throw new Error("Email panels render inside EmailView");return e}function _i({onClick:e,children:t}){return mr("button",{type:"button",onClick:e,className:"af-font-medium af-underline af-underline-offset-2 hover:af-no-underline",children:t})}function Pi({reason:e}){let{openSetup:t,onOpenStoreSettings:s}=Wt(),n=e&&Ni.has(e)?mr(_i,{onClick:t,children:"Finish setup"}):e==="checkout_consent_off"&&s?mr(_i,{onClick:s,children:"Open Store settings"}):null;return n&&Kc(kp,{children:[" ",n]})}function Cp(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 qn(e,t){return Cp(e)===t?!0:e instanceof Error&&e.message.includes(t)}function Wn(e){return e instanceof Error&&e.message?e.message:"Something went wrong. Try again."}function ia(){let{onOrgAction:e}=Wt(),[t,s]=Vs.useState(!1),[n,a]=Vs.useState(null),r=Vs.useCallback(async(o,c={})=>{s(!0),a(null);try{return{ok:!0,result:await e(o,c)}}catch(d){return a(Wn(d)),{ok:!1,error:d}}finally{s(!1)}},[e]);return{busy:t,error:n,setError:a,run:r}}function Ce({tone:e="info",children:t,className:s}){return mr("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",s),children:t})}function Wa({children:e,action:t,id:s}){return Kc("div",{id:s,className:"af-mb-2 af-mt-6 af-flex af-items-center af-justify-between af-gap-2 first:af-mt-0",children:[mr("h3",{className:"af-text-sm af-font-semibold",children:e}),t]})}function De(e){return e.toLocaleString("en-US")}import{jsx as ja,jsxs as sn}from"react/jsx-runtime";var Eo="I confirm that everyone in this file agreed to receive marketing email from my business.",Tp={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 Ci({onImported:e}){let{canWrite:t}=Wt(),[s,n]=jn.useState(""),[a,r]=jn.useState(null),[o,c]=jn.useState(""),[d,l]=jn.useState(!1),[i,m]=jn.useState(null),v=ia(),g=async()=>{if(!d||!s.trim())return;let u=o.split(",").map(p=>p.trim()).filter(Boolean),f=await v.run("importContacts",{csv:s,attested:!0,...u.length?{tags:u}:{}});if(f.ok){let p=f.result;m(p),e?.(p)}};if(i){let u=new Map;for(let f of i.skipped_rows)u.set(f.reason,(u.get(f.reason)??0)+1);return sn("div",{className:"af-space-y-2 af-rounded-md af-border af-p-3","data-testid":"import-report",children:[ja("div",{className:"af-font-medium",children:"Import finished"}),sn("p",{className:"af-text-sm",children:[De(i.rows)," rows: ",De(i.created)," new, ",De(i.updated)," updated, ",De(i.skipped)," skipped."]}),u.size>0&&ja("ul",{className:"af-list-disc af-pl-5 af-text-sm af-text-muted-foreground",children:[...u].map(([f,p])=>sn("li",{children:[De(p)," ",Tp[f]??f]},f))}),ja("p",{className:"af-text-xs af-text-muted-foreground",children:"Your first send to imported contacts goes to a sample first."}),ja(h,{type:"button",size:"sm",variant:"outline",onClick:()=>{m(null),n(""),r(null),l(!1)},children:"Import another file"})]})}return sn("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:u=>{u.preventDefault(),g()},children:[sn("label",{className:"af-block af-space-y-1",children:[ja("span",{className:"af-text-sm af-font-medium",children:"CSV file"}),ja("input",{"aria-label":"CSV file",type:"file",accept:".csv,text/csv",className:"af-block af-text-sm",onChange:async u=>{let f=u.target.files?.[0];f&&(r(f.name),n(await f.text()))}}),ja("span",{className:"af-block af-text-xs af-text-muted-foreground",children:'Needs an "email" column. Tags in a "tags" column are applied too.'}),a&&ja("span",{className:"af-block af-text-xs",children:a})]}),sn("label",{className:"af-block af-space-y-1",children:[ja("span",{className:"af-text-xs af-text-muted-foreground",children:"Tag everyone in this file (optional, comma-separated)"}),ja(Q,{"aria-label":"Tags for imported contacts",value:o,onChange:u=>c(u.target.value)})]}),sn("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[ja("input",{"aria-label":"Consent attestation",type:"checkbox",className:"af-mt-1",checked:d,onChange:u=>l(u.target.checked)}),sn("span",{children:[Eo," Importing people who didn't agree can get your sending paused."]})]}),v.error&&ja(Ce,{tone:"error",children:v.error}),ja(h,{type:"submit",size:"sm",disabled:!t||!d||!s.trim()||v.busy,children:v.busy?"Importing\u2026":"Import contacts"})]})}import{Fragment as Yc,jsx as _e,jsxs as Rt}from"react/jsx-runtime";var Ep={subscribed:"Subscribed",pending:"Confirming",none:"Not opted in",unsubscribed:"Unsubscribed"};function Zc(){let{siteId:e,canWrite:t,refreshKey:s}=Wt(),[n,a]=Es.useState(""),[r,o]=Es.useState(""),[c,d]=Es.useState(0),[l,i]=Es.useState(0),[m,v]=Es.useState(new Set),[g,u]=Es.useState(!1),f=Ri({siteId:e,q:r,offset:c,refreshKey:l+s}),p=ia(),b=()=>i(_=>_+1),x=f.stats.data,N=f.contacts.data,P=f.tags.data??[],y=x?x.growth.slice(-4).reduce((_,k)=>_+k.new_subscribers,0):null,R=async()=>{let _=await p.run("exportContacts",{});if(!_.ok||typeof _.result!="string"||typeof document>"u")return;let k=URL.createObjectURL(new Blob([_.result],{type:"text/csv;charset=utf-8"})),S=document.createElement("a");S.href=k,S.download=`contacts-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(S),S.click(),document.body.removeChild(S),URL.revokeObjectURL(k)};return Rt("div",{children:[Rt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:[_e(et,{label:"Contacts",valueClassName:"af-text-base af-font-semibold",children:x?De(x.total):_e(J,{className:"af-h-6 af-w-16"})}),_e(et,{label:"Can be emailed",valueClassName:"af-text-base af-font-semibold",children:x?De(x.mailable):_e(J,{className:"af-h-6 af-w-16"})}),_e(et,{label:"New subscribers, last 4 weeks",valueClassName:"af-text-base af-font-semibold",children:y!==null?De(y):_e(J,{className:"af-h-6 af-w-16"})})]}),Rt("div",{className:"af-mt-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[Rt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:_=>{_.preventDefault(),d(0),o(n.trim())},children:[_e(Q,{"aria-label":"Search contacts",placeholder:"Search by email or name",value:n,onChange:_=>a(_.target.value)}),_e(h,{type:"submit",variant:"outline",size:"sm",children:"Search"})]}),_e(h,{type:"button",variant:"outline",size:"sm",disabled:!t,onClick:()=>u(_=>!_),children:g?"Close import":"Import"}),_e(h,{type:"button",variant:"outline",size:"sm",disabled:!t||p.busy,onClick:()=>void R(),children:"Export"})]}),g&&_e("div",{className:"af-mt-3",children:_e(Ci,{onImported:b})}),p.error&&_e(Ce,{tone:"error",className:"af-mt-2",children:p.error}),t&&m.size>0&&_e(Dp,{tags:P.filter(_=>!_.system),count:m.size,busy:p.busy,onApply:async(_,k)=>{(await p.run("bulkTagContacts",{action:_,tag_id:k,contact_ids:[...m]})).ok&&(v(new Set),b())}}),_e("div",{className:"af-mt-3",children:f.contacts.error?_e(Lt,{message:"Couldn't load contacts.",onRetry:()=>void f.contacts.refetch()}):N?N.contacts.length===0?_e(sa,{children:r?"No contacts match.":"No contacts yet. Signups from your forms and checkout appear here, or import a list."}):Rt(Yc,{children:[_e("ul",{className:"af-divide-y af-rounded-md af-border",children:N.contacts.map(_=>_e(Ip,{contact:_,canWrite:t,busy:p.busy,selected:m.has(_.id),onSelect:k=>v(S=>{let C=new Set(S);return k?C.add(_.id):C.delete(_.id),C}),onUnsubscribe:async()=>{(await p.run("unsubscribeContact",{contactId:_.id})).ok&&b()}},_.id))}),Rt("div",{className:"af-mt-2 af-flex af-items-center af-justify-between af-text-xs af-text-muted-foreground",children:[Rt("span",{children:[De(c+1),"\u2013",De(c+N.contacts.length)," of ",De(N.total)]}),Rt("div",{className:"af-flex af-gap-2",children:[_e(h,{type:"button",variant:"ghost",size:"sm",disabled:c===0,onClick:()=>d(Math.max(0,c-zn)),children:"Previous"}),_e(h,{type:"button",variant:"ghost",size:"sm",disabled:c+N.contacts.length>=N.total,onClick:()=>d(c+zn),children:"Next"})]})]})]}):_e(J,{className:"af-h-24 af-w-full"})}),_e(Ap,{tags:P,canWrite:t,onChanged:b})]})}function Ip({contact:e,canWrite:t,busy:s,selected:n,onSelect:a,onUnsubscribe:r}){return Rt("li",{className:"af-flex af-items-center af-gap-3 af-px-3 af-py-2",children:[t&&_e("input",{type:"checkbox","aria-label":`Select ${e.email}`,checked:n,onChange:o=>a(o.target.checked)}),Rt("div",{className:"af-min-w-0 af-flex-1",children:[Rt("div",{className:"af-truncate af-text-sm",children:[e.email,e.name?Rt("span",{className:"af-text-muted-foreground",children:[" \xB7 ",e.name]}):null]}),Rt("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-1",children:[_e(te,{variant:e.mailable?"success":"secondary",children:e.status==="subscribed"&&!e.mailable?"Suppressed":Ep[e.status]}),e.tags.map(o=>_e(te,{variant:"outline",children:o.label},o.id))]})]}),t&&(e.status==="subscribed"||e.status==="pending")&&_e(h,{type:"button",variant:"ghost",size:"sm",disabled:s,onClick:r,children:"Unsubscribe"})]})}function Dp({tags:e,count:t,busy:s,onApply:n}){let[a,r]=Es.useState("");return Rt("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:[Rt("span",{children:[De(t)," selected"]}),Rt("select",{"aria-label":"Tag for selected contacts",className:"af-rounded-md af-border af-px-2 af-py-1",value:a,onChange:o=>r(o.target.value),children:[_e("option",{value:"",children:"Choose a tag\u2026"}),e.map(o=>_e("option",{value:o.id,children:o.label},o.id))]}),_e(h,{type:"button",size:"sm",variant:"outline",disabled:!a||s,onClick:()=>n("add",a),children:"Add tag"}),_e(h,{type:"button",size:"sm",variant:"ghost",disabled:!a||s,onClick:()=>n("remove",a),children:"Remove tag"})]})}function Ap({tags:e,canWrite:t,onChanged:s}){let[n,a]=Es.useState(""),[r,o]=Es.useState(null),c=ia();return Rt("div",{children:[_e(Wa,{children:"Tags"}),e.length===0?_e("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."}):_e("ul",{className:"af-divide-y af-rounded-md af-border",children:e.map(d=>_e("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:r?.id===d.id?Rt("form",{className:"af-flex af-flex-1 af-gap-2",onSubmit:async l=>{l.preventDefault(),(await c.run("updateTag",{tagId:d.id,label:r.label.trim()})).ok&&(o(null),s())},children:[_e(Q,{"aria-label":`New name for ${d.label}`,value:r.label,onChange:l=>o({id:d.id,label:l.target.value})}),_e(h,{type:"submit",size:"sm",disabled:!r.label.trim()||c.busy,children:"Save"})]}):Rt(Yc,{children:[Rt("span",{children:[d.label," ",Rt("span",{className:"af-text-muted-foreground",children:["\xB7 ",De(d.total)," contacts, ",De(d.mailable)," can be emailed"]})]}),t&&!d.system&&_e(h,{type:"button",size:"sm",variant:"ghost",onClick:()=>o({id:d.id,label:d.label}),children:"Rename"})]})},d.id))}),t&&Rt("form",{className:"af-mt-2 af-flex af-gap-2",onSubmit:async d=>{d.preventDefault(),(await c.run("createTag",{label:n.trim()})).ok&&(a(""),s())},children:[_e(Q,{"aria-label":"New tag",placeholder:"New tag",value:n,maxLength:100,onChange:d=>a(d.target.value)}),_e(h,{type:"submit",size:"sm",variant:"outline",disabled:!n.trim()||c.busy,children:"Add tag"})]}),c.error&&_e(Ce,{tone:"error",className:"af-mt-2",children:c.error})]})}import*as rt from"react";import{ArrowLeft as Op}from"lucide-react";function ki({siteId:e,refreshKey:t=0}){let{api:s}=q();return Ta(()=>s.getBroadcasts(e),`${e}|${t}`,e)}function Ti({siteId:e,kind:t,refreshKey:s=0}){let{api:n}=q();return Ta(()=>n.getEmailDrafts(e,t),`${e}|${t??""}|${s}`,`${e}|${t??""}`)}import*as Et from"react";import{Fragment as Jc,jsx as Ue,jsxs as rs}from"react/jsx-runtime";function Xc({draftId:e,renderCommit:t,onSaved:s}){let{api:n}=q(),{siteId:a,canWrite:r,refreshKey:o}=Wt(),[c,d]=Et.useState(null),[l,i]=Et.useState(null),[m,v]=Et.useState(null),[g,u]=Et.useState(null),[f,p]=Et.useState(!1),[b,x]=Et.useState(null),N=ia(),P=ia(),y=Et.useRef(!1),R=Et.useRef(!1),_=Et.useCallback(C=>{y.current=C},[]),k=Et.useCallback(async(C={})=>{u(null),v(null);let[T,w]=await Promise.allSettled([n.getEmailDraft(a,e),n.previewEmailDraft(a,e)]);if(C.unlessDirty&&y.current){R.current=!0;return}if(T.status==="rejected"){u(Wn(T.reason));return}d(T.value),w.status==="fulfilled"?i(w.value):(i(null),v(qn(w.reason,"postal_address_missing")?{text:"Add your business postal address to preview this email.",code:"postal_address_missing"}:{text:Wn(w.reason),code:null}))},[n,a,e]);Et.useEffect(()=>{d(null),i(null),k()},[k]);let S=Et.useRef(o);return Et.useEffect(()=>{if(o!==S.current){if(S.current=o,y.current){R.current=!0;return}k({unlessDirty:!0})}},[o,k]),g?rs(Ce,{tone:"error",children:["Couldn't load this email. ",g]}):c?rs("div",{className:"af-space-y-4",children:[rs("div",{children:[Ue("div",{className:"af-text-xs af-text-muted-foreground",children:"Subject"}),Ue("div",{className:"af-font-medium",children:c.subject||"(no subject)"}),c.preheader&&Ue("div",{className:"af-text-sm af-text-muted-foreground",children:c.preheader})]}),f?Ue(Lp,{draft:c,onDirtyChange:_,busy:N.busy,error:N.error,onCancel:()=>{y.current=!1,p(!1),R.current&&(R.current=!1,k())},onSave:async C=>{let T=await N.run("updateDraft",{draftId:e,expected_version:c.version,...C});T.ok?(y.current=!1,R.current=!1,p(!1),await k(),s?.()):qn(T.error,"version_conflict")&&(N.setError("This email changed while you were editing. We've loaded the latest version."),y.current=!1,R.current=!1,p(!1),await k())}},c.version):rs("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ue(h,{type:"button",variant:"outline",size:"sm",disabled:!r,onClick:()=>p(!0),children:"Edit text"}),Ue(h,{type:"button",variant:"outline",size:"sm",disabled:!r||P.busy,onClick:async()=>{x(null);let C=await P.run("testSendDraft",{draftId:e});C.ok&&x(C.result?.sent_to??"your email")},children:"Send a test to me"})]}),N.error&&!f&&Ue(Ce,{tone:"warning",children:N.error}),b&&rs(Ce,{tone:"success",children:["Test sent to ",b,"."]}),P.error&&Ue(Ce,{tone:"error",children:P.error}),l?Ue("iframe",{title:"Email preview",sandbox:"",srcDoc:l.html,className:"af-h-[480px] af-w-full af-rounded-md af-border af-bg-white"}):m?rs(Ce,{tone:"warning",children:[m.text,Ue(Pi,{reason:m.code})]}):Ue(J,{className:"af-h-40 af-w-full"}),l&&t?.({draft:c,preview:l,reload:k})]}):Ue(J,{className:"af-h-40 af-w-full"})}function Lp({draft:e,busy:t,error:s,onSave:n,onCancel:a,onDirtyChange:r}){let[o,c]=Et.useState(e.subject),[d,l]=Et.useState(e.preheader??""),[i,m]=Et.useState(e.blocks),v=o!==e.subject||d!==(e.preheader??"")||i!==e.blocks;Et.useEffect(()=>r(v),[v,r]);let g=(u,f)=>m(p=>p.map((b,x)=>x===u?{...b,...f}:b));return rs("form",{className:"af-space-y-3 af-rounded-md af-border af-p-3",onSubmit:u=>{u.preventDefault(),n({subject:o,preheader:d.trim()||null,blocks:i})},children:[Ue(Hs,{label:"Subject",children:Ue(Q,{"aria-label":"Subject",value:o,maxLength:200,onChange:u=>c(u.target.value)})}),Ue(Hs,{label:"Preview text",children:Ue(Q,{"aria-label":"Preview text",value:d,maxLength:200,onChange:u=>l(u.target.value)})}),i.map((u,f)=>rs("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[u.type==="heading"&&Ue(Hs,{label:"Heading",children:Ue(Q,{"aria-label":`Heading ${f+1}`,value:u.text,onChange:p=>g(f,{text:p.target.value})})}),u.type==="text"&&Ue(Hs,{label:"Text",children:Ue("textarea",{"aria-label":`Text ${f+1}`,className:"af-min-h-[96px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",value:u.text,onChange:p=>g(f,{text:p.target.value})})}),u.type==="image"&&rs(Jc,{children:[Ue(Hs,{label:"Image URL",children:Ue(Q,{"aria-label":`Image URL ${f+1}`,value:u.url,onChange:p=>g(f,{url:p.target.value})})}),Ue(Hs,{label:"Image description",children:Ue(Q,{"aria-label":`Image description ${f+1}`,value:u.alt??"",onChange:p=>g(f,{alt:p.target.value})})})]}),u.type==="button"&&rs(Jc,{children:[Ue(Hs,{label:"Button label",children:Ue(Q,{"aria-label":`Button label ${f+1}`,value:u.label,onChange:p=>g(f,{label:p.target.value})})}),Ue(Hs,{label:"Button link",children:Ue(Q,{"aria-label":`Button link ${f+1}`,value:u.url,onChange:p=>g(f,{url:p.target.value})})})]}),u.type==="cart"&&Ue(Hs,{label:"Cart button label",children:Ue(Q,{"aria-label":`Cart button label ${f+1}`,value:u.label,onChange:p=>g(f,{label:p.target.value})})})]},f)),s&&Ue(Ce,{tone:"error",children:s}),rs("div",{className:"af-flex af-gap-2",children:[Ue(h,{type:"submit",size:"sm",disabled:t,children:"Save changes"}),Ue(h,{type:"button",variant:"ghost",size:"sm",onClick:a,children:"Cancel"})]})]})}function Hs({label:e,children:t}){return rs("label",{className:"af-block af-space-y-1",children:[Ue("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}import{jsx as we,jsxs as ht}from"react/jsx-runtime";var Bp={scheduled:"Scheduled",unscheduled:"Edited \u2014 send again",sending:"Sending",sent:"Sent",cancelled:"Cancelled",failed:"Failed"};function eu({initialDraftId:e}){let{siteId:t,canWrite:s,refreshKey:n}=Wt(),[a,r]=rt.useState(0),o=a+n,[c,d]=rt.useState(e??null),l=Ti({siteId:t,kind:"broadcast",refreshKey:o}),i=ki({siteId:t,refreshKey:o}),m=ia();return c?ht("div",{className:"af-space-y-4",children:[ht(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(null),children:[we(Op,{className:"af-mr-1 af-h-4 af-w-4"}),"All broadcasts"]}),we(Xc,{draftId:c,onSaved:()=>r(v=>v+1),renderCommit:v=>we($p,{...v,onCommitted:()=>r(g=>g+1)})})]}):ht("div",{children:[we(Wa,{children:"Drafts"}),l.error?we(Lt,{message:"Couldn't load drafts.",onRetry:()=>void l.refetch()}):l.data?l.data.length===0?we(sa,{children:"Ask the assistant to write a newsletter. Its draft shows up here for you to review and send."}):we("ul",{className:"af-divide-y af-rounded-md af-border",children:l.data.map(v=>ht("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2",children:[we("span",{className:"af-truncate af-text-sm",children:v.subject||"(no subject)"}),we(h,{type:"button",variant:"outline",size:"sm",onClick:()=>d(v.id),children:"Review"})]},v.id))}):we(J,{className:"af-h-10 af-w-full"}),we(Wa,{children:"Sent and scheduled"}),m.error&&we(Ce,{tone:"error",children:m.error}),i.error?we(Lt,{message:"Couldn't load broadcasts.",onRetry:()=>void i.refetch()}):i.data?i.data.length===0?we(sa,{children:"Nothing sent yet."}):we("ul",{className:"af-divide-y af-rounded-md af-border",children:i.data.map(v=>we(Fp,{broadcast:v,canCancel:s&&(v.status==="scheduled"||v.status==="unscheduled"||v.status==="sending"),busy:m.busy,onCancel:async()=>{(await m.run("cancelBroadcast",{sendId:v.id})).ok&&r(u=>u+1)}},v.id))}):we(J,{className:"af-h-10 af-w-full"})]})}function Fp({broadcast:e,canCancel:t,busy:s,onCancel:n}){return ht("li",{className:"af-space-y-1 af-px-3 af-py-2",children:[ht("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[we("span",{className:"af-truncate af-text-sm af-font-medium",children:e.subject}),ht("div",{className:"af-flex af-items-center af-gap-2",children:[we(te,{variant:e.status==="failed"?"destructive":e.status==="sent"?"success":"secondary",children:Bp[e.status]}),t&&we(h,{type:"button",variant:"ghost",size:"sm",disabled:s,onClick:n,children:"Cancel"})]})]}),ht("div",{className:"af-text-xs af-text-muted-foreground",children:[e.scheduled_at&&e.status==="scheduled"?`Sends ${new Date(e.scheduled_at).toLocaleString()} \xB7 `:"",De(e.recipients.planned)," recipients \xB7 ",De(e.stats.delivered)," delivered \xB7 ",De(e.stats.opened)," opened \xB7"," ",De(e.stats.clicked)," clicked \xB7 ",De(e.stats.bounced)," bounced \xB7 ",De(e.stats.complained)," complaints \xB7"," ",De(e.stats.unsubscribed)," unsubscribed"]}),e.status_reason&&we("div",{className:"af-text-xs af-text-muted-foreground",children:Hn(e.status_reason)})]})}var tu=e=>JSON.stringify([e.id,e.version,e.targeting??null,e.proposed_send_at??null]);function Qc(e){let t=e.targeting??null,s=e.proposed_send_at?new Date(e.proposed_send_at):null,n=s!==null&&s.getTime()>Date.now();return{key:tu(e),draftId:e.id,tagIds:t?.tag_ids??[],match:t?.match??"any",scheduleAt:n?Up(s):"",suggested:t!==null||s!==null,timePassed:s!==null&&!n}}function Up(e){let t=s=>String(s).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}var Mp=(e,t)=>e.match===t.match&&e.scheduleAt===t.scheduleAt&&e.tagIds.length===t.tagIds.length&&e.tagIds.every(s=>t.tagIds.includes(s));function $p({draft:e,preview:t,reload:s,onCommitted:n}){let{api:a}=q(),{siteId:r,canWrite:o,settings:c,refreshKey:d}=Wt(),[l,i]=rt.useState(null),[m,v]=rt.useState(!1),[g,u]=rt.useState(null),[f,p]=rt.useState(()=>Qc(e)),[b,x]=rt.useState(f.tagIds),[N,P]=rt.useState(f.match),[y,R]=rt.useState(f.scheduleAt),[_,k]=rt.useState(0),S=!Mp({tagIds:b,match:N,scheduleAt:y},f),C=tu(e);rt.useEffect(()=>{if(C===f.key||e.id===f.draftId&&S)return;let Y=Qc(e);p(Y),x(Y.tagIds),P(Y.match),R(Y.scheduleAt),k(0)},[C,e,f,S]);let T=rt.useMemo(()=>l?new Set(l.map(Y=>Y.id)):null,[l]),w=T!==null&&b.every(Y=>T.has(Y));rt.useEffect(()=>{if(!T||b.every(pe=>T.has(pe)))return;let Y=pe=>pe.filter(Fe=>T.has(Fe));k(pe=>pe+b.length-Y(b).length),x(Y(b)),p(pe=>({...pe,tagIds:Y(pe.tagIds)}))},[T,b]);let[W,K]=rt.useState(null),[$,ne]=rt.useState(null),[ie,ue]=rt.useState(null),F=ia();rt.useEffect(()=>{a.getMarketingTags(r).then(Y=>{i(Y),v(!1)},()=>{i(null),v(!0)}),a.getMarketingContactStats(r).then(u,()=>u(null))},[a,r,d]);let Z=y?new Date(y).toISOString():null,B=JSON.stringify([b,N,Z]),le=W?.plan??null,oe=W!==null&&W.key===B,Ke=rt.useRef(0),xe=rt.useCallback(async()=>{let Y=++Ke.current;ne(null);try{let pe=await a.estimateBroadcast(r,{targeting:{tag_ids:b,match:N},scheduled_at:Z});Y===Ke.current&&K({key:B,plan:pe})}catch(pe){if(Y!==Ke.current)return;K(null),ne(Wn(pe))}},[a,r,b,N,Z,B,d]),Me=rt.useRef(!1);rt.useEffect(()=>{if(!w&&b.length>0)return;if(!Me.current){Me.current=!0,xe();return}let Y=setTimeout(()=>void xe(),300);return()=>clearTimeout(Y)},[xe,w,b.length]);let We=c&&!c.readiness.can_send?Hn(c.readiness.reason):null,ke=le!==null&&!le.fits,St=g?Math.max(0,g.by_status.subscribed-g.mailable):null,I=g&&le&&St!==null?Math.max(0,g.total-le.recipients-St):null,U=!o||F.busy||!le||!oe||ke||le.recipients===0||We!==null||m&&b.length>0,O=async()=>{ue(null);let Y=await F.run("commitBroadcast",{draft_id:e.id,expected_version:t.version,targeting:{tag_ids:b,match:N},scheduled_at:Z});if(Y.ok){ue({tone:"success",text:Z?"Scheduled.":"Sending now."}),n();return}qn(Y.error,"version_conflict")?(F.setError(null),await s(),ue({tone:"warning",text:"This email changed since you previewed it. Check the latest version above, then send again."})):qn(Y.error,"over_allowance")&&await xe()},be=Y=>x(pe=>pe.includes(Y)?pe.filter(Fe=>Fe!==Y):[...pe,Y]);return ht("div",{className:"af-space-y-3 af-rounded-md af-border af-p-3",children:[f.suggested&&!S&&we(Ce,{children:"Suggested by your assistant \u2014 review before sending."}),we(Wa,{children:"Who gets it"}),m&&we(Ce,{tone:"warning",children:b.length>0?"Couldn't load your tags, so this targeted send can't go out yet. Refresh to try again.":"Couldn't load your tags. Refresh to target by tag."}),_>0&&we(Ce,{tone:"warning",children:_===1?"A suggested tag no longer exists, so it was left out.":"Some suggested tags no longer exist, so they were left out."}),l&&l.length>0?ht("div",{className:"af-space-y-2",children:[we("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map(Y=>ht("label",{className:"af-flex af-items-center af-gap-1 af-text-sm",children:[we("input",{type:"checkbox",checked:b.includes(Y.id),onChange:()=>be(Y.id)}),Y.label]},Y.id))}),b.length>1&&ht("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:["Contacts with",ht("select",{"aria-label":"Tag match",value:N,onChange:Y=>P(Y.target.value),className:"af-rounded-md af-border af-px-2 af-py-1",children:[we("option",{value:"any",children:"any of these tags"}),we("option",{value:"all",children:"all of these tags"})]})]}),b.length===0&&we("p",{className:"af-text-xs af-text-muted-foreground",children:"No tags picked: everyone who can be emailed."})]}):we("p",{className:"af-text-sm af-text-muted-foreground",children:"Everyone who can be emailed."}),ht("label",{className:"af-block af-space-y-1",children:[we("span",{className:"af-text-xs af-text-muted-foreground",children:"Send later (optional)"}),we(Q,{"aria-label":"Schedule time",type:"datetime-local",value:y,onChange:Y=>R(Y.target.value)})]}),f.timePassed&&!y&&we(Ce,{tone:"warning",children:"The suggested time has passed, so this isn't scheduled. Pick a new time or send now."}),$?ht(Ce,{tone:"error",children:["Couldn't work out the audience. ",$]}):le?ht("div",{className:"af-space-y-2 af-text-sm","data-testid":"broadcast-plan",children:[ht("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[we(Io,{label:"Will receive it",value:le.recipients}),we(Io,{label:"Suppressed (bounced or complained)",value:St}),we(Io,{label:"Not included",value:I})]}),ht("p",{className:"af-text-muted-foreground",children:[De(le.allowance.remaining)," of ",De(le.allowance.monthly)," emails left this month."]}),le.sample_size!==null&&ht(Ce,{children:["We'll send to ",De(le.sample_size)," people first and check for bounces before sending the rest."]}),le.ramp_days.length>1&&ht(Ce,{children:["Your domain is new, so this goes out over ",le.ramp_days.length," days:"," ",le.ramp_days.map(Y=>`${De(Y.recipients)} on ${Y.date}`).join(", "),"."]})]}):we(J,{className:"af-h-12 af-w-full"}),ke&&le&&ht(Ce,{tone:"warning",children:["This send needs ",De(le.recipients)," emails, but only ",De(le.allowance.remaining)," are left this month. Narrow the audience or wait for next month."]}),We&&ht(Ce,{tone:"warning",children:[We,we(Pi,{reason:c?.readiness.reason})]}),ie&&we(Ce,{tone:ie.tone,children:ie.text}),F.error&&we(Ce,{tone:"error",children:F.error}),we(h,{type:"button",disabled:U,onClick:()=>void O(),children:Z?"Schedule":"Send now"})]})}function Io({label:e,value:t}){return ht("div",{className:"af-rounded-md af-border af-px-2 af-py-1",children:[we("div",{className:"af-text-xs af-text-muted-foreground",children:e}),we("div",{className:"af-font-semibold",children:t===null?"\u2014":De(t)})]})}import*as fa from"react";import{jsx as ve,jsxs as Jt}from"react/jsx-runtime";var Ei="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 Vp(e){let{status:t,dmarc_status:s,sending_domain:n}=e.domain;return!n||t==="none"?"No sending domain yet.":t==="verified"?s==="ok"?`Verified. Emails send from ${n}.`:`${n} is verified, but your domain still needs a DMARC record.`:t==="failed"?`${n} couldn't be verified. Check the DNS records below.`:`Waiting for the DNS records on ${n} to take effect. This can take a few hours.`}function Do({onStartDomainSetup:e}){let{settings:t,refetchSettings:s,canWrite:n,settingsSection:a}=Wt(),r=t!==null;return fa.useEffect(()=>{r&&a&&document.getElementById(pr(a))?.scrollIntoView?.({block:"start"})},[r,a]),t?Jt("div",{children:[ve(Wa,{id:pr("domain"),children:"Sending domain"}),ve(Ao,{settings:t,canWrite:n,onStartDomainSetup:e,onChanged:s}),ve(zp,{settings:t}),ve(Wp,{settings:t,canWrite:n,onSaved:s},qp(t)),ve(Lo,{canWrite:n})]}):ve(J,{className:"af-h-40 af-w-full"})}function Ao({settings:e,canWrite:t,onStartDomainSetup:s,onChanged:n}){let[a,r]=fa.useState(null),[o,c]=fa.useState(!1),[d,l]=fa.useState(null),i=e.domain.status==="verified"&&e.domain.dmarc_status==="ok";return Jt("div",{children:[ve("p",{className:"af-text-sm",children:Vp(e)}),!i&&s&&ve(h,{type:"button",size:"sm",className:"af-mt-2",disabled:!t||o,onClick:async()=>{c(!0),l(null);try{r(await s()),await n()}catch(m){l(m instanceof Error?m.message:"Couldn't start domain setup.")}finally{c(!1)}},children:e.domain.sending_domain?"Check domain setup":"Set up sending domain"}),d&&ve(Ce,{tone:"error",className:"af-mt-2",children:d}),a?.records&&a.records.length>0&&Jt("div",{className:"af-mt-3 af-space-y-1",children:[ve("p",{className:"af-text-sm",children:"Add these records at your domain provider:"}),Jt("table",{className:"af-w-full af-text-left af-text-xs",children:[ve("thead",{children:Jt("tr",{children:[ve("th",{className:"af-py-1 af-pr-2",children:"Type"}),ve("th",{className:"af-py-1 af-pr-2",children:"Name"}),ve("th",{className:"af-py-1 af-pr-2",children:"Value"}),ve("th",{className:"af-py-1",children:"Priority"})]})}),ve("tbody",{children:a.records.map((m,v)=>Jt("tr",{className:"af-border-t af-align-top",children:[ve("td",{className:"af-py-1 af-pr-2",children:m.type}),ve("td",{className:"af-break-all af-py-1 af-pr-2",children:m.name}),ve("td",{className:"af-break-all af-py-1 af-pr-2",children:m.value}),ve("td",{className:"af-py-1",children:m.priority??""})]},v))})]})]}),a&&ve(Hp,{result:a})]})}function Hp({result:e}){return e.status==="no_domain"?ve(Ce,{tone:"warning",className:"af-mt-2",children:"Emails send from your own domain, so this site needs a custom domain first. Connect one, then come back to finish here."}):e.status==="not_available"?ve(Ce,{tone:"warning",className:"af-mt-2",children:"Email sending isn't available for this site. It needs the Pro plan."}):e.records&&e.records.length>0?null:ve("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",children:"We added the DNS records for you. Verification usually finishes within a few hours."})}function zp({settings:e}){let{monthly:t,sent:s,reserved:n}=e.allowance,a=s+n;return Jt("div",{children:[ve(Wa,{children:"Monthly allowance"}),Jt("p",{className:"af-text-sm",children:[De(a)," of ",De(t)," emails used this month (",De(Math.max(0,t-a))," left). Receipts and form notifications don't count."]})]})}function qp(e){return JSON.stringify([e.business_name,e.postal_address,e.reply_to,e.brand,e.double_opt_in,e.checkout_marketing_consent,e.stripe_account_country])}function Wp({settings:e,canWrite:t,onSaved:s}){let[n,a]=fa.useState(e.business_name??""),[r,o]=fa.useState(e.postal_address??""),[c,d]=fa.useState(e.reply_to??""),[l,i]=fa.useState(e.brand.color),[m,v]=fa.useState(e.brand.logo_url??""),[g,u]=fa.useState(e.double_opt_in),[f,p]=fa.useState(!1),[b,x]=fa.useState(!1),N=ia();return Jt("form",{onSubmit:async P=>{P.preventDefault(),x(!1),(await N.run("updateSettings",{business_name:n.trim()||null,postal_address:r.trim()||null,reply_to:c.trim()||null,double_opt_in:g,brand:{color:l,logo_url:m.trim()||null}})).ok&&(x(!0),await s())},children:[ve(Wa,{id:pr("sender"),children:"Sender details"}),Jt("div",{className:"af-space-y-3",children:[ve(gr,{label:"Business name (shown as the sender)",children:ve(Q,{"aria-label":"Business name",value:n,disabled:!t,onChange:P=>a(P.target.value)})}),ve(gr,{label:"Postal address (required in every email)",children:ve("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",value:r,disabled:!t,onChange:P=>o(P.target.value)})}),ve(gr,{label:"Replies go to (your account email or an address on your domain)",children:ve(Q,{"aria-label":"Reply-to email",type:"email",value:c,disabled:!t,onChange:P=>d(P.target.value)})})]}),ve(Wa,{children:"Brand"}),Jt("div",{className:"af-flex af-flex-wrap af-gap-3",children:[ve(gr,{label:"Brand color",children:ve(Q,{"aria-label":"Brand color",type:"color",className:"af-h-9 af-w-16 af-p-1",value:l,disabled:!t,onChange:P=>i(P.target.value)})}),ve(gr,{label:"Logo URL (https)",children:ve(Q,{"aria-label":"Logo URL",value:m,disabled:!t,onChange:P=>v(P.target.value)})})]}),ve(Wa,{id:pr("signups"),children:"Signups"}),ve("div",{className:"af-space-y-3 af-text-sm",children:Jt("div",{className:"af-relative af-flex af-items-center af-gap-2",children:[Jt("label",{className:"af-flex af-items-center af-gap-2",children:[ve("input",{"aria-label":"Double opt-in",type:"checkbox",checked:g,disabled:!t,onChange:P=>u(P.target.checked)}),"Double opt-in"]}),ve("span",{role:"button",tabIndex:0,"aria-label":"About double opt-in","aria-describedby":"af-double-opt-in-help",title:Ei,className:"af-inline-flex af-h-4 af-w-4 af-cursor-help af-items-center af-justify-center af-rounded-full af-border af-text-[10px]",onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onFocus:()=>p(!0),onBlur:()=>p(!1),children:"?"}),ve("div",{id:"af-double-opt-in-help",role:"tooltip",hidden:!f,className:"af-absolute af-left-0 af-top-6 af-z-10 af-max-w-sm af-rounded-md af-border af-bg-background af-p-2 af-text-xs af-shadow",children:Ei})]})}),N.error&&ve(Ce,{tone:"error",className:"af-mt-3",children:N.error}),b&&ve(Ce,{tone:"success",className:"af-mt-3",children:"Saved."}),t&&ve(h,{type:"submit",size:"sm",className:"af-mt-3",disabled:N.busy,children:"Save settings"})]})}function Lo({canWrite:e,heading:t=!0}){let{api:s}=q(),{siteId:n,refreshKey:a}=Wt(),r=Ta(async()=>Promise.all((await s.getForms()).map(l=>s.getForm(l.id))),`${n}|${a}`,n),[o,c]=fa.useState({}),d=ia();return!r.data||r.data.length===0?null:Jt("div",{children:[t&&ve(Wa,{children:"Newsletter signup forms"}),ve("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:"Submitting a newsletter signup form subscribes the visitor. Other forms need their own opt-in checkbox."}),ve("ul",{className:"af-divide-y af-rounded-md af-border",children:r.data.map(l=>Jt("li",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-3 af-py-2 af-text-sm",children:[ve("span",{className:"af-truncate",children:l.name}),Jt("label",{className:"af-flex af-items-center af-gap-2",children:[ve("input",{type:"checkbox","aria-label":`${l.name} is a newsletter signup`,checked:(l.id in o?o[l.id]:l.purpose)==="newsletter",disabled:!e||d.busy,onChange:async i=>{let m=i.target.checked?"newsletter":"general";(await d.run("setFormPurpose",{formId:l.id,purpose:m})).ok&&c(g=>({...g,[l.id]:m}))}}),"Newsletter signup"]})]},l.id))}),d.error&&ve(Ce,{tone:"error",className:"af-mt-2",children:d.error})]})}function gr({label:e,children:t}){return Jt("label",{className:"af-block af-space-y-1",children:[ve("span",{className:"af-text-xs af-text-muted-foreground",children:e}),t]})}import*as Ii from"react";import{Check as au,Mail as jp}from"lucide-react";import{jsx as at,jsxs as Ea}from"react/jsx-runtime";var Gp=["Signups from your site's forms land here automatically.","The assistant drafts your newsletters. You review and press Send.","Every email carries the unsubscribe link, consent record and postal address the law asks for."];function su({onStartDomainSetup:e}){let{api:t}=q(),{siteId:s,settings:n,refetchSettings:a,canWrite:r,refreshKey:o}=Wt(),c=Ta(()=>t.getMarketingContactStats(s),`${s}|${o}`,s);if(!n)return null;let d=n.domain.status==="verified"&&n.domain.dmarc_status==="ok",l=!!n.postal_address,i=c.data?.by_status.subscribed??0;return Ea("div",{className:"af-mx-auto af-max-w-2xl",children:[Ea("div",{className:"af-mb-6 af-rounded-lg af-border af-bg-muted/40 af-p-5",children:[Ea("div",{className:"af-mb-2 af-flex af-items-center af-gap-2",children:[at(jp,{className:"af-h-5 af-w-5","aria-hidden":!0}),at("h3",{className:"af-text-lg af-font-semibold",children:"Turn visitors into a list you own"})]}),at("p",{className:"af-text-sm af-text-muted-foreground",children:"Collect subscribers from your site, then send them newsletters from your own domain, branded with your logo and colors."}),at("ul",{className:"af-mt-3 af-space-y-1.5 af-text-sm",children:Gp.map(m=>Ea("li",{className:"af-flex af-gap-2",children:[at(au,{className:"af-mt-0.5 af-h-4 af-w-4 af-shrink-0 af-text-primary","aria-hidden":!0}),m]},m))}),i>0&&Ea("p",{className:"af-mt-3 af-text-sm af-font-medium",children:[De(i)," ",i===1?"subscriber is":"subscribers are"," already waiting for your first email."]})]}),at("h3",{className:"af-mb-3 af-text-sm af-font-semibold",children:"Set up sending"}),!r&&at(Ce,{className:"af-mb-3",children:"Only the site owner can finish setup."}),Ea("ol",{className:"af-space-y-3",children:[Ea(Oo,{n:1,title:"Send from your own domain",done:d,children:[at("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."}),at(Ao,{settings:n,canWrite:r,onStartDomainSetup:e,onChanged:a})]}),at(Oo,{n:2,title:"Add your sender details",done:l,summary:l?n.business_name??void 0:void 0,children:at(Kp,{settings:n,canWrite:r,onSaved:a})}),Ea(Oo,{n:3,title:"Collect subscribers",optional:!0,children:[at("p",{className:"af-mb-2 af-text-sm af-text-muted-foreground",children:'Mark a form as a newsletter signup, or ask the assistant to "add a newsletter signup to my footer".'}),at(Lo,{canWrite:r,heading:!1})]})]})]})}function Oo({n:e,title:t,done:s=!1,optional:n=!1,summary:a,children:r}){return Ea("li",{className:"af-rounded-lg af-border af-p-4","aria-label":`Step ${e}: ${t}${s?" (done)":""}`,children:[Ea("div",{className:"af-flex af-items-center af-gap-3",children:[at("span",{className:G("af-flex af-h-6 af-w-6 af-shrink-0 af-items-center af-justify-center af-rounded-full af-text-xs af-font-semibold",s?"af-bg-primary af-text-primary-foreground":"af-border"),children:s?at(au,{className:"af-h-3.5 af-w-3.5","aria-hidden":!0}):e}),at("span",{className:"af-text-sm af-font-medium",children:t}),n&&at("span",{className:"af-text-xs af-text-muted-foreground",children:"Optional"}),s&&a&&at("span",{className:"af-truncate af-text-xs af-text-muted-foreground",children:a})]}),!s&&at("div",{className:"af-mt-3 af-pl-9",children:r})]})}function Kp({settings:e,canWrite:t,onSaved:s}){let[n,a]=Ii.useState(e.business_name??""),[r,o]=Ii.useState(e.postal_address??""),[c,d]=Ii.useState(e.reply_to??""),l=ia();return Ea("form",{className:"af-space-y-3",onSubmit:async i=>{i.preventDefault(),(await l.run("updateSettings",{business_name:n.trim()||null,postal_address:r.trim()||null,reply_to:c.trim()||null,double_opt_in:e.double_opt_in})).ok&&await s()},children:[Ea("label",{className:"af-block af-space-y-1",children:[at("span",{className:"af-text-xs af-text-muted-foreground",children:"Business name (shown as the sender)"}),at(Q,{"aria-label":"Business name",value:n,disabled:!t,onChange:i=>a(i.target.value)})]}),Ea("label",{className:"af-block af-space-y-1",children:[at("span",{className:"af-text-xs af-text-muted-foreground",children:"Postal address (required in every email)"}),at("textarea",{"aria-label":"Postal address",className:"af-min-h-[64px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm",value:r,disabled:!t,onChange:i=>o(i.target.value)})]}),Ea("label",{className:"af-block af-space-y-1",children:[at("span",{className:"af-text-xs af-text-muted-foreground",children:"Replies go to (optional: your account email or an address on your domain)"}),at(Q,{"aria-label":"Reply-to email",type:"email",value:c,disabled:!t,onChange:i=>d(i.target.value)})]}),l.error&&at(Ce,{tone:"error",children:l.error}),t&&at(h,{type:"submit",size:"sm",disabled:l.busy||!r.trim(),children:"Save sender details"})]})}import{Fragment as iu,jsx as _t,jsxs as Gn}from"react/jsx-runtime";var Yp=[{id:"audience",label:"Audience"},{id:"broadcasts",label:"Broadcasts"},{id:"settings",label:"Settings"}],Jp={broadcast:"broadcasts",welcome:"broadcasts",recovery:"broadcasts"},Xp={complaint_rate:"Too many recipients marked your emails as spam.",bounce_rate:"Too many of your emails bounced."};function nu(e){return _t(Qp,{...e},e.siteId)}function Qp({siteId:e,isOwnerSide:t,needsPaidPlan:s,initialDraftId:n,onOrgAction:a,onRequestReview:r,onStartDomainSetup:o,onBackToWebsite:c,onOpenStoreSettings:d,refreshKey:l=0,className:i}){let{api:m}=q(),v=Ta(()=>m.getMarketingSettings(e),`${e}|${l}`,e),[g,u]=Ia.useState(n?"broadcasts":"audience"),[f,p]=Ia.useState(!n),[b,x]=Ia.useState(null),N=w=>b===w?n:void 0,[P,y]=Ia.useState(!!n),[R,_]=Ia.useState(null),k=Ia.useCallback(()=>y(!1),[]),S=Ia.useCallback(w=>{u("settings"),_(w??null)},[]),C=!P&&v.data!==null&&ru(v.data);Ia.useEffect(()=>{if(!n||s)return;let w=!0;return m.getEmailDraft(e,n).then(W=>{w&&(u(Jp[W.kind]),x(W.kind),p(!0))},()=>w&&p(!0)),()=>{w=!1}},[m,e,n,s]);let T=Ia.useMemo(()=>({siteId:e,canWrite:t,onOrgAction:a,settings:v.data,refetchSettings:v.refetch,refreshKey:l,openSetup:k,openSettings:S,settingsSection:R,onOpenStoreSettings:d}),[e,t,a,v.data,v.refetch,l,k,S,R,d]);return s?_t(Nt,{title:"Email Marketing",onBackToWebsite:c,className:i,children:_t(Ys,{icon:Zp,heading:"Email marketing is on the Pro plan.",body:"Upgrade to collect subscribers and send newsletters from your own domain."})}):_t(Nt,{title:"Email Marketing",onBackToWebsite:c,className:i,children:_t(To.Provider,{value:T,children:C?_t(su,{onStartDomainSetup:o}):Gn(iu,{children:[_t(eg,{settingsError:v.error,onRetry:()=>void v.refetch(),onRequestReview:r}),!t&&_t(Ce,{className:"af-mb-3",children:"Only the site owner can send email or change these settings."}),_t("div",{role:"tablist","aria-label":"Email sections",className:"af-mb-4 af-flex af-flex-wrap af-gap-1 af-border-b",children:Yp.map(w=>_t("button",{type:"button",role:"tab","aria-selected":g===w.id,onClick:()=>{u(w.id),_(null)},className:G("af-border-b-2 af-px-3 af-py-2 af-text-sm",g===w.id?"af-border-primary af-font-medium":"af-border-transparent af-text-muted-foreground"),children:w.label},w.id))}),_t("div",{role:"tabpanel",children:f?g==="audience"?_t(Zc,{}):g==="broadcasts"?_t(eu,{initialDraftId:N("broadcast")}):_t(Do,{onStartDomainSetup:o}):_t(J,{className:"af-h-24 af-w-full"})})]})})})}function ru(e){return!e.paused.paused_at&&!e.readiness.can_send&&Ni.has(e.readiness.reason??"")}function eg({settingsError:e,onRetry:t,onRequestReview:s}){let{settings:n,openSetup:a}=Wt(),[r,o]=Ia.useState("idle");return e?_t(Lt,{message:"Couldn't load email settings.",onRetry:t}):n?n.paused.paused_at?Gn(Ce,{tone:"warning",className:"af-mb-3",children:[_t("div",{className:"af-font-medium",children:"Sending is paused."}),Gn("p",{children:[Xp[n.paused.reason??""]??"We paused sending to protect your domain's reputation."," Your contacts are safe, and our team decides when sending resumes."]}),s&&(r==="sent"?_t("p",{className:"af-mt-1 af-font-medium",children:"Review requested. We'll email you when it's done."}):_t(h,{type:"button",size:"sm",variant:"outline",className:"af-mt-2",disabled:r==="sending",onClick:async()=>{o("sending");try{await s(),o("sent")}catch{o("failed")}},children:"Request review"})),r==="failed"&&_t("p",{className:"af-mt-1",children:"Couldn't send the request. Try again."})]}):n.readiness.can_send?Gn(Ce,{tone:"success",className:"af-mb-3",children:["Ready to send from ",n.domain.sending_domain??"your domain","."]}):Gn(Ce,{tone:"warning",className:"af-mb-3",children:["You can collect and manage contacts now. ",Hn(n.readiness.reason),ru(n)&&Gn(iu,{children:[" ",_t(_i,{onClick:a,children:"Finish setup"})]})]}):_t(J,{className:"af-mb-3 af-h-10 af-w-full"})}import*as Vt from"react";var tg=2e3,Xt=()=>({data:null,error:null,isLoading:!0});function Kn(e,{refreshKey:t,breakdowns:s=[],filters:n=[]}={}){let{api:a}=q(),[r,o]=Vt.useState(Xt),[c,d]=Vt.useState(Xt),[l,i]=Vt.useState(Xt),[m,v]=Vt.useState(Xt),[g,u]=Vt.useState(Xt),f=F=>Object.fromEntries(F.map(Z=>[Z,Xt()])),[p,b]=Vt.useState(()=>f(s)),x=Vt.useRef(0),N=Vt.useRef(0),P=Vt.useRef("idle"),y=s.join(","),R=qs()??"",_=JSON.stringify(n),k=`${e}:${y}:${_}:${R}`,[S,C]=Vt.useState({api:a,fetchIdentity:k});(S.api!==a||S.fetchIdentity!==k)&&(C({api:a,fetchIdentity:k}),x.current+=1,o(Xt),d(Xt),i(Xt),v(Xt),b(f(y?y.split(","):[])));let T=`${e}:${String(t??"")}:${R}`,[w,W]=Vt.useState({api:a,conversionsIdentity:T});(w.api!==a||w.conversionsIdentity!==T)&&(W({api:a,conversionsIdentity:T}),N.current+=1,P.current="idle",u(Xt));let K=Vt.useCallback(async F=>{let Z=++x.current,B=y?y.split(","):[];o(Xt),d(Xt),i(Xt),v(Xt),b(Object.fromEntries(B.map(I=>[I,Xt()])));let le=P.current!=="pending"&&(F?.force===!0||P.current==="idle"),oe=(I,U)=>U.then(O=>{Z===x.current&&I({data:O,error:null,isLoading:!1})},O=>{Z===x.current&&I({data:null,error:O instanceof Error?O:new Error("Failed to fetch report"),isLoading:!1})}),Ke=a.getAnalyticsStatus(),xe=oe(o,Ke),Me=Symbol("status-timeout"),We,ke=await Promise.race([Ke.then(I=>I,()=>null),new Promise(I=>{We=setTimeout(()=>I(Me),tg)})]);if(clearTimeout(We),Z!==x.current)return;if(ke===Me&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),ke!==null&&ke!==Me&&(ke.collecting!==!0||ke.first_seen===null&&!ke.first_seen_unavailable||ke.first_seen!==null&&ke.first_seen_in_reports===!1)){let I={data:null,error:null,isLoading:!1};d(I),i(I),v(I),b(Object.fromEntries(B.map(U=>[U,{...I}]))),le&&(u(I),P.current="done"),await xe;return}await Promise.all([ke===Me?Promise.resolve():xe,oe(d,a.getAnalyticsSummary(e,n)),oe(i,a.getAnalyticsTimeseries(e,n)),oe(v,a.getAnalyticsChannels(e,n)),le?(()=>{P.current="pending";let I=++N.current;return u(Xt),a.getAnalyticsConversions(e).then(U=>{I===N.current&&(u({data:U,error:null,isLoading:!1}),P.current="done")},U=>{I===N.current&&(u({data:null,error:U instanceof Error?U:new Error("Failed to fetch report"),isLoading:!1}),P.current="done")})})():Promise.resolve(),...B.map(I=>a.getAnalyticsBreakdown(I,e,n).then(U=>{Z===x.current&&b(O=>({...O,[I]:{data:U,error:null,isLoading:!1}}))},U=>{Z===x.current&&b(O=>({...O,[I]:{data:null,error:U instanceof Error?U:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[a,e,y,_,T,R]),$=Vt.useCallback(async()=>{let F=x.current;try{let Z=await a.getAnalyticsStatus();if(F!==x.current)return;o({data:Z,error:null,isLoading:!1})}catch(Z){if(F!==x.current)return;o(B=>({data:B.data,error:Z instanceof Error?Z:new Error("Failed to fetch status"),isLoading:!1}))}},[a]),ne=Vt.useCallback(()=>K({force:!0}),[K]);Vt.useEffect(()=>{K()},[K,t]);let ie=r.isLoading||c.isLoading||l.isLoading||m.isLoading||g.isLoading||Object.values(p).some(F=>F.isLoading),ue=[l,c,m,g,...Object.values(p)].map(F=>F.data?.status==="ok"?F.data.timezone:void 0).find(F=>F!==void 0);return{status:r,summary:c,timeseries:l,channels:m,conversions:g,breakdowns:p,reportedZone:ue,isLoading:ie,refetch:ne,refetchStatus:$}}import*as Ht from"react";var Bo=3e4,Fo=3;function Di(e={}){let t="collecting"in e,{collecting:s,statusFailed:n=!1,identity:a}=e,{api:r}=q(),[o,c]=Ht.useState(null),[d,l]=Ht.useState(null),[i,m]=Ht.useState(!1),[v,g]=Ht.useState(null),[u,f]=Ht.useState(!1),[p,b]=Ht.useState(!0),[x,N]=Ht.useState(0),P=Ht.useRef(0),y=Ht.useRef(0),R=Ht.useRef(void 0);s!==void 0&&(R.current=s);let _=t?R.current===!0||R.current===void 0&&n:!0,[k,S]=Ht.useState({api:r,identity:a}),C=a!==void 0&&a!==k.identity;(k.api!==r||C)&&(R.current=void 0,S({api:r,identity:a}),y.current+=1,P.current=0,c(null),l(null),m(!1),g(null),f(!1),b(!0),N(0));let T=Ht.useRef(()=>{}),w=Ht.useRef(null),W=Ht.useCallback(async()=>{if(w.current!==null&&w.current===y.current)return;let K=++y.current;w.current=K;try{let $=await r.getAnalyticsRealtime();if(K!==y.current)return;if($.status==="unreachable"){f(!0),m(!0),b(!1),N(ne=>ne+1);return}P.current=0,f(!1),c($.data.current_visitors),l($.as_of),m(!1),g(null),b(!1),N(ne=>ne+1)}catch($){if(K!==y.current)return;P.current+=1,b(!1),N(ne=>ne+1),m(!0),P.current>=Fo&&g($ instanceof Error?$:new Error("Realtime unavailable"))}finally{w.current===K&&(w.current=null)}},[r]);return T.current=()=>void W(),Ht.useEffect(()=>{let K,$=()=>{K===void 0&&(K=setInterval(()=>T.current(),Bo))},ne=()=>{K!==void 0&&(clearInterval(K),K=void 0)},ie=()=>{typeof document<"u"&&document.hidden?ne():(T.current(),$())};return _?((typeof document>"u"||!document.hidden)&&(T.current(),$()),document?.addEventListener("visibilitychange",ie),()=>{ne(),document?.removeEventListener("visibilitychange",ie),y.current+=1}):()=>{document?.removeEventListener("visibilitychange",ie)}},[k.api,k.identity,_]),{currentVisitors:o,asOf:d,isStale:i,error:v,isUnreachable:u,isInitialLoad:p,polls:x}}import*as xt from"react";import*as lu from"react";import{jsx as Uo,jsxs as ou}from"react/jsx-runtime";function ag(){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 Mo({value:e,chosen:t,onChange:s}){let n=Jn(),a=t===null&&n!==null&&e===n,r=lu.useMemo(()=>{let o=ag();return o.includes(e)?o:[e,...o]},[e]);return ou("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[Uo("span",{className:"af-sr-only",children:"Reporting timezone"}),ou("select",{value:a?"":e,onChange:o=>s(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[Uo("option",{value:"",children:n?`${n.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(o=>Uo("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var Ai=(e,{published:t}={})=>{let s=t===!1,n=e!=null&&(!e.collecting||s&&e.first_seen===null&&!e.first_seen_unavailable),a=!n&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=a||r;return{notCollecting:n,awaitingFirstVisit:a,firstVisitTooRecent:r,holdingForFirstData:o,nothingToReport:n||o}};import*as vr from"react";var sg=3e4;function Li({status:e,holdingForFirstData:t,refetchStatus:s,refetch:n}){vr.useEffect(()=>{if(!t)return;let r,o=()=>{r===void 0&&(r=setInterval(()=>void s(),sg))},c=()=>{r!==void 0&&(clearInterval(r),r=void 0)},d=()=>{typeof document<"u"&&document.hidden?c():(s(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",d),()=>{c(),document?.removeEventListener("visibilitychange",d)}},[t,s]);let a=vr.useRef(void 0);vr.useEffect(()=>{if(!e){a.current=void 0;return}let r=a.current;a.current=t,r===!0&&!t&&n()},[e,t,n])}import*as hn from"react";var ng=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ma(e){let t=Math.abs(e);if(t<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[n,a]of s)if(t>=n){let r=e/n,o=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(o)>=1e3&&n!==1e9?ma(o*n):`${o}${a}`}return String(e)}function Zn(e){return`${(e*100).toFixed(1)}%`}function br(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function 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`:br(t)}function du(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function fu(e,t){if(!(!Number.isFinite(e)||e<=0))for(let s of t){let n=Math.ceil(e/s);if(n<=5)return Array.from({length:n+1},(a,r)=>Number((r*s).toPrecision(12)))}}function yr(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function mu(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 $o(e){let t=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${ng[t-1]} ${s}`}function cu(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function rg(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function pu(e,t,s="UTC"){let n=new Map(t.map(o=>[o.date,o])),a=[],r=cu(e.to,s);for(let o=cu(e.from,s);o<r;o=rg(o))a.push(n.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return a}function gu(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=new Date(`${e}T00:00:00Z`);if(Number.isNaN(n.getTime()))return e;let a=String(n.getUTCDate()).padStart(2,"0");return`${t[n.getUTCDay()]}, ${a} ${s[n.getUTCMonth()]}`}import{Fragment as og,jsx as nn,jsxs as ig}from"react/jsx-runtime";function vu({what:e="This report",onRetry:t,collecting:s}){return ig("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:[nn("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),nn("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:s===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),t?nn("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 Oi({what:e="No data"}){return nn("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 zs({sourced:e,error:t,isLoading:s,what:n,onRetry:a,collecting:r,children:o}){return s?nn("div",{role:"status","aria-label":`Loading ${n}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?nn(vu,{what:n,onRetry:a,collecting:r}):!e||e.status==="unreachable"?nn(vu,{what:n,onRetry:a,collecting:r}):nn(og,{children:o(e.data)})}import{Fragment as lg,jsx as Da,jsxs as yn}from"react/jsx-runtime";function Vo({rows:e,dimension:t,metric:s,metricLabel:n,secondary:a,emptyCopy:r="No data for this period",onFilter:o,canFilter:c,maxRows:d=9}){let[l,i]=hn.useState(!1);if(e.length===0)return Da(Oi,{what:r});let m=e.reduce((u,f)=>Math.max(u,Number(f[s]??0)),0)||1,v=Math.max(0,e.length-d),g=l?e:e.slice(0,d);return yn(lg,{children:[yn("table",{className:"af-w-full af-text-sm",children:[Da("thead",{children:yn("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:n})]})}),Da("tbody",{children:g.map((u,f)=>{let p=Number(u[s]??0),b=u[t]??null,x=yr(b),N=a?u[a]:null,P=b!==null&&(c?c(b,N):!0);return yn("tr",{className:"af-border-t af-border-border",children:[yn("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/m*100)}%`}}),b!==null&&o&&P?Da("button",{type:"button",onClick:()=>o(b,N),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}):Da("span",{className:"af-relative af-break-words af-text-foreground",children:x}),N?Da("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:N}):null]}),Da("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:ma(p)})]},`${x}-${N??""}-${f}`)})})]}),v>0?Da("button",{type:"button",onClick:()=>i(u=>!u),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length}`}):null]})}function hr({title:e,tabs:t,defaultTabId:s,headerRight:n}){let[a,r]=hn.useState(s),o=t.find(g=>g.id===a)??t[0],c=hn.useId(),d=g=>`${c}-tab-${g}`,l=g=>`${c}-panel-${g}`,i=hn.useRef(null),m=(g,u)=>{g.preventDefault();let f=(u+t.length)%t.length;r(t[f].id),i.current?.querySelectorAll('[role="tab"]')?.[f]?.focus()};return yn("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[yn("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:g=>{let u=t.findIndex(f=>f.id===a);g.key==="ArrowRight"&&m(g,u+1),g.key==="ArrowLeft"&&m(g,u-1),g.key==="Home"&&m(g,0),g.key==="End"&&m(g,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(g=>Da("button",{id:d(g.id),role:"tab",type:"button","aria-selected":g.id===a,"aria-controls":l(g.id),tabIndex:g.id===a?0:-1,onClick:()=>r(g.id),className:g.id===a?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:g.label},g.id))}),n]}),o?Da("div",{id:l(o.id),role:"tabpanel","aria-labelledby":d(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}import*as Aa from"react";import*as rn from"@radix-ui/react-popover";var xn=3,Sn=100;import{jsx as It,jsxs as Is}from"react/jsx-runtime";var xr={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"},cg=Object.keys(xr);function bu(e){let t=xr[e.dimension],s=e.operator==="is_not"?"is not":"is",n=e.values.map(a=>yr(a)).join(" or ");return`${t} ${s} ${n}`}function Ho(e,t){let s=e.findIndex(n=>n.dimension===t.dimension&&(n.operator??"is")===(t.operator??"is"));if(s>=0){let n=[...new Set([...e[s].values,...t.values])];return n.length>Sn||n.length===e[s].values.length?e:e.map((a,r)=>r===s?{...a,values:n}:a)}return t.values.length>Sn||e.length>=xn?e:[...e,t]}function ug(e,t){let s={};for(let[n,a]of Object.entries(t)){let r=e.get(n)??new Set;for(let o of a)r.add(o);e.set(n,r),s[n]=[...r]}return s}function yu(e,t){let s=e.findIndex(n=>n.dimension===t.dimension&&(n.operator??"is")===(t.operator??"is"));return s>=0?e.map((n,a)=>a===s?t:n):t.values.length>Sn||e.length>=xn?e:[...e,t]}function dg(e){return{dimension:e,operator:"is",search:"",picked:[]}}function hu(e,t,s,n={}){if(e.api!==t.api||e.period!==t.period)return e.api=t.api,e.period=t.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let a=ug(e.byDimension,s);for(let[r,o]of Object.entries(n)){let c=e.foldsByLabel.get(r)??new Set;for(let d of o)c.add(d);e.foldsByLabel.set(r,c)}return{suggestions:a,folds:new Map([...e.foldsByLabel].map(([r,o])=>[r,[...o]]))}}function xu(e){let{filters:t,onChange:s}=e,n=t.length>=xn;return Aa.useEffect(()=>{if(t.length===0)return;let a=r=>{let o=r.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||r.key==="Escape"&&s([])};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[t.length,s]),Is("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((a,r)=>Is("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:[It("span",{className:"af-text-foreground",children:bu(a)}),It("button",{type:"button","aria-label":`Remove filter ${bu(a)}`,onClick:()=>s(t.filter((o,c)=>c!==r)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${a.dimension}-${a.operator??"is"}`)),It(fg,{...e,disabled:n}),t.length>0?It("button",{type:"button",onClick:()=>s([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function fg({filters:e,onChange:t,suggestions:s,resetKey:n,disabled:a,expandValues:r}){let[o,c]=Aa.useState(!1),d=Aa.useRef(null),[l,i]=Aa.useState(null);Aa.useEffect(()=>{i(d.current?.closest(".aifeatures-admin")??null)},[]);let[m,v]=Aa.useState(null),[g,u]=Aa.useState("is"),[f,p]=Aa.useState(""),[b,x]=Aa.useState([]);Aa.useEffect(()=>{o||(v(null),u("is"),p(""),x([]))},[o]);let N=Aa.useRef(n);N.current!==n&&(N.current=n,o&&c(!1),m!==null&&v(null),b.length>0&&x([]),f!==""&&p(""),g!=="is"&&u("is"));let P=C=>{let T=dg(C);v(T.dimension),x(T.picked),p(T.search),u(T.operator)},R=(m?s[m]??[]:[]).filter(C=>C.toLowerCase().includes(f.trim().toLowerCase())),_=m===null||b.length===0?null:Ho(e,{dimension:m,operator:g,values:r?r(m,b):b}),k=_!==null&&_!==e,S=()=>{let C=_;!C||C===e||(t(C),c(!1))};return Is(rn.Root,{open:o,onOpenChange:c,children:[It(rn.Trigger,{asChild:!0,children:It("button",{ref:d,type:"button",disabled:!1,title:a?`At most ${xn} 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"})}),It(rn.Portal,{container:l,children:It(rn.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:m===null?Is("div",{children:[It("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),It("div",{className:"af-max-h-96 af-overflow-y-auto",children:cg.filter(C=>s[C]!==void 0).map(C=>{let T=s[C]?.length??0,w=!e.some(W=>W.dimension===C)&&e.length>=xn;return Is("button",{type:"button",onClick:()=>P(C),disabled:T===0||w,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:[It("span",{children:xr[C]}),It("span",{className:"af-text-muted-foreground",children:T===0?"no data":w?"no room":T})]},C)})})]}):Is("div",{children:[Is("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[It("button",{type:"button",onClick:()=>P(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),It("span",{className:"af-text-xs af-font-medium af-text-foreground",children:xr[m]}),Is("select",{"aria-label":"Operator",value:g,onChange:C=>u(C.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[It("option",{value:"is",children:"is"}),It("option",{value:"is_not",children:"is not"})]})]}),It("input",{type:"text",value:f,onChange:C=>p(C.target.value),placeholder:"Search\u2026","aria-label":`Search ${xr[m]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),It("div",{className:"af-max-h-48 af-overflow-y-auto",children:R.length===0?Is("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",f,"\u201D."]}):R.map(C=>Is("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:[It("input",{type:"checkbox",checked:b.includes(C),disabled:!b.includes(C)&&b.length>=Sn,onChange:T=>x(w=>T.target.checked?[...w,C]:w.filter(W=>W!==C))}),It("span",{className:"af-break-all",children:yr(C)})]},C))}),It("button",{type:"button",onClick:S,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:b.length<=1?"Apply filter":b.length>=Sn?`Apply filter (${b.length} values \u2014 the maximum)`:`Apply filter (${b.length} values)`})]})})})]})}import{Fragment as gg,jsx as pa,jsxs as Bi}from"react/jsx-runtime";var mg=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:ma,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:ma,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:ma,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:Zn,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:br,chart:"visit_duration_seconds"}];function pg({current:e,previous:t,downIsGood:s}){if(t===0)return null;let n=(e-t)/t;if(Math.abs(n)<5e-4)return null;let a=n>0,r=s?!a:a,o=`${a?"+":""}${(n*100).toFixed(1)}%`;return pa("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 Su({summary:e,selected:t,onSelect:s}){return pa("div",{className:"af-@container",children:pa("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:mg.map(n=>{let a=n.chart===t,r=s!==void 0,o=Bi(gg,{children:[pa("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:n.label}),Bi("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[pa("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:n.format(n.get(e.current))}),e.previous?pa(pg,{current:n.get(e.current),previous:n.get(e.previous),downIsGood:n.downIsGood}):null]})]});return r?pa("button",{type:"button","aria-pressed":a,onClick:()=>s(n.chart),className:a?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:o},n.key):pa("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},n.key)})})})}function zo({currentVisitors:e,asOf:t,isStale:s,isUnreachable:n,isInitialLoad:a=!1,scopeIsSiteWide:r=!1}){if(a&&!n)return Bi("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:[pa("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),pa("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(n||e===null)return pa("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?mu(t):"freshness unknown",c=r?" across the whole site, not the current filter,":"",d=s?`${e} current visitors${c} ${o} (not updating)`:`${e} current visitors${c} ${o}`;return Bi("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:d,children:[pa("span",{"aria-hidden":"true",className:s?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),pa("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),pa("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),pa("span",{className:"af-sr-only",children:d})]})}import*as Nu from"react";import{Star as vg}from"lucide-react";import{Fragment as wu,jsx as jt,jsxs as wn}from"react/jsx-runtime";function Fi(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Ui({rows:e,denominator:t,windowPrecedesCollection:s=!1,coverageUnknown:n=!1,emptyCopy:a="No conversions in this period",maxRows:r=9,primaryConversion:o}){let[c,d]=Nu.useState(!1),l=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||Fi(p,o)),i=s?jt("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This period starts before we began collecting for this site, so these counts cover less time than the dates suggest."}):n?jt("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 wn(wu,{children:[jt(Oi,{what:a}),i]});let m=l.slice(0,r),v=o?l.find(p=>Fi(p,o)):void 0,g=v&&!m.includes(v)?l.filter(p=>m.includes(p)||p===v).slice(0,Math.max(0,r-1)).concat(v):m,u=c?e:g,f=Math.max(0,e.length-g.length);return wn(wu,{children:[wn("table",{className:"af-w-full af-text-sm",children:[jt("thead",{children:wn("tr",{className:"af-text-xs af-text-muted-foreground",children:[jt("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),jt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),jt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),jt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),jt("tbody",{children:u.map((p,b)=>wn("tr",{className:"af-border-t af-border-border","aria-current":Fi(p,o)?"true":void 0,children:[jt("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Fi(p,o)?wn("span",{className:"af-flex af-items-center af-gap-1.5",children:[jt(vg,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),jt("span",{className:"af-font-medium af-text-foreground",children:p.goal}),jt("span",{className:"af-sr-only",children:"(your main conversion)"})]}):p.goal}),jt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:ma(p.visitors)}),jt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:ma(p.events)}),jt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:p.conversion_rate===null?jt("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Zn(p.conversion_rate)})]},`${p.goal}-${b}`))})]}),f>0?jt("button",{type:"button",onClick:()=>d(p=>!p),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:c?"Show fewer":`Show all ${e.length} goals`}):null,wn("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",ma(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),i]})}import{Area as bg,AreaChart as yg,CartesianGrid as hg,ResponsiveContainer as xg,Tooltip as Sg,XAxis as wg,YAxis as Ng}from"recharts";import{jsx as ga,jsxs as Sr}from"react/jsx-runtime";var Mi={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Wo={visitors:ma,visits:ma,pageviews:ma,views_per_visit:e=>e.toFixed(2),bounce_rate:Zn,visit_duration_seconds:br},Rg=31,_g=new Set(["visitors","visits","pageviews"]),Pg={...Wo,bounce_rate:du,visit_duration_seconds:uu},qo=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Cg=[5,10,15,30,60,120,300,600,900,1800,3600,7200],kg=[.01,.02,.05,.1,.2,.25,.5,1],Tg=[.25,.5,1,2,5,10,25,50],Eg={visitors:qo,visits:qo,pageviews:qo,views_per_visit:Tg,bounce_rate:kg,visit_duration_seconds:Cg};function Ig({active:e,payload:t,label:s,metric:n}){if(!e||!t||t.length===0)return null;let a=t[0].payload;return Sr("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:[ga("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Mi[n]}),Sr("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[ga("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),ga("span",{className:"af-text-muted-foreground",children:gu(String(s))}),ga("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Wo[n](Number(a[n]??0))})]})]})}function $i({rows:e,window:t,metric:s,timeZone:n="UTC",height:a=260}){let r=pu(t,e,n),o=Wo[s],c=Pg[s],d=fu(r.reduce((i,m)=>Math.max(i,Number(m[s]??0)),0),Eg[s]),l=`${Mi[s]} by day: ${r.map(i=>`${$o(i.date)}: ${o(Number(i[s]??0))}`).join("; ")}.`;return Sr("figure",{"aria-label":`${Mi[s]} over time`,className:"af-m-0",children:[ga(xg,{width:"100%",height:a,children:Sr(yg,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[ga("defs",{children:Sr("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[ga("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),ga("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),ga(hg,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),ga(wg,{dataKey:"date",tickFormatter:$o,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),ga(Ng,{allowDecimals:!_g.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...d?{ticks:d,domain:[0,d[d.length-1]]}:{},tickFormatter:i=>c(i),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),ga(Sg,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:ga(Ig,{metric:s})}),ga(bg,{type:"linear",dataKey:s,name:Mi[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=Rg?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),ga("figcaption",{className:"af-sr-only",children:l})]})}import{Fragment as jo,jsx as Pe,jsxs as oa}from"react/jsx-runtime";var Dg="2026-08-13",Ag=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Lg=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Og({filters:e,onFiltersChange:t,refreshKey:s,onBackToWebsite:n,primaryConversion:a,className:r,published:o,lastPublishedAt:c}){let[d,l]=xt.useState(30),[i,m]=xt.useState(()=>Gi()),v=e!==void 0&&t!==void 0,[g,u]=xt.useState(e??[]),{api:f}=q(),[p,b]=xt.useState(f);p!==f&&(b(f),!v&&g.length>0&&u([]));let x=v?e:g,N=xt.useCallback(O=>{t&&t(O),v||u(O)},[t,v]),P=xt.useCallback((O,be,Y)=>{let pe=Array.isArray(be)?be:[be];if(pe.length===0)return null;let Fe=Ho(x,{dimension:O,operator:"is",values:pe});if(Y&&(!Y.value||(Fe=yu(Fe,{dimension:Y.dimension,operator:"is",values:[Y.value]}),!Fe.find(Pt=>Pt.dimension===Y.dimension&&Pt.operator!=="is_not")?.values.includes(Y.value))))return null;let mt=Fe.find(ze=>ze.dimension===O&&ze.operator!=="is_not");return pe.every(ze=>mt?.values.includes(ze))?JSON.stringify(Fe)===JSON.stringify(x)?null:Fe:null},[x]),y=xt.useCallback((O,be,Y)=>P(O,be,Y)!==null,[P]),R=xt.useCallback((O,be,Y)=>{let pe=P(O,be,Y);pe&&N(pe)},[P,N]),[_,k]=xt.useState("visitors"),S=Kn(d,{refreshKey:s,breakdowns:Lg,filters:x}),C=S.status.data,T=S.reportedZone??C?.timezone,w=T??i??Jn()??"UTC",{notCollecting:W,awaitingFirstVisit:K,firstVisitTooRecent:$,holdingForFirstData:ne}=Ai(C,{published:o}),ie=o===!1,ue=Di({collecting:K||W?!1:C?.collecting,statusFailed:S.status.error!=null,identity:C?.analytics_id}),F=xt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),Z=xt.useMemo(()=>{let O=S.breakdowns.sources?.data,be={};if(!O||O.status!=="ok")return be;for(let Y of O.data){let pe=Y.source,Fe=Y.sources;typeof pe=="string"&&Array.isArray(Fe)&&Fe.length>0&&(be[pe]=Fe)}return be},[S.breakdowns.sources?.data]),B=xt.useMemo(()=>{let O=(pe,Fe)=>{let mt=S.breakdowns[pe]?.data;return!mt||mt.status!=="ok"?[]:[...new Set(mt.data.map(ze=>ze[Fe]).filter(ze=>typeof ze=="string"&&ze!==""))]};return{channel:S.channels.data?.status==="ok"?[...new Set(S.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")}},[S.breakdowns,S.channels.data]),[le,oe]=xt.useState({}),Ke=JSON.stringify(B),[xe,Me]=xt.useState(new Map),We=JSON.stringify(Z);xt.useEffect(()=>{let{suggestions:O,folds:be}=hu(F.current,{api:f,period:d},JSON.parse(Ke),JSON.parse(We));oe(O),Me(be)},[Ke,We,f,d]);let ke=xt.useCallback((O,be)=>O!=="source"?be:[...new Set(be.flatMap(Y=>{let pe=[...xe.get(Y)??[],...Z[Y]??[]];return pe.length>0?pe:[Y]}))],[xe,Z]),St=xt.useMemo(()=>{let O=S.conversions.error;return O instanceof Ft&&O.details?.code==="goals_exceed_report_budget"?O.message:null},[S.conversions.error]),I=xt.useMemo(()=>{let O=[S.summary,S.timeseries,S.channels,...Object.values(S.breakdowns)];for(let be of O){let Y=be?.error;if(Y instanceof Ft&&Y.details?.code==="filter_unsupported")return Y.message}return null},[S.summary,S.timeseries,S.channels,S.breakdowns]),U=(O,be,Y,pe,Fe,mt,ze,Pt,de)=>()=>{let Ae=S.breakdowns[O];return Pe(zs,{sourced:Ae?.data??null,error:Ae?.error,isLoading:Ae?.isLoading,what:be,collecting:C?.collecting,onRetry:S.refetch,children:pt=>{let La=Kt=>Pt?ke(Pt,[Kt]):Kt;return Pe(Vo,{rows:pt,dimension:Y,metric:pe,metricLabel:Fe,secondary:mt,emptyCopy:x.length>0?"No data for this filter":ze,canFilter:Pt?(Kt,va)=>y(Pt,La(Kt),de?{dimension:de,value:va}:void 0):()=>!1,onFilter:Pt?(Kt,va)=>R(Pt,La(Kt),de?{dimension:de,value:va}:void 0):void 0})}})};if(Li({status:C,holdingForFirstData:ne,refetchStatus:S.refetchStatus,refetch:S.refetch}),W){let O=!!c&&String(c).slice(0,10)<Dg;return Pe(Nt,{title:"Analytics",onBackToWebsite:n,className:r,children:oa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Pe("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),Pe("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:ie?"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 K?Pe(Nt,{title:"Analytics",onBackToWebsite:n,className:r,children:oa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Pe("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),Pe("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."})]})}):$?oa(Nt,{title:"Analytics",onBackToWebsite:n,className:r,children:[Pe("div",{className:"af-mb-3 af-flex af-justify-end",children:Pe(Mo,{value:w,chosen:i,onChange:O=>{Ki(O),m(O)}})}),oa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Pe("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),oa("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",C?.timezone?` ${C.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),Pe("div",{className:"af-mt-4 af-flex af-justify-center",children:Pe(zo,{currentVisitors:ue.currentVisitors,asOf:ue.asOf,isStale:ue.isStale,isUnreachable:ue.isUnreachable||ue.error!==null,isInitialLoad:ue.isInitialLoad})})]})]}):Pe(Nt,{title:"Analytics",onBackToWebsite:n,className:r,children:oa("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[oa("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Pe("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Ag.map(O=>Pe("button",{type:"button","aria-pressed":O.value===d,onClick:()=>l(O.value),className:O.value===d?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:O.label},O.value))}),Pe(Mo,{value:w,chosen:i,onChange:O=>{Ki(O),m(O)}}),Pe(zo,{currentVisitors:ue.currentVisitors,asOf:ue.asOf,isStale:ue.isStale,isUnreachable:ue.isUnreachable||ue.error!==null,isInitialLoad:ue.isInitialLoad,scopeIsSiteWide:x.length>0})]}),Pe(xu,{filters:x,onChange:N,suggestions:le,expandValues:ke,resetKey:f}),I?oa("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Pe("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),Pe("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:I}),Pe("button",{type:"button",onClick:()=>N([]),className:"af-mt-4 af-rounded-md af-border af-border-border af-px-3 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Clear filters"})]}):null,!I&&C?.timezone_defaulted?Pe("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,I?null:oa(jo,{children:[Pe(zs,{sourced:S.summary.data,error:S.summary.error,isLoading:S.summary.isLoading,what:"The traffic summary",collecting:C?.collecting,onRetry:S.refetch,children:O=>oa(jo,{children:[Pe(Su,{summary:O,selected:_,onSelect:k}),O.previous_unavailable?oa("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]})}),Pe("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:Pe(zs,{sourced:S.timeseries.data,error:S.timeseries.error,isLoading:S.timeseries.isLoading,what:"The visitors chart",collecting:C?.collecting,onRetry:S.refetch,children:O=>{let be=S.timeseries.data?.status==="ok"?S.timeseries.data.window:{from:"",to:""};return Pe($i,{rows:O,window:be,metric:_,timeZone:T??"UTC"})}})}),oa("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[Pe(hr,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>Pe(zs,{sourced:S.channels.data,error:S.channels.error,isLoading:S.channels.isLoading,what:"Channels",collecting:C?.collecting,onRetry:S.refetch,children:O=>Pe(Vo,{rows:O,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:be=>y("channel",be),onFilter:be=>R("channel",be)})})},{id:"sources",label:"Sources",render:U("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:U("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),Pe(hr,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:U("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:U("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:U("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),Pe(hr,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:U("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:U("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:U("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),Pe(hr,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:U("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:U("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:U("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),oa("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[Pe("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:Pe("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),oa("div",{className:"af-px-3 af-py-2",children:[x.length>0?oa("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?oa("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:[Pe("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),Pe("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:St})]}):Pe(zs,{sourced:S.conversions.data,error:S.conversions.error,isLoading:S.conversions.isLoading,what:"Conversions",collecting:C?.collecting,onRetry:S.refetch,children:O=>{let be=S.conversions.data?.status==="ok"?S.conversions.data:null;return Pe(jo,{children:Pe(Ui,{rows:O,primaryConversion:a,denominator:be?.denominator??0,windowPrecedesCollection:be?.window_precedes_collection??!1,coverageUnknown:be?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import*as Du from"react";import{Phone as Tu,Mail as Ko,ShoppingBag as Mg,ExternalLink as $g,MessageCircle as Vg,Download as Hg,Target as Au}from"lucide-react";import*as is from"react";import{Check as Go,ChevronLeft as Bg,Loader2 as Ru}from"lucide-react";import{jsx as st,jsxs as Gt}from"react/jsx-runtime";var _u=90,Pu=100;function Fg(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Cu(e){return!!e.label&&e.label!==e.target}function Ug(e,t,s){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:n,with_a_value:a}=t;return n===0?e===0?"Nothing specific has converted here yet.":null:a===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":a<n?s?`These cover ${a.toLocaleString()} of ${n.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${a.toLocaleString()} of ${n.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function wr(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function ku({current:e,onChange:t,onClose:s}){let{api:n}=q(),[a,r]=is.useState(null),[o,c]=is.useState(!1),[d,l]=is.useState({at:"goals"}),[i,m]=is.useState(null),[v,g]=is.useState(null),[u,f]=is.useState(!1),[p,b]=is.useState(null),x=is.useRef(0);is.useEffect(()=>{let R=!0;return r(null),c(!1),l({at:"goals"}),m(null),g(null),f(!1),b(null),x.current+=1,n.getAnalyticsConversions(_u).then(_=>{if(R){if(_.status!=="ok"){c(!0);return}r(_.data)}}).catch(()=>{R&&c(!0)}),()=>{R=!1}},[n]);let N=R=>{l({at:"targets",row:R}),m(null),g(null),f(!1),b(null);let _=++x.current;n.getAnalyticsGoalTargets(R.goal,_u,Pu).then(k=>{if(_===x.current){if(k.status!=="ok"){g("failed");return}m(k.data),f(k.truncated===!0),b(k.coverage??null)}}).catch(k=>{if(_!==x.current)return;let S=k instanceof Ft?k.details?.code:void 0;g(S==="goal_has_no_targets"?"no-values":"failed")})},P=R=>{t(R),s()};if(o)return st("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 Gt("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[st(Ru,{className:"af-h-4 af-w-4 af-animate-spin"}),st("span",{children:"Loading your conversions\u2026"})]});if(d.at==="targets"){let R=d.row,_=new Map;for(let k of i??[])_.set(k.label,(_.get(k.label)??0)+1);return Gt("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:[st("header",{className:"af-flex af-items-center af-gap-1",children:Gt(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>l({at:"goals"}),children:[st(Bg,{className:"af-h-4 af-w-4"}),st("span",{children:"All conversions"})]})}),Gt("button",{type:"button","aria-current":e&&wr(R,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>P({goal:R.goal,implicit:R.implicit}),children:[e&&wr(R,e)&&!e.target&&st(Go,{className:"af-h-4 af-w-4 af-shrink-0"}),Gt("span",{children:["Any ",R.goal.toLowerCase()]})]}),v==="no-values"&&st("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),v==="failed"&&Gt("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[st("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),st(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>N(R),children:"Try again"})]}),!i&&v===null&&Gt("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:[st(Ru,{className:"af-h-4 af-w-4 af-animate-spin"}),st("span",{children:"Loading\u2026"})]}),i&&st("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Ug(i.length,p,u)}),u&&Gt("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Pu,". If what you want isn\u2019t here, pick the conversion itself instead."]}),i?.some(Cu)&&st("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 S=!!(e&&wr(R,e)&&e.target===k.target),C=_.get(k.label)>1;return Cu(k)?Gt("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:[Gt("span",{className:"af-min-w-0",children:[st("span",{className:"af-block af-truncate",children:k.label}),C&&st("span",{className:"af-block af-truncate af-text-xs",children:k.target})]}),st("span",{className:"af-shrink-0 af-text-xs",children:k.visitors.toLocaleString()})]},k.target):Gt("button",{type:"button","aria-current":S?"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:R.goal,implicit:R.implicit,target:k.target,...k.label&&k.label!==k.target?{label:k.label}:{}}),children:[Gt("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[S&&st(Go,{className:"af-h-4 af-w-4 af-shrink-0"}),Gt("span",{className:"af-min-w-0",children:[st("span",{className:"af-block af-truncate",children:k.label}),C&&st("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:k.target})]})]}),st("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:k.visitors.toLocaleString()})]},k.target)})]})}let y=e?.goal&&!a.some(R=>wr(R,e));return Gt("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[y&&Gt("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&&st("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(R=>{let _=e?wr(R,e):!1;return Gt("div",{className:"af-flex af-items-center af-gap-1",children:[Gt("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:()=>P({goal:R.goal,implicit:R.implicit}),children:[Gt("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[_&&st(Go,{className:"af-h-4 af-w-4 af-shrink-0"}),st("span",{className:"af-truncate",children:R.goal})]}),st("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:R.visitors.toLocaleString()})]}),Fg(R)&&st(h,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${R.goal}`,onClick:()=>N(R),children:"Narrow"})]},R.goal)}),e?.goal&&st("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 jg,jsx as Nn,jsxs as Iu}from"react/jsx-runtime";function zg(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let s of t)try{let{hostname:n}=new URL(s);if(n)return n.toLowerCase().replace(/^www\./,"")}catch{}return null}function qg(e){if(Zo(e,"whatsapp"))return!0;let t=zg(e);return t===null?!1:["wa.me","whatsapp.com"].some(s=>t===s||t.endsWith(`.${s}`))}function Zo(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var Eu=[{goal:"Contact",target:e=>Zo(e,"tel"),icon:Tu,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Zo(e,"mailto"),icon:Ko,line:"This site is set up to get you emails."},{goal:"Contact",icon:Tu,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>qg(e),icon:Vg,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:$g,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Ko,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Ko,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:Mg,line:"This site is set up to sell."},{goal:"File Download",icon:Hg,line:"This site is set up to get your file downloaded."}];function Lu(e){let{goal:t,target:s}=e;return e.implicit!==!0?null:(s?Eu.find(a=>a.goal===t&&a.target?.(s)):void 0)??Eu.find(a=>a.goal===t&&!a.target)??null}function Wg(e){return Lu(e)?.icon??Au}function Ou({primaryConversion:e,onChange:t}){let[s,n]=Du.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?Lu(e):null,o=e?.label?.trim(),c=e?Wg(e):Au,d=e?.goal?o?`Your main conversion is ${o}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",l=Iu(jg,{children:[Nn(c,{className:"af-h-4 af-w-4 af-shrink-0"}),Nn("span",{children:d})]});return t?Iu(Kr,{open:s,onOpenChange:n,children:[Nn(Zr,{asChild:!0,children:Nn("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})}),Nn(ir,{align:"start",className:"af-w-80 af-p-1",children:s&&Nn(ku,{current:e,onChange:t,onClose:()=>n(!1)})})]}):Nn("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:l})}import{Fragment as Gg,jsx as on,jsxs as Vi}from"react/jsx-runtime";function Bu({refreshKey:e,onViewAll:t,primaryConversion:s}){let n=Kn(7,{refreshKey:e,breakdowns:[]}),a=n.status.data??void 0,{nothingToReport:r,notCollecting:o,holdingForFirstData:c}=Ai(a);return Li({status:a,holdingForFirstData:c,refetchStatus:n.refetchStatus,refetch:n.refetch}),Vi("section",{className:"af-rounded-md af-border af-p-3",children:[Vi("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[on("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&on(h,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?on("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."}):Vi(Gg,{children:[on(zs,{sourced:n.timeseries.data,error:n.timeseries.error,isLoading:n.timeseries.isLoading,what:"The visitors chart",collecting:a?.collecting,onRetry:n.refetch,children:d=>{let l=n.timeseries.data?.status==="ok"?n.timeseries.data:null;return on($i,{rows:d,window:l?.window??{from:"",to:""},metric:"visitors",timeZone:l?.timezone,height:140})}}),Vi("div",{className:"af-mt-3",children:[on("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),on(zs,{sourced:n.conversions.data,error:n.conversions.error,isLoading:n.conversions.isLoading,what:"Conversions",collecting:a?.collecting,onRetry:n.refetch,children:d=>{let l=n.conversions.data?.status==="ok"?n.conversions.data:null;return on(Ui,{rows:d,primaryConversion:s,denominator:l?.denominator??0,windowPrecedesCollection:l?.window_precedes_collection??!1,coverageUnknown:l?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as bs,jsxs as Nr}from"react/jsx-runtime";var Yo=5;function Jo({title:e,viewAllLabel:t,onViewAll:s}){return Nr("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:e}),s&&bs(h,{type:"button",variant:"ghost",size:"sm",onClick:s,children:t})]})}function Kg({refreshKey:e,onBackToWebsite:t,primaryConversion:s,onChangePrimaryConversion:n,onOpenSurface:a,needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:c}){let d=Bn({refreshKey:e}),l=(d.summary?.products.count??0)>0||(d.summary?.commerce?.storefront_orders??!1),i=l||(d.summary?.commerce?.invoicing??!1);return bs(Nt,{title:"Dashboard",onBackToWebsite:t,children:Nr("div",{className:"af-flex af-flex-col af-gap-4",children:[bs(Ou,{primaryConversion:s,onChange:n}),bs(Bu,{refreshKey:e,onViewAll:a&&(()=>a("analytics")),primaryConversion:s}),Nr("section",{className:"af-rounded-md af-border af-p-3",children:[bs(Jo,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:a&&(()=>a("leads"))}),bs(vi,{refreshKey:e,maxRows:Yo,onViewAll:a&&(()=>a("leads"))})]}),l&&Nr("section",{className:"af-rounded-md af-border af-p-3",children:[bs(Jo,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:a&&(()=>a("orders"))}),bs(Js,{refreshKey:e,maxRows:Yo,onViewAll:a&&(()=>a("orders"))})]}),i&&Nr("section",{className:"af-rounded-md af-border af-p-3",children:[bs(Jo,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:a&&(()=>a("invoices"))}),bs(Qs,{refreshKey:e,maxRows:Yo,onViewAll:a&&(()=>a("invoices")),needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:c})]})]})})}export{zn as AUDIENCE_PAGE_SIZE,Ft as AifeaturesApiError,Mu as AifeaturesProvider,Og as AnalyticsView,Ci as ContactImport,si as CustomerDetail,ni as CustomersList,Ei as DOUBLE_OPT_IN_HELP,Kg as DashboardView,ko as EMAIL_ORG_ACTIONS,Gc as EMAIL_READINESS_TEXT,nu as EmailView,ta as ExportCsvButton,Vr as FormSettings,Fr as FormSubmissions,Sl as FormsDashboard,kr as FormsList,Eo as IMPORT_ATTESTATION,po as InvoiceDetail,or as InvoiceLabelBadge,wi as InvoiceSettingsPanel,Qs as InvoicesList,jc as InvoicesView,vi as LeadsView,xn as MAX_ANALYTICS_FILTERS,Sn as MAX_ANALYTICS_FILTER_VALUES,qc as NotificationRecipientsSettings,Qr as OrderDetail,mn as OrderStatusBadge,Js as OrdersList,tc as OrdersView,Xl as PaymentsDashboard,Dn as PaymentsSetup,jr as ProductSettings,qr as ProductsList,cc as ProductsView,Pn as PromosPanel,Fo as REALTIME_FAILURES_BEFORE_ERROR,Bo as REALTIME_POLL_MS,go as RetainerStatusBadge,In as RetainersPanel,Vc as StoreSettings,Ar as SubmissionDetail,Nc as SubscriptionsView,Wr as VariantsEditor,Nt as ViewShell,Mr as WebhookDeliveries,$r as WebhookSettings,Pp as buildEmailOrgRequest,Us as chargedTotal,Zi as createApiClient,Hn as emailReadinessText,j as formatPrice,_p as isEmailOrgAction,Xa as isZeroDecimalCurrency,bt as toMajorUnits,Zt as toMinorUnits,q as useAifeatures,q as useAifeaturesContext,Kn as useAnalytics,Ri as useAudience,ki as useBroadcasts,Bn as useBusinessSummary,Br as useCsvExport,ai as useCustomers,Ti as useEmailDrafts,Ur as useEventDestinations,Rn as useForms,Tn as useInvoices,Gr as useOrders,Ks as usePaymentsStatus,pi as usePeople,gi as usePerson,An as useProducts,Di as useRealtimeVisitors,Ln as useRetainers,an as useSiteSettings,Ir as useSubmissions,bi as useSubscriptions};