@aifeatures/admin-react 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +13 -1
- package/dist/index.d.ts +13 -1
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import*as hn from"react";var Kr="aifeatures:analytics:timezone",Zr;function gs(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function Xi(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function yn(){return Jr()??gs()}function Jr(){if(Zr!==void 0)return Zr;try{let e=window.localStorage.getItem(Kr);return Xi(e)?e:null}catch{return null}}function Yr(e){if(!(e!==null&&!Xi(e))){Zr=e;try{e===null?window.localStorage.removeItem(Kr):window.localStorage.setItem(Kr,e)}catch{}}}function Us(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 Ms(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 vs(e,t){let n=t.toString();return n?`${e}?${n}`:e}function Qi(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 eo(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 Xr(e,t="https://aifeatures.dev"){async function n(a,r={}){let o=`${t}${a}`,d=await fetch(o,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!d.ok){let c;try{c=await d.json()}catch{}throw new St(Ms(c?.error,d.status),d.status,c)}if(d.status!==204)return d.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(Ms(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 d=o.toString(),c=`/api/v1/forms/${a}/submissions${d?`?${d}`:""}`;return n(c)},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(vs(`/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,d=o.name,c=o.id??o.name,u=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(c)}`,i=await fetch(u,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){let l;try{l=await i.json()}catch{}throw new St(Ms(l?.error,i.status),i.status,l)}let g=await i.blob(),v=URL.createObjectURL(g),f=document.createElement("a");f.href=v,f.download=d,document.body.appendChild(f),f.click(),document.body.removeChild(f),URL.revokeObjectURL(v)},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 d=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:o});if(!d.ok){let c;try{c=await d.json()}catch{}throw new St(Ms(c?.error,d.status),d.status,c)}return d.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=Qi(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(vs("/api/v1/orders/export",Qi(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=eo(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(vs("/api/v1/retainers/export",eo(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(vs("/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?${Us(a,r)}`)},async getAnalyticsTimeseries(a,r){return n(`/api/v1/analytics/timeseries?${Us(a,r)}`)},async getAnalyticsRealtime(){return n("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,r){return n(`/api/v1/analytics/channels?${Us(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 d=new URLSearchParams({goal:a,period:String(r)}),c=yn();return c&&d.set("timezone",c),o!==void 0&&d.set("limit",String(o)),n(`/api/v1/analytics/conversions/targets?${d.toString()}`)},async getAnalyticsBreakdown(a,r,o){let d=a.split("/").map(encodeURIComponent).join("/");return n(`/api/v1/analytics/${d}?${Us(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(vs("/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 bs,jsxs as Sc}from"react/jsx-runtime";var to=hn.createContext(null);function xc(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 wc({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:n=!1,className:s,children:a}){let r=hn.useMemo(()=>xc(e),[e]),o=hn.useMemo(()=>Xr(e,t),[e,t]),d=hn.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return r?bs("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:Sc("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[bs("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),bs("p",{className:"af-text-sm af-text-destructive",children:r})]})}):bs(to.Provider,{value:d,children:bs("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:a})})}function ee(){let e=hn.useContext(to);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as mn from"react";import{ArrowLeft as Cu,Settings as Tu,Inbox as ku}from"lucide-react";import*as $s from"react";import*as Aa from"@radix-ui/react-tabs";import{clsx as Nc}from"clsx";import{extendTailwindMerge as _c}from"tailwind-merge";var Rc=_c({prefix:"af-"});function W(...e){return Rc(Nc(e))}import{jsx as Qr}from"react/jsx-runtime";var Vs=Aa.Root,ys=$s.forwardRef(({className:e,...t},n)=>Qr(Aa.List,{ref:n,className:W("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));ys.displayName=Aa.List.displayName;var Da=$s.forwardRef(({className:e,...t},n)=>Qr(Aa.Trigger,{ref:n,className:W("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));Da.displayName=Aa.Trigger.displayName;var La=$s.forwardRef(({className:e,...t},n)=>Qr(Aa.Content,{ref:n,className:W("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));La.displayName=Aa.Content.displayName;import*as ao from"react";import{Slot as Pc}from"@radix-ui/react-slot";import{cva as Cc}from"class-variance-authority";import{jsx as kc}from"react/jsx-runtime";var Tc=Cc("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"}}),S=ao.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...a},r)=>kc(s?Pc:"button",{className:W(Tc({variant:t,size:n,className:e})),ref:r,...a}));S.displayName="Button";import{Inbox as no,Settings as Ac}from"lucide-react";import*as cn from"react";import{jsx as ln}from"react/jsx-runtime";var $e=cn.forwardRef(({className:e,...t},n)=>ln("div",{className:"af-relative af-w-full af-overflow-auto",children:ln("table",{ref:n,className:W("af-w-full af-caption-bottom af-text-sm",e),...t})}));$e.displayName="Table";var Ve=cn.forwardRef(({className:e,...t},n)=>ln("thead",{ref:n,className:W("[&_tr]:af-border-b",e),...t}));Ve.displayName="TableHeader";var He=cn.forwardRef(({className:e,...t},n)=>ln("tbody",{ref:n,className:W("[&_tr:last-child]:af-border-0",e),...t}));He.displayName="TableBody";var Ec=cn.forwardRef(({className:e,...t},n)=>ln("tfoot",{ref:n,className:W("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Ec.displayName="TableFooter";var be=cn.forwardRef(({className:e,...t},n)=>ln("tr",{ref:n,className:W("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));be.displayName="TableRow";var H=cn.forwardRef(({className:e,...t},n)=>ln("th",{ref:n,className:W("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));H.displayName="TableHead";var z=cn.forwardRef(({className:e,...t},n)=>ln("td",{ref:n,className:W("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));z.displayName="TableCell";var Ic=cn.forwardRef(({className:e,...t},n)=>ln("caption",{ref:n,className:W("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Ic.displayName="TableCaption";import*as Oa from"react";function Gn(){let{api:e}=ee(),[t,n]=Oa.useState([]),[s,a]=Oa.useState(!0),[r,o]=Oa.useState(null),d=Oa.useCallback(async()=>{try{a(!0),o(null);let g=await e.getForms();n(g)}catch(g){o(g instanceof Error?g:new Error("Failed to fetch forms"))}finally{a(!1)}},[e]);Oa.useEffect(()=>{d()},[d]);let c=Oa.useCallback(async g=>{let v=await e.createForm(g);return n(f=>[...f,v]),v},[e]),u=Oa.useCallback(async(g,v)=>{let f=await e.updateForm(g,v);return n(l=>l.map(m=>m.id===g?f:m)),f},[e]),i=Oa.useCallback(async g=>{await e.deleteForm(g),n(v=>v.filter(f=>f.id!==g))},[e]);return{forms:t,isLoading:s,error:r,refetch:d,createForm:c,updateForm:u,deleteForm:i}}import{jsx as ea,jsxs as un}from"react/jsx-runtime";function Hs({onSelectForm:e,className:t}){let{forms:n,isLoading:s,error:a}=Gn();return s?ea("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:ea("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):a?ea("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:[ea(no,{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.",ea("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):ea("div",{className:t,children:un($e,{children:[ea(Ve,{children:un(be,{children:[ea(H,{children:"Name"}),ea(H,{className:"af-text-right",children:"Actions"})]})}),ea(He,{children:n.map(r=>un(be,{children:[ea(z,{className:"af-font-medium",children:r.name}),ea(z,{className:"af-text-right",children:un("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[un(S,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[ea(no,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),un(S,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[ea(Ac,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}import{AlertTriangle as Bc}from"lucide-react";import{cva as Dc}from"class-variance-authority";import{jsx as Oc}from"react/jsx-runtime";var Lc=Dc("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 se({className:e,variant:t,...n}){return Oc("div",{className:W(Lc({variant:t}),e),...n})}import{jsx as Ln,jsxs as zs}from"react/jsx-runtime";var Fc={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 qs(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 ei(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function Uc(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 hs({deliveries:e,label:t="Email needs attention"}){return ei(e)?zs("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(Bc,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Ka({deliveries:e,problemsOnly:t=!1,className:n=""}){let s=(e??[]).filter(a=>!t||ei([a]));return s.length?Ln("div",{className:`af-space-y-3 ${n}`,"aria-label":"Email delivery",children:s.map(a=>{let r=qs(a),o=Uc(a);return zs("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[zs("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Ln("span",{className:"af-font-medium",children:Fc[a.kind]??"Email notification"}),Ln(se,{variant:r.variant,children:r.label})]}),zs("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",a.recipients.join(", ")]}),a.recipients.length>1&&ei([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 eu,ChevronLeft as tu,ChevronRight as au,Eye as nu,Inbox as su,Paperclip as ru}from"lucide-react";import*as xn from"react";import*as Pe from"@radix-ui/react-select";import{Check as Mc,ChevronDown as so,ChevronUp as $c}from"lucide-react";import{jsx as Mt,jsxs as ti}from"react/jsx-runtime";var ya=Pe.Root;var ha=Pe.Value,fa=xn.forwardRef(({className:e,children:t,...n},s)=>ti(Pe.Trigger,{ref:s,className:W("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...n,children:[t,Mt(Pe.Icon,{asChild:!0,children:Mt(so,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));fa.displayName=Pe.Trigger.displayName;var ro=xn.forwardRef(({className:e,...t},n)=>Mt(Pe.ScrollUpButton,{ref:n,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:Mt($c,{className:"af-h-4 af-w-4"})}));ro.displayName=Pe.ScrollUpButton.displayName;var io=xn.forwardRef(({className:e,...t},n)=>Mt(Pe.ScrollDownButton,{ref:n,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:Mt(so,{className:"af-h-4 af-w-4"})}));io.displayName=Pe.ScrollDownButton.displayName;var ma=xn.forwardRef(({className:e,children:t,position:n="popper",...s},a)=>Mt(Pe.Portal,{children:ti(Pe.Content,{ref:a,className:W("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",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(ro,{}),Mt(Pe.Viewport,{className:W("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(io,{})]})}));ma.displayName=Pe.Content.displayName;var Vc=xn.forwardRef(({className:e,...t},n)=>Mt(Pe.Label,{ref:n,className:W("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));Vc.displayName=Pe.Label.displayName;var Ye=xn.forwardRef(({className:e,children:t,...n},s)=>ti(Pe.Item,{ref:s,className:W("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...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(Pe.ItemIndicator,{children:Mt(Mc,{className:"af-h-4 af-w-4"})})}),Mt(Pe.ItemText,{children:t})]}));Ye.displayName=Pe.Item.displayName;var Hc=xn.forwardRef(({className:e,...t},n)=>Mt(Pe.Separator,{ref:n,className:W("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));Hc.displayName=Pe.Separator.displayName;import*as xa from"react";function js({formId:e,initialPageSize:t=25}){let{api:n}=ee(),[s,a]=xa.useState([]),[r,o]=xa.useState(0),[d,c]=xa.useState(!0),[u,i]=xa.useState(null),[g,v]=xa.useState(0),[f,l]=xa.useState(t),m=xa.useCallback(async()=>{if(e)try{c(!0),i(null);let h={limit:f,offset:g*f},w=await n.getSubmissions(e,h);a(w.submissions),o(w.total)}catch(h){i(h instanceof Error?h:new Error("Failed to fetch submissions"))}finally{c(!1)}},[n,e,g,f]);xa.useEffect(()=>{m()},[m]);let p=xa.useCallback(async h=>{await n.deleteSubmission(h),a(w=>w.filter(k=>k.id!==h)),o(w=>w-1)},[n]),b=Math.ceil(r/f);return{submissions:s,total:r,isLoading:d,error:u,page:g,pageSize:f,hasNextPage:g<b-1,hasPreviousPage:g>0,setPage:v,setPageSize:h=>{l(h),v(0)},refetch:m,deleteSubmission:p}}import*as lo from"react";import{ArrowLeft as zc,Download as qc,Globe as jc,Clock as Gc,FileText as Wc,Loader2 as Kc,Monitor as Zc,Mail as Jc}from"lucide-react";import{jsx as dt,jsxs as ft}from"react/jsx-runtime";function oo(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Yc(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 Gs({submission:e,onBack:t}){let{api:n}=ee(),[s,a]=lo.useState(null),r=c=>c.id??c.name,o=async c=>{a(r(c));try{await n.downloadAttachment(e.id,c)}catch(u){console.error("Download failed:",u)}finally{a(null)}},d=Object.entries(e.data).filter(([c])=>!c.startsWith("_"));return ft("div",{children:[ft("div",{className:"af-mb-6",children:[ft(S,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[dt(zc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),dt("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),ft("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",oo(e.metadata.submitted_at)]})]}),ft("div",{className:"af-space-y-6",children:[dt(Ka,{deliveries:e.email_deliveries}),ft("div",{children:[dt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),ft("div",{className:"af-space-y-3",children:[d.map(([c,u])=>ft("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[dt("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:c.replace(/_/g," ")}),dt("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof u=="string"&&u.includes(`
|
|
3
|
-
`)?dt("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:u}):String(u)})]},c)),d.length===0&&dt("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&ft("div",{children:[dt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),dt("div",{className:"af-space-y-2",children:e.attachments.map((c,u)=>ft("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[ft("div",{className:"af-flex af-items-center af-gap-2",children:[dt(Wc,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),dt("span",{className:"af-text-sm",children:c.name}),ft("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Yc(c.size),")"]})]}),ft(S,{variant:"ghost",size:"sm",onClick:()=>o(c),disabled:s===r(c),children:[s===r(c)?dt(Kc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):dt(qc,{className:"af-h-4 af-w-4 af-mr-1"}),s===r(c)?"Downloading...":"Download"]})]},u))})]}),ft("div",{children:[dt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),ft("div",{className:"af-space-y-2 af-text-sm",children:[ft("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[dt(Gc,{className:"af-h-4 af-w-4"}),dt("span",{children:oo(e.metadata.submitted_at)})]}),e.metadata.ip_address&&ft("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[dt(jc,{className:"af-h-4 af-w-4"}),ft("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&ft("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[dt(Zc,{className:"af-h-4 af-w-4 af-mt-0.5"}),dt("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&ft("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[dt(Jc,{className:"af-h-4 af-w-4"}),ft("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{Download as Qc}from"lucide-react";import*as On from"react";var Xc=/^\+[1-9]\d{1,14}$/;function co(e){let t=e==null?"":String(e),n=!Xc.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 Ws(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function Ks(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 Zs({fetchCsv:e,filename:t}){let[n,s]=On.useState(!1),[a,r]=On.useState(null),o=On.useRef(!1);return{exportCsv:On.useCallback(async()=>{if(!o.current){o.current=!0,s(!0),r(null);try{let c=await e();Ks(c,Ws(t))}catch(c){r(c instanceof Error?c:new Error("Export failed"))}finally{o.current=!1,s(!1)}}},[e,t]),exporting:n,error:a}}import{jsx as uo,jsxs as fo}from"react/jsx-runtime";function $t({fetchCsv:e,filename:t,label:n="Export CSV",disabled:s,className:a}){let{exportCsv:r,exporting:o,error:d}=Zs({fetchCsv:e,filename:t});return fo("span",{className:a,children:[fo(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||o,"aria-busy":o,children:[uo(Qc,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Exporting\u2026":n]}),d&&uo("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}import{jsx as we,jsxs as bt}from"react/jsx-runtime";function iu(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ou(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 lu=["message","comments","comment","inquiry","question","details","body","notes"];function cu(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=(lu.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 Js({formId:e,className:t,defaultSubmissionId:n,submissionId:s,onSelectSubmission:a}){let{api:r}=ee(),{submissions:o,total:d,isLoading:c,error:u,page:i,pageSize:g,hasNextPage:v,hasPreviousPage:f,setPage:l,setPageSize:m}=js({formId:e}),p=wn.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[b,h]=wn.useState(n??null),w=a?s??null:b,k=a??h,y=F=>!!F&&F.id===w&&F.form_id===e,N=o.find(y),[R,A]=wn.useState(null),x=y(R)?R:null,[P,T]=wn.useState(null);if(wn.useEffect(()=>{if(T(null),!w||N||x)return;let F=!1;return r.getSubmission(w).then(X=>{if(!F){if(X.form_id!==e){T("This submission could not be found.");return}A(X)}}).catch(()=>{F||T("This submission could not be found.")}),()=>{F=!0}},[r,e,w,N,x]),w){let F=N??x;return F?we("div",{className:t,children:we(Gs,{submission:F,onBack:()=>k(null)})}):P?bt("div",{className:t,children:[bt(S,{variant:"ghost",size:"sm",onClick:()=>k(null),className:"af-mb-2 af--ml-2",children:[we(eu,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),we("p",{className:"af-text-sm af-text-destructive",children:P})]}):we("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:we("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(c)return we("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:we("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(u)return we("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:bt("div",{className:"af-text-destructive",children:["Error: ",u.message]})});if(o.length===0&&i===0)return bt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[we(su,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),bt("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",we("br",{}),"Submissions will appear here when visitors use your form."]})]});let _=i*g+1,K=Math.min((i+1)*g,d);return bt("div",{className:t,children:[we("div",{className:"af-mb-2 af-flex af-justify-end",children:we($t,{fetchCsv:p,filename:"submissions"})}),bt($e,{children:[we(Ve,{children:bt(be,{children:[we(H,{children:"Email"}),we(H,{children:"Preview"}),we(H,{children:"Date"}),we(H,{className:"af-text-right",children:"Actions"})]})}),we(He,{children:o.map(F=>{let X=ou(F.data),Q=cu(F.data);return bt(be,{children:[bt(z,{className:"af-font-medium",children:[bt("div",{className:"af-flex af-items-center af-gap-2",children:[X||we("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),F.attachments.length>0&&bt("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${F.attachments.length} attachment(s)`,children:[we(ru,{className:"af-h-3 af-w-3"}),we("span",{className:"af-text-xs",children:F.attachments.length})]})]}),we(hs,{deliveries:F.email_deliveries,label:"Notification email needs attention"})]}),we(z,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:Q||we("span",{className:"af-italic",children:"No preview available"})}),we(z,{className:"af-text-muted-foreground",children:iu(F.metadata.submitted_at)}),we(z,{className:"af-text-right",children:we(S,{variant:"ghost",size:"icon",onClick:()=>k(F.id),title:"View details",children:we(nu,{className:"af-h-4 af-w-4"})})})]},F.id)})})]}),bt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[bt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[bt("span",{children:["Showing ",_,"-",K," of ",d]}),bt(ya,{value:String(g),onValueChange:F=>m(Number(F)),children:[we(fa,{className:"af-w-[70px] af-h-8",children:we(ha,{})}),bt(ma,{children:[we(Ye,{value:"10",children:"10"}),we(Ye,{value:"25",children:"25"}),we(Ye,{value:"50",children:"50"}),we(Ye,{value:"100",children:"100"})]})]}),we("span",{children:"per page"})]}),bt("div",{className:"af-flex af-items-center af-gap-2",children:[bt(S,{variant:"outline",size:"sm",onClick:()=>l(i-1),disabled:!f,children:[we(tu,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),bt(S,{variant:"outline",size:"sm",onClick:()=>l(i+1),disabled:!v,children:["Next",we(au,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as ga from"react";import{Plus as Nu,X as _u,Loader2 as Ru,Check as Pu}from"lucide-react";import*as mo from"react";import{jsx as uu}from"react/jsx-runtime";var ce=mo.forwardRef(({className:e,type:t,...n},s)=>uu("input",{type:t,className:W("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:s,...n}));ce.displayName="Input";import*as po from"react";import{cva as du}from"class-variance-authority";import{jsx as mu}from"react/jsx-runtime";var fu=du("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),ye=po.forwardRef(({className:e,...t},n)=>mu("label",{ref:n,className:W(fu(),e),...t}));ye.displayName="Label";import*as Sa from"react";import{Plus as bu,Loader2 as ni,Copy as yu,Check as hu,Trash2 as xu,RefreshCw as wu,AlertTriangle as Su}from"lucide-react";import*as xs from"react";import*as Nt from"@radix-ui/react-dialog";import{X as pu}from"lucide-react";import{jsx as dn,jsxs as ai}from"react/jsx-runtime";var Za=Nt.Root;var gu=Nt.Portal;var go=xs.forwardRef(({className:e,...t},n)=>dn(Nt.Overlay,{ref:n,className:W("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));go.displayName=Nt.Overlay.displayName;var Ba=xs.forwardRef(({className:e,children:t,...n},s)=>dn(gu,{children:ai("div",{className:"aifeatures-admin",children:[dn(go,{}),ai(Nt.Content,{ref:s,className:W("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...n,children:[t,ai(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(pu,{className:"af-h-4 af-w-4"}),dn("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Ba.displayName=Nt.Content.displayName;var Fa=({className:e,...t})=>dn("div",{className:W("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Fa.displayName="DialogHeader";var Ua=({className:e,...t})=>dn("div",{className:W("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ua.displayName="DialogFooter";var Ma=xs.forwardRef(({className:e,...t},n)=>dn(Nt.Title,{ref:n,className:W("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Ma.displayName=Nt.Title.displayName;var $a=xs.forwardRef(({className:e,...t},n)=>dn(Nt.Description,{ref:n,className:W("af-text-sm af-text-muted-foreground",e),...t}));$a.displayName=Nt.Description.displayName;import*as pa from"react";function Ys(){let{api:e}=ee(),[t,n]=pa.useState([]),[s,a]=pa.useState(!0),[r,o]=pa.useState(null),d=pa.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]);pa.useEffect(()=>{d()},[d]);let c=pa.useCallback(async f=>{let l=await e.createEventDestination(f);return n(m=>[l,...m]),l},[e]),u=pa.useCallback(async(f,l)=>{let m=await e.updateEventDestination(f,l);return n(p=>p.map(b=>b.id===f?m:b)),m},[e]),i=pa.useCallback(async f=>{await e.deleteEventDestination(f),n(l=>l.filter(m=>m.id!==f))},[e]),g=pa.useCallback(async f=>{let l=await e.rotateEventDestinationSecret(f);return n(m=>m.map(p=>p.id===f?l:p)),l},[e]),v=pa.useCallback(f=>e.getEventDestinationSecret(f),[e]);return{destinations:t,isLoading:s,error:r,refetch:d,createDestination:c,updateDestination:u,deleteDestination:i,rotateSecret:g,getSecret:v}}import*as fn from"react";import{Loader2 as vo,RotateCw as vu}from"lucide-react";import{jsx as wa,jsxs as ws}from"react/jsx-runtime";function Xs({destinationId:e,limit:t=25,className:n}){let{api:s}=ee(),[a,r]=fn.useState([]),[o,d]=fn.useState(!0),[c,u]=fn.useState(null),[i,g]=fn.useState(null),v=fn.useCallback(async()=>{try{d(!0),u(null),r(await s.getEventDeliveries(e,t))}catch(l){u(l instanceof Error?l.message:"Failed to load deliveries")}finally{d(!1)}},[s,e,t]);fn.useEffect(()=>{v()},[v]);let f=async l=>{try{g(l.id),u(null);let m=await s.retryEventDelivery(e,l.id);r(p=>p.map(b=>b.id===l.id?m:b))}catch(m){u(m instanceof Error?m.message:"Retry failed")}finally{g(null)}};return o?ws("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[wa(vo,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):c?wa("div",{className:"af-text-sm af-text-destructive af-py-2",children:c}):a.length===0?wa("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):wa("div",{className:n,children:wa("div",{className:"af-divide-y af-border af-rounded",children:a.map(l=>{let m=l.delivered_at!==null;return ws("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[ws("div",{className:"af-min-w-0",children:[ws("div",{className:"af-flex af-items-center af-gap-2",children:[m?wa(se,{variant:"secondary",children:l.last_status??200}):wa(se,{variant:"destructive",children:l.last_status??"failed"}),wa("span",{className:"af-text-sm af-truncate",children:l.type})]}),ws("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[l.event_id," \xB7 ",l.created_at,l.attempts>0&&` \xB7 ${l.attempts} failed ${l.attempts===1?"attempt":"attempts"}`]}),!m&&l.last_error&&wa("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:l.last_error})]}),wa(S,{variant:"ghost",size:"sm",title:"Send this event again",disabled:i===l.id,onClick:()=>f(l),children:i===l.id?wa(vo,{className:"af-h-4 af-w-4 af-animate-spin"}):wa(vu,{className:"af-h-4 af-w-4"})})]},l.id)})})})}import{jsx as Ie,jsxs as yt}from"react/jsx-runtime";function Qs({formId:e,topics:t,description:n,className:s}){let{destinations:a,isLoading:r,error:o,createDestination:d,updateDestination:c,deleteDestination:u,rotateSecret:i,getSecret:g}=Ys(),[v,f]=Sa.useState(""),[l,m]=Sa.useState(!1),[p,b]=Sa.useState(null),[h,w]=Sa.useState(null),[k,y]=Sa.useState(null),[N,R]=Sa.useState(!1),[A,x]=Sa.useState(null),[P,T]=Sa.useState(null),[_,K]=Sa.useState(null),F=Sa.useMemo(()=>a.filter(V=>V.form_id===e),[a,e]),X=async()=>{let V=v.trim();if(V){if(!V.startsWith("https://")){b("Webhook URLs must start with https://");return}try{m(!0),b(null),await d({url:V,form_id:e,...t&&t.length>0?{topics:t}:{}}),f("")}catch(fe){b(fe instanceof Error?fe.message:"Failed to add webhook")}finally{m(!1)}}},Q=async V=>{try{T(V.id),b(null),await i(V.id),R(!1),y(await g(V.id))}catch(fe){b(fe instanceof Error?fe.message:"Failed to rotate secret")}finally{T(null)}},ne=async V=>{try{T(V.id),b(null),await c(V.id,{status:"active"})}catch(fe){b(fe instanceof Error?fe.message:"Failed to re-enable")}finally{T(null)}},te=async()=>{if(A)try{T(A.id),await u(A.id),x(null)}catch(V){b(V instanceof Error?V.message:"Failed to delete")}finally{T(null)}},$=async V=>{if(h===V.id){w(null),y(null);return}try{T(V.id),b(null),R(!1),w(V.id),y(await g(V.id))}catch(fe){w(null),b(fe instanceof Error?fe.message:"Failed to read secret")}finally{T(null)}},M=async()=>{if(k)try{await navigator.clipboard.writeText(k),R(!0)}catch{}};return yt("div",{className:s,children:[yt("div",{className:"af-space-y-1",children:[Ie(ye,{children:"Webhooks"}),Ie("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:[Ie(ce,{value:v,placeholder:"https://hooks.zapier.com/...",onChange:V=>f(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),X())},disabled:l}),yt(S,{onClick:X,disabled:l||!v.trim(),children:[l?Ie(ni,{className:"af-h-4 af-w-4 af-animate-spin"}):Ie(bu,{className:"af-h-4 af-w-4"}),Ie("span",{className:"af-ml-1",children:"Add"})]})]}),(p||o)&&Ie("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:[Ie(ni,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&F.length===0&&Ie("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),F.map(V=>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:[Ie("span",{className:"af-font-mono af-text-sm af-truncate",children:V.url}),V.status==="disabled"?Ie(se,{variant:"destructive",children:"Disabled"}):Ie(se,{variant:"secondary",children:"Active"})]}),Ie("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:V.topics.includes("*")?"All events":V.topics.join(", ")})]}),yt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[Ie(S,{variant:"ghost",size:"sm",onClick:()=>K(_===V.id?null:V.id),children:_===V.id?"Hide log":"Deliveries"}),Ie(S,{variant:"ghost",size:"sm",onClick:()=>$(V),disabled:P===V.id,children:h===V.id?"Hide secret":"Show secret"}),Ie(S,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:P===V.id,onClick:()=>x(V),children:Ie(xu,{className:"af-h-4 af-w-4"})})]})]}),V.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:[Ie(Su,{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."," ",V.disabled_reason]}),Ie(S,{variant:"outline",size:"sm",className:"af-mt-2",disabled:P===V.id,onClick:()=>ne(V),children:"Re-enable"})]})]}),h===V.id&&k&&yt("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[Ie("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:[Ie(ce,{readOnly:!0,value:k,className:"af-font-mono"}),Ie(S,{variant:"outline",title:"Copy signing secret",onClick:M,children:N?Ie(hu,{className:"af-h-4 af-w-4"}):Ie(yu,{className:"af-h-4 af-w-4"})}),Ie(S,{variant:"outline",title:"Rotate signing secret",disabled:P===V.id,onClick:()=>Q(V),children:P===V.id?Ie(ni,{className:"af-h-4 af-w-4 af-animate-spin"}):Ie(wu,{className:"af-h-4 af-w-4"})})]})]}),_===V.id&&Ie(Xs,{destinationId:V.id})]},V.id))]}),Ie(Za,{open:!!A,onOpenChange:V=>{!V&&!P&&x(null)},children:yt(Ba,{children:[yt(Fa,{children:[Ie(Ma,{children:"Delete this webhook?"}),yt($a,{children:["New submissions will stop being sent to ",A?.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(Ua,{children:[Ie(S,{variant:"outline",onClick:()=>x(null),disabled:!!P,children:"Cancel"}),Ie(S,{variant:"destructive",onClick:te,disabled:!!P,children:P?"Deleting...":"Delete"})]})]})})]})}import{jsx as Ue,jsxs as Va}from"react/jsx-runtime";function er({form:e,onSaved:t,className:n}){let{updateForm:s}=Gn(),[a,r]=ga.useState(!1),[o,d]=ga.useState(null),[c,u]=ga.useState(null),[i,g]=ga.useState(e.name),[v,f]=ga.useState(e.redirect_url||""),[l,m]=ga.useState(e.email_recipients),[p,b]=ga.useState("");ga.useEffect(()=>{g(e.name),f(e.redirect_url||""),m(e.email_recipients),u(null)},[e]);let h=ga.useCallback(async R=>{try{r(!0),u(null);let A=await s(e.id,R);d(new Date),t?.(A)}catch(A){u(A instanceof Error?A.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);ga.useEffect(()=>{if(o){let R=setTimeout(()=>d(null),2e3);return()=>clearTimeout(R)}},[o]);let w=async()=>{let R=p.trim().toLowerCase();if(!R)return;if(!R.includes("@")){u("Please enter a valid email address");return}if(l.includes(R)){u("This email is already added");return}let A=[...l,R];m(A),b(""),u(null),await h({email_recipients:A})},k=async R=>{let A=l.filter(x=>x!==R);m(A),await h({email_recipients:A})},y=async()=>{i!==e.name&&await h({name:i})},N=async()=>{let R=v||null;R!==e.redirect_url&&await h({redirect_url:R})};return Va("div",{className:`af-space-y-6 af-relative ${n||""}`,children:[(a||o)&&Ue("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:a?Va("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:[Ue(Ru,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),Ue("span",{className:"af-text-sm",children:"Saving..."})]}):Va("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:[Ue(Pu,{className:"af-h-4 af-w-4 af-text-green-600"}),Ue("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Va("div",{className:"af-space-y-2",children:[Ue(ye,{htmlFor:"form-name",children:"Form Name"}),Ue(ce,{id:"form-name",value:i,onChange:R=>g(R.target.value),onBlur:y,placeholder:"Contact Form"}),Ue("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),Va("div",{className:"af-space-y-2",children:[Ue(ye,{children:"Email Recipients"}),Ue("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),Va("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[l.map(R=>Va(se,{variant:"secondary",className:"af-gap-1",children:[R,Ue("button",{type:"button",onClick:()=>k(R),className:"af-ml-1 hover:af-text-destructive",disabled:a,children:Ue(_u,{className:"af-h-3 af-w-3"})})]},R)),l.length===0&&Ue("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Va("div",{className:"af-flex af-gap-2",children:[Ue(ce,{type:"email",value:p,onChange:R=>b(R.target.value),placeholder:"Add email address",onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),w())},disabled:a}),Ue(S,{type:"button",variant:"outline",onClick:w,disabled:!p.trim()||a,children:Ue(Nu,{className:"af-h-4 af-w-4"})})]})]}),Va("div",{className:"af-space-y-2",children:[Ue(ye,{htmlFor:"redirect-url",children:"Redirect URL"}),Ue(ce,{id:"redirect-url",value:v,onChange:R=>f(R.target.value),onBlur:N,placeholder:"/thank-you"}),Ue("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."})]}),Va("div",{className:"af-space-y-2",children:[Ue(ye,{children:"Form Endpoint"}),Ue("div",{className:"af-flex af-items-center af-gap-2",children:Ue("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})}),Ue("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),Va("div",{className:"af-space-y-2",children:[Ue(ye,{children:"Captcha Protection"}),Ue("div",{className:"af-flex af-items-center af-gap-2",children:Ue(se,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),Ue("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),Ue(Qs,{formId:e.id}),c&&Ue("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:c})]})}import{jsx as ta,jsxs as Ja}from"react/jsx-runtime";function bo({className:e,location:t,onNavigate:n,submissionId:s}){let{api:a}=ee(),[r,o]=mn.useState({submissionId:s});mn.useEffect(()=>{s&&o({submissionId:s})},[s]);let d=n?t??{}:r,c=n??o,[u,i]=mn.useState(null),g=`${d.formId??""}|${d.submissionId??""}`,[v,f]=mn.useState(null),l=v?.key===g?v.message:null,m=d.formId??(u&&u.submissionId===d.submissionId?u.formId:void 0);mn.useEffect(()=>{let R=d.submissionId;if(!R||d.formId)return;let A=!1;return a.getSubmission(R).then(x=>{A||(f(null),i({submissionId:R,formId:x.form_id}))}).catch(()=>{A||f({key:g,message:"This submission could not be found."})}),()=>{A=!0}},[a,d.submissionId,d.formId,g]);let[p,b]=mn.useState(null);mn.useEffect(()=>{if(!m||p?.id===m)return;let R=!1;return a.getForm(m).then(A=>{R||(f(null),b(A))}).catch(()=>{R||f({key:g,message:"This form could not be found."})}),()=>{R=!0}},[a,m,p?.id,g]);let h=(R,A)=>{b(R),c({formId:R.id,tab:A})},w=()=>c({});if(!d.formId&&!d.submissionId)return Ja("div",{className:e,children:[Ja("div",{className:"af-mb-6",children:[ta("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),ta("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),ta(Hs,{onSelectForm:h})]});let y=Ja(S,{variant:"ghost",size:"sm",onClick:w,className:"af-mb-2 af--ml-2",children:[ta(Cu,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(l)return Ja("div",{className:e,children:[y,ta("p",{className:"af-text-sm af-text-destructive",children:l})]});if(!m||p?.id!==m)return ta("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:ta("div",{className:"af-text-muted-foreground",children:"Loading..."})});let N=d.submissionId?"submissions":d.tab??"submissions";return Ja("div",{className:e,children:[Ja("div",{className:"af-mb-6",children:[y,ta("h2",{className:"af-text-lg af-font-semibold",children:p.name})]}),Ja(Vs,{value:N,onValueChange:R=>c({formId:m,tab:R}),children:[Ja(ys,{className:"af-mb-4",children:[Ja(Da,{value:"submissions",className:"af-gap-2",children:[ta(ku,{className:"af-h-4 af-w-4"}),"Submissions"]}),Ja(Da,{value:"settings",className:"af-gap-2",children:[ta(Tu,{className:"af-h-4 af-w-4"}),"Settings"]})]}),ta(La,{value:"submissions",children:ta(Js,{formId:m,submissionId:d.submissionId,onSelectSubmission:R=>c({formId:m,tab:"submissions",submissionId:R??void 0})})}),ta(La,{value:"settings",children:ta(er,{form:p,onSaved:b})})]})]})}import*as Me from"react";import*as Ya from"react";function Sn(){let{api:e}=ee(),[t,n]=Ya.useState(null),[s,a]=Ya.useState(!0),[r,o]=Ya.useState(null),d=Ya.useRef(0),c=Ya.useCallback(async()=>{let u=++d.current;try{a(!0),o(null);let i=await e.getPaymentsStatus();if(u!==d.current)return;n(i)}catch(i){if(u!==d.current)return;o(i instanceof Error?i:new Error("Failed to fetch payments status"))}finally{u===d.current&&a(!1)}},[e]);return Ya.useEffect(()=>{c()},[c]),{status:t,isLoading:s,error:r,refetch:c}}var Eu=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Na(e){return Eu.has(e.toLowerCase())}function j(e,t,n){let s=Na(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=Na(t)?n:n*100;return Math.round(s)}function it(e,t){return Na(t)?e:e/100}function tr(e){return e.amount_paid??Math.max(0,pn(e)-(e.credit_applied??0))}import{Fragment as Du,jsx as De,jsxs as qe}from"react/jsx-runtime";function Ss(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 yo(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 Wn(){let{api:e,siteToken:t}=ee();return De(Iu,{api:e},t)}function Iu({api:e}){let{status:t,error:n}=Sn(),[s,a]=Me.useState([]),[r,o]=Me.useState(null),[d,c]=Me.useState(null),[u,i]=Me.useState(!1),[g,v]=Me.useState(!1),[f,l]=Me.useState(""),[m,p]=Me.useState(null),[b,h]=Me.useState(null),[w,k]=Me.useState(!1),y=Me.useRef(0),N=Me.useCallback(async x=>{let P=++y.current;i(!0),l("");try{let T=await e.getPromos(x);if(P!==y.current)return;a(_=>x?[..._,...T.promos.filter(K=>!_.some(F=>F.id===K.id))]:T.promos),o(T.next_cursor),c(T.checkout_enabled)}catch(T){P===y.current&&l(Ss(T))}finally{P===y.current&&i(!1)}},[e]);Me.useEffect(()=>(N(),()=>{y.current++}),[N]);async function R(x){let P=++y.current;i(!0),l(""),k(!1);try{let T=await e.getPromo(x);P===y.current&&p(T)}catch(T){P===y.current&&l(Ss(T))}finally{P===y.current&&i(!1)}}async function A(){if(m){v(!0),i(!0),l("");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.");k(!1),await N()}catch(x){l(Ss(x))}finally{v(!1),i(!1)}}}return b?De(Au,{currency:t?.currency??void 0,replaces:b.replaces,onCancel:()=>h(null),onSave:async x=>{let P=b.replaces?await e.replacePromo(b.replaces.id,x):await e.createPromo(x),T=await e.getPromo(P.id);if(T.status==="pending"||T.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(T),h(null),await N()}}):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:[De("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),De(S,{disabled:u||!t?.currency,onClick:()=>{l(""),h({})},children:"Create promo code"})]}),De("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."}),d===!1&&De("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&&De("p",{className:"af-text-sm",children:n?Ss(n):"Connect Stripe and set the payment currency before creating codes."}),f&&qe("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[f," ",De(S,{variant:"outline",disabled:u,onClick:()=>m?void R(m.id):void N(),children:"Refresh"})]}),m?qe("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[De(S,{variant:"ghost",disabled:g,onClick:()=>{p(null),k(!1),N()},children:"Back to codes"}),qe("h4",{className:"af-font-semibold af-break-all",children:[m.code," \xB7 ",m.name]}),qe("p",{children:[yo(m)," \xB7 ",m.status]}),qe("p",{className:"af-text-sm",children:[m.times_redeemed==null?"Usage unavailable":`${m.times_redeemed} redemptions`,m.max_redemptions!=null?` / ${m.max_redemptions} maximum`:""]}),qe("p",{className:"af-text-sm",children:[m.minimum_amount!=null&&m.currency?`Minimum order: ${j(m.minimum_amount,m.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),qe("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."]}),De("p",{className:"af-text-sm",children:m.expires_at?`Expires ${new Date(m.expires_at).toLocaleString()}`:"No expiry"}),qe("div",{className:"af-flex af-flex-wrap af-gap-2",children:[De(S,{variant:"outline",disabled:u,onClick:()=>void R(m.id),children:"Refresh details"}),De(S,{variant:"outline",disabled:u||m.status==="pending"||m.status==="unavailable"||!t?.currency,onClick:()=>h({replaces:m}),children:"Replace with new code"}),De(S,{variant:"outline",disabled:u||!["active","pending","unavailable"].includes(m.status),onClick:()=>k(!0),children:m.status==="pending"?"Cancel pending offer":"Disable code"})]}),w&&qe("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[qe("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."]}),De(S,{disabled:u,onClick:()=>void A(),children:m.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",De(S,{variant:"ghost",disabled:u,onClick:()=>k(!1),children:"Cancel"})]})]}):qe(Du,{children:[s.map(x=>qe("button",{type:"button",disabled:u,onClick:()=>void R(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:[qe("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[De("span",{className:"af-font-semibold af-break-all",children:x.code}),De("span",{className:"af-text-sm",children:x.status})]}),qe("div",{className:"af-text-sm",children:[yo(x)," \xB7"," ",x.times_redeemed==null?"Usage unavailable":`${x.times_redeemed} redemptions`]})]},x.id)),!u&&!f&&s.length===0&&De("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),u&&De("p",{role:"status",children:"Loading promo codes\u2026"}),r&&De(S,{variant:"outline",disabled:u,onClick:()=>void N(r),children:"Load more"})]})]})}function Au({currency:e,replaces:t,onCancel:n,onSave:s}){let[a,r]=Me.useState(""),[o,d]=Me.useState(t?.name??""),[c,u]=Me.useState(t?.amount_off!=null?"fixed":"percent"),[i,g]=Me.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(it(t.amount_off,e)):"")),[v,f]=Me.useState(t?.minimum_amount!=null&&e?String(it(t.minimum_amount,e)):""),[l,m]=Me.useState(()=>{if(!t?.expires_at)return"";let ne=new Date(t.expires_at);return Number.isFinite(ne.getTime())?new Date(ne.getTime()-ne.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,b]=Me.useState(t?.max_redemptions?.toString()??""),[h,w]=Me.useState(t?.duration??"once"),[k,y]=Me.useState(t?.duration_in_months?.toString()??"3"),[N,R]=Me.useState(null),[A,x]=Me.useState(!1),[P,T]=Me.useState(""),_=Me.useRef(!1),K=e&&Na(e)?"1":"0.01";async function F(ne){if(ne.preventDefault(),_.current)return;T("");let te=N;if(!te){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 $=Ot(i,e),M=v?Ot(v,e):null;if(c==="fixed"&&(!$||$>999999999999)||v&&(!M||M>999999999999)){T("Enter a positive amount within the supported range.");return}if(l&&new Date(l).getTime()<=Date.now()){T("Choose a future expiry.");return}te={request_id:crypto.randomUUID(),code:a.trim().toUpperCase(),name:o.trim(),duration:h,...c==="percent"?{percent_off:Number(i)}:{amount_off:$,currency:e},...v?{minimum_amount:M,currency:e}:{},...l?{expires_at:new Date(l).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...h==="repeating"?{duration_in_months:Number(k)}:{}},R(te)}_.current=!0,x(!0);try{await s(te)}catch($){T(Ss($)),$ instanceof St&&$.status>=400&&$.status<500&&$.details?.retryable!==!0&&R(null)}finally{_.current=!1,x(!1)}}let X=(ne,te,$,M={})=>qe("label",{className:"af-grid af-gap-1 af-text-sm",children:[ne,De(ce,{"aria-label":ne,value:te,onChange:V=>$(V.target.value),...M})]}),Q="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return qe("form",{onSubmit:F,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[De("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&De("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:A||!!N,className:"af-grid af-gap-4",children:[X("Code",a,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),X("Name",o,d,{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:Q,value:c,onChange:ne=>u(ne.target.value),children:[De("option",{value:"percent",children:"Percentage"}),qe("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),X("Discount",i,g,{type:"number",required:!0,min:c==="percent"?"0.01":K,max:c==="percent"?"100":void 0,step:c==="percent"?"0.01":K}),X("Minimum order amount",v,f,{type:"number",min:K,step:K,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."]}),X("Expires at (local time)",l,m,{type:"datetime-local",step:1}),X("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:Q,value:h,onChange:ne=>w(ne.target.value),children:[De("option",{value:"once",children:"First invoice only"}),De("option",{value:"forever",children:"Every invoice"}),De("option",{value:"repeating",children:"Number of months"})]})]}),h==="repeating"&&X("Months",k,y,{type:"number",required:!0,min:1,max:36,step:1})]}),P&&De("p",{role:"alert",className:"af-text-sm af-text-destructive",children:P}),N&&!A&&qe("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",De("span",{className:"af-break-all",children:N.request_id})]}),qe("div",{className:"af-flex af-flex-wrap af-gap-2",children:[De(S,{type:"submit",disabled:A,children:A?"Saving\u2026":N?"Retry same request":t?"Create replacement":"Create code"}),De(S,{type:"button",variant:"ghost",disabled:A||!!N,onClick:n,children:"Cancel"})]})]})}import*as ns from"react";import{ArrowLeft as nf,FileText as sf,Package as rf,Receipt as of,Settings as lf,Users as cf}from"lucide-react";import*as ar from"react";import{Package as Lu,Pencil as Ou,Plus as ho,Trash2 as Bu}from"lucide-react";import{jsx as ze,jsxs as Vt}from"react/jsx-runtime";function Fu(e){if(e.allow_custom_amount){let t=e.min_amount!==null?j(e.min_amount,e.currency):"?",n=e.max_amount!==null?j(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${n})`}return e.unit_amount===null?"Varies by variant":j(e.unit_amount,e.currency)}function Uu(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function nr({productsState:e,onSelectProduct:t,onCreateProduct:n,className:s}){let{products:a,isLoading:r,error:o,deleteProduct:d}=e,[c,u]=ar.useState(null),[i,g]=ar.useState(!1),[v,f]=ar.useState(null),l=async()=>{if(c)try{g(!0),f(null),await d(c.id),u(null)}catch(m){f(m instanceof Error?m.message:"Failed to delete product")}finally{g(!1)}};return r?ze("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:ze("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?ze("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:[ze(Lu,{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.",ze("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),Vt(S,{variant:"outline",onClick:()=>n?.(),children:[ze(ho,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Vt("div",{className:s,children:[ze("div",{className:"af-flex af-justify-end af-mb-4",children:Vt(S,{variant:"outline",size:"sm",onClick:()=>n?.(),children:[ze(ho,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Vt($e,{children:[ze(Ve,{children:Vt(be,{children:[ze(H,{children:"Name"}),ze(H,{children:"Price"}),ze(H,{children:"Fulfillment"}),ze(H,{children:"Status"}),ze(H,{className:"af-text-right",children:"Actions"})]})}),ze(He,{children:a.map(m=>Vt(be,{children:[ze(z,{className:"af-font-medium",children:m.name}),ze(z,{children:Fu(m)}),ze(z,{className:"af-text-muted-foreground",children:Uu(m)}),ze(z,{children:ze(se,{variant:m.active?"success":"secondary",children:m.active?"Active":"Inactive"})}),ze(z,{className:"af-text-right",children:Vt("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Vt(S,{variant:"ghost",size:"sm",onClick:()=>t?.(m),children:[ze(Ou,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Vt(S,{variant:"ghost",size:"sm",onClick:()=>{f(null),u(m)},children:[ze(Bu,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},m.id))})]}),ze(Za,{open:!!c,onOpenChange:m=>{!m&&!i&&u(null)},children:Vt(Ba,{children:[Vt(Fa,{children:[ze(Ma,{children:"Delete product?"}),Vt($a,{children:['"',c?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),v&&ze("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),Vt(Ua,{children:[ze(S,{variant:"outline",onClick:()=>u(null),disabled:i,children:"Cancel"}),ze(S,{variant:"destructive",onClick:l,disabled:i,children:i?"Deleting...":"Delete"})]})]})})]})}import*as Xe from"react";import{FileText as $u,Link2 as Vu,Loader2 as So,Plus as Hu,Upload as zu,X as qu}from"lucide-react";import*as ht from"react";import{Loader2 as xo,Plus as si,Trash2 as wo,X as Mu}from"lucide-react";import{jsx as Z,jsxs as pe}from"react/jsx-runtime";function ri(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function sr({productId:e,currency:t,className:n}){let{api:s}=ee(),a=Na(t)?"1":"0.01",[r,o]=ht.useState(null),[d,c]=ht.useState(!0),[u,i]=ht.useState(null),[g,v]=ht.useState(null),[f,l]=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&&c(!1)}},[s,e]);ht.useEffect(()=>{p()},[p]);let b=async E=>{v(null),l(!0);try{await E(),await p()}catch(B){m.current&&v(B instanceof Error?B.message:"Something went wrong")}finally{m.current&&l(!1)}},[h,w]=ht.useState(""),[k,y]=ht.useState(""),[N,R]=ht.useState({}),A=()=>b(async()=>{let E=h.trim(),B=k.split(",").map(O=>O.trim()).filter(Boolean);if(!E)throw new Error("Option name is required");if(B.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:E,values:B}),m.current&&(w(""),y(""))}),x=E=>b(async()=>{let B=(N[E.id]??"").trim();if(!B)throw new Error("Enter a value");await s.updateOption(E.id,{add_values:[B]}),m.current&&R(O=>({...O,[E.id]:""}))}),P=(E,B)=>b(()=>s.updateOption(E.id,{remove_values:[B]})),T=E=>b(()=>s.deleteOption(E.id)),[_,K]=ht.useState(null),[F,X]=ht.useState(null),[Q,ne]=ht.useState(!1),[te,$]=ht.useState(null),M=r?.options??[],V=r?.variants??[],fe=()=>{X(null),K({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(M.map(E=>[E.id,E.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Ke=E=>{X(null);let B=E.inventory?.on_hand??0,O=B<0?"":String(B);K({variant:E,title:E.title??"",sku:E.sku??"",unitAmount:E.unit_amount!=null?String(it(E.unit_amount,t)):"",compareAt:E.compare_at_amount!=null?String(it(E.compare_at_amount,t)):"",active:E.active,optionValues:{},tracked:E.inventory?.tracked??!1,onHand:O,initialOnHand:O,allowBackorder:E.inventory?.allow_backorder??!1})},vt=async()=>{if(!_)return;X(null);let E=_.variant?.allow_custom_amount??!1,B=null,O=null;if(!E){if(B=Ot(_.unitAmount,t),B===null||B<=0){X("Enter a valid price");return}if(_.compareAt.trim()&&(O=Ot(_.compareAt,t),O===null||O<=B)){X("Compare-at price must be greater than the price");return}}let me=_.onHand.trim()!==_.initialOnHand.trim(),ve=parseInt(_.onHand,10);if(_.tracked&&me&&(!Number.isFinite(ve)||ve<0)){X("On-hand quantity must be zero or more");return}try{if(ne(!0),_.variant)await s.updateVariant(_.variant.id,{title:_.title.trim()||null,sku:_.sku.trim()||null,...E?{}:{unit_amount:B,compare_at_amount:O},active:_.active}),await s.setVariantInventory(_.variant.id,{tracked:_.tracked,on_hand:_.tracked&&me?ve:void 0,allow_backorder:_.allowBackorder});else{let _e={};for(let Le of M){let nt=_.optionValues[Le.id];if(!nt){X(`Choose a ${Le.title}`),ne(!1);return}_e[Le.title]=nt}await s.createVariant(e,{title:_.title.trim()||null,sku:_.sku.trim()||null,unit_amount:B,compare_at_amount:O,active:_.active,option_values:M.length>0?_e:void 0,inventory:_.tracked?{tracked:!0,on_hand:ve,allow_backorder:_.allowBackorder}:{tracked:!1,allow_backorder:_.allowBackorder}})}await p(),m.current&&K(null)}catch(_e){if(m.current&&X(_e instanceof Error?_e.message:"Failed to save variant"),_.variant)try{let Le=await s.getProduct(e);m.current&&o(Le)}catch{}}finally{m.current&&ne(!1)}},Ee=()=>b(async()=>{te&&(await s.deleteVariant(te.id),m.current&&$(null))}),Fe=_?.variant?.allow_custom_amount??!1,Ze=_?.variant!=null&&_.variant.option_values.length===0&&M.length>0&&!_.variant.active,Te=_?.variant?.inventory!=null&&_.variant.inventory.on_hand<0?-_.variant.inventory.on_hand:null;function kt(E){let B=E.inventory;if(!B||!B.tracked)return Z("span",{className:"af-text-muted-foreground",children:"Unlimited"});let O=B.available??B.on_hand;return O<0?pe("span",{children:[-O," backordered"]}):pe("span",{children:[O," in stock",B.allow_backorder&&Z("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return d?Z("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${n||""}`,children:Z(xo,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):u?Z("div",{className:n,children:Z("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})}):pe("div",{className:`af-space-y-6 ${n||""}`,children:[pe("div",{className:"af-space-y-3",children:[pe("div",{children:[Z(ye,{children:"Options"}),Z("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."})]}),M.length>0&&Z("div",{className:"af-space-y-3",children:M.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:[Z("span",{className:"af-text-sm af-font-medium",children:E.title}),Z(S,{variant:"ghost",size:"sm",onClick:()=>T(E),disabled:f,children:Z(wo,{className:"af-h-4 af-w-4"})})]}),Z("div",{className:"af-flex af-flex-wrap af-gap-2",children:E.values.map(B=>pe(se,{variant:"secondary",className:"af-gap-1",children:[B.value,Z("button",{type:"button",onClick:()=>P(E,B.value),className:"af-ml-1 hover:af-text-destructive",disabled:f,title:"Remove value",children:Z(Mu,{className:"af-h-3 af-w-3"})})]},B.id))}),pe("div",{className:"af-flex af-gap-2",children:[Z(ce,{value:N[E.id]??"",onChange:B=>R(O=>({...O,[E.id]:B.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),x(E))},disabled:f}),Z(S,{type:"button",variant:"outline",size:"sm",onClick:()=>x(E),disabled:f||!(N[E.id]??"").trim(),children:Z(si,{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:[Z(ye,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),Z(ce,{id:"new-option-title",value:h,onChange:E=>w(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:[Z(ye,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),Z(ce,{id:"new-option-values",value:k,onChange:E=>y(E.target.value),placeholder:"S, M, L",disabled:f})]}),pe(S,{type:"button",variant:"outline",onClick:A,disabled:f||!h.trim()||!k.trim(),children:[Z(si,{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:[Z(ye,{children:"Variants"}),pe(S,{type:"button",variant:"outline",size:"sm",onClick:fe,disabled:f||M.length===0,children:[Z(si,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),M.length===0&&Z("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),V.length===0?Z("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):pe($e,{children:[Z(Ve,{children:pe(be,{children:[Z(H,{children:"Variant"}),Z(H,{children:"SKU"}),Z(H,{children:"Price"}),Z(H,{children:"Stock"}),Z(H,{children:"Status"}),Z(H,{className:"af-text-right",children:"Actions"})]})}),Z(He,{children:V.map(E=>pe(be,{children:[Z(z,{className:"af-font-medium",children:ri(E)}),Z(z,{className:"af-text-muted-foreground",children:E.sku||"-"}),Z(z,{children:E.unit_amount!=null?pe("span",{children:[E.compare_at_amount!=null&&Z("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:j(E.compare_at_amount,E.currency)}),j(E.unit_amount,E.currency)]}):E.allow_custom_amount?Z("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),Z(z,{children:kt(E)}),Z(z,{children:Z(se,{variant:E.active?"success":"secondary",children:E.active?"Active":"Inactive"})}),Z(z,{className:"af-text-right",children:pe("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[Z(S,{variant:"ghost",size:"sm",onClick:()=>Ke(E),disabled:f,children:"Edit"}),Z(S,{variant:"ghost",size:"icon",onClick:()=>$(E),disabled:f,title:"Delete variant",children:Z(wo,{className:"af-h-4 af-w-4"})})]})})]},E.id))})]})]}),g&&Z("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g}),Z(Za,{open:_!==null,onOpenChange:E=>{!E&&!Q&&K(null)},children:pe(Ba,{children:[pe(Fa,{children:[Z(Ma,{children:_?.variant?"Edit variant":"Add variant"}),Z($a,{children:"Price, markdown, and stock live on the variant."})]}),_&&pe("div",{className:"af-space-y-3",children:[_.variant?_.variant.option_values.length>0&&pe("div",{className:"af-text-sm",children:[Z("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),ri(_.variant)]}):M.map(E=>pe("div",{className:"af-space-y-1",children:[Z(ye,{className:"af-text-xs af-text-muted-foreground",children:E.title}),pe(ya,{value:_.optionValues[E.id]??"",onValueChange:B=>K(O=>O&&{...O,optionValues:{...O.optionValues,[E.id]:B}}),children:[Z(fa,{children:Z(ha,{placeholder:`Choose ${E.title}`})}),Z(ma,{children:E.values.map(B=>Z(Ye,{value:B.value,children:B.value},B.id))})]})]},E.id)),Fe?pe("div",{className:"af-space-y-1",children:[Z(ye,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),Z("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(ye,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),Z(ce,{id:"variant-price",type:"number",min:"0",step:a,value:_.unitAmount,onChange:E=>K(B=>B&&{...B,unitAmount:E.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),pe("div",{className:"af-space-y-1",children:[Z(ye,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),Z(ce,{id:"variant-compare",type:"number",min:"0",step:a,value:_.compareAt,onChange:E=>K(B=>B&&{...B,compareAt:E.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),pe("div",{className:"af-space-y-1",children:[Z(ye,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),Z(ce,{id:"variant-sku",value:_.sku,onChange:E=>K(B=>B&&{...B,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:[Z("input",{type:"checkbox",checked:_.tracked,onChange:E=>K(B=>B&&{...B,tracked:E.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),_.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:[Z(ye,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),Z(ce,{id:"variant-onhand",type:"number",min:"0",step:"1",value:_.onHand,onChange:E=>K(B=>B&&{...B,onHand:E.target.value}),placeholder:Te!=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:[Z("input",{type:"checkbox",checked:_.allowBackorder,onChange:E=>K(B=>B&&{...B,allowBackorder:E.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Te!=null&&pe("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Te," 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:[Z("input",{type:"checkbox",checked:_.active,onChange:E=>K(B=>B&&{...B,active:E.target.checked}),className:"af-h-4 af-w-4",disabled:Ze}),"Active (buyers can purchase this variant)"]}),Ze&&Z("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."})]}),F&&Z("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:F})]}),pe(Ua,{children:[Z(S,{variant:"outline",onClick:()=>K(null),disabled:Q,children:"Cancel"}),pe(S,{onClick:vt,disabled:Q,children:[Q?Z(xo,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,_?.variant?"Save":"Add variant"]})]})]})}),Z(Za,{open:te!==null,onOpenChange:E=>{!E&&!f&&$(null)},children:pe(Ba,{children:[pe(Fa,{children:[Z(Ma,{children:"Delete variant?"}),Z($a,{children:te&&`"${ri(te)}" will no longer be purchasable. Past orders are unaffected.`})]}),pe(Ua,{children:[Z(S,{variant:"outline",onClick:()=>$(null),disabled:f,children:"Cancel"}),Z(S,{variant:"destructive",onClick:Ee,disabled:f,children:"Delete"})]})]})})]})}import{Fragment as Gu,jsx as ge,jsxs as ke}from"react/jsx-runtime";function ju(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 rr({productsState:e,product:t,currency:n,onSaved:s,className:a}){let{createProduct:r,updateProduct:o,attachProductFile:d,attachProductFileFromUrl:c}=e,u=!!t,i=t?.currency??n,g=Na(i)?"1":"0.01",v=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[f,l]=Xe.useState(!1),[m,p]=Xe.useState(null),b=Xe.useRef(!0);Xe.useEffect(()=>(b.current=!0,()=>{b.current=!1}),[]);let[h,w]=Xe.useState(t?.name??""),[k,y]=Xe.useState(t?.description??""),[N,R]=Xe.useState(t?.allow_custom_amount?"custom":"fixed"),[A,x]=Xe.useState(t?.unit_amount!=null?String(it(t.unit_amount,i)):""),[P,T]=Xe.useState(t?.min_amount!=null?String(it(t.min_amount,i)):""),[_,K]=Xe.useState(t?.max_amount!=null?String(it(t.max_amount,i)):""),[F,X]=Xe.useState(String(t?.max_quantity??10)),Q=Xe.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(it(t.unit_amount,i)):"",minAmount:t?.min_amount!=null?String(it(t.min_amount,i)):"",maxAmount:t?.max_amount!=null?String(it(t.max_amount,i)):"",maxQuantity:String(t?.max_quantity??10)}).current,[ne,te]=Xe.useState(t?.collect_shipping_address??!1),[$,M]=Xe.useState(t?.active??!0),[V,fe]=Xe.useState(t?.images??[]),[Ke,vt]=Xe.useState(""),[Ee,Fe]=Xe.useState(t?.fulfillment??null),[Ze,Te]=Xe.useState(!1),[kt,E]=Xe.useState(""),[B,O]=Xe.useState(null),me=Xe.useRef(null),ve=f||Ze,_e=()=>{let oe=Ke.trim();if(oe){if(V.includes(oe)){p("This image URL is already added");return}fe(Re=>[...Re,oe]),vt(""),p(null)}},Le=oe=>{fe(Re=>Re.filter(st=>st!==oe))},nt=async()=>{if(p(null),!h.trim()){p("Product name is required");return}let oe=null,Re=null,st=null,da=!u||N!==Q.pricingMode||(N==="fixed"?A!==Q.unitAmount:P!==Q.minAmount||_!==Q.maxAmount),Lt=!u||F!==Q.maxQuantity,Yt=v||N==="fixed";if(!(v||!da))if(N==="fixed"){if(oe=Ot(A,i),oe===null||oe<=0){p("Enter a valid price");return}}else{if(Re=Ot(P,i),st=Ot(_,i),Re===null||st===null){p("Enter valid minimum and maximum amounts");return}if(st<Re){p("Maximum amount must be at least the minimum amount");return}}let Ut=parseInt(F,10);if(Yt&&Lt&&(!Number.isFinite(Ut)||Ut<1)){p("Max quantity must be at least 1");return}try{l(!0);let We;if(u&&t){let rt={name:h.trim(),description:k.trim()||null,images:V,collect_shipping_address:ne,active:$};!v&&da&&(rt.allow_custom_amount=N==="custom",N==="fixed"?rt.unit_amount=oe:(rt.min_amount=Re,rt.max_amount=st)),Yt&&Lt&&(rt.max_quantity=Ut),We=await o(t.id,rt),Q.pricingMode=We.allow_custom_amount?"custom":"fixed",Q.unitAmount=We.unit_amount!=null?String(it(We.unit_amount,i)):"",Q.minAmount=We.min_amount!=null?String(it(We.min_amount,i)):"",Q.maxAmount=We.max_amount!=null?String(it(We.max_amount,i)):"",Q.maxQuantity=String(We.max_quantity)}else{let rt={name:h.trim(),allow_custom_amount:N==="custom",collect_shipping_address:ne,active:$};k.trim()&&(rt.description=k.trim()),V.length>0&&(rt.images=V),N==="fixed"?(rt.unit_amount=oe,rt.max_quantity=Ut):(rt.min_amount=Re,rt.max_amount=st),We=await r(rt)}if(!b.current)return;Fe(We.fulfillment),s?.(We)}catch(We){if(!b.current)return;p(We instanceof Error?We.message:"Failed to save product")}finally{b.current&&l(!1)}},Oe=async oe=>{let Re=oe.target.files?.[0];if(!(!Re||!t))try{Te(!0),O(null);let st=await d(t.id,Re);if(!b.current)return;Fe(st.fulfillment),s?.(st)}catch(st){if(!b.current)return;O(st instanceof Error?st.message:"Failed to upload file")}finally{b.current&&(Te(!1),me.current&&(me.current.value=""))}},ut=async()=>{let oe=kt.trim();if(!(!oe||!t))try{Te(!0),O(null);let Re=await c(t.id,oe);if(!b.current)return;Fe(Re.fulfillment),E(""),s?.(Re)}catch(Re){if(!b.current)return;O(Re instanceof Error?Re.message:"Failed to fetch file")}finally{b.current&&Te(!1)}};return ke("div",{className:`af-space-y-6 ${a||""}`,children:[ke("div",{className:"af-space-y-2",children:[ge(ye,{htmlFor:"product-name",children:"Name"}),ge(ce,{id:"product-name",value:h,onChange:oe=>w(oe.target.value),placeholder:"My product"})]}),ke("div",{className:"af-space-y-2",children:[ge(ye,{htmlFor:"product-description",children:"Description"}),ge("textarea",{id:"product-description",value:k,onChange:oe=>y(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"})]}),ke("div",{className:"af-space-y-2",children:[ge(ye,{children:"Pricing"}),v?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."}):ke(Gu,{children:[ke(ya,{value:N,onValueChange:oe=>R(oe),children:[ge(fa,{className:"af-w-[260px]",children:ge(ha,{})}),ke(ma,{children:[ge(Ye,{value:"fixed",children:"Fixed price"}),ge(Ye,{value:"custom",children:"Buyer chooses the amount"})]})]}),N==="fixed"?ge("div",{className:"af-flex af-items-end af-gap-3",children:ke("div",{className:"af-space-y-1",children:[ke(ye,{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:g,value:A,onChange:oe=>x(oe.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):ke("div",{className:"af-space-y-1",children:[ke("div",{className:"af-flex af-items-end af-gap-3",children:[ke("div",{className:"af-space-y-1",children:[ke(ye,{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:g,value:P,onChange:oe=>T(oe.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),ke("div",{className:"af-space-y-1",children:[ke(ye,{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:g,value:_,onChange:oe=>K(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."})]}),ke("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||N==="fixed")&&ke("div",{className:"af-space-y-1",children:[ge(ye,{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:F,onChange:oe=>X(oe.target.value),className:"af-w-[140px]"})]})]}),ke("div",{className:"af-space-y-2",children:[ge(ye,{children:"Images"}),ge("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),ke("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[V.map(oe=>ke(se,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[ge("span",{className:"af-truncate",children:oe}),ge("button",{type:"button",onClick:()=>Le(oe),className:"af-ml-1 hover:af-text-destructive",disabled:f,children:ge(qu,{className:"af-h-3 af-w-3"})})]},oe)),V.length===0&&ge("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),ke("div",{className:"af-flex af-gap-2",children:[ge(ce,{type:"url",value:Ke,onChange:oe=>vt(oe.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:oe=>{oe.key==="Enter"&&(oe.preventDefault(),_e())},disabled:f}),ge(S,{type:"button",variant:"outline",onClick:_e,disabled:!Ke.trim()||f,children:ge(Hu,{className:"af-h-4 af-w-4"})})]})]}),ke("div",{className:"af-space-y-2",children:[ge(ye,{children:"Digital File"}),ge("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),u?ke("div",{className:"af-space-y-3",children:[Ee?.type==="download"&&ke("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[ge($u,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),ge("span",{className:"af-text-sm",children:Ee.filename}),Ee.size!=null&&ke("span",{className:"af-text-xs af-text-muted-foreground",children:["(",ju(Ee.size),")"]})]}),Ee?.type==="redirect"&&Ee.url&&ke("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[ge(Vu,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),ke("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Ee.url]})]}),ke("div",{className:"af-flex af-items-center af-gap-2",children:[ge("input",{ref:me,type:"file",onChange:Oe,className:"af-hidden",disabled:ve}),ke(S,{type:"button",variant:"outline",size:"sm",onClick:()=>me.current?.click(),disabled:ve,children:[Ze?ge(So,{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"}),Ee?.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(S,{type:"button",variant:"outline",size:"sm",onClick:ut,disabled:!kt.trim()||ve,children:"Fetch from URL"})]}),B&&ge("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:B})]}):ge("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),ke("div",{className:"af-space-y-2",children:[ge(ye,{children:"Settings"}),ke("div",{className:"af-space-y-2",children:[ke("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ge("input",{type:"checkbox",checked:ne,onChange:oe=>te(oe.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),ke("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ge("input",{type:"checkbox",checked:$,onChange:oe=>M(oe.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),u&&t&&ke("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[ge(ye,{children:"Options & Variants"}),ge(sr,{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:ke(S,{type:"button",onClick:nt,disabled:ve,children:[f?ge(So,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,u?"Save changes":"Create product"]})})]})}import*as Rt from"react";import{ChevronLeft as vd,ChevronRight as Do,Loader2 as bd,Receipt as yd,Search as hd,SlidersHorizontal as xd}from"lucide-react";import*as ot from"react";var Wu=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function ir({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ee(),[s,a]=ot.useState([]),[r,o]=ot.useState(0),[d,c]=ot.useState(!0),[u,i]=ot.useState(null),[g,v]=ot.useState(0),[f,l]=ot.useState(e),[m,p]=ot.useState(void 0),[b,h]=ot.useState(""),[w,k]=ot.useState(""),[y,N]=ot.useState(""),[R,A]=ot.useState(!1),[x,P]=ot.useState(!1),[T,_]=ot.useState(void 0),K=T?T.join(","):"",F=ot.useMemo(()=>{if(!K)return;let $=new Set(K.split(","));return Wu.filter(M=>!$.has(M))},[K]),X=ot.useMemo(()=>{let $={};return m?$.status=m:F?$.excludeStatus=F:R||($.excludeStatus=["pending","expired"]),b.trim()&&($.customerEmail=b.trim()),w.trim()&&($.from=w.trim()),y.trim()&&($.to=y.trim()),x&&($.unfulfilledOnly=!0),$},[m,F,R,b,w,y,x]),Q=ot.useRef(0),ne=ot.useCallback(async()=>{let $=++Q.current;try{c(!0),i(null);let M={...X,limit:f,offset:g*f},V=await n.getOrders(M);if($!==Q.current)return;a(V.orders),o(V.total)}catch(M){if($!==Q.current)return;i(M instanceof Error?M:new Error("Failed to fetch orders"))}finally{$===Q.current&&c(!1)}},[n,g,f,X,t]);ot.useEffect(()=>{ne()},[ne]);let te=Math.ceil(r/f);return{orders:s,total:r,isLoading:d,error:u,page:g,pageSize:f,hasNextPage:g<te-1,hasPreviousPage:g>0,setPage:v,setPageSize:$=>{l($),v(0)},status:m,setStatus:$=>{p($),v(0)},statusIn:T,setStatusIn:$=>{_($&&$.length>0?$:void 0),v(0)},customerEmail:b,setCustomerEmail:$=>{h($),v(0)},from:w,setFrom:$=>{k($),v(0)},to:y,setTo:$=>{N($),v(0)},showAbandoned:R,setShowAbandoned:$=>{A($),v(0)},unfulfilledOnly:x,setUnfulfilledOnly:$=>{P($),v(0)},clearFilters:()=>{p(void 0),_(void 0),A(!1),P(!1),h(""),k(""),N(""),v(0)},filters:X,refetch:ne}}import*as mt from"react";import{ArrowLeft as Ju,Check as Ro,ChevronLeft as Yu,ChevronRight as Xu,ClipboardCopy as Qu,Copy as ed,Download as td,Loader2 as ur,Mail as Po,MoreHorizontal as ad,Package as nd,RotateCcw as sd,Truck as rd,Undo2 as Co}from"lucide-react";import*as No from"react";import*as Xa from"@radix-ui/react-popover";import{jsx as ii}from"react/jsx-runtime";var or=Xa.Root,lr=Xa.Trigger;var Ns=No.forwardRef(({className:e,align:t="end",sideOffset:n=4,...s},a)=>ii(Xa.Portal,{children:ii("div",{className:"aifeatures-admin",children:ii(Xa.Content,{ref:a,align:t,sideOffset:n,className:W("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...s})})}));Ns.displayName=Xa.Content.displayName;import{jsx as cr}from"react/jsx-runtime";var Ku={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Zu(e){return Ku[e]??e}function _o(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 Bn({status:e,className:t}){return cr(se,{variant:_o(e),className:t,children:Zu(e)})}function Fn({status:e}){return cr(Bn,{status:e})}function Kn({order:e,className:t}){return e.line_items.some(n=>n.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?cr(se,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?cr(se,{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 md,jsx as I,jsxs as Y}from"react/jsx-runtime";var Io="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Un="af-text-xs af-text-muted-foreground";function oi(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 id(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ao(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 dr=24,od=["paid","partially_refunded"],ld=["paid","partially_refunded","disputed"],cd=/^[A-Za-z0-9 _-]*$/,To=100;function ui(e,t,n,s,a){let r=od.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 ${dr} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${n} of ${dr} 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<dr&&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<dr&&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 ko({title:e,recipient:t,status:n,attempts:s,side:a,orderStatus:r,action:o,delivery:d}){if(d)return Y("div",{children:[I(Ka,{deliveries:[d]}),o&&I("div",{className:"af-mt-2",children:o})]});let c=ui(a,n,s,r,t);return Y("div",{children:[Y("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Y("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(se,{variant:c.variant,className:"af-shrink-0",children:c.label})]}),c.detail&&I("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:c.detail}),o&&I("div",{className:"af-mt-2",children:o})]})}function Eo(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let n=id(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}: ${Ao(a)}`)}function ud(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function di({value:e,label:t,children:n,className:s,size:a="icon"}){let[r,o]=mt.useState(!1);if(!ud())return null;let d=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},c=r?I(Ro,{className:"af-h-3 af-w-3"}):I(ed,{className:"af-h-3 af-w-3"});return a==="icon"?I(S,{variant:"ghost",size:"icon",className:W("af-h-6 af-w-6 af-shrink-0",s),onClick:d,title:t,"aria-label":t,children:c}):Y(S,{variant:"outline",size:"sm",className:s,onClick:d,"aria-label":t,children:[r?I(Ro,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):I(Qu,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":n]})}function li({label:e,value:t}){return Y("div",{children:[I("div",{className:Un,children:e}),Y("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(di,{value:t,label:`Copy ${e}`})]})]})}function dd({src:e}){let[t,n]=mt.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(nd,{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 Y("section",{className:W("af-rounded-lg af-border af-p-4",s),children:[Y("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[I("h4",{className:Io,children:e}),t]}),I("div",{className:"af-mt-3",children:n})]})}function aa({label:e,emphasis:t,divider:n,children:s}){return Y("div",{className:W("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":Un,children:e}),I("span",{className:W("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function ci({onSelect:e,disabled:t,icon:n,children:s}){return Y(S,{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 fd(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(tr(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?qs(n):ui("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?qs(n):ui("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 ${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 fr({order:e,onBack:t,onRefund:n,onOrderUpdated:s,allowFulfillment:a=!1,onPrevOrder:r,onNextOrder:o,hasPrevOrder:d=!1,hasNextOrder:c=!1}){let{api:u}=ee(),[i,g]=mt.useState(e),[v,f]=mt.useState(null),[l,m]=mt.useState(null),[p,b]=mt.useState(!1),[h,w]=mt.useState(!1),[k,y]=mt.useState(!1),[N,R]=mt.useState(!1),[A,x]=mt.useState(""),[P,T]=mt.useState(!1),[_,K]=mt.useState(null),[F,X]=mt.useState(!1),[Q,ne]=mt.useState(""),[te,$]=mt.useState([]),[M,V]=mt.useState(!1),[fe,Ke]=mt.useState(!1),[vt,Ee]=mt.useState(null);mt.useEffect(()=>{g(e)},[e]);let Fe=L=>{let Ae=L.id===i.id&&L.email_deliveries===void 0?{...L,email_deliveries:i.email_deliveries}:L;g(Ae),s?.(Ae)},Ze=Object.entries(i.metadata??{}),Te=Math.max(0,tr(i)-i.amount_refunded),kt=(i.status==="paid"||i.status==="partially_refunded")&&Te>0,E=i.exclusive_tax_total!=null,B=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=te.reduce((L,Ae)=>L+B(i.line_items[Ae]??{}),0)+(M?O:0),ve=i.tax_total??0,_e=Math.max(0,(i.exclusive_tax_total??0)-i.line_items.reduce((L,Ae)=>L+(Ae.exclusiveTax??0),0)),Le=E?M&&O>0?_e: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,nt=i.source==="subscription"&&(i.credit_applied??0)>0&&i.line_items.length===1?Math.min(me+Le,Te):me+Le,Oe=te.length>0||M,ut=Oe?nt:Ot(Q,i.currency),oe=Na(i.currency)?"1":"0.01",Re=async()=>{try{b(!0),f(null),m(null),await u.resendOrderReceipt(i.id);let L=await u.getOrder(i.id);Fe(L),m("Receipt email queued.")}catch(L){f(L instanceof Error?L.message:"Failed to resend receipt")}finally{b(!1)}},st=async()=>{try{w(!0),f(null),m(null);let L=await u.resetOrderDownloads(i.id);Fe(L),y(!1),m("Download count reset.")}catch(L){f(L instanceof Error?L.message:"Failed to reset downloads")}finally{w(!1)}},da=i.line_items.some(L=>L.collectShippingAddress===!0&&!L.refunded&&!L.unavailableReason),Lt=typeof i.merchant_fulfilled_at=="string",Yt=ld.includes(i.status)||i.status==="refunded"&&i.line_items.some(L=>L.collectShippingAddress===!0&&L.amountNet===0&&!L.refunded&&!L.unavailableReason),Ut=A.trim(),We=cd.test(Ut)&&Ut.length<=To,rt=async L=>{try{T(!0),K(null),m(null);let Ae=await u.setOrderFulfillment(i.id,{fulfilled:L,...L&&Ut?{trackingNumber:Ut}:{}});Fe(Ae),x(""),m(L?"Marked as shipped.":"Marked as not shipped.")}catch(Ae){Ae instanceof St&&Ae.status===409?K(`This order is ${i.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):K(Ae instanceof Error?Ae.message:"Failed to update the order")}finally{T(!1)}},Ia=()=>{Ee(null),ne(String(it(Te,i.currency))),$([]),V(!1),X(!0)},Dn=L=>$(Ae=>Ae.includes(L)?Ae.filter(Qt=>Qt!==L):[...Ae,L]),Xt=async(L,Ae)=>{if(n)try{Ke(!0),Ee(null),await n(i,L,Ae);let Qt=await u.getOrder(i.id);Fe(Qt),X(!1),m("Refund issued.")}catch(Qt){Ee(Qt instanceof Error?Qt.message:"Refund failed")}finally{Ke(!1)}},jr=async()=>{if(Oe){if(nt<=0){Ee("The lines you picked were charged nothing");return}if(nt>Te){Ee(`That selection exceeds the refundable remainder (${j(Te,i.currency)})`);return}await Xt(nt,{...te.length>0?{line_items:[...te].sort((Ae,Qt)=>Ae-Qt)}:{},...M?{shipping:!0}:{}});return}let L=Ot(Q,i.currency);if(L===null||L<=0){Ee("Enter a valid refund amount");return}if(L>Te){Ee(`Amount exceeds the refundable remainder (${j(Te,i.currency)})`);return}await Xt(L,{amount:L})},q=()=>Xt(Te,{full:!0}),Je=!i.subscription_history_only&&i.fulfillment_type==="download",Wa=!i.subscription_history_only&&a&&da,Gr=fd(i),G=i.shipping_address?Eo(i.shipping_address).join(`
|
|
4
|
-
`):"",jt=i.shipping_total!=null,Wr=i.exclusive_tax_total??(i.automatic_tax&&i.tax_behavior==="exclusive"?i.tax_total??0:0),Wi=i.exclusive_tax_total!=null?Math.max(0,(i.tax_total??0)-Wr):i.automatic_tax&&i.tax_behavior==="exclusive"?0:i.tax_total??0,Ki=Wr>0,hc=Wi>0,Zi=i.amount_subtotal!=null||jt||Ki||(i.discount_total??0)>0,ps=[];return i.subscription_history_only||ps.push(I(ci,{icon:p?I(ur,{className:"af-h-4 af-w-4 af-animate-spin"}):I(Po,{className:"af-h-4 af-w-4"}),disabled:p||i.fulfillment_status!=="fulfilled",onSelect:()=>{R(!1),Re()},children:"Resend receipt"},"resend")),Je&&ps.push(I(ci,{icon:I(sd,{className:"af-h-4 af-w-4"}),disabled:h,onSelect:()=>{R(!1),y(!0)},children:"Reset download count"},"reset")),kt&&ps.push(Y("div",{children:[I(ci,{icon:I(Co,{className:"af-h-4 af-w-4"}),disabled:!n,onSelect:()=>{R(!1),Ia()},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")),Y("div",{children:[Y("div",{className:"af-mb-6",children:[Y(S,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[I(Ju,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),Y("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[Y("div",{className:"af-min-w-0",children:[Y("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(Bn,{status:i.status}),a&&!i.subscription_history_only&&I(Kn,{order:i}),i.is_test&&I(se,{variant:"outline",children:"Test"})]}),Y("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",oi(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."})]}),Y("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||o)&&Y("div",{className:"af-flex af-items-center",children:[I(S,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!d,"aria-label":"Previous order",children:I(Yu,{className:"af-h-4 af-w-4"})}),I(S,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!c,"aria-label":"Next order",children:I(Xu,{className:"af-h-4 af-w-4"})})]}),Wa&&(Lt?Y("div",{className:"af-flex af-items-center af-gap-1",children:[Y("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",i.merchant_fulfilled_at?` \xB7 ${oi(i.merchant_fulfilled_at)}`:""]}),Yt&&Y(S,{variant:"ghost",size:"sm",onClick:()=>rt(!1),disabled:P,children:[P?I(ur,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):I(Co,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Yt?Y("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[I(ce,{value:A,onChange:L=>x(L.target.value),placeholder:"Tracking number (optional)",maxLength:To,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:P}),Y(S,{variant:"default",className:"af-shrink-0",onClick:()=>rt(!0),disabled:P||!We,children:[P?I(ur,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):I(rd,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),ps.length>0&&Y(or,{open:N,onOpenChange:R,children:[I(lr,{asChild:!0,children:I(S,{variant:"outline",size:"icon","aria-label":"More actions",children:I(ad,{className:"af-h-4 af-w-4"})})}),I(Ns,{children:I("div",{className:"af-space-y-0.5",children:ps})})]})]})]}),Wa&&!Lt&&!We&&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."}),_&&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:_}),l&&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:l}),v&&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:v})]}),Y("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[Y("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,Ae)=>{let Qt=typeof L.name=="string"&&L.name?L.name:"Item",Ji=typeof L.quantity=="number"&&L.quantity>0?L.quantity:1,Yi=typeof L.unitAmount=="number";return Y("li",{className:"af-flex af-items-start af-gap-3",children:[I(dd,{src:typeof L.imageUrl=="string"&&L.imageUrl?L.imageUrl:void 0}),Y("div",{className:"af-min-w-0 af-flex-1",children:[Y("div",{className:"af-text-sm af-font-medium",children:[Qt,typeof L.variantTitle=="string"&&L.variantTitle&&Y("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",L.variantTitle]})]}),Y("div",{className:Un,children:[Ji," \xD7"," ",Yi?j(L.unitAmount,i.currency):"\u2014"]}),L.unavailableReason==="oversold"&&!L.refunded&&I(se,{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(se,{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"||Yi?j(L.amountNet??L.unitAmount*Ji,i.currency):"\u2014"})]},Ae)})})}),Ze.length>0&&I(Qa,{title:"Order details",children:I("dl",{className:"af-space-y-2",children:Ze.map(([L,Ae])=>Y("div",{children:[I("dt",{className:W(Un,"af-capitalize"),children:L.replace(/_/g," ")}),I("dd",{className:"af-text-sm af-break-words",children:Ao(Ae)})]},L))})}),I(Qa,{title:"Totals",children:Y("div",{className:"af-w-full",children:[Zi&&I(aa,{label:"Subtotal",children:j(i.amount_subtotal??i.amount_total+(i.discount_total??0),i.currency)}),(i.discount_total??0)>0&&Y(aa,{label:"Discount",children:["\u2212",j(i.discount_total,i.currency)]}),jt&&I(aa,{label:"Shipping",children:i.shipping_total===0?"Free":j(i.shipping_total??0,i.currency)}),Ki&&I(aa,{label:"Tax",children:j(Wr,i.currency)}),I(aa,{label:"Total",emphasis:!0,divider:Zi,children:j(pn(i),i.currency)}),(i.credit_applied??0)>0&&Y(aa,{label:"Credit applied",children:["\u2212",j(i.credit_applied,i.currency)]}),i.amount_paid!=null&&I(aa,{label:"Amount paid",children:j(i.amount_paid,i.currency)}),hc&&I(aa,{label:"incl. tax",children:j(Wi,i.currency)}),i.base_currency!=null&&i.base_amount_total!=null&&Y(aa,{label:"Your price",children:[j(i.base_amount_total,i.base_currency),Y("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",i.currency.toUpperCase()]})]}),i.amount_refunded>0&&Y(md,{children:[Y(aa,{label:"Refunded",children:["\u2212",j(i.amount_refunded,i.currency),(i.shipping_refunded??0)>0&&Y("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",j(i.shipping_refunded??0,i.currency)," ","shipping"]})]}),I(aa,{label:"Net",children:I("span",{className:"af-font-medium",children:j(Math.max(0,tr(i)-i.amount_refunded),i.currency)})})]})]})}),i.application_fee_state&&Y(Qa,{title:"Platform fee",children:[i.application_fee_original!=null&&I(aa,{label:"Collected",children:j(i.application_fee_original,i.application_fee_currency??i.currency)}),i.application_fee_returned!=null&&I(aa,{label:"Returned",children:j(i.application_fee_returned,i.application_fee_currency??i.currency)}),i.application_fee_retained!=null&&I(aa,{label:"Retained",children:j(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:Gr.map(L=>Y("li",{className:"af-flex af-gap-3",children:[I("span",{"aria-hidden":"true",className:W("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")}),Y("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:oi(L.at)})]})]},L.key))})})]}),Y("div",{className:"af-space-y-6",children:[I(Qa,{title:"Customer",children:Y("div",{className:"af-space-y-2",children:[Y("div",{children:[I("div",{className:Un,children:"Email"}),Y("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(di,{value:i.customer_email,label:"Copy email"})]})]}),i.customer_name&&Y("div",{children:[I("div",{className:Un,children:"Name"}),I("div",{className:"af-text-sm",children:i.customer_name})]}),i.customer&&Y("div",{children:[I("div",{className:Un,children:"Customer record"}),Y("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(se,{variant:"secondary",children:"Linked"})]})]})]})}),i.shipping_address&&I(Qa,{title:"Ship to",action:I(di,{value:G,label:"Copy address",size:"sm",children:"Copy address"}),children:I("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Eo(i.shipping_address).map((L,Ae)=>I("div",{children:L},Ae))})}),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."})}):Y(Qa,{title:"Emails",children:[I(Ka,{deliveries:i.email_deliveries?.filter(L=>!["purchase_receipt","merchant_sale"].includes(L.kind)),problemsOnly:!0,className:"af-mb-4"}),Y("div",{className:"af-space-y-4",children:[I(ko,{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:Y(S,{variant:"outline",size:"sm",onClick:Re,disabled:p||i.fulfillment_status!=="fulfilled",children:[p?I(ur,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):I(Po,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),I(ko,{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:Y("div",{className:"af-space-y-2",children:[Y("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[I(td,{className:"af-h-4 af-w-4"}),Y("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"})]})}),Y("details",{className:"af-rounded-lg af-border af-p-4",children:[I("summary",{className:W(Io,"af-cursor-pointer af-select-none"),children:"Technical details"}),Y("div",{className:"af-mt-3 af-space-y-2",children:[I(li,{label:"Order ID",value:i.id}),i.stripe_checkout_session_id&&I(li,{label:"Checkout session",value:i.stripe_checkout_session_id}),i.stripe_payment_intent_id&&I(li,{label:"Payment",value:i.stripe_payment_intent_id})]})]})]})]}),I(Za,{open:k,onOpenChange:L=>{!L&&!h&&y(!1)},children:Y(Ba,{children:[Y(Fa,{children:[I(Ma,{children:"Reset download count?"}),I($a,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),Y(Ua,{children:[I(S,{variant:"outline",onClick:()=>y(!1),disabled:h,children:"Cancel"}),I(S,{onClick:st,disabled:h,children:h?"Resetting...":"Reset"})]})]})}),I(Za,{open:F,onOpenChange:L=>{!L&&!fe&&X(!1)},children:Y(Ba,{children:[Y(Fa,{children:[I(Ma,{children:"Refund order"}),Y($a,{children:["Refund up to ",j(Te,i.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),Y("div",{className:"af-space-y-4",children:[(i.line_items.length>0||O>0)&&Y("div",{className:"af-space-y-2",children:[I(ye,{children:"Items"}),Y("div",{className:"af-space-y-2",children:[i.line_items.map((L,Ae)=>{let Qt=L.refunded===!0;return Y("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[I("input",{type:"checkbox",checked:te.includes(Ae),onChange:()=>Dn(Ae),disabled:fe||Qt||!!L.unavailableReason||B(L)<=0,className:"af-h-4 af-w-4"}),Y("span",{className:Qt?"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:Qt?"Refunded":j(B(L),i.currency)})]},Ae)}),O>0&&Y("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[I("input",{type:"checkbox",checked:M,onChange:L=>V(L.target.checked),disabled:fe,className:"af-h-4 af-w-4"}),I("span",{children:"Shipping"}),I("span",{className:"af-ml-auto af-text-muted-foreground",children:j(O,i.currency)})]})]})]}),Y("div",{className:"af-space-y-2",children:[Y(ye,{htmlFor:"refund-amount",children:["Amount (",i.currency.toUpperCase(),")"]}),I(ce,{id:"refund-amount",type:"number",min:"0",step:oe,value:Oe?String(it(nt,i.currency)):Q,onChange:L=>ne(L.target.value),disabled:fe||Oe}),Oe&&I("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),vt&&I("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:vt}),Y(Ua,{children:[I(S,{variant:"outline",onClick:()=>X(!1),disabled:fe,children:"Cancel"}),I(S,{variant:"outline",onClick:q,disabled:fe,children:"Refund everything"}),I(S,{variant:"destructive",onClick:jr,disabled:fe,children:fe?"Refunding...":ut!==null&&ut>0?`Refund ${j(ut,i.currency)}`:"Refund"})]})]})})]})}import*as mr from"react";import{ArrowLeft as pd,RefreshCw as gd}from"lucide-react";import{jsx as na,jsxs as Nn}from"react/jsx-runtime";function _t({title:e,onBackToWebsite:t,hideBackButton:n=!1,children:s,className:a}){let r=mr.useRef(null);return mr.useEffect(()=>{r.current?.focus()},[]),Nn("div",{className:W("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:[na("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(S,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[na(pd,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),na("div",{className:"af-p-4",children:s})]})}function re({className:e}){return na("div",{"aria-hidden":"true",className:W("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function lt({label:e,children:t,detail:n,valueClassName:s}){return Nn("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[na("div",{className:"af-text-xs af-text-muted-foreground",children:e}),na("div",{className:W("af-mt-1 af-text-lg af-font-semibold",s),children:t}),n&&na("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:n})]})}function va({message:e,onRetry:t}){return Nn("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[na("span",{children:e}),Nn(S,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[na(gd,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Ha({icon:e,children:t}){return Nn("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,na("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function Zn({icon:e,heading:t,body:n,action:s,className:a,children:r}){return Nn("div",{className:W("af-px-6 af-py-10 af-text-center",a),children:[na(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),na("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),na("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:n}),s&&na(S,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}import{jsx as U,jsxs as Se}from"react/jsx-runtime";var wd={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Lo={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Oo(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 Bo(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 pr(e){return e.customer?.name||e.customer_name||null}function Sd({onRefund:e,className:t,refreshKey:n,initialOrderId:s,showFulfillment:a=!1,emptyMessage:r,onDetailOpenChange:o,maxRows:d,onViewAll:c}){let u=typeof d=="number",{api:i}=ee(),g=ir({refreshKey:n}),{orders:v,total:f,isLoading:l,error:m,page:p,pageSize:b,hasNextPage:h,hasPreviousPage:w,setPage:k,setPageSize:y,customerEmail:N,setCustomerEmail:R,setStatusIn:A,from:x,setFrom:P,to:T,setTo:_,showAbandoned:K,setShowAbandoned:F,setUnfulfilledOnly:X,filters:Q,refetch:ne}=g,te=Rt.useCallback(()=>i.exportOrdersCsv(Q),[i,Q]),[$,M]=Rt.useState("list"),[V,fe]=Rt.useState(null),[Ke,vt]=Rt.useState(""),[Ee,Fe]=Rt.useState(""),[Ze,Te]=Rt.useState(!u&&a?"needs_shipping":"all"),[kt,E]=Rt.useState(!1),[B,O]=Rt.useState(!!s&&!u),[me,ve]=Rt.useState(null);Rt.useEffect(()=>{if(!s||u)return;let G=!1;return O(!0),ve(null),i.getOrder(s).then(jt=>{G||(fe(jt),M("detail"))}).catch(()=>{G||ve("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{G||O(!1)}),()=>{G=!0}},[i,s,u]);let _e=Rt.useCallback(G=>{Te(G);let jt=Lo[G];A(jt.statusIn),X(jt.unfulfilledOnly)},[A,X]);Rt.useEffect(()=>{a&&!u&&X(!0)},[]);let Le=Rt.useRef(!a);Rt.useEffect(()=>{Le.current||l||(Le.current=!0,v.length===0&&_e("all"))},[l,v.length,_e]);let nt=$==="detail"&&!!V;Rt.useEffect(()=>{o?.(nt)},[nt,o]);let Oe=(x?1:0)+(T?1:0)+(K?1:0),ut=Oe>0||!!N||!!Ee,oe=!!x&&!!T&&x>T,Re=!u||!!c,st=G=>{if(u){c?.();return}fe(G),M("detail")},da=()=>{M("list"),fe(null),ne()},Lt=G=>{let jt=G.trim();if(!jt){Fe(""),N&&R("");return}if(jt.startsWith("#")||/^\d+$/.test(jt)){Fe(jt),N&&R("");return}Fe(""),R(jt)},Yt=()=>{vt(""),Fe(""),R(""),P(""),_(""),F(!1),E(!1)},Ut=Ee.replace(/^#/,"").toLowerCase(),We=Ut?v.filter(G=>String(G.order_number??"")===Ut||G.id.toLowerCase().startsWith(Ut)):v,rt=u?We.slice(0,d):We,Ia=V?v.findIndex(G=>G.id===V.id):-1,Dn=Ia>0,Xt=Ia>=0&&Ia<v.length-1;if(B)return U("div",{className:t,children:U("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:U(bd,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if($==="detail"&&V)return U("div",{className:t,children:U(fr,{order:V,onBack:da,onRefund:e,onOrderUpdated:G=>fe(G),allowFulfillment:a,onPrevOrder:Dn?()=>fe(v[Ia-1]):void 0,onNextOrder:Xt?()=>fe(v[Ia+1]):void 0,hasPrevOrder:Dn,hasNextOrder:Xt},V.id)});let q=Se("div",{className:"af-mb-4 af-space-y-3",children:[me&&U("p",{className:"af-text-xs af-text-muted-foreground",children:me}),Se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[U("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(G=>U("button",{type:"button","aria-pressed":Ze===G,onClick:()=>_e(G),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Ze===G?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:wd[G]},G))}),Se("div",{className:"af-relative af-w-full af-max-w-xs",children:[U(hd,{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"}),U(ce,{type:"text",value:Ke,onChange:G=>vt(G.target.value),onBlur:()=>Lt(Ke),onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),Lt(Ke))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),Se(S,{type:"button",variant:Oe>0?"secondary":"ghost",size:"sm",onClick:()=>E(G=>!G),"aria-expanded":kt,children:[U(xd,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Oe>0&&U(se,{variant:"secondary",className:"af-ml-2",children:Oe})]}),ut&&U(S,{type:"button",variant:"ghost",size:"sm",onClick:Yt,children:"Clear filters"}),U($t,{fetchCsv:te,filename:"orders",disabled:!!Ee,className:"af-ml-auto"})]}),(kt||!!x||!!T)&&Se("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:[U(ye,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),U(ce,{id:"orders-from",type:"date",value:x,max:T||void 0,onChange:G=>P(G.target.value),className:"af-w-[170px]"}),U(ye,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),U(ce,{id:"orders-to",type:"date",value:T,min:x||void 0,onChange:G=>_(G.target.value),className:"af-w-[170px]"}),!Lo[Ze].statusIn&&U(S,{type:"button",variant:K?"secondary":"ghost",size:"sm",onClick:()=>F(!K),"aria-pressed":K,children:K?"Hide abandoned":"Show abandoned"})]}),oe&&U("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(l)return Se("div",{className:t,children:[u?null:q,U("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(G=>Se("div",{className:"af-rounded-md af-border af-p-3",children:[Se("div",{className:"af-flex af-items-center af-justify-between",children:[U(re,{className:"af-h-4 af-w-16"}),U(re,{className:"af-h-4 af-w-14"})]}),U(re,{className:"af-mt-2 af-h-3 af-w-40"}),U(re,{className:"af-mt-2 af-h-3 af-w-24"})]},G))}),U("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Se($e,{children:[U(Ve,{children:Se(be,{children:[U(H,{children:"Order"}),U(H,{children:"Date"}),U(H,{children:"Customer"}),U(H,{children:"Items"}),U(H,{className:"af-text-right",children:"Total"}),U(H,{children:"Status"}),U(H,{className:"af-w-8"})]})}),U(He,{"aria-hidden":"true",children:[0,1,2,3,4].map(G=>Se(be,{children:[U(z,{children:U(re,{className:"af-h-4 af-w-14"})}),U(z,{children:U(re,{className:"af-h-4 af-w-24"})}),U(z,{children:U(re,{className:"af-h-4 af-w-40"})}),U(z,{children:U(re,{className:"af-h-4 af-w-32"})}),U(z,{children:U(re,{className:"af-ml-auto af-h-4 af-w-16"})}),U(z,{children:U(re,{className:"af-h-5 af-w-16"})}),U(z,{})]},G))})]})}),U("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(m)return Se("div",{className:t,children:[u?null:q,Se("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[U("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),U(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>ne(),children:"Try again"})]})]});let Je=Ze!=="all";if(We.length===0&&p===0)return ut||Je?Se("div",{className:t,children:[!u&&q,U(Ha,{children:"No orders match these filters."})]}):U("div",{className:t,children:U(Zn,{icon:yd,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!u&&U(S,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>F(!0),children:"Show abandoned checkouts"})})});let Wa=p*b+1,Gr=Math.min((p+1)*b,f);return Se("div",{className:t,children:[u?null:q,U("div",{className:"af-space-y-3 lg:af-hidden",children:rt.map(G=>Se("button",{type:"button",onClick:()=>st(G),disabled:!Re,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Re?" hover:af-bg-muted/50":""}`,children:[Se("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[U("span",{className:"af-font-medium",children:gn(G)}),U("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:j(pn(G),G.currency)})]}),Se("div",{className:"af-mt-1 af-min-w-0",children:[Se("div",{className:"af-truncate af-text-sm",children:[G.customer_email||U("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),pr(G)&&Se("span",{className:"af-text-muted-foreground",children:[" \xB7 ",pr(G)]})]}),U("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Bo(G)}),G.amount_refunded>0&&Se("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(G.amount_refunded,G.currency)," refunded"]})]}),Se("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[U(Bn,{status:G.status}),U(hs,{deliveries:G.email_deliveries}),G.is_test&&U(se,{variant:"outline",children:"Test"}),a&&U(Kn,{order:G}),U("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Oo(G.created_at)})]})]},G.id))}),U("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Se($e,{children:[U(Ve,{children:Se(be,{children:[U(H,{children:"Order"}),U(H,{children:"Date"}),U(H,{children:"Customer"}),U(H,{children:"Items"}),U(H,{className:"af-text-right",children:"Total"}),U(H,{children:"Status"}),U(H,{className:"af-w-8"})]})}),U(He,{children:rt.map(G=>Se(be,{onClick:Re?()=>st(G):void 0,className:Re?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[Se(z,{className:"af-whitespace-nowrap af-font-medium",children:[U("button",{type:"button",onClick:jt=>{jt.stopPropagation(),st(G)},disabled:!Re,"aria-label":`Open order ${gn(G)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Re?" hover:af-underline":""}`,children:gn(G)}),G.is_test&&U(se,{variant:"outline",className:"af-ml-2",children:"Test"})]}),U(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Oo(G.created_at)}),Se(z,{className:"af-max-w-[220px]",children:[U("div",{className:"af-truncate",children:G.customer_email||U("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),pr(G)&&U("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:pr(G)})]}),U(z,{className:"af-max-w-[220px]",children:U("div",{className:"af-truncate af-text-muted-foreground",children:Bo(G)})}),Se(z,{className:"af-whitespace-nowrap af-text-right",children:[U("div",{className:"af-font-medium af-tabular-nums",children:j(pn(G),G.currency)}),G.amount_refunded>0&&Se("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(G.amount_refunded,G.currency)," ","refunded"]})]}),U(z,{children:Se("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[U(Bn,{status:G.status}),U(hs,{deliveries:G.email_deliveries}),a&&U(Kn,{order:G})]})}),U(z,{className:"af-w-8 af-text-right",children:U(Do,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},G.id))})]})}),u?null:Se("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Se("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[U("span",{children:Ut?`${We.length} matching this page`:`Showing ${Wa}-${Gr} of ${f}`}),Se(ya,{value:String(b),onValueChange:G=>y(Number(G)),children:[U(fa,{className:"af-w-[70px] af-h-8",children:U(ha,{})}),Se(ma,{children:[U(Ye,{value:"10",children:"10"}),U(Ye,{value:"25",children:"25"}),U(Ye,{value:"50",children:"50"}),U(Ye,{value:"100",children:"100"})]})]}),U("span",{children:"per page"})]}),Se("div",{className:"af-flex af-items-center af-gap-2",children:[Se(S,{variant:"outline",size:"sm",onClick:()=>k(p-1),disabled:!w,children:[U(vd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Se(S,{variant:"outline",size:"sm",onClick:()=>k(p+1),disabled:!h,children:["Next",U(Do,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function _n(e){return U(Sd,{...e},e.maxRows==null?"full":"compact")}import*as Jn from"react";import{ChevronLeft as Pd,ChevronRight as Cd,Eye as Td,Search as kd,Users as Ed}from"lucide-react";import*as sa from"react";function gr({initialPageSize:e=25}={}){let{api:t}=ee(),[n,s]=sa.useState([]),[a,r]=sa.useState(0),[o,d]=sa.useState(!0),[c,u]=sa.useState(null),[i,g]=sa.useState(0),[v,f]=sa.useState(e),[l,m]=sa.useState(""),p=sa.useRef(0),b=sa.useCallback(async()=>{let w=++p.current;try{d(!0),u(null);let k={limit:v,offset:i*v};l.trim()&&(k.email=l.trim());let y=await t.getCustomers(k);if(w!==p.current)return;s(y.customers),r(y.total)}catch(k){if(w!==p.current)return;u(k instanceof Error?k:new Error("Failed to fetch customers"))}finally{w===p.current&&d(!1)}},[t,i,v,l]);sa.useEffect(()=>{b()},[b]);let h=Math.ceil(a/v);return{customers:n,total:a,isLoading:o,error:c,page:i,pageSize:v,hasNextPage:i<h-1,hasPreviousPage:i>0,setPage:g,setPageSize:w=>{f(w),g(0)},email:l,setEmail:w=>{m(w),g(0)},refetch:b}}import*as Mn from"react";import{ArrowLeft as Nd,Loader2 as _d}from"lucide-react";import{jsx as Be,jsxs as Bt}from"react/jsx-runtime";function Fo(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 Rd(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 vr({customer:e,onBack:t,className:n}){let{api:s}=ee(),[a,r]=Mn.useState(null),[o,d]=Mn.useState([]),[c,u]=Mn.useState(!0),[i,g]=Mn.useState(null);Mn.useEffect(()=>{let l=!1;return u(!0),g(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([m,p])=>{l||(r(m),d(p.orders))}).catch(m=>{l||g(m instanceof Error?m.message:"Failed to load customer")}).finally(()=>{l||u(!1)}),()=>{l=!0}},[s,e.id,e.email]);let v=a?.addresses??[],f=a?.order_count??o.length;return Bt("div",{className:n,children:[Bt("div",{className:"af-mb-6",children:[Bt(S,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[Be(Nd,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),Be("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 ",Fo(e.created_at)]})]}),c?Be("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Be(_d,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):i?Be("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:[Be(Ka,{deliveries:a?.email_deliveries}),Bt("div",{children:[Be("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:[Be("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),Be("span",{children:e.email})]}),e.name&&Bt("div",{className:"af-flex af-gap-2",children:[Be("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),Be("span",{children:e.name})]}),e.phone&&Bt("div",{className:"af-flex af-gap-2",children:[Be("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),Be("span",{children:e.phone})]}),Bt("div",{className:"af-flex af-gap-2",children:[Be("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),Be("span",{children:f})]})]})]}),v.length>0&&Bt("div",{children:[Be("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),Be("div",{className:"af-flex af-flex-wrap af-gap-3",children:v.map(l=>Bt("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[l.is_default&&Be(se,{variant:"secondary",className:"af-mb-1",children:"Default"}),Rd(l).map((m,p)=>Be("div",{children:m},p))]},l.id))})]}),Bt("div",{children:[Be("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?Be("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):Bt($e,{children:[Be(Ve,{children:Bt(be,{children:[Be(H,{children:"Date"}),Be(H,{children:"Amount"}),Be(H,{children:"Status"})]})}),Be(He,{children:o.map(l=>Bt(be,{children:[Be(z,{className:"af-text-muted-foreground",children:Fo(l.created_at)}),Be(z,{children:j(pn(l),l.currency)}),Be(z,{children:Be(Fn,{status:l.status})})]},l.id))})]})]})]})]})}import{Fragment as Ad,jsx as Ne,jsxs as xt}from"react/jsx-runtime";function Id(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function br({className:e}){let{customers:t,total:n,isLoading:s,error:a,page:r,pageSize:o,hasNextPage:d,hasPreviousPage:c,setPage:u,setPageSize:i,email:g,setEmail:v,refetch:f}=gr(),{api:l}=ee(),m=Jn.useCallback(()=>l.exportCustomersCsv(),[l]),[p,b]=Jn.useState("list"),[h,w]=Jn.useState(null),[k,y]=Jn.useState(""),N=T=>{w(T),b("detail")},R=()=>{b("list"),w(null),f()};if(p==="detail"&&h)return Ne("div",{className:e,children:Ne(vr,{customer:h,onBack:R})});let A=xt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Ne(ce,{type:"email",value:k,onChange:T=>y(T.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),v(k.trim()))}}),xt(S,{type:"button",variant:"outline",size:"sm",onClick:()=>v(k.trim()),children:[Ne(kd,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),g&&Ne(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>{y(""),v("")},children:"Clear"}),Ne($t,{fetchCsv:m,filename:"customers",className:"af-ml-auto"})]});if(s)return xt("div",{className:e,children:[A,Ne("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ne("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(a)return xt("div",{className:e,children:[A,Ne("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:[g&&A,xt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[Ne(Ed,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ne("p",{className:"af-text-muted-foreground af-text-center",children:g?"No customers match that email.":xt(Ad,{children:["No customers yet.",Ne("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:[A,xt($e,{children:[Ne(Ve,{children:xt(be,{children:[Ne(H,{children:"Email"}),Ne(H,{children:"Name"}),Ne(H,{children:"Phone"}),Ne(H,{children:"Customer since"}),Ne(H,{className:"af-text-right",children:"Actions"})]})}),Ne(He,{children:t.map(T=>xt(be,{children:[Ne(z,{className:"af-font-medium",children:T.email}),Ne(z,{children:T.name||Ne("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Ne(z,{children:T.phone||Ne("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Ne(z,{className:"af-text-muted-foreground",children:Id(T.created_at)}),Ne(z,{className:"af-text-right",children:Ne(S,{variant:"ghost",size:"icon",onClick:()=>N(T),title:"View customer",children:Ne(Td,{className:"af-h-4 af-w-4"})})})]},T.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(ya,{value:String(o),onValueChange:T=>i(Number(T)),children:[Ne(fa,{className:"af-w-[70px] af-h-8",children:Ne(ha,{})}),xt(ma,{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"})]}),xt("div",{className:"af-flex af-items-center af-gap-2",children:[xt(S,{variant:"outline",size:"sm",onClick:()=>u(r-1),disabled:!c,children:[Ne(Pd,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),xt(S,{variant:"outline",size:"sm",onClick:()=>u(r+1),disabled:!d,children:["Next",Ne(Cd,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Ce from"react";import{ArrowLeft as Dd,ChevronLeft as Ld,ChevronRight as Uo,Copy as Od,Download as Bd,ExternalLink as Fd,FileText as Vo,Loader2 as Ud,Search as Md}from"lucide-react";import*as wt from"react";function Yn({initialPageSize:e=25,refreshKey:t,includeAggregates:n=!1}={}){let{api:s}=ee(),[a,r]=wt.useState([]),[o,d]=wt.useState(0),[c,u]=wt.useState(null),[i,g]=wt.useState(!0),[v,f]=wt.useState(null),[l,m]=wt.useState(0),[p,b]=wt.useState(e),[h,w]=wt.useState(void 0),[k,y]=wt.useState(""),[N,R]=wt.useState(""),[A,x]=wt.useState(""),[P,T]=wt.useState(""),[_,K]=wt.useState(""),F=h?h.join(","):"",X=wt.useRef(0),Q=wt.useCallback(async()=>{let te=++X.current;g(!0),f(null);try{let $={labels:F?F.split(","):void 0,customerEmail:k||void 0,q:N||void 0,from:A||void 0,to:P||void 0,retainerId:_||void 0,includeAggregates:n,limit:p,offset:l*p},M=await s.getInvoices($);if(te!==X.current)return;if(l>0&&l*p>=M.total){m(Math.max(0,Math.ceil(M.total/p)-1));return}r(M.invoices),d(M.total),n&&u(M.aggregates??null)}catch($){if(te!==X.current)return;f($ instanceof Error?$:new Error("Failed to fetch invoices"))}finally{te===X.current&&g(!1)}},[s,F,k,N,A,P,_,l,p,n]);wt.useEffect(()=>{Q()},[Q,t]);let ne=te=>$=>{m(0),te($)};return{invoices:a,total:o,aggregates:c,isLoading:i,error:v,page:l,pageSize:p,hasNextPage:(l+1)*p<o,hasPreviousPage:l>0,setPage:m,setPageSize:ne(b),labels:h,setLabels:ne(w),customerEmail:k,setCustomerEmail:ne(y),q:N,setQ:ne(R),from:A,setFrom:ne(x),to:P,setTo:ne(T),retainerId:_,setRetainerId:ne(K),clearFilters:()=>{m(0),w(void 0),y(""),R(""),x(""),T(""),K("")},refetch:Q}}import{Fragment as Gd,jsx as D,jsxs as J}from"react/jsx-runtime";var $d={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 gi(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:$d[e.label]??e.label}function Vd(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 pi={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Hd={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function _s({invoice:e,className:t}){return J("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[D(se,{variant:Vd(e.label),className:t,children:gi(e)}),e.collection_method==="charge_automatically"&&D(se,{variant:"secondary",children:"Managed in Stripe"})]})}function xr({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(se,{variant:n,className:t,children:pi[e.state]??e.state})}function Xn(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function Ra(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 Mo={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},yr={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},fi=100,mi=5e3;async function zd(e,t){let n=[],s=0;for(let a=0;a<mi;a+=fi){let r=await e.getInvoices({...t,limit:fi,offset:a});if(s=r.total,n.push(...r.invoices),r.invoices.length<fi||n.length>=s)break}return{invoices:n.slice(0,mi),total:s,truncated:s>n.length||s>mi}}function Ho(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,Xn(s),gi(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),j(s.amount_subtotal,s.currency),j(s.tax_total,s.currency),j(s.amount_total,s.currency),s.amount_due===null?"":j(s.amount_due,s.currency),s.amount_paid===null?"":j(s.amount_paid,s.currency),j(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?"":j(s.discount_total,s.currency),s.collection_method??""]);return[t,...n].map(s=>s.map(co).join(",")).join(`
|
|
5
|
-
`)}function qd(e){Ks(new Blob([Ho(e)],{type:"text/csv;charset=utf-8"}),Ws("invoices"))}function jd({className:e,refreshKey:t,initialInvoiceId:n,onDetailOpenChange:s,onConnectStripe:a,onUpgradePlan:r,needsPaidPlan:o=!1,retainerFilter:d=null,onClearRetainerFilter:c,maxRows:u,onViewAll:i}){let g=typeof u=="number",{api:v}=ee(),{invoices:f,total:l,isLoading:m,error:p,page:b,pageSize:h,hasNextPage:w,hasPreviousPage:k,setPage:y,labels:N,setLabels:R,customerEmail:A,setCustomerEmail:x,q:P,setQ:T,from:_,setFrom:K,to:F,setTo:X,retainerId:Q,setRetainerId:ne,refetch:te}=Yn({refreshKey:t}),[$,M]=Ce.useState(typeof u=="number"?"all":"open"),[V,fe]=Ce.useState(""),[Ke,vt]=Ce.useState(null),Ee=Ce.useRef(0),Fe=!g||!!i,Ze=Ce.useCallback(q=>{if(g){i?.();return}Ee.current++,kt(!1),vt(q)},[g,i]),[Te,kt]=Ce.useState(!1),[E,B]=Ce.useState(0),[O,me]=Ce.useState(null),[ve,_e]=Ce.useState(!1),[Le,nt]=Ce.useState(0);Ce.useEffect(()=>{vt(q=>{if(!q)return q;let Je=f.find(Wa=>Wa.id===q.id);return Je&&Je!==q?Je:q})},[f]);let[Oe,ut]=Ce.useState(!1),[oe,Re]=Ce.useState(null),st=async()=>{if(!Oe){ut(!0),Re(null);try{let{invoices:q,total:Je,truncated:Wa}=await zd(v,{labels:N,customerEmail:A,q:P,from:_,to:F,retainerId:Q});qd(q),Re(Wa?`Exported the first ${q.length.toLocaleString()} of ${Je.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Re("Couldn't export \u2014 try again.")}finally{ut(!1)}}},da=!A&&!P&&!_&&!F&&!Q,[Lt,Yt]=Ce.useState(null);Ce.useEffect(()=>{if(m||l>0||!da||$!=="open")return;let q=!1;return v.getInvoices({limit:1}).then(Je=>{q||Yt(Je.total>0)}).catch(()=>{q||Yt(!0)}),()=>{q=!0}},[v,m,l,da,$,t]),Ce.useEffect(()=>{R(g?yr.all:yr.open)},[]),Ce.useEffect(()=>{let q=d?.id??"";q!==Q&&(ne(q),q&&(M("all"),R(yr.all),x(""),T(""),fe(""),K(""),X("")))},[d?.id]),Ce.useEffect(()=>{let q=!1;return _e(!1),v.getInvoiceSettings().then(Je=>{q||me({payments_active:Je.payments_active,blocked:Je.blocked})}).catch(()=>{q||_e(!0)}),()=>{q=!0}},[v,t,Le]),Ce.useEffect(()=>{if(!n||g)return;let q=!1,Je=Ee.current;return kt(!1),v.getInvoice(n).then(Wa=>{!q&&Je===Ee.current&&vt(Wa)}).catch(()=>{!q&&Je===Ee.current&&kt(!0)}),()=>{q=!0}},[v,n,E,g]),Ce.useEffect(()=>{s?.(Ke!==null)},[Ke,s]);let Ut=q=>{M(q),R(yr[q])},We=q=>{let Je=q.trim();if(!Je){P&&T(""),A&&x("");return}if(Je.includes("@")){P&&T(""),x(Je);return}A&&x(""),T(Je.replace(/^#/,""))},rt=f,Ia=g?rt.slice(0,u):rt,Dn=Te&&J("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(S,{type:"button",variant:"link",size:"sm",onClick:()=>B(q=>q+1),children:"Retry opening invoice"})]});if(Ke)return J("div",{className:e,children:[Dn,D(vi,{invoice:Ke,refreshKey:t,onBack:()=>{Ze(null),te()}},Ke.id)]});let Xt=J("div",{className:"af-mb-4 af-space-y-3",children:[ve&&J("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",D(S,{type:"button",variant:"link",size:"sm",onClick:()=>nt(q=>q+1),children:"Retry setup check"})]}),Dn,O?.blocked&&J("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."]}),d&&J("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[J(se,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",d.label]}),c&&D(S,{type:"button",variant:"link",size:"sm",onClick:c,children:"Clear schedule filter"})]}),J("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(Mo).map(q=>D("button",{type:"button","aria-pressed":$===q,onClick:()=>Ut(q),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",$===q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Mo[q]},q))}),J("div",{className:"af-relative af-w-full af-max-w-xs",children:[D(Md,{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:V,onChange:q=>fe(q.target.value),onBlur:()=>We(V),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),We(V))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),J("div",{className:"af-flex af-items-center af-gap-2",children:[D(ye,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),D(ce,{id:"invoices-from",type:"date",value:_,max:F||void 0,onChange:q=>K(q.target.value),className:"af-invoice-date af-w-[150px]"})]}),J("div",{className:"af-flex af-items-center af-gap-2",children:[D(ye,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),D(ce,{id:"invoices-to",type:"date",value:F,min:_||void 0,onChange:q=>X(q.target.value),className:"af-invoice-date af-w-[150px]"})]}),J(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>void st(),disabled:Oe||m||!!p||l===0,"aria-busy":Oe,children:[D(Bd,{className:"af-h-4 af-w-4 af-mr-1"}),Oe?"Exporting\u2026":"Export CSV (all matching)"]})]}),oe&&D("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:oe})]});return m?J("div",{className:e,children:[g?null:Xt,D("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(q=>J("div",{className:"af-rounded-md af-border af-p-3",children:[J("div",{className:"af-flex af-items-center af-justify-between",children:[D(re,{className:"af-h-4 af-w-20"}),D(re,{className:"af-h-4 af-w-16"})]}),D(re,{className:"af-mt-2 af-h-3 af-w-40"})]},q))})]}):p?J("div",{className:e,children:[g?null:Xt,J("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",D(S,{type:"button",variant:"link",size:"sm",onClick:()=>void te(),children:"Retry"})]})]}):l===0&&da&&($==="all"||Lt===!1)&&($==="open"||$==="all")?O?.blocked?J("div",{className:e,children:[g?null:Xt,D(hr,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?J("div",{className:e,children:[g?null:Xt,D(hr,{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?J("div",{className:e,children:[g?null:Xt,D(hr,{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})]}):J("div",{className:e,children:[g?null:Xt,D(hr,{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."})]}):J("div",{className:e,children:[g?null:Xt,Ia.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."}):J(Gd,{children:[D("div",{className:"af-space-y-3 lg:af-hidden",children:Ia.map(q=>J("button",{type:"button",onClick:()=>Ze(q),disabled:!Fe,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Fe?" hover:af-bg-muted/50":""}`,children:[J("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[D("span",{className:"af-font-medium",children:Xn(q)}),D(_s,{invoice:q})]}),D("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:q.customer_name??q.customer_email??"\u2014"}),q.delivery&&D("div",{className:"af-mt-1",children:D(xr,{delivery:q.delivery})}),J("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:q.collection_method==="charge_automatically"?"Automatic collection":q.due_at?`Due ${Ra(q.due_at)}`:"Due on receipt"}),D("span",{className:"af-font-medium af-tabular-nums",children:j(q.amount_due??q.amount_total,q.currency)})]})]},q.id))}),D("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:J($e,{children:[D(Ve,{children:J(be,{children:[D(H,{children:"Invoice"}),D(H,{children:"Created"}),D(H,{children:"Customer"}),D(H,{children:"Due"}),D(H,{className:"af-text-right",children:"Amount"}),D(H,{children:"Status"}),D(H,{children:"Delivery"}),D(H,{className:"af-w-8"})]})}),D(He,{children:Ia.map(q=>J(be,{className:Fe?"af-cursor-pointer":void 0,onClick:Fe?()=>Ze(q):void 0,children:[D(z,{className:"af-font-medium",children:D("button",{type:"button",disabled:!Fe,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Fe?" hover:af-underline":""}`,onClick:Je=>{Je.stopPropagation(),Ze(q)},"aria-label":`Open invoice ${Xn(q)}`,children:Xn(q)})}),D(z,{children:Ra(q.created_at)}),J(z,{children:[D("div",{children:q.customer_name??"\u2014"}),D("div",{className:"af-text-xs af-text-muted-foreground",children:q.customer_email})]}),D(z,{children:q.collection_method==="charge_automatically"?"Automatic":q.due_at?Ra(q.due_at):"On receipt"}),D(z,{className:"af-text-right af-tabular-nums",children:j(q.amount_due??q.amount_total,q.currency)}),D(z,{children:D(_s,{invoice:q})}),D(z,{children:D(xr,{delivery:q.delivery})}),D(z,{children:D(Uo,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},q.id))})]})}),g?null:J("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[J("span",{children:[l," invoice",l===1?"":"s"]}),J("div",{className:"af-flex af-items-center af-gap-1",children:[D(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b-1),disabled:!k,"aria-label":"Previous page",children:D(Ld,{className:"af-h-4 af-w-4"})}),J("span",{className:"af-tabular-nums",children:[b*h+1,"\u2013",Math.min((b+1)*h,l)]}),D(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(b+1),disabled:!w,"aria-label":"Next page",children:D(Uo,{className:"af-h-4 af-w-4"})})]})]})]})]})}function hr({heading:e,body:t,action:n}){return D(Zn,{icon:Vo,heading:e,body:t,action:n})}function Pn(e){return D(jd,{...e},e.maxRows==null?"full":"compact")}var vn="af-text-xs af-text-muted-foreground";function $o(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function vi({invoice:e,onBack:t,refreshKey:n,className:s}){let{api:a}=ee(),r=Ce.useRef(null);Ce.useEffect(()=>{r.current?.focus()},[e.id]);let[o,d]=Ce.useState(!1),[c,u]=Ce.useState(null),[i,g]=Ce.useState(!1),[v,f]=Ce.useState(!1),l=Ce.useRef(0),[m,p]=Ce.useState(null),[b,h]=Ce.useState(!1),[w,k]=Ce.useState(0);Ce.useEffect(()=>{let _=!1;return h(!1),a.getInvoice(e.id).then(K=>{_||p({source:e,value:K})}).catch(()=>{_||h(!0)}),()=>{_=!0}},[a,e,n,w]);let y=m?.source===e?m.value:e,N=y.collection_method==="charge_automatically";Ce.useEffect(()=>(l.current++,u(null),g(!1),f(!1),d(!1),()=>{l.current++}),[a,y,n]);let R=_=>_==null?"\u2014":j(_,y.currency),A=async()=>{if(!(!y.pay_url||!$o()))try{await navigator.clipboard.writeText(y.pay_url),d(!0),setTimeout(()=>d(!1),1500)}catch{}},x=async()=>{if(c){u(null);return}let _=++l.current;f(!1),g(!0);try{let K=await a.getInvoicePreview(y.id);_===l.current&&u(K)}catch{_===l.current&&f(!0)}finally{_===l.current&&g(!1)}},P=y.bill_to,T=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(_=>!!_&&_.length>0):[];return J("div",{className:s,children:[J("div",{className:"af-mb-4",children:[J(S,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[D(Dd,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),J("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[J("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",Xn(y)]}),D(_s,{invoice:y}),D(xr,{delivery:y.delivery})]}),J("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&&J("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(S,{type:"button",variant:"link",size:"sm",onClick:()=>k(_=>_+1),children:"Retry details"})]}),y.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."}),y.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."}),J("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[J("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[J("section",{className:"af-rounded-md af-border af-p-4",children:[J($e,{children:[D(Ve,{children:J(be,{children:[D(H,{children:"Description"}),D(H,{className:"af-text-right",children:"Qty"}),D(H,{className:"af-text-right",children:"Amount"})]})}),D(He,{children:y.line_items.map((_,K)=>J(be,{children:[D(z,{style:{overflowWrap:"anywhere"},children:_.description}),D(z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:_.quantity}),D(z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:R(_.amount)})]},K))})]}),J("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[D(Rn,{label:"Subtotal",value:R(y.amount_subtotal)}),(y.discount_total??0)>0&&D(Rn,{label:"Discount",value:`-${R(y.discount_total)}`}),y.tax_total>0&&D(Rn,{label:y.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:R(y.tax_total)}),D(Rn,{label:"Total",value:R(y.amount_total),strong:!0}),y.credit_applied>0&&D(Rn,{label:"Credit applied",value:`-${R(y.credit_applied)}`}),y.amount_due!==null&&y.amount_due!==y.amount_total&&D(Rn,{label:"Amount due",value:R(y.amount_due),strong:!0}),y.amount_paid!==null&&y.amount_paid>0&&D(Rn,{label:"Amount paid",value:R(y.amount_paid)}),y.amount_refunded>0&&D(Rn,{label:"Refunded",value:R(y.amount_refunded)})]}),y.credit_notes?.length>0&&J("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[D("div",{className:vn,children:"Credit notes"}),y.credit_notes.map(_=>J("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[J("span",{className:"af-text-muted-foreground",children:[Ra(_.created_at)," \xB7 ",_.origin==="dashboard"?"issued in Stripe":"refund",_.stripe_credit_note_id?"":" \xB7 being created"]}),J("span",{className:"af-tabular-nums",children:["-",j(_.amount,_.currency)]})]},_.id))]})]}),(y.note||y.footer)&&J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[y.note&&J("div",{children:[D("div",{className:vn,children:"Note"}),D("div",{className:"af-whitespace-pre-wrap af-break-words",children:y.note})]}),y.footer&&J("div",{children:[D("div",{className:vn,children:"Footer"}),D("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:y.footer})]})]}),c&&!N&&J("section",{className:"af-rounded-md af-border af-p-4",children:[J("div",{className:W(vn,"af-break-words"),children:["Email preview \u2014 ",c.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:c.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),J("div",{className:"af-min-w-0 af-space-y-4",children:[J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[D(_a,{label:"Created",value:Ra(y.created_at)}),D(_a,{label:"Due",value:y.collection_method==="charge_automatically"?"Managed in Stripe":y.due_at?Ra(y.due_at):"On receipt"}),y.paid_at&&D(_a,{label:"Paid",value:Ra(y.paid_at)}),y.payment_method&&D(_a,{label:"Paid by",value:y.paid_out_of_band?`${y.payment_method} (recorded outside Stripe)`:y.payment_method}),y.payment_state!=="none"&&D(_a,{label:"Payment",value:y.payment_state==="processing"?"Processing":y.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),y.delivery&&D(_a,{label:"Delivery",value:`${pi[y.delivery.state]} \xB7 ${y.delivery.recipient}`}),y.marked_uncollectible_at&&D(_a,{label:"Written off",value:Ra(y.marked_uncollectible_at)}),y.correction_reason&&D(_a,{label:"Correction",value:y.correction_reason}),y.replaced_by_order_id&&D(_a,{label:"Replaced by",value:y.replaced_by_order_id}),y.collection_method==="charge_automatically"?D(_a,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):y.retainer_id&&D(_a,{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&&D(_a,{label:"Replaces",value:y.replaces_order_id})]}),J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[D("div",{className:vn,children:"Reminders"}),N?D("div",{children:"View automatic payment reminders in Stripe."}):y.reminders.disabled?D("div",{children:"Off for this invoice."}):y.reminders.paused_until?J("div",{children:["Paused until ",Ra(y.reminders.paused_until),"."]}):y.reminders.next_at?J("div",{children:["Next on ",Ra(y.reminders.next_at),"."]}):y.reminders.final_sent_at?J("div",{children:["Final reminder sent ",Ra(y.reminders.final_sent_at),"."]}):D("div",{children:"None scheduled."}),!N&&J("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",y.reminders.schedule.length===0?"none":y.reminders.schedule.map(_=>_<0?`${-_}d before`:_===0?"due day":`${_}d after`).join(", ")]})]}),y.communications&&y.communications.length>0&&J("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"}),y.communications.map(_=>J("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[J("span",{className:"af-min-w-0 af-break-words",children:[Hd[_.kind]??_.kind,_.kind==="reminder"&&_.slot!==null?` #${_.slot}`:"",J("span",{className:"af-text-muted-foreground",children:[" \xB7 ",_.recipient]})]}),J("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[pi[_.state]??_.state," \xB7 ",Ra(_.state_at??_.created_at)]})]},_.id))]}),T.length>0&&J("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[D("div",{className:vn,children:"Bill to"}),T.map((_,K)=>D("div",{className:"af-break-words",children:_},K))]}),J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[y.pay_url&&J(S,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void A(),disabled:!$o(),children:[D(Od,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":N?"Copy invoice link":"Copy pay link"]}),y.pdf_url&&D(S,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:J("a",{href:y.pdf_url,target:"_blank",rel:"noreferrer",children:[D(Fd,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!N&&J(S,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void x(),disabled:i,children:[i?D(Ud,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):D(Vo,{className:"af-h-4 af-w-4 af-mr-1"}),c?"Hide email preview":v?"Retry email preview":"Show email preview"]}),v&&!N&&D("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),y.pay_url&&D("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:y.pay_url}),D("p",{className:"af-text-xs af-text-muted-foreground",children:N?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function _a({label:e,value:t}){return J("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[D("span",{className:W(vn,"af-shrink-0"),children:e}),D("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function Rn({label:e,value:t,strong:n}){return J("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[D("dt",{className:W(vn,n&&"af-font-medium af-text-foreground"),children:e}),D("dd",{className:W("af-tabular-nums",n&&"af-font-semibold"),children:t})]})}import{Repeat as Wd}from"lucide-react";import{jsx as pt,jsxs as za}from"react/jsx-runtime";var Kd={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},zo={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Zd(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 qo(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>zo[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>zo[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Kd[e.status]}function jo(e){let t=e.interval==="year"?"every year":"every month";return`${j(e.amount,e.currency)} ${t}`}function Jd(e){return e.status==="canceled"?`Ended ${wr(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${wr(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 ${wr(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${wr(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function wr(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 bi({retainer:e,className:t}){return pt(se,{variant:Zd(e.status),className:W("af-max-w-full af-whitespace-normal af-break-words",t),children:qo(e)})}function Qn({retainers:e,isLoading:t,error:n,onRetry:s,onShowCycles:a,activeRetainerId:r,total:o,endedTotal:d=0,isLoadingMore:c=!1,onLoadMore:u,includeEnded:i=!1,onIncludeEndedChange:g,exportCsv:v,className:f}){let l=!!g;if(!t&&!n&&e.length===0&&!(l&&(i||d>0)))return null;let m=o!==void 0?Math.max(0,o-e.length):0;return za("section",{className:W("af-mb-6",f),"aria-label":"Recurring invoices",children:[za("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[pt(Wd,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),pt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),pt("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."}),l&&pt(S,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":i,onClick:()=>g?.(!i),children:i?"Hide ended recurring invoices":d>0&&e.length===0?`Show ended recurring invoices (${d})`:"Show ended recurring invoices"}),v&&pt($t,{fetchCsv:v,filename:"retainers",className:l?void 0:"af-ml-auto"})]}),n?za("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",pt(S,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?pt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(p=>za("div",{className:"af-rounded-md af-border af-p-3",children:[pt(re,{className:"af-h-4 af-w-48"}),pt(re,{className:"af-mt-2 af-h-3 af-w-32"})]},p))}):e.length===0?pt("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."}):pt("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 za("li",{className:W("af-rounded-md af-border af-p-3",b&&"af-border-primary af-bg-muted/40"),children:[za("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[za("div",{className:"af-min-w-0",children:[pt("div",{className:"af-truncate af-font-medium",children:p.customer_name??p.customer_email??"\u2014"}),pt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:p.description})]}),pt(bi,{retainer:p})]}),p.collection_method==="charge_automatically"?za("div",{className:"af-mt-2 af-space-y-1",children:[pt(se,{variant:"secondary",children:"Managed in Stripe"}),pt("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."})]}):pt("div",{className:"af-mt-2 af-text-sm",children:jo(p)}),za("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:[za("span",{children:[Jd(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&&pt(S,{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&&za("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&&u&&pt("div",{className:"af-mt-2",children:pt(S,{type:"button",variant:"outline",size:"sm",onClick:u,disabled:c,children:c?"Loading\u2026":`Load more (${m} more)`})})]})}import*as Wo from"react";import{AlertTriangle as Go,CheckCircle2 as Yd,CreditCard as yi,Loader2 as Xd,RefreshCw as Qd}from"lucide-react";import{jsx as Qe,jsxs as Et}from"react/jsx-runtime";function es({onConnectStripe:e,onUpgradePlan:t,whenActive:n,className:s}){let{status:a,isLoading:r,error:o,refetch:d}=Sn(),[c,u]=Wo.useState(!1),i=async()=>{u(!0);try{await d()}finally{u(!1)}};return r&&!a?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 payment status..."})}):o||!a?Qe("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?Qe("div",{className:s,children:n}):Qe("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:[Qe(Yd,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),Et("div",{children:[Qe("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:[Qe(yi,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Et("div",{children:[Qe("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),Qe("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(S,{onClick:e,children:[Qe(yi,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):Qe("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:[Qe(Go,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Et("div",{children:[Qe("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),Qe("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?Qe(S,{onClick:t,children:"Upgrade plan"}):Qe("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:[Qe(Go,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),Et("div",{children:[Qe("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?Qe("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."}):Qe("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(S,{onClick:e,children:[Qe(yi,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),Et(S,{variant:"outline",onClick:i,disabled:c,children:[c?Qe(Xd,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Qe(Qd,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as Gt from"react";function hi(e,t,n){return e.map(s=>s.id===t?{...s,...n}:s)}function ts({includeStats:e=!1,refreshKey:t}={}){let{api:n}=ee(),[s,a]=Gt.useState([]),[r,o]=Gt.useState(!0),[d,c]=Gt.useState(null),u=Gt.useRef(0),i=Gt.useCallback(async()=>{let p=++u.current;try{o(!0),c(null);let b=await n.getProducts(e?{include:"stats"}:{});if(p!==u.current)return;a(b)}catch(b){if(p!==u.current)return;c(b instanceof Error?b:new Error("Failed to fetch products"))}finally{p===u.current&&o(!1)}},[n,e,t]);Gt.useEffect(()=>{i()},[i]);let g=Gt.useCallback(async p=>{let b=await n.createProduct(p);return a(h=>[b,...h]),b},[n]),v=Gt.useCallback(async(p,b)=>{let h=await n.updateProduct(p,b);return a(w=>hi(w,p,h)),h},[n]),f=Gt.useCallback(async p=>{await n.deleteProduct(p),a(b=>b.filter(h=>h.id!==p))},[n]),l=Gt.useCallback(async(p,b)=>{let h=await n.attachProductFile(p,b);return a(w=>hi(w,p,h)),h},[n]),m=Gt.useCallback(async(p,b)=>{let h=await n.attachProductFileFromUrl(p,b);return a(w=>hi(w,p,h)),h},[n]);return{products:s,isLoading:r,error:d,refetch:i,createProduct:g,updateProduct:v,deleteProduct:f,attachProductFile:l,attachProductFileFromUrl:m}}import*as Wt from"react";var xi=["creating","active","paused","canceling"],ef=["canceled","failed"],tf={statuses:xi},af={};function as({refreshKey:e,includeEnded:t=!1,limit:n=50}={}){let{api:s}=ee(),[a,r]=Wt.useState([]),[o,d]=Wt.useState(0),[c,u]=Wt.useState(0),[i,g]=Wt.useState(!0),[v,f]=Wt.useState(!1),[l,m]=Wt.useState(null),[p,b]=Wt.useState(t),h=Wt.useRef(0),w=Wt.useCallback(async()=>{let y=++h.current;g(!0),f(!1),m(null);try{let N=await s.getRetainers({statuses:p?void 0:xi,limit:n,offset:0});if(y!==h.current)return;if(r(N.retainers),d(N.total),!p&&N.total===0){let R=await s.getRetainers({statuses:ef,limit:1,offset:0});if(y!==h.current)return;u(R.total)}else u(0)}catch(N){if(y!==h.current)return;m(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{y===h.current&&g(!1)}},[s,p,n]);Wt.useEffect(()=>{w()},[w,e]);let k=Wt.useCallback(async()=>{if(i||v||a.length>=o)return;let y=h.current;f(!0);try{let N=await s.getRetainers({statuses:p?void 0:xi,limit:n,offset:a.length});if(y!==h.current)return;r(R=>{let A=new Set(R.map(x=>x.id));return[...R,...N.retainers.filter(x=>!A.has(x.id))]}),d(N.total)}catch(N){if(y!==h.current)return;m(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{y===h.current&&f(!1)}},[s,p,n,i,v,a.length,o]);return{retainers:a,total:o,endedTotal:c,hasMore:a.length<o,isLoading:i,isLoadingMore:v,error:l,includeEnded:p,setIncludeEnded:b,loadMore:k,refetch:w,filters:p?af:tf}}import{Fragment as df,jsx as je,jsxs as ra}from"react/jsx-runtime";function Ko({className:e,defaultTab:t="products",onConnectStripe:n,onRefund:s,onUpgradePlan:a}){let[r,o]=ns.useState(t),[d,c]=ns.useState("list"),[u,i]=ns.useState(null),g=ts(),{status:v,error:f}=Sn(),l=v?.currency,m=w=>{i(w),c("edit")},p=()=>{i(null),c("create")},b=()=>{c("list"),i(null)},h=w=>{i(w),c("edit")};return ra("div",{className:e,children:[ra("div",{className:"af-mb-6",children:[je("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),je("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),ra(Vs,{value:r,onValueChange:w=>o(w),children:[ra(ys,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[ra(Da,{value:"products",className:"af-gap-2",children:[je(rf,{className:"af-h-4 af-w-4"}),"Products"]}),ra(Da,{value:"orders",className:"af-gap-2",children:[je(of,{className:"af-h-4 af-w-4"}),"Orders"]}),ra(Da,{value:"invoices",className:"af-gap-2",children:[je(sf,{className:"af-h-4 af-w-4"}),"Invoices"]}),ra(Da,{value:"customers",className:"af-gap-2",children:[je(cf,{className:"af-h-4 af-w-4"}),"Customers"]}),je(Da,{value:"promos",children:"Promo codes"}),ra(Da,{value:"setup",className:"af-gap-2",children:[je(lf,{className:"af-h-4 af-w-4"}),"Setup"]})]}),je(La,{value:"products",children:d==="list"?je(nr,{productsState:g,onSelectProduct:m,onCreateProduct:p}):ra("div",{children:[ra("div",{className:"af-mb-6",children:[ra(S,{variant:"ghost",size:"sm",onClick:b,className:"af-mb-2 af--ml-2",children:[je(nf,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),je("h3",{className:"af-text-lg af-font-semibold",children:d==="create"?"New Product":u?.name})]}),d==="create"&&!l?je("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:f?ra("div",{className:"af-text-destructive",children:["Error: ",f.message]}):je("div",{className:"af-text-muted-foreground",children:"Loading..."})}):je(rr,{productsState:g,product:d==="edit"?u:null,currency:l??"usd",onSaved:h},d==="edit"?u?.id??"edit":"new")]})}),je(La,{value:"orders",children:je(_n,{onRefund:s})}),je(La,{value:"invoices",children:je(uf,{onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:v?.reason==="needs_paid_plan"})}),je(La,{value:"customers",children:je(br,{})}),je(La,{value:"promos",children:je(Wn,{})}),je(La,{value:"setup",children:je(es,{onConnectStripe:n,onUpgradePlan:a})})]})]})}function uf({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:n}){let s=as(),[a,r]=ns.useState(null),[o,d]=ns.useState(!1);return ra(df,{children:[!o&&je(Qn,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:a?.id??null,onShowCycles:c=>r(u=>u?.id===c.id?null:c),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),je(Pn,{onDetailOpenChange:d,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 Jo from"react";import*as en from"react";function ss({refreshKey:e}={}){let{api:t}=ee(),[n,s]=en.useState(null),[a,r]=en.useState(!0),[o,d]=en.useState(null),c=en.useRef(0),u=en.useCallback(async()=>{let i=++c.current;try{r(!0),d(null);let g=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(i!==c.current)return;s(g)}catch(g){if(i!==c.current)return;d(g instanceof Error?g:new Error("Failed to fetch summary"))}finally{i===c.current&&r(!1)}},[t,e]);return en.useEffect(()=>{u()},[u]),{summary:n,isLoading:a,error:o,refetch:u}}import{Fragment as wi,jsx as It,jsxs as Si}from"react/jsx-runtime";function Zo(e,t){if(e.settled.complete)return{headline:j(e.settled.gross,e.settled.currency),extra:[]};let n=e.totals[0];return n?{headline:j(n.gross,n.currency),extra:e.totals.slice(1).map(s=>`+ ${j(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:j(0,t),extra:[]}}function Yo({refreshKey:e,initialOrderId:t,isOwner:n=!1,onRefund:s,onBackToWebsite:a,className:r}){let{summary:o,isLoading:d,error:c,refetch:u}=ss({refreshKey:e}),[i,g]=Jo.useState(!1),v=It("div",{className:"af-mb-6",children:c&&!o?It(va,{message:"Couldn't load your revenue summary.",onRetry:()=>u()}):It("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:d||!o?Si(wi,{children:[It(lt,{label:"This week",children:It(re,{className:"af-h-6 af-w-24"})}),It(lt,{label:"Today",children:It(re,{className:"af-h-6 af-w-24"})}),It(lt,{label:"Needs attention",children:It(re,{className:"af-h-6 af-w-10"})})]}):It(wi,{children:(()=>{let f=Zo(o.revenue.d7,o.currency),l=Zo(o.revenue.today,o.currency);return Si(wi,{children:[It(lt,{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(lt,{label:"Today",detail:l.extra.length>0?It("div",{children:l.extra.map(m=>It("div",{children:m},m))}):void 0,children:l.headline}),It(lt,{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 Si(_t,{title:"Orders",onBackToWebsite:a,hideBackButton:i,className:r,children:[v,It(_n,{refreshKey:e,initialOrderId:t,onDetailOpenChange:g,showFulfillment:!0,onRefund:n?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as Pa from"react";import{ImageOff as vf,Package as bf,Search as yf}from"lucide-react";import*as tn from"react";import{ArrowLeft as pf,ImageOff as gf}from"lucide-react";import{jsx as qa,jsxs as Rs}from"react/jsx-runtime";var Xo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Cn="af-text-xs af-text-muted-foreground",Sr="af-text-sm af-font-medium af-tabular-nums",ff=3;function mf(e){let t=e.pricing,n=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let c=e.min_amount??t?.min_amount??null,u=e.max_amount??t?.max_amount??null;return c!==null&&u!==null?{text:`Buyer chooses (${j(c,n)} \u2013 ${j(u,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?j(a,n):`${j(a,n)} \u2013 ${j(r,n)}`,d=t?.compare_at_amount??null;return{text:o,compareAt:d!==null&&d>r?j(d,n):null}}function Nr({product:e,className:t}){let n=mf(e);return Rs("div",{className:t,children:[qa("span",{className:Sr,children:n.text}),n.compareAt&&qa("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:n.compareAt})]})}function _r({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?qa(se,{variant:"destructive",children:"Out of stock"}):t.low_stock?Rs(se,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?qa(se,{variant:"secondary",children:"Backorder"}):t.available===null?null:Rs(se,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?qa(se,{variant:"warning",children:"Low stock"}):null}function Rr(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Pr(e){return e.map(t=>j(t.amount,t.currency)).join(" + ")}function Qo(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 el({variant:e}){let t=e.inventory;if(!t||!t.tracked)return qa("span",{className:"af-text-muted-foreground",children:"Not tracked"});let n=t.available??0;return t.allow_backorder?Rs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[qa("span",{className:"af-tabular-nums",children:Math.max(0,n)}),qa(se,{variant:"secondary",children:n<0?`${Math.abs(n)} on backorder`:"Backorder"})]}):n<=0?qa(se,{variant:"destructive",children:"Out of stock"}):Rs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[qa("span",{className:"af-tabular-nums",children:n}),n<=ff&&qa(se,{variant:"warning",children:"Low"})]})}import{jsx as ue,jsxs as et}from"react/jsx-runtime";function Ps({title:e,children:t,className:n}){return et("section",{className:W("af-rounded-lg af-border af-p-4",n),children:[ue("h4",{className:Xo,children:e}),ue("div",{className:"af-mt-3",children:t})]})}function tl({src:e,className:t}){let[n,s]=tn.useState(!1);return tn.useEffect(()=>s(!1),[e]),!e||n?ue("div",{"aria-hidden":"true",className:W("af-flex af-items-center af-justify-center af-bg-muted",t),children:ue(gf,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):ue("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:W("af-object-cover",t)})}function al({product:e,showStats:t=!1,onBack:n}){let{api:s}=ee(),[a,r]=tn.useState(null),[o,d]=tn.useState(!0),[c,u]=tn.useState(null),[i,g]=tn.useState(0),[v,f]=tn.useState(0);tn.useEffect(()=>{let y=!1;return d(!0),u(null),s.getProduct(e.id).then(N=>{y||r(N)}).catch(N=>{y||u(N instanceof Error?N:new Error("Failed to load product"))}).finally(()=>{y||d(!1)}),()=>{y=!0}},[s,e.id,i]);let l=a?{...e,...a}:e,m=l.images.length>0?l.images:e.images,p=m[v]??m[0],b=Rr(l),h=t?l.stats:void 0,w=a?.variants??[],k=w.length>1;return et("div",{children:[et("div",{className:"af-mb-6",children:[et(S,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[ue(pf,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),et("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:l.name}),ue(se,{variant:l.active?"success":"secondary",children:l.active?"Active":"Draft"}),ue(_r,{product:l})]}),ue(Nr,{product:l,className:"af-mt-1"}),!l.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."})]}),et("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[et("div",{className:"af-space-y-2",children:[ue(tl,{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((y,N)=>ue("button",{type:"button",onClick:()=>f(N),"aria-label":`Show photo ${N+1} of ${m.length}`,"aria-pressed":N===v,className:W("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",N===v?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:ue(tl,{src:y,className:"af-h-12 af-w-12 af-rounded-md"})},`${y}-${N}`))})]}),et("div",{className:"af-space-y-6",children:[l.description&&ue(Ps,{title:"Description",children:ue("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:l.description})}),o?et(Ps,{title:"Variants",children:[ue("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(y=>et("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[ue(re,{className:"af-h-4 af-w-28"}),ue(re,{className:"af-h-4 af-w-20"}),ue(re,{className:"af-h-4 af-w-16"})]},y))}),ue("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):c?ue(va,{message:"Couldn't load this product's variants.",onRetry:()=>g(y=>y+1)}):k?ue(Ps,{title:`Variants \xB7 ${w.length}`,children:ue("div",{className:"af-overflow-x-auto",children:et($e,{children:[ue(Ve,{children:et(be,{children:[ue(H,{children:"Variant"}),ue(H,{children:"SKU"}),ue(H,{className:"af-text-right",children:"Price"}),ue(H,{children:"Stock"})]})}),ue(He,{children:w.map(y=>et(be,{children:[et(z,{className:"af-font-medium",children:[y.title||y.option_values.map(N=>N.value).join(" / ")||"\u2014",!y.active&&ue(se,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),ue(z,{className:"af-text-muted-foreground",children:y.sku?ue("code",{className:"af-font-mono af-text-xs af-break-all",children:y.sku}):"\u2014"}),et(z,{className:"af-whitespace-nowrap af-text-right",children:[ue("div",{className:Sr,children:Qo(y)}),y.compare_at_amount!==null&&y.unit_amount!==null&&y.compare_at_amount>y.unit_amount&&ue("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:j(y.compare_at_amount,y.currency)})]}),ue(z,{className:"af-text-sm",children:ue(el,{variant:y})})]},y.id))})]})})}):null,ue(Ps,{title:"Details",children:et("dl",{className:"af-space-y-2",children:[et("div",{children:[ue("dt",{className:Cn,children:"Delivery"}),ue("dd",{className:"af-text-sm",children:b==="Digital download"?l.fulfillment.filename??"Digital download":b??"Nothing to deliver"})]}),l.fulfillment.type==="redirect"&&l.fulfillment.url&&et("div",{children:[ue("dt",{className:Cn,children:"Sends buyers to"}),ue("dd",{className:"af-break-all af-text-sm",children:l.fulfillment.url})]}),et("div",{children:[ue("dt",{className:Cn,children:"Shipping address"}),ue("dd",{className:"af-text-sm",children:l.collect_shipping_address?"Collected at checkout":"Not collected"})]}),et("div",{children:[ue("dt",{className:Cn,children:"Most one buyer can order"}),ue("dd",{className:"af-text-sm af-tabular-nums",children:l.max_quantity})]})]})}),h&&ue(Ps,{title:"Last 30 days",children:et("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[et("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})]}),et("div",{children:[ue("dt",{className:Cn,children:"Orders"}),ue("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:h.orders})]}),et("div",{children:[ue("dt",{className:Cn,children:"Gross"}),ue("dd",{className:Sr,children:h.gross.length>0?Pr(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 tt}from"react/jsx-runtime";var hf={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},xf=["all","active","draft","low_stock","out_of_stock"];function nl(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,n=new Date(t).getTime();return Number.isNaN(n)?0:n}function sl(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function wf(e){return e.inventory?.out_of_stock??!1}function Sf(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return sl(e);case"out_of_stock":return wf(e);default:return!0}}function Nf({product:e,showStats:t,onOpen:n}){let s=e.images[0],a=t?e.stats:void 0,r=Rr(e),o=e.variant_count??0;return tt("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(vf,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),tt("div",{className:"af-space-y-2 af-p-3",children:[tt("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[tt("div",{className:"af-min-w-0",children:[ie("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),ie(Nr,{product:e,className:"af-mt-0.5"})]}),!e.active&&ie(se,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),tt("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ie(_r,{product:e}),o>1&&tt(se,{variant:"outline",children:[o," variants"]}),r&&ie(se,{variant:"outline",children:r})]}),a&&tt("div",{className:"af-text-xs af-text-muted-foreground",children:[a.units_sold," sold",a.gross.length>0?` \xB7 ${Pr(a.gross)}`:""," ",ie("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function _f(){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=>tt("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"}),tt("div",{className:"af-space-y-2 af-p-3",children:[ie(re,{className:"af-w-32"}),ie(re,{className:"af-w-16"}),ie(re,{className:"af-h-5 af-w-24"})]})]},e))})}function rl({refreshKey:e,showStats:t=!1,onBackToWebsite:n,className:s}){let{products:a,isLoading:r,error:o,refetch:d}=ts({includeStats:t,refreshKey:e}),[c,u]=Pa.useState(!1),[i,g]=Pa.useState(null),[v,f]=Pa.useState("all"),{api:l}=ee(),m=Pa.useCallback(()=>l.exportProductsCsv(),[l]),[p,b]=Pa.useState(""),[h,w]=Pa.useState("newest"),k=Pa.useMemo(()=>{if(!t)return null;let F=null;for(let X of a)!X.stats||X.stats.units_sold===0||(!F||X.stats.units_sold>(F.stats?.units_sold??0))&&(F=X);return F},[a,t]),y=Pa.useMemo(()=>a.filter(sl).length,[a]),N=p.trim().toLowerCase(),R=Pa.useMemo(()=>{let X=[...a.filter(Q=>Sf(Q,v)&&(!N||Q.name.toLowerCase().includes(N)))];return h==="name"?X.sort((Q,ne)=>Q.name.localeCompare(ne.name)):h==="best_selling"?X.sort((Q,ne)=>(ne.stats?.units_sold??0)-(Q.stats?.units_sold??0)):X.sort((Q,ne)=>nl(ne.created_at)-nl(Q.created_at)),X},[a,v,N,h]),A=v!=="all"||!!N,x=()=>{f("all"),b("")},P=r||o!==null&&a.length===0,T=ie("div",{className:"af-mb-6",children:ie("div",{className:W("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:P?tt(Tn,{children:[ie(lt,{label:"Products",children:ie(re,{className:"af-h-6 af-w-10"})}),t?tt(Tn,{children:[ie(lt,{label:"Best seller",children:ie(re,{className:"af-h-6 af-w-28"})}),ie(lt,{label:"Low stock",children:ie(re,{className:"af-h-6 af-w-10"})})]}):ie(lt,{label:"Active",children:ie(re,{className:"af-h-6 af-w-10"})})]}):tt(Tn,{children:[ie(lt,{label:"Products",children:a.length}),t?tt(Tn,{children:[ie(lt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:k?`${k.stats?.units_sold??0} sold, last 30 days`:void 0,children:k?ie("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:k.name}):ie("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),ie(lt,{label:"Low stock",children:y})]}):ie(lt,{label:"Active",children:a.filter(F=>F.active).length})]})})}),_=tt("div",{className:"af-mb-4 af-space-y-3",children:[tt("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:xf.map(F=>ie("button",{type:"button","aria-pressed":v===F,onClick:()=>f(F),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",v===F?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:hf[F]},F))}),tt("div",{className:"af-relative af-w-full af-max-w-xs",children:[ie(yf,{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:F=>b(F.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),tt(ya,{value:h,onValueChange:F=>w(F),children:[ie(fa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:ie(ha,{})}),tt(ma,{children:[ie(Ye,{value:"newest",children:"Newest"}),ie(Ye,{value:"name",children:"Name A\u2013Z"}),t&&ie(Ye,{value:"best_selling",children:"Best selling"})]})]}),A&&ie(S,{type:"button",variant:"ghost",size:"sm",onClick:x,children:"Clear filters"}),ie($t,{fetchCsv:m,filename:"products",label:A?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&a.length===0?ie(re,{className:"af-h-4 af-w-28"}):ie("p",{className:"af-text-sm af-text-muted-foreground",children:A?`${R.length} of ${a.length} products`:`${a.length} ${a.length===1?"product":"products"}${y>0?` \xB7 ${y} low stock`:""}`})]}),K;return i?K=ie(al,{product:i,showStats:t,onBack:()=>{g(null),d()}},i.id):r&&a.length===0?K=tt(Tn,{children:[_,ie(_f,{}),ie("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&a.length===0?K=ie("div",{className:"af-flex af-justify-center af-py-8",children:ie(va,{message:"Couldn't load your products.",onRetry:()=>d()})}):a.length===0?K=tt(Ha,{icon:ie(bf,{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."]}):K=tt(Tn,{children:[_,o&&ie("div",{className:"af-mb-4",children:ie(va,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>d()})}),R.length===0?tt(Ha,{children:["No products match these filters.",ie("br",{}),ie(S,{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:R.map(F=>ie(Nf,{product:F,showStats:t,onOpen:()=>g(F)},F.id))})]}),ie(_t,{title:"Products",onBackToWebsite:n,hideBackButton:!!i,className:s,children:c?tt(Tn,{children:[ie(S,{variant:"ghost",onClick:()=>u(!1),children:"Back to products"}),ie(Wn,{})]}):tt(Tn,{children:[!i&&ie("div",{className:"af-mb-4 af-flex af-justify-end",children:ie(S,{variant:"outline",onClick:()=>u(!0),children:"Promo codes"})}),!i&&T,K]})})}import*as Ca from"react";import{ArrowLeft as dl,Check as Rf,ChevronLeft as il,ChevronRight as ol,ClipboardCopy as Pf,Mail as _i,Search as Cf,Users as Tf}from"lucide-react";import*as ia from"react";function Cr({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ee(),[s,a]=ia.useState([]),[r,o]=ia.useState(!0),[d,c]=ia.useState(null),[u,i]=ia.useState(0),[g]=ia.useState(e),[v,f]=ia.useState(""),[l,m]=ia.useState(void 0),p=ia.useRef(0),b=ia.useCallback(async()=>{let h=++p.current;try{o(!0),c(null);let w={limit:g,offset:u*g};v.trim()&&(w.q=v.trim()),l&&(w.source=l);let k=await n.getPeople(w);if(h!==p.current)return;a(k.people)}catch(w){if(h!==p.current)return;c(w instanceof Error?w:new Error("Failed to fetch people"))}finally{h===p.current&&o(!1)}},[n,u,g,v,l,t]);return ia.useEffect(()=>{b()},[b]),{people:s,isLoading:r,error:d,page:u,pageSize:g,hasNextPage:s.length===g,hasPreviousPage:u>0,setPage:i,q:v,setQ:h=>{f(h),i(0)},source:l,setSource:h=>{m(h),i(0)},refetch:b}}import*as an from"react";function Tr(e,{refreshKey:t}={}){let{api:n}=ee(),[s,a]=an.useState(null),[r,o]=an.useState(e!==null),[d,c]=an.useState(null),u=an.useRef(0),i=an.useCallback(async()=>{if(e===null){a(null),o(!1),c(null);return}let g=++u.current;try{o(!0),c(null);let v=await n.getPerson(e);if(g!==u.current)return;a(v)}catch(v){if(g!==u.current)return;c(v instanceof Error?v:new Error("Failed to fetch person"))}finally{g===u.current&&o(!1)}},[n,e,t]);return an.useEffect(()=>{i()},[i]),{person:s,isLoading:r,error:d,refetch:i}}import{jsx as C,jsxs as le}from"react/jsx-runtime";var Ni="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",kf="af-text-xs af-text-muted-foreground";function rs(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 Ri(e,t){let n=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(n)}`}function Ef(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function If({value:e,label:t}){let[n,s]=Ca.useState(!1);return Ef()?le(S,{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?C(Rf,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):C(Pf,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),n?"Copied":"Copy email"]}):null}function ll(e){return le("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&le(se,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&C(se,{variant:"secondary",children:"Contact form"})]})}function cl(e){return e.name?e.name:e.email?e.email:C("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Af=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Df=40;function Lf(e){let t=Object.entries(e).filter(([a])=>!a.startsWith("_")),s=t.find(([a,r])=>Af.test(a)&&typeof r=="string"&&r.trim())??t.filter(([,a])=>typeof a=="string"&&a.trim().length>=Df).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 Of(e){return e.replace(/_/g," ")}function Bf(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Ff({data:e}){let{message:t,rest:n}=Lf(e);return t===null&&n.length===0?C("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):le("div",{className:"af-space-y-3",children:[t!==null&&C("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),n.length>0&&C("dl",{className:"af-space-y-1",children:n.map(([s,a])=>le("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[C("dt",{className:W(kf,"af-w-28 af-shrink-0 af-capitalize"),children:Of(s)}),C("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Bf(a)})]},s))})]})}function fl({formName:e,createdAt:t,data:n}){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:[C(se,{variant:"outline",children:"Form submission (unverified)"}),e&&C("span",{className:"af-text-xs af-text-muted-foreground",children:e}),C("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:rs(t)})]}),C(Ff,{data:n})]})}function Uf(e){return e.charged_total??e.amount_total}function Mf({email:e,refreshKey:t,onBack:n}){let{person:s,isLoading:a,error:r,refetch:o}=Tr(e,{refreshKey:t}),d=Ri(e,s?.submissions[0]?.form_name);return le("div",{children:[le("div",{className:"af-mb-6",children:[le(S,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[C(dl,{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:[a?C(re,{className:"af-h-7 af-w-48"}):C("h3",{className:"af-text-xl af-font-semibold af-break-all",children:s?.name||e}),le("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[C("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),C(If,{value:e,label:"Copy email address"})]})]}),C(S,{asChild:!0,children:le("a",{href:d,children:[C(_i,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),a?le("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(c=>le("div",{className:"af-rounded-md af-border af-p-3",children:[C(re,{className:"af-w-40"}),C(re,{className:"af-mt-2 af-w-64"})]},c)),C("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):r||!s?C("div",{className:"af-flex af-justify-center af-py-8",children:C(va,{message:"Couldn't load this person.",onRetry:()=>o()})}):le("div",{className:"af-space-y-6",children:[s.customer&&le("div",{children:[C("h4",{className:W(Ni,"af-mb-3"),children:"Customer"}),le("dl",{className:"af-space-y-1 af-text-sm",children:[s.customer.name&&le("div",{className:"af-flex af-gap-2",children:[C("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),C("dd",{children:s.customer.name})]}),s.customer.phone&&le("div",{className:"af-flex af-gap-2",children:[C("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),C("dd",{children:s.customer.phone})]}),le("div",{className:"af-flex af-gap-2",children:[C("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),C("dd",{children:rs(s.customer.created_at)})]})]})]}),s.orders.length>0&&le("div",{children:[C("h4",{className:W(Ni,"af-mb-3"),children:"Purchases"}),C("div",{className:"af-overflow-x-auto",children:le($e,{children:[C(Ve,{children:le(be,{children:[C(H,{children:"Order"}),C(H,{children:"Date"}),C(H,{className:"af-text-right",children:"Total"}),C(H,{children:"Status"})]})}),C(He,{children:s.orders.map(c=>le(be,{children:[C(z,{className:"af-whitespace-nowrap af-font-medium",children:gn(c)}),C(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rs(c.created_at)}),C(z,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:j(Uf(c),c.currency)}),C(z,{children:C(Fn,{status:c.status})})]},c.id))})]})}),C("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."})]}),s.submissions.length>0&&le("div",{children:[C("h4",{className:W(Ni,"af-mb-3"),children:"Messages"}),C("div",{className:"af-space-y-3",children:s.submissions.map(c=>C(fl,{formName:c.form_name,createdAt:c.created_at,data:c.data},c.id))})]})]})]})}function $f({submissionId:e,onBack:t}){let{api:n}=ee(),[s,a]=Ca.useState(null),[r,o]=Ca.useState(!0),[d,c]=Ca.useState(null),[u,i]=Ca.useState(0);return Ca.useEffect(()=>{let g=!1;return o(!0),c(null),n.getSubmission(e).then(v=>{g||a(v)}).catch(v=>{g||c(v instanceof Error?v:new Error("Failed to load submission"))}).finally(()=>{g||o(!1)}),()=>{g=!0}},[n,e,u]),le("div",{children:[le("div",{className:"af-mb-6",children:[le(S,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[C(dl,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),C("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),r?C(re,{className:"af-mt-1 af-h-4 af-w-32"}):s&&C("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:rs(s.metadata.submitted_at)})]}),r?le("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[C(re,{className:"af-w-40"}),C(re,{className:"af-mt-2 af-w-64"}),C(re,{className:"af-mt-2 af-w-52"}),C("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):d||!s?C("div",{className:"af-flex af-justify-center af-py-8",children:C(va,{message:"Couldn't load this submission.",onRetry:()=>i(g=>g+1)})}):le("div",{className:"af-space-y-3",children:[C(fl,{formName:null,createdAt:s.metadata.submitted_at,data:s.data}),C("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 Vf={all:"All",customers:"Customers",leads:"Leads"},Hf=["all","customers","leads"],ul={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:d,error:c,page:u,pageSize:i,hasNextPage:g,hasPreviousPage:v,setPage:f,q:l,setQ:m,source:p,setSource:b,refetch:h}=Cr({refreshKey:e}),[w,k]=Ca.useState({kind:"list"}),[y,N]=Ca.useState(""),R=p==="customer"?"customers":p==="lead"?"leads":"all",A=ne=>{ul[ne]!==p&&b(ul[ne])},{api:x}=ee(),P=Ca.useCallback(()=>x.exportPeopleCsv({...l?{q:l}:{},...p?{source:p}:{}}),[x,l,p]),T=!r||!!a,_=ne=>{if(r){a?.();return}ne.email?k({kind:"person",email:ne.email}):ne.submission_id&&k({kind:"submission",submissionId:ne.submission_id})},K=()=>{k({kind:"list"}),h()},F=ne=>{let te=ne.trim();te!==l&&m(te)},X=r?o.slice(0,s):o,Q;if(w.kind==="person")Q=C(Mf,{email:w.email,refreshKey:e,onBack:K});else if(w.kind==="submission")Q=C($f,{submissionId:w.submissionId,onBack:K});else{let ne=le("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[C("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:Hf.map(te=>C("button",{type:"button","aria-pressed":R===te,onClick:()=>A(te),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",R===te?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Vf[te]},te))}),le("div",{className:"af-relative af-w-full af-max-w-xs",children:[C(Cf,{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"}),C(ce,{type:"text",value:y,onChange:te=>N(te.target.value),onBlur:()=>F(y),onKeyDown:te=>{te.key==="Enter"&&(te.preventDefault(),F(y))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),l&&C(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>{N(""),m("")},children:"Clear search"}),C($t,{fetchCsv:P,filename:"people",className:"af-ml-auto"})]});if(d)Q=le("div",{children:[r?null:ne,C("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(te=>le("div",{className:"af-rounded-md af-border af-p-3",children:[le("div",{className:"af-flex af-items-center af-justify-between",children:[C(re,{className:"af-h-4 af-w-32"}),C(re,{className:"af-h-4 af-w-16"})]}),C(re,{className:"af-mt-2 af-h-5 af-w-28"}),C(re,{className:"af-mt-2 af-h-3 af-w-56"})]},te))}),C("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:le($e,{children:[C(Ve,{children:le(be,{children:[C(H,{children:"Person"}),C(H,{children:"Came from"}),C(H,{children:"Latest message"}),C(H,{children:"Last activity"}),C(H,{className:"af-w-8"}),C(H,{className:"af-w-8"})]})}),C(He,{"aria-hidden":"true",children:[0,1,2,3,4].map(te=>le(be,{children:[C(z,{children:C(re,{className:"af-h-4 af-w-40"})}),C(z,{children:C(re,{className:"af-h-5 af-w-24"})}),C(z,{children:C(re,{className:"af-h-4 af-w-56"})}),C(z,{children:C(re,{className:"af-h-4 af-w-24"})}),C(z,{}),C(z,{})]},te))})]})}),C("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(c)Q=le("div",{children:[r?null:ne,C("div",{className:"af-flex af-justify-center af-py-8",children:C(va,{message:"Couldn't load your leads.",onRetry:()=>h()})})]});else if(X.length===0&&u===0){let te=!!l||R!=="all";Q=le("div",{children:[te&&ne,te?C(Ha,{children:l?"Nobody matches that search.":R==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):C(Zn,{icon:Tf,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)Q=le("div",{children:[r?null:ne,C(Ha,{children:"No more results."}),C("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:le(S,{variant:"outline",size:"sm",onClick:()=>f(u-1),children:[C(il,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let te=u*i+1,$=u*i+o.length;Q=le("div",{children:[r?null:ne,C("div",{className:"af-space-y-3 lg:af-hidden",children:X.map((M,V)=>le("div",{onClick:T?()=>_(M):void 0,className:`af-rounded-md af-border af-p-3${T?" 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:[C("button",{type:"button",onClick:fe=>{fe.stopPropagation(),_(M)},disabled:!T,"aria-label":`Open ${M.name||M.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${T?" hover:af-underline":""}`,children:cl(M)}),M.name&&M.email&&C("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:M.email})]}),le("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[C("span",{className:"af-text-xs af-text-muted-foreground",children:rs(M.last_activity_at)}),M.email&&C(S,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:C("a",{href:Ri(M.email),onClick:fe=>fe.stopPropagation(),"aria-label":`Email ${M.email}`,children:C(_i,{className:"af-h-4 af-w-4"})})})]})]}),C("div",{className:"af-mt-2",children:ll(M)}),M.latest_message_excerpt&&C("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:M.latest_message_excerpt})]},M.email??M.submission_id??V))}),C("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:le($e,{children:[C(Ve,{children:le(be,{children:[C(H,{children:"Person"}),C(H,{children:"Came from"}),C(H,{children:"Latest message"}),C(H,{children:"Last activity"}),C(H,{className:"af-w-8",children:C("span",{className:"af-sr-only",children:"Reply"})}),C(H,{className:"af-w-8"})]})}),C(He,{children:X.map((M,V)=>le(be,{onClick:T?()=>_(M):void 0,className:T?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[le(z,{className:"af-max-w-[260px] af-font-medium",children:[C("button",{type:"button",onClick:fe=>{fe.stopPropagation(),_(M)},disabled:!T,"aria-label":`Open ${M.name||M.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${T?" hover:af-underline":""}`,children:cl(M)}),M.name&&M.email&&C("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:M.email})]}),C(z,{children:ll(M)}),C(z,{className:"af-max-w-[320px]",children:M.latest_message_excerpt?C("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:M.latest_message_excerpt}):C("span",{className:"af-text-muted-foreground",children:"\u2014"})}),C(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:rs(M.last_activity_at)}),C(z,{className:"af-w-8",children:M.email&&C(S,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:C("a",{href:Ri(M.email),onClick:fe=>fe.stopPropagation(),"aria-label":`Email ${M.email}`,children:C(_i,{className:"af-h-4 af-w-4"})})})}),C(z,{className:"af-w-8 af-text-right",children:C(ol,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},M.email??M.submission_id??V))})]})}),!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:[C("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${te}-${$}`}),le("div",{className:"af-flex af-items-center af-gap-2",children:[le(S,{variant:"outline",size:"sm",onClick:()=>f(u-1),disabled:!v,children:[C(il,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),le(S,{variant:"outline",size:"sm",onClick:()=>f(u+1),disabled:!g,children:["Next",C(ol,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?C("div",{className:n,children:Q}):C(_t,{title:"Leads",onBackToWebsite:t,hideBackButton:w.kind!=="list",className:n,children:Q})}function kr(e){return C(zf,{...e},e.maxRows==null?"full":"compact")}import*as yl from"react";import{ChevronLeft as ml,ChevronRight as qf,Repeat as jf}from"lucide-react";import*as oa from"react";function Er({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ee(),[s,a]=oa.useState([]),[r,o]=oa.useState(0),[d,c]=oa.useState(!0),[u,i]=oa.useState(null),[g,v]=oa.useState(0),[f,l]=oa.useState(e),[m,p]=oa.useState(void 0),b=oa.useRef(0),h=oa.useCallback(async()=>{let k=++b.current;try{c(!0),i(null);let y={limit:f,offset:g*f};m&&(y.status=m);let N=await n.getSubscriptions(y);if(k!==b.current)return;a(N.subscriptions),o(N.total)}catch(y){if(k!==b.current)return;i(y instanceof Error?y:new Error("Failed to fetch subscriptions"))}finally{k===b.current&&c(!1)}},[n,g,f,m,t]);oa.useEffect(()=>{h()},[h]);let w=Math.ceil(r/f);return{subscriptions:s,total:r,isLoading:d,error:u,page:g,pageSize:f,hasNextPage:g<w-1,hasPreviousPage:g>0,setPage:v,setPageSize:k=>{l(k),v(0)},status:m,setStatus:k=>{p(k),v(0)},refetch:h}}import{jsx as ae,jsxs as at}from"react/jsx-runtime";function pl(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function gl({sub:e}){return e.status==="canceled"?ae(se,{variant:"outline",children:"Canceled"}):e.status==="past_due"?ae(se,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?ae(se,{variant:"warning",children:"Scheduled to cancel"}):ae(se,{variant:"success",children:"Active"}):ae(se,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Gf(e,t){let n=j(t,e.currency);return e.plan_interval_count===1?`${n} / ${e.plan_interval}`:`${n} every ${e.plan_interval_count} ${e.plan_interval}s`}function vl({sub:e}){let t=e.current_amount!==e.plan_amount;return at("div",{children:[ae("div",{className:"af-font-medium af-tabular-nums",children:Gf(e,e.current_amount)}),t&&at("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",j(e.plan_amount,e.currency)]})]})}function bl(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${pl(e.current_period_end)}`:"Ends at period end":e.current_period_end?pl(e.current_period_end):"\u2014"}function hl({refreshKey:e,onBackToWebsite:t,className:n}){let{subscriptions:s,total:a,isLoading:r,error:o,page:d,pageSize:c,hasNextPage:u,hasPreviousPage:i,setPage:g,status:v,refetch:f}=Er({refreshKey:e}),{api:l}=ee(),m=yl.useCallback(()=>l.exportSubscriptionsCsv(v?{status:v}:{}),[l,v]),p;if(r)p=at("div",{children:[ae("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(b=>at("div",{className:"af-rounded-md af-border af-p-3",children:[at("div",{className:"af-flex af-items-center af-justify-between",children:[ae(re,{className:"af-h-4 af-w-40"}),ae(re,{className:"af-h-4 af-w-20"})]}),ae(re,{className:"af-mt-2 af-h-3 af-w-32"}),ae(re,{className:"af-mt-2 af-h-5 af-w-24"})]},b))}),ae("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:at($e,{children:[ae(Ve,{children:at(be,{children:[ae(H,{children:"Subscriber"}),ae(H,{children:"Plan"}),ae(H,{className:"af-text-right",children:"Amount"}),ae(H,{children:"Renews"}),ae(H,{children:"Status"})]})}),ae(He,{"aria-hidden":"true",children:[0,1,2,3,4].map(b=>at(be,{children:[ae(z,{children:ae(re,{className:"af-h-4 af-w-44"})}),ae(z,{children:ae(re,{className:"af-h-4 af-w-32"})}),ae(z,{className:"af-text-right",children:ae(re,{className:"af-ml-auto af-h-4 af-w-24"})}),ae(z,{children:ae(re,{className:"af-h-4 af-w-24"})}),ae(z,{children:ae(re,{className:"af-h-5 af-w-20"})})]},b))})]})}),ae("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=ae("div",{className:"af-flex af-justify-center af-py-8",children:ae(va,{message:"Couldn't load your subscriptions.",onRetry:()=>f()})});else if(s.length===0&&d===0)p=ae(Ha,{icon:ae(jf,{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=at("div",{children:[ae(Ha,{children:"No more results."}),ae("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:at(S,{variant:"outline",size:"sm",onClick:()=>g(d-1),children:[ae(ml,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let b=d*c+1,h=d*c+s.length;p=at("div",{children:[ae("div",{className:"af-mb-3 af-flex af-justify-end",children:ae($t,{fetchCsv:m,filename:"subscriptions"})}),ae("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(w=>at("div",{className:"af-rounded-md af-border 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:[ae("div",{className:"af-truncate af-text-sm af-font-medium",children:w.customer_email||ae("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),ae("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:w.plan_title||"Untitled plan"})]}),ae("div",{className:"af-shrink-0 af-text-right",children:ae(vl,{sub:w})})]}),at("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[ae(gl,{sub:w}),w.is_test&&ae(se,{variant:"outline",children:"Test"}),ae("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:bl(w)})]}),ae(Ka,{deliveries:w.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},w.id))}),ae("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:at($e,{children:[ae(Ve,{children:at(be,{children:[ae(H,{children:"Subscriber"}),ae(H,{children:"Plan"}),ae(H,{className:"af-text-right",children:"Amount"}),ae(H,{children:"Renews"}),ae(H,{children:"Status"})]})}),ae(He,{children:s.map(w=>at(be,{children:[ae(z,{className:"af-max-w-[240px]",children:ae("div",{className:"af-truncate af-font-medium",children:w.customer_email||ae("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),ae(z,{className:"af-max-w-[220px]",children:ae("div",{className:"af-truncate",children:w.plan_title||ae("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),ae(z,{className:"af-whitespace-nowrap af-text-right",children:ae(vl,{sub:w})}),ae(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:bl(w)}),at(z,{children:[at("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ae(gl,{sub:w}),w.is_test&&ae(se,{variant:"outline",children:"Test"})]}),ae(Ka,{deliveries:w.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},w.id))})]})}),at("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[ae("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${b}-${h} of ${a}`}),at("div",{className:"af-flex af-items-center af-gap-2",children:[at(S,{variant:"outline",size:"sm",onClick:()=>g(d-1),disabled:!i,children:[ae(ml,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),at(S,{variant:"outline",size:"sm",onClick:()=>g(d+1),disabled:!u,children:["Next",ae(qf,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return ae(_t,{title:"Subscriptions",onBackToWebsite:t,className:n,children:p})}import*as rn from"react";import{Loader2 as am}from"lucide-react";import*as Ht from"react";import*as Ir from"react";var $n=typeof window>"u"?Ir.useEffect:Ir.useLayoutEffect;var Ar=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},Wf=(e,t)=>e instanceof Error?e:new Error(t);function Kf(e){let t={};return e.due_days!==void 0&&(t.invoice_due_days=e.due_days),e.reminder_schedule!==void 0&&(t.invoice_reminder_schedule=e.reminder_schedule),e.footer!==void 0&&(t.invoice_footer=e.footer),t}function xl(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}=ee(),[a,r]=Ht.useState(null),[o,d]=Ht.useState(!0),[c,u]=Ht.useState(null),i=Ht.useRef(null),[g,v]=Ht.useState(()=>xl(s,e)),f=g.api!==s||g.siteId!==e,l=g;f&&(l=xl(s,e),v(l),r(null),d(!0),u(null));let m=Ht.useRef(l);$n(()=>{m.current!==l&&(m.current=l,i.current=null)},[l]);let p=(x,P)=>m.current===x&&P>x.applied,b=(x,P,T)=>p(x,P)?(x.applied=P,i.current=T,r(T),d(!1),!0):!1,h=async x=>{for(;x.writing;)await x.idle;let P=++x.seq;try{let T=await x.api.getSite(x.siteId);return b(x,P,T)&&u(null),{seq:P,error:null}}catch(T){return{seq:P,error:Wf(T,"Failed to load store settings")}}},w=(x,P)=>{let T=async()=>{if(m.current!==x)throw new Error("Not saved: the store switched to another site first.");x.writing=!0,x.idle=new Promise(K=>{x.markIdle=K});try{return await P(++x.seq)}finally{x.writing=!1,x.markIdle()}},_=x.queue.then(T,T);return x.queue=_.catch(()=>{}),_},k=Ht.useCallback(async()=>{let x=await h(l);x.error&&p(l,x.seq)&&(u(x.error),d(!1))},[l]);Ht.useEffect(()=>{k()},[k,t]);let y=Ht.useCallback(x=>w(l,async P=>{let T=await l.api.updateSite(l.siteId,x),{currency_restatement:_,...K}=T;return b(l,P,K)&&u(F=>F instanceof Ar?F:null),T}),[l]),N=Ht.useRef(n);$n(()=>{N.current=n});let R=Ht.useCallback(async(x,P)=>{await w(l,()=>x());let T=await h(l);return T.error&&p(l,T.seq)&&i.current&&(b(l,T.seq,{...i.current,...P}),u(new Ar(`Saved, but couldn't refresh settings: ${T.error.message}`))),m.current===l?i.current:null},[l]),A=Ht.useCallback(x=>{let P=N.current;return R(()=>P(x),Kf(x))},[R]);return{site:f?null:a,isLoading:f||o,error:f?null:c,refetch:k,updateSite:y,saveInvoiceSettings:n?A:null}}import*as Pt from"react";import{Loader2 as wl}from"lucide-react";import{jsx as Ta,jsxs as nn}from"react/jsx-runtime";function Dr(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var ja="af-grid af-gap-1 af-text-sm",Sl="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",Nl="af-min-h-[72px] af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50";function la({children:e}){return Ta("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Cs({children:e}){return Ta("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:[Ta("h3",{id:o,className:"af-text-sm af-font-semibold",children:n}),s&&Ta(la,{children:s})]}),a]})});function Ti({label:e,description:t,checked:n,onSave:s,disabled:a=!1,disabledReason:r}){let[o,d]=Pt.useState(null),[c,u]=Pt.useState(null),i=o??n,g=async v=>{d(v),u(null);try{await s(v)}catch(f){u(Dr(f))}finally{d(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:[Ta("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":i,checked:i,disabled:a||o!==null,onChange:v=>void g(v.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&&Ta(wl,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&Ta(la,{children:t})]})]}),(a&&r||c)&&nn("div",{className:"af-space-y-1 af-pl-6",children:[a&&r&&Ta(la,{children:r}),c&&Ta(Cs,{children:c})]})]})}var Ci=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Pi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Zf(e,t,n,s=[]){if(!Pi(e)||!Pi(t)||!Pi(n))return{draft:Ci(e,t)?n:e,dropped:[]};let a=[],r={...n};for(let o of Object.keys(n))Ci(e[o],t[o])||(s.includes(o)?a.push(o):r[o]=e[o]);return{draft:r,dropped:a}}function is(e,t){let n=JSON.stringify(e),[s,a]=Pt.useState(e),[r,o]=Pt.useState([]),d=Pt.useRef(e),c=Pt.useRef(e),u=Pt.useRef(s);$n(()=>{c.current=e,u.current=s});let i=Pt.useRef(t?.when);Pt.useEffect(()=>{let v=Object.is(i.current,t?.when)?[]:t?.fields??[];if(i.current=t?.when,Ci(d.current,c.current)&&v.length===0)return;let f=Zf(u.current,d.current,c.current,v);d.current=c.current,a(f.draft),f.dropped.length&&o(f.dropped)},[n,t?.when]);let g=Pt.useCallback(v=>{a(v??c.current),o([])},[]);return{draft:s,setDraft:a,dirty:JSON.stringify(s)!==n,reset:g,dropped:r}}function os({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(S,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&Ta(wl,{className:"af-animate-spin"}),"Save"]}),Ta(S,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:a,children:"Discard"}),n&&Ta("p",{role:"alert",className:W("af-text-sm af-text-destructive"),children:n})]}):null}function ls(){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(Dr(o))}finally{t(!1)}},[]);return{saving:e,error:n,setError:s,run:a}}function _l({what:e}){return nn(la,{children:["Only the site owner can change ",e,"."]})}import*as ka from"react";import{ExternalLink as Jf,Plus as Yf,X as Tl}from"lucide-react";import{Fragment as tm,jsx as de,jsxs as he}from"react/jsx-runtime";var Ei=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function kl({site:e,updateSite:t}){return de("div",{className:"af-space-y-4",children:de(Ti,{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 Rl(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(it(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(it(e.free_shipping_over,e.currency))}}function El({site:e,updateSite:t,refetch:n,providerSlot:s,currencyChanging:a=!1}){let{draft:r,setDraft:o,dirty:d,reset:c,dropped:u}=is(Rl(e),{when:e.currency,fields:["rates","threshold"]}),{saving:i,error:g,setError:v,run:f}=ls(),l=e.currency.toUpperCase(),m=()=>f(async()=>{let b={},h=[...new Set(r.countries.split(/[\s,]+/).map(x=>x.trim().toUpperCase()).filter(Boolean))],w=h.find(x=>!/^[A-Z]{2}$/.test(x));if(w)throw new Error(`"${w}" isn't a two-letter country code (e.g. US, CA).`);let k=h.length?h:null;Ei(k,e.shipping_countries)||(b.shipping_countries=k);let y=[];for(let x of r.rates){let P=x.label.trim(),T=Ot(x.amount,e.currency);if(!P)throw new Error("Every rate needs a name.");if(x.amount.trim()===""||T===null)throw new Error(`Enter a price for "${P}" (0 for free).`);y.push({label:P,amount:T})}let N=y.length?y:null;Ei(N,e.shipping_rates)||(b.shipping_rates=N);let R=null;if(r.threshold.trim()!==""&&(R=Ot(r.threshold,e.currency),R===null||R===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(R!==e.free_shipping_over&&(b.free_shipping_over=R),Object.keys(b).length===0){c();return}("shipping_rates"in b||"free_shipping_over"in b)&&(b.expected_currency=e.currency);let A;try{A=await t(b)}catch(x){throw x instanceof St&&x.details?.code==="currency_changed"&&await n?.(),x}c(Rl(A))}),p=(b,h)=>o({...r,rates:r.rates.map((w,k)=>k===b?{...w,...h}:w)});return he("fieldset",{disabled:i||a,className:"af-space-y-4",children:[he("label",{className:ja,children:["Countries you ship to",de(ce,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:b=>o({...r,countries:b.target.value})}),de(la,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),he("div",{className:"af-space-y-2",children:[he("p",{className:"af-text-sm",children:["Flat shipping rates (",l,")"]}),r.rates.length===0&&de(la,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((b,h)=>he("div",{className:"af-flex af-items-center af-gap-2",children:[de(ce,{"aria-label":`Rate ${h+1} name`,value:b.label,placeholder:"Standard",onChange:w=>p(h,{label:w.target.value})}),de(ce,{"aria-label":`Rate ${h+1} price`,type:"number",min:"0",step:"any",value:b.amount,placeholder:"0",className:"af-w-32",onChange:w=>p(h,{amount:w.target.value})}),de(S,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${h+1}`,onClick:()=>o({...r,rates:r.rates.filter((w,k)=>k!==h)}),children:de(Tl,{})})]},h)),he(S,{type:"button",variant:"outline",size:"sm",onClick:()=>o({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[de(Yf,{})," Add rate"]}),de(la,{children:"Buyers pick one at checkout. The first is preselected."})]}),he("label",{className:ja,children:["Free shipping over (",l,")",de(ce,{"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})}),de(la,{children:"Orders at or above this get the cheapest rate free."})]}),u.length>0&&he("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",l,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),de(os,{dirty:d,saving:i,error:g,onSave:()=>void m(),onDiscard:()=>{v(null),c()}}),s]})}var ki="exclusive",Xf=[{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 Qf({href:e,children:t}){return he("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,de(Jf,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function Il({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=is(e.tax_behavior??ki),{saving:o,error:d,setError:c,run:u}=ls(),[i,g]=ka.useState(!1),v=e.stripe_tax_enabled,f=v||i,l=()=>u(async()=>{let b=n;if(b===e.tax_behavior){r();return}let h={tax_behavior:b};b!=="inclusive"&&e.tax_rate_bps!=null&&(h.tax_rate_bps=null);let w=await t(h);r(w.tax_behavior??ki)}),m=()=>u(async()=>{let b={stripe_tax_enabled:!0,tax_behavior:n};n!=="inclusive"&&e.tax_rate_bps!=null&&(b.tax_rate_bps=null);let h=await t(b);r(h.tax_behavior??ki),g(!1)}),p=(a||i)&&n!=="inclusive"&&e.tax_rate_bps!=null;return he("div",{className:"af-space-y-5",children:[he("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[de("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."}),de("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."}),de("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:Xf.map(b=>de("li",{children:de(Qf,{href:b.href,children:b.label})},b.href))})]}),de(Ti,{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:f,onSave:async b=>{if(i){g(!1),c(null),r();return}if(b&&!e.tax_behavior){g(!0);return}return t({stripe_tax_enabled:b})}}),f&&he("fieldset",{disabled:o,className:"af-space-y-4 af-pl-6",children:[he("label",{className:ja,children:["Do your prices already include tax?",he("select",{"aria-label":"Your prices",className:Sl,value:n,onChange:b=>s(b.target.value),children:[de("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),de("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),de(la,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),p&&he(la,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),i?he("div",{className:"af-space-y-2",children:[he("div",{className:"af-flex af-gap-2",children:[de(S,{type:"button",size:"sm",disabled:o,onClick:()=>void m(),children:"Turn on"}),de(S,{type:"button",size:"sm",variant:"outline",disabled:o,onClick:()=>{g(!1),c(null),r()},children:"Cancel"})]}),d&&de(Cs,{children:d})]}):de(os,{dirty:a,saving:o,error:d,onSave:()=>void l(),onDiscard:()=>{c(null),r()}})]})]})}function Pl(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function Al({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=is(Pl(e)),{saving:o,error:d,setError:c,run:u}=ls(),i=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),g=()=>u(async()=>{let v={},f=null;if(i&&n.rate.trim()!==""){let b=Number(n.rate);if(!Number.isFinite(b)||b<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");f=Math.round(b*100)}i&&f!==e.tax_rate_bps&&(v.tax_rate_bps=f),f!=null&&e.tax_behavior!=="inclusive"&&(v.tax_behavior="inclusive");let l=n.taxId.trim()||null;l!==e.tax_id&&(v.tax_id=l);let m=n.label.trim()||null;if(m!==e.tax_label&&(v.tax_label=m),Object.keys(v).length===0){r();return}let p=await t(v);r(Pl(p))});return he("fieldset",{disabled:o,className:"af-space-y-4",children:[he("label",{className:ja,children:["Tax rate (%)",de(ce,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!i,value:i?n.rate:"",onChange:v=>s({...n,rate:v.target.value})}),de(la,{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."})]}),he("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[he("label",{className:ja,children:["Tax ID",de(ce,{"aria-label":"Tax ID",value:n.taxId,maxLength:64,placeholder:"DE123456789",onChange:v=>s({...n,taxId:v.target.value})})]}),he("label",{className:ja,children:["Tax label",de(ce,{"aria-label":"Tax label",value:n.label,maxLength:24,placeholder:"Tax",onChange:v=>s({...n,label:v.target.value})})]})]}),de(os,{dirty:a,saving:o,error:d,onSave:()=>void g(),onDiscard:()=>{c(null),r()}})]})}function Dl({site:e,updateSite:t,onChangeStart:n}){let[s,a]=ka.useState(e.currency.toUpperCase()),[r,o]=ka.useState(!1),[d,c]=ka.useState(!1),[u,i]=ka.useState(null),g=e.currency.toUpperCase(),v=ka.useRef(g);ka.useEffect(()=>{v.current!==g&&(a(b=>b===v.current?g:b),v.current=g)},[g]);let f=s.trim().toUpperCase(),l=f!==g,m=/^[A-Z]{3}$/.test(f),p=async()=>{c(!0);let b=n?.(),h=!1;i(null);try{let w=await t({currency:f.toLowerCase()});h=!0;let k=w.currency_restatement;k&&!k.applied?i(k.reason?`Not changed: ${k.reason}.`:"The currency was not changed."):(a(w.currency.toUpperCase()),v.current=w.currency.toUpperCase()),o(!1)}catch(w){i(Dr(w))}finally{c(!1),b?.(h)}};return he("div",{className:"af-space-y-3",children:[he("div",{className:"af-flex af-items-end af-gap-2",children:[he("label",{className:ja,children:["Store currency",de(ce,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:d||r,onChange:b=>{a(b.target.value),i(null)}})]}),l&&!r&&he(tm,{children:[de(S,{type:"button",size:"sm",disabled:!m,onClick:()=>o(!0),children:"Change currency"}),de(S,{type:"button",size:"sm",variant:"ghost",onClick:()=>{a(g),i(null)},children:"Discard"})]})]}),de(la,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&he("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[he("p",{className:"af-text-sm",children:["Change the store currency from ",g," to ",f,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",f,":"," ",j(2e3,g)," becomes ",j(2e3,f),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),he("div",{className:"af-flex af-gap-2",children:[de(S,{type:"button",size:"sm",disabled:d,onClick:()=>void p(),children:"Confirm change"}),de(S,{type:"button",size:"sm",variant:"ghost",disabled:d,onClick:()=>o(!1),children:"Cancel"})]})]}),u&&de(Cs,{children:u})]})}function Cl(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function em(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 Ll({site:e,save:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=is(Cl(e)),{saving:o,error:d,setError:c,run:u}=ls();if(!t)return he("div",{className:"af-space-y-2 af-text-sm",children:[he("p",{children:["Due ",e.invoice_due_days," days after sending"]}),he("p",{children:["Reminders: ",em(e.invoice_reminder_schedule)]}),he("p",{children:["Footer: ",e.invoice_footer||"None"]}),de(_l,{what:"invoice defaults"})]});let i=()=>u(async()=>{let g={},v=Number(n.dueDays);if(n.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&&(g.due_days=v);let l=n.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(l.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(l)].sort((h,w)=>h-w);Ei(m,e.invoice_reminder_schedule)||(g.reminder_schedule=m);let p=n.footer.trim()||null;if(p!==e.invoice_footer&&(g.footer=p),Object.keys(g).length===0){r();return}let b=await t(g);r(b?Cl(b):void 0)});return he("fieldset",{disabled:o,className:"af-space-y-4",children:[he("label",{className:ja,children:["Days until due",de(ce,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:n.dueDays,onChange:g=>s({...n,dueDays:g.target.value})})]}),he("label",{className:ja,children:["Reminder schedule",de(ce,{"aria-label":"Reminder schedule",value:n.reminders,placeholder:"Off",onChange:g=>s({...n,reminders:g.target.value})}),de(la,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),he("label",{className:ja,children:["Invoice footer",de("textarea",{"aria-label":"Invoice footer",className:Nl,maxLength:300,value:n.footer,onChange:g=>s({...n,footer:g.target.value})})]}),de(os,{dirty:a,saving:o,error:d,onSave:()=>void i(),onDiscard:()=>{c(null),r()}})]})}function Ol({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=is(e.default_email_recipients),{saving:o,error:d,setError:c,run:u}=ls(),[i,g]=ka.useState(""),[v,f]=ka.useState(null),l=()=>{let p=i.trim().toLowerCase();if(p){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p)){f("Enter a valid email address.");return}if(n.some(b=>b.toLowerCase()===p)){f("Already added.");return}s([...n,p]),g(""),f(null)}},m=()=>u(async()=>{let p=await t({default_email_recipients:n});r(p.default_email_recipients)});return he("fieldset",{disabled:o,className:"af-space-y-3",children:[he("div",{className:"af-flex af-flex-wrap af-gap-2",children:[n.map(p=>he(se,{variant:"secondary",className:"af-gap-1",children:[p,de("button",{type:"button","aria-label":`Remove ${p}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(n.filter(b=>b!==p)),children:de(Tl,{className:"af-h-3 af-w-3"})})]},p)),n.length===0&&de("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),he("div",{className:"af-flex af-gap-2",children:[de(ce,{"aria-label":"Add notification email",type:"email",value:i,placeholder:"Add email address",onChange:p=>{g(p.target.value),f(null)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),l())}}),de(S,{type:"button",variant:"outline",disabled:!i.trim(),onClick:l,children:"Add"})]}),v&&de(Cs,{children:v}),de(os,{dirty:a,saving:o,error:d,onSave:()=>void m(),onDiscard:()=>{c(null),r()}})]})}import{jsx as ba,jsxs as Bl}from"react/jsx-runtime";function Fl({siteId:e,refreshKey:t,section:n,shippingProviderSlot:s,onConnectStripe:a,onUpgradePlan:r,className:o}){let{site:d,isLoading:c,error:u,refetch:i,updateSite:g}=kn({siteId:e,refreshKey:t}),v=rn.useRef(i),f=rn.useRef(e);$n(()=>{v.current=i,f.current=e});let l=rn.useRef({}),[m,p]=rn.useState([]),b=m.some(N=>N.siteId===e),h=rn.useCallback(()=>{let N={siteId:e},R=v.current;return p(A=>[...A,N]),A=>{let x=()=>p(T=>T.filter(_=>_!==N));!(f.current===N.siteId)||A&&v.current===R?x():v.current().finally(x)}},[e]),w=N=>R=>{l.current[N]=R},k=d!==null&&d.payments_active;if(rn.useEffect(()=>{if(!k||!n)return;let N=l.current[n];N&&(N.scrollIntoView?.({behavior:"smooth",block:"start"}),N.focus({preventScroll:!0}))},[k,n]),c)return Bl("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[ba(am,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!d)return ba("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u?.message??"Could not load store settings."});if(!d.payments_active)return ba(es,{className:o,onConnectStripe:a,onUpgradePlan:r,whenActive:ba("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:d,updateSite:g,refetch:i};return Bl("div",{className:`af-space-y-6 ${o??""}`,children:[u&&ba("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u.message}),ba(sn,{ref:w("checkout"),id:"checkout",title:"Checkout",children:ba(kl,{...y})}),ba(sn,{ref:w("shipping"),id:"shipping",title:"Shipping",children:ba(El,{...y,providerSlot:s,currencyChanging:b})}),ba(sn,{ref:w("tax"),id:"tax",title:"Tax",children:ba(Il,{...y})}),ba(sn,{ref:w("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:ba(Dl,{...y,onChangeStart:h})})]},e)}import{Loader2 as nm}from"lucide-react";import{jsx as Vn,jsxs as Ul}from"react/jsx-runtime";function Lr({siteId:e,refreshKey:t,onSaveInvoiceSettings:n,className:s}){let{site:a,isLoading:r,error:o,updateSite:d,refetch:c,saveInvoiceSettings:u}=kn({siteId:e,refreshKey:t,onSaveInvoiceSettings:n});return r?Ul("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Vn(nm,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):a?Ul("div",{className:`af-space-y-6 ${s??""}`,children:[o&&Vn("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}),Vn(sn,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:Vn(Ll,{site:a,save:u})}),Vn(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:Vn(Al,{site:a,updateSite:d,refetch:c})})]},e):Vn("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 sm}from"lucide-react";import{jsx as Ts,jsxs as Ml}from"react/jsx-runtime";function $l({siteId:e,refreshKey:t,className:n}){let{site:s,isLoading:a,error:r,updateSite:o,refetch:d}=kn({siteId:e,refreshKey:t});return a?Ml("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Ts(sm,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?Ml("div",{className:`af-space-y-3 ${n??""}`,children:[r&&Ts("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}),Ts(sn,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:Ts(Ol,{site:s,updateSite:o,refetch:d})})]},e):Ts("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 cs from"react";import{Fragment as Vl,jsx as zt,jsxs as ks}from"react/jsx-runtime";function Hl({refreshKey:e,initialInvoiceId:t,onBackToWebsite:n,onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:r,siteId:o,onSaveInvoiceSettings:d,className:c}){let{aggregates:u,isLoading:i,error:g,refetch:v}=Yn({refreshKey:e,initialPageSize:1,includeAggregates:!0}),f=as({refreshKey:e}),{api:l}=ee(),m=f.filters,p=cs.useCallback(()=>l.exportRetainersCsv(m),[l,m]),[b,h]=cs.useState(!1),[w,k]=cs.useState(null),[y,N]=cs.useState(!1),R=zt("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:g||!i&&!u?ks("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(S,{type:"button",variant:"link",size:"sm",onClick:()=>void v(),children:"Retry totals"})]}):i||!u?ks(Vl,{children:[zt(lt,{label:"Outstanding",children:zt(re,{className:"af-h-6 af-w-24"})}),zt(lt,{label:"Overdue",children:zt(re,{className:"af-h-6 af-w-24"})}),zt(lt,{label:"Paid this month",children:zt(re,{className:"af-h-6 af-w-24"})})]}):ks(Vl,{children:[zt(lt,{label:"Outstanding",detail:`${u.outstanding.count} open`,children:j(u.outstanding.amount,u.currency)}),zt(lt,{label:"Overdue",detail:u.overdue.count===0?"Nothing overdue":`${u.overdue.count} overdue`,valueClassName:u.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:j(u.overdue.amount,u.currency)}),zt(lt,{label:"Paid this month",detail:`${u.paid_this_month.count} paid`,children:j(u.paid_this_month.amount,u.currency)})]})});return ks(_t,{title:"Invoices",onBackToWebsite:n,hideBackButton:b,className:c,children:[R,o&&!b&&ks("div",{className:"af-mb-6",children:[zt(S,{type:"button",variant:"outline",size:"sm","aria-expanded":y,"aria-controls":"af-invoice-settings",onClick:()=>N(A=>!A),children:"Invoice settings"}),y&&zt("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:zt(Lr,{siteId:o,refreshKey:e,onSaveInvoiceSettings:d})})]}),!b&&zt(Qn,{retainers:f.retainers,isLoading:f.isLoading,error:f.error,onRetry:()=>void f.refetch(),activeRetainerId:w?.id??null,onShowCycles:A=>k(x=>x?.id===A.id?null:A),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:w?{id:w.id,label:`${w.customer_name??w.customer_email??"Recurring invoices"} \u2014 ${w.description}`}:null,onClearRetainerFilter:()=>k(null)})]})}import*as Ct from"react";var rm=2e3,Ft=()=>({data:null,error:null,isLoading:!0});function us(e,{refreshKey:t,breakdowns:n=[],filters:s=[]}={}){let{api:a}=ee(),[r,o]=Ct.useState(Ft),[d,c]=Ct.useState(Ft),[u,i]=Ct.useState(Ft),[g,v]=Ct.useState(Ft),[f,l]=Ct.useState(Ft),m=$=>Object.fromEntries($.map(M=>[M,Ft()])),[p,b]=Ct.useState(()=>m(n)),h=Ct.useRef(0),w=Ct.useRef(0),k=Ct.useRef("idle"),y=n.join(","),N=yn()??"",R=JSON.stringify(s),A=`${e}:${y}:${R}:${N}`,[x,P]=Ct.useState({api:a,fetchIdentity:A});(x.api!==a||x.fetchIdentity!==A)&&(P({api:a,fetchIdentity:A}),h.current+=1,o(Ft),c(Ft),i(Ft),v(Ft),b(m(y?y.split(","):[])));let T=`${e}:${String(t??"")}:${N}`,[_,K]=Ct.useState({api:a,conversionsIdentity:T});(_.api!==a||_.conversionsIdentity!==T)&&(K({api:a,conversionsIdentity:T}),w.current+=1,k.current="idle",l(Ft));let F=Ct.useCallback(async $=>{let M=++h.current,V=y?y.split(","):[];o(Ft),c(Ft),i(Ft),v(Ft),b(Object.fromEntries(V.map(E=>[E,Ft()])));let fe=k.current!=="pending"&&($?.force===!0||k.current==="idle"),Ke=(E,B)=>B.then(O=>{M===h.current&&E({data:O,error:null,isLoading:!1})},O=>{M===h.current&&E({data:null,error:O instanceof Error?O:new Error("Failed to fetch report"),isLoading:!1})}),vt=a.getAnalyticsStatus(),Ee=Ke(o,vt),Fe=Symbol("status-timeout"),Ze,Te=await Promise.race([vt.then(E=>E,()=>null),new Promise(E=>{Ze=setTimeout(()=>E(Fe),rm)})]);if(clearTimeout(Ze),M!==h.current)return;if(Te===Fe&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Te!==null&&Te!==Fe&&(Te.collecting!==!0||Te.first_seen===null&&!Te.first_seen_unavailable||Te.first_seen!==null&&Te.first_seen_in_reports===!1)){let E={data:null,error:null,isLoading:!1};c(E),i(E),v(E),b(Object.fromEntries(V.map(B=>[B,{...E}]))),fe&&(l(E),k.current="done"),await Ee;return}await Promise.all([Te===Fe?Promise.resolve():Ee,Ke(c,a.getAnalyticsSummary(e,s)),Ke(i,a.getAnalyticsTimeseries(e,s)),Ke(v,a.getAnalyticsChannels(e,s)),fe?(()=>{k.current="pending";let E=++w.current;return l(Ft),a.getAnalyticsConversions(e).then(B=>{E===w.current&&(l({data:B,error:null,isLoading:!1}),k.current="done")},B=>{E===w.current&&(l({data:null,error:B instanceof Error?B:new Error("Failed to fetch report"),isLoading:!1}),k.current="done")})})():Promise.resolve(),...V.map(E=>a.getAnalyticsBreakdown(E,e,s).then(B=>{M===h.current&&b(O=>({...O,[E]:{data:B,error:null,isLoading:!1}}))},B=>{M===h.current&&b(O=>({...O,[E]:{data:null,error:B instanceof Error?B:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[a,e,y,R,T,N]),X=Ct.useCallback(async()=>{let $=h.current;try{let M=await a.getAnalyticsStatus();if($!==h.current)return;o({data:M,error:null,isLoading:!1})}catch(M){if($!==h.current)return;o(V=>({data:V.data,error:M instanceof Error?M:new Error("Failed to fetch status"),isLoading:!1}))}},[a]),Q=Ct.useCallback(()=>F({force:!0}),[F]);Ct.useEffect(()=>{F()},[F,t]);let ne=r.isLoading||d.isLoading||u.isLoading||g.isLoading||f.isLoading||Object.values(p).some($=>$.isLoading),te=[u,d,g,f,...Object.values(p)].map($=>$.data?.status==="ok"?$.data.timezone:void 0).find($=>$!==void 0);return{status:r,summary:d,timeseries:u,channels:g,conversions:f,breakdowns:p,reportedZone:te,isLoading:ne,refetch:Q,refetchStatus:X}}import*as Tt from"react";var Ii=3e4,Ai=3;function Or(e={}){let t="collecting"in e,{collecting:n,statusFailed:s=!1,identity:a}=e,{api:r}=ee(),[o,d]=Tt.useState(null),[c,u]=Tt.useState(null),[i,g]=Tt.useState(!1),[v,f]=Tt.useState(null),[l,m]=Tt.useState(!1),[p,b]=Tt.useState(!0),[h,w]=Tt.useState(0),k=Tt.useRef(0),y=Tt.useRef(0),N=Tt.useRef(void 0);n!==void 0&&(N.current=n);let R=t?N.current===!0||N.current===void 0&&s:!0,[A,x]=Tt.useState({api:r,identity:a}),P=a!==void 0&&a!==A.identity;(A.api!==r||P)&&(N.current=void 0,x({api:r,identity:a}),y.current+=1,k.current=0,d(null),u(null),g(!1),f(null),m(!1),b(!0),w(0));let T=Tt.useRef(()=>{}),_=Tt.useRef(null),K=Tt.useCallback(async()=>{if(_.current!==null&&_.current===y.current)return;let F=++y.current;_.current=F;try{let X=await r.getAnalyticsRealtime();if(F!==y.current)return;if(X.status==="unreachable"){m(!0),g(!0),b(!1),w(Q=>Q+1);return}k.current=0,m(!1),d(X.data.current_visitors),u(X.as_of),g(!1),f(null),b(!1),w(Q=>Q+1)}catch(X){if(F!==y.current)return;k.current+=1,b(!1),w(Q=>Q+1),g(!0),k.current>=Ai&&f(X instanceof Error?X:new Error("Realtime unavailable"))}finally{_.current===F&&(_.current=null)}},[r]);return T.current=()=>void K(),Tt.useEffect(()=>{let F,X=()=>{F===void 0&&(F=setInterval(()=>T.current(),Ii))},Q=()=>{F!==void 0&&(clearInterval(F),F=void 0)},ne=()=>{typeof document<"u"&&document.hidden?Q():(T.current(),X())};return R?((typeof document>"u"||!document.hidden)&&(T.current(),X()),document?.addEventListener("visibilitychange",ne),()=>{Q(),document?.removeEventListener("visibilitychange",ne),y.current+=1}):()=>{document?.removeEventListener("visibilitychange",ne)}},[A.api,A.identity,R]),{currentVisitors:o,asOf:c,isStale:i,error:v,isUnreachable:l,isInitialLoad:p,polls:h}}import*as ct from"react";import*as ql from"react";import{jsx as Di,jsxs as zl}from"react/jsx-runtime";function im(){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 Li({value:e,chosen:t,onChange:n}){let s=gs(),a=t===null&&s!==null&&e===s,r=ql.useMemo(()=>{let o=im();return o.includes(e)?o:[e,...o]},[e]);return zl("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[Di("span",{className:"af-sr-only",children:"Reporting timezone"}),zl("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:[Di("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(o=>Di("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var Br=(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 Es from"react";var om=3e4;function Fr({status:e,holdingForFirstData:t,refetchStatus:n,refetch:s}){Es.useEffect(()=>{if(!t)return;let r,o=()=>{r===void 0&&(r=setInterval(()=>void n(),om))},d=()=>{r!==void 0&&(clearInterval(r),r=void 0)},c=()=>{typeof document<"u"&&document.hidden?d():(n(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",c),()=>{d(),document?.removeEventListener("visibilitychange",c)}},[t,n]);let a=Es.useRef(void 0);Es.useEffect(()=>{if(!e){a.current=void 0;return}let r=a.current;a.current=t,r===!0&&!t&&s()},[e,t,s])}import*as zn from"react";var lm=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Kt(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?Kt(o*s):`${o}${a}`}return String(e)}function ds(e){return`${(e*100).toFixed(1)}%`}function Is(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 Gl(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`:Is(t)}function Wl(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Kl(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 As(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Zl(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 Oi(e){let t=Number(e.slice(5,7)),n=Number(e.slice(8,10));return`${lm[t-1]} ${n}`}function jl(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function cm(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Jl(e,t,n="UTC"){let s=new Map(t.map(o=>[o.date,o])),a=[],r=jl(e.to,n);for(let o=jl(e.from,n);o<r;o=cm(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 Yl(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 dm,jsx as En,jsxs as um}from"react/jsx-runtime";function Xl({what:e="This report",onRetry:t,collecting:n}){return um("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 Ur({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(Xl,{what:s,onRetry:a,collecting:r}):!e||e.status==="unreachable"?En(Xl,{what:s,onRetry:a,collecting:r}):En(dm,{children:o(e.data)})}import{Fragment as fm,jsx as ca,jsxs as Hn}from"react/jsx-runtime";function Bi({rows:e,dimension:t,metric:n,metricLabel:s,secondary:a,emptyCopy:r="No data for this period",onFilter:o,canFilter:d,maxRows:c=9}){let[u,i]=zn.useState(!1);if(e.length===0)return ca(Ur,{what:r});let g=e.reduce((l,m)=>Math.max(l,Number(m[n]??0)),0)||1,v=Math.max(0,e.length-c),f=u?e:e.slice(0,c);return Hn(fm,{children:[Hn("table",{className:"af-w-full af-text-sm",children:[ca("thead",{children:Hn("tr",{className:"af-text-xs af-text-muted-foreground",children:[ca("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),ca("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),ca("tbody",{children:f.map((l,m)=>{let p=Number(l[n]??0),b=l[t]??null,h=As(b),w=a?l[a]:null,k=b!==null&&(d?d(b,w):!0);return Hn("tr",{className:"af-border-t af-border-border",children:[Hn("td",{className:"af-relative af-py-1.5 af-pr-2",children:[ca("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/g*100)}%`}}),b!==null&&o&&k?ca("button",{type:"button",onClick:()=>o(b,w),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}):ca("span",{className:"af-relative af-break-words af-text-foreground",children:h}),w?ca("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:w}):null]}),ca("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Kt(p)})]},`${h}-${w??""}-${m}`)})})]}),v>0?ca("button",{type:"button",onClick:()=>i(l=>!l),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:u?"Show fewer":`Show all ${e.length}`}):null]})}function Ds({title:e,tabs:t,defaultTabId:n,headerRight:s}){let[a,r]=zn.useState(n),o=t.find(f=>f.id===a)??t[0],d=zn.useId(),c=f=>`${d}-tab-${f}`,u=f=>`${d}-panel-${f}`,i=zn.useRef(null),g=(f,l)=>{f.preventDefault();let m=(l+t.length)%t.length;r(t[m].id),i.current?.querySelectorAll('[role="tab"]')?.[m]?.focus()};return Hn("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[Hn("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:[ca("div",{ref:i,role:"tablist","aria-label":e,onKeyDown:f=>{let l=t.findIndex(m=>m.id===a);f.key==="ArrowRight"&&g(f,l+1),f.key==="ArrowLeft"&&g(f,l-1),f.key==="Home"&&g(f,0),f.key==="End"&&g(f,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(f=>ca("button",{id:c(f.id),role:"tab",type:"button","aria-selected":f.id===a,"aria-controls":u(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?ca("div",{id:u(o.id),role:"tabpanel","aria-labelledby":c(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}import*as ua from"react";import*as In from"@radix-ui/react-popover";var fs=3,ms=100;import{jsx as gt,jsxs as on}from"react/jsx-runtime";var Ls={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"},mm=Object.keys(Ls);function Ql(e){let t=Ls[e.dimension],n=e.operator==="is_not"?"is not":"is",s=e.values.map(a=>As(a)).join(" or ");return`${t} ${n} ${s}`}function Fi(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 pm(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 ec(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 gm(e){return{dimension:e,operator:"is",search:"",picked:[]}}function tc(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=pm(e.byDimension,n);for(let[r,o]of Object.entries(s)){let d=e.foldsByLabel.get(r)??new Set;for(let c of o)d.add(c);e.foldsByLabel.set(r,d)}return{suggestions:a,folds:new Map([...e.foldsByLabel].map(([r,o])=>[r,[...o]]))}}function ac(e){let{filters:t,onChange:n}=e,s=t.length>=3;return ua.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:[gt("span",{className:"af-text-foreground",children:Ql(a)}),gt("button",{type:"button","aria-label":`Remove filter ${Ql(a)}`,onClick:()=>n(t.filter((o,d)=>d!==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"}`)),gt(vm,{...e,disabled:s}),t.length>0?gt("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 vm({filters:e,onChange:t,suggestions:n,resetKey:s,disabled:a,expandValues:r}){let[o,d]=ua.useState(!1),c=ua.useRef(null),[u,i]=ua.useState(null);ua.useEffect(()=>{i(c.current?.closest(".aifeatures-admin")??null)},[]);let[g,v]=ua.useState(null),[f,l]=ua.useState("is"),[m,p]=ua.useState(""),[b,h]=ua.useState([]);ua.useEffect(()=>{o||(v(null),l("is"),p(""),h([]))},[o]);let w=ua.useRef(s);w.current!==s&&(w.current=s,o&&d(!1),g!==null&&v(null),b.length>0&&h([]),m!==""&&p(""),f!=="is"&&l("is"));let k=P=>{let T=gm(P);v(T.dimension),h(T.picked),p(T.search),l(T.operator)},N=(g?n[g]??[]:[]).filter(P=>P.toLowerCase().includes(m.trim().toLowerCase())),R=g===null||b.length===0?null:Fi(e,{dimension:g,operator:f,values:r?r(g,b):b}),A=R!==null&&R!==e,x=()=>{let P=R;!P||P===e||(t(P),d(!1))};return on(In.Root,{open:o,onOpenChange:d,children:[gt(In.Trigger,{asChild:!0,children:gt("button",{ref:c,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"})}),gt(In.Portal,{container:u,children:gt(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:g===null?on("div",{children:[gt("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),gt("div",{className:"af-max-h-96 af-overflow-y-auto",children:mm.filter(P=>n[P]!==void 0).map(P=>{let T=n[P]?.length??0,_=!e.some(K=>K.dimension===P)&&e.length>=3;return on("button",{type:"button",onClick:()=>k(P),disabled:T===0||_,className:"af-flex af-w-full af-items-center af-justify-between af-rounded-md af-px-2 af-py-1.5 af-text-left af-text-xs af-text-foreground hover:af-bg-muted disabled:af-text-muted-foreground disabled:hover:af-bg-transparent",children:[gt("span",{children:Ls[P]}),gt("span",{className:"af-text-muted-foreground",children:T===0?"no data":_?"no room":T})]},P)})})]}):on("div",{children:[on("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[gt("button",{type:"button",onClick:()=>k(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),gt("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Ls[g]}),on("select",{"aria-label":"Operator",value:f,onChange:P=>l(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:[gt("option",{value:"is",children:"is"}),gt("option",{value:"is_not",children:"is not"})]})]}),gt("input",{type:"text",value:m,onChange:P=>p(P.target.value),placeholder:"Search\u2026","aria-label":`Search ${Ls[g]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),gt("div",{className:"af-max-h-48 af-overflow-y-auto",children:N.length===0?on("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",m,"\u201D."]}):N.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:[gt("input",{type:"checkbox",checked:b.includes(P),disabled:!b.includes(P)&&b.length>=100,onChange:T=>h(_=>T.target.checked?[..._,P]:_.filter(K=>K!==P))}),gt("span",{className:"af-break-all",children:As(P)})]},P))}),gt("button",{type:"button",onClick:x,disabled:!A,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>=100?`Apply filter (${b.length} values \u2014 the maximum)`:`Apply filter (${b.length} values)`})]})})})]})}import{Fragment as hm,jsx as Zt,jsxs as Mr}from"react/jsx-runtime";var bm=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Kt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Kt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Kt,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:ds,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Is,chart:"visit_duration_seconds"}];function ym({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 Zt("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 nc({summary:e,selected:t,onSelect:n}){return Zt("div",{className:"af-@container",children:Zt("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:bm.map(s=>{let a=s.chart===t,r=n!==void 0,o=Mr(hm,{children:[Zt("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),Mr("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Zt("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?Zt(ym,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?Zt("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):Zt("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},s.key)})})})}function Ui({currentVisitors:e,asOf:t,isStale:n,isUnreachable:s,isInitialLoad:a=!1,scopeIsSiteWide:r=!1}){if(a&&!s)return Mr("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:[Zt("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Zt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return Zt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?Zl(t):"freshness unknown",d=r?" across the whole site, not the current filter,":"",c=n?`${e} current visitors${d} ${o} (not updating)`:`${e} current visitors${d} ${o}`;return Mr("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:c,children:[Zt("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"}),Zt("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Zt("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),Zt("span",{className:"af-sr-only",children:c})]})}import*as rc from"react";import{Star as xm}from"lucide-react";import{Fragment as sc,jsx as At,jsxs as qn}from"react/jsx-runtime";function $r(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function Vr({rows:e,denominator:t,windowPrecedesCollection:n=!1,coverageUnknown:s=!1,emptyCopy:a="No conversions in this period",maxRows:r=9,primaryConversion:o}){let[d,c]=rc.useState(!1),u=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||$r(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(u.length===0)return qn(sc,{children:[At(Ur,{what:a}),i]});let g=u.slice(0,r),v=o?u.find(p=>$r(p,o)):void 0,f=v&&!g.includes(v)?u.filter(p=>g.includes(p)||p===v).slice(0,Math.max(0,r-1)).concat(v):g,l=d?e:f,m=Math.max(0,e.length-f.length);return qn(sc,{children:[qn("table",{className:"af-w-full af-text-sm",children:[At("thead",{children:qn("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:l.map((p,b)=>qn("tr",{className:"af-border-t af-border-border","aria-current":$r(p,o)?"true":void 0,children:[At("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:$r(p,o)?qn("span",{className:"af-flex af-items-center af-gap-1.5",children:[At(xm,{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:Kt(p.visitors)}),At("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Kt(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"}):ds(p.conversion_rate)})]},`${p.goal}-${b}`))})]}),m>0?At("button",{type:"button",onClick:()=>c(p=>!p),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:d?"Show fewer":`Show all ${e.length} goals`}):null,qn("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Kt(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),i]})}import{Area as wm,AreaChart as Sm,CartesianGrid as Nm,ResponsiveContainer as _m,Tooltip as Rm,XAxis as Pm,YAxis as Cm}from"recharts";import{jsx as Jt,jsxs as Os}from"react/jsx-runtime";var Hr={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},$i={visitors:Kt,visits:Kt,pageviews:Kt,views_per_visit:e=>e.toFixed(2),bounce_rate:ds,visit_duration_seconds:Is},Tm=31,km=new Set(["visitors","visits","pageviews"]),Em={...$i,bounce_rate:Wl,visit_duration_seconds:Gl},Mi=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Im=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Am=[.01,.02,.05,.1,.2,.25,.5,1],Dm=[.25,.5,1,2,5,10,25,50],Lm={visitors:Mi,visits:Mi,pageviews:Mi,views_per_visit:Dm,bounce_rate:Am,visit_duration_seconds:Im};function Om({active:e,payload:t,label:n,metric:s}){if(!e||!t||t.length===0)return null;let a=t[0].payload;return Os("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:[Jt("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Hr[s]}),Os("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[Jt("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),Jt("span",{className:"af-text-muted-foreground",children:Yl(String(n))}),Jt("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:$i[s](Number(a[s]??0))})]})]})}function zr({rows:e,window:t,metric:n,timeZone:s="UTC",height:a=260}){let r=Jl(t,e,s),o=$i[n],d=Em[n],c=Kl(r.reduce((i,g)=>Math.max(i,Number(g[n]??0)),0),Lm[n]),u=`${Hr[n]} by day: ${r.map(i=>`${Oi(i.date)}: ${o(Number(i[n]??0))}`).join("; ")}.`;return Os("figure",{"aria-label":`${Hr[n]} over time`,className:"af-m-0",children:[Jt(_m,{width:"100%",height:a,children:Os(Sm,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[Jt("defs",{children:Os("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[Jt("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),Jt("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),Jt(Nm,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Jt(Pm,{dataKey:"date",tickFormatter:Oi,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Jt(Cm,{allowDecimals:!km.has(n),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...c?{ticks:c,domain:[0,c[c.length-1]]}:{},tickFormatter:i=>d(i),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Jt(Rm,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Jt(Om,{metric:n})}),Jt(wm,{type:"linear",dataKey:n,name:Hr[n],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=Tm?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),Jt("figcaption",{className:"af-sr-only",children:u})]})}import{Fragment as Vi,jsx as xe,jsxs as qt}from"react/jsx-runtime";var Bm="2026-08-13",Fm=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Um=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Mm({filters:e,onFiltersChange:t,refreshKey:n,onBackToWebsite:s,primaryConversion:a,className:r,published:o,lastPublishedAt:d}){let[c,u]=ct.useState(30),[i,g]=ct.useState(()=>Jr()),v=e!==void 0&&t!==void 0,[f,l]=ct.useState(e??[]),{api:m}=ee(),[p,b]=ct.useState(m);p!==m&&(b(m),!v&&f.length>0&&l([]));let h=v?e:f,w=ct.useCallback(O=>{t&&t(O),v||l(O)},[t,v]),k=ct.useCallback((O,me,ve)=>{let _e=Array.isArray(me)?me:[me];if(_e.length===0)return null;let Le=Fi(h,{dimension:O,operator:"is",values:_e});if(ve&&(!ve.value||(Le=ec(Le,{dimension:ve.dimension,operator:"is",values:[ve.value]}),!Le.find(ut=>ut.dimension===ve.dimension&&ut.operator!=="is_not")?.values.includes(ve.value))))return null;let nt=Le.find(Oe=>Oe.dimension===O&&Oe.operator!=="is_not");return _e.every(Oe=>nt?.values.includes(Oe))?JSON.stringify(Le)===JSON.stringify(h)?null:Le:null},[h]),y=ct.useCallback((O,me,ve)=>k(O,me,ve)!==null,[k]),N=ct.useCallback((O,me,ve)=>{let _e=k(O,me,ve);_e&&w(_e)},[k,w]),[R,A]=ct.useState("visitors"),x=us(c,{refreshKey:n,breakdowns:Um,filters:h}),P=x.status.data,T=x.reportedZone??P?.timezone,_=T??i??gs()??"UTC",{notCollecting:K,awaitingFirstVisit:F,firstVisitTooRecent:X,holdingForFirstData:Q}=Br(P,{published:o}),ne=o===!1,te=Or({collecting:F||K?!1:P?.collecting,statusFailed:x.status.error!=null,identity:P?.analytics_id}),$=ct.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),M=ct.useMemo(()=>{let O=x.breakdowns.sources?.data,me={};if(!O||O.status!=="ok")return me;for(let ve of O.data){let _e=ve.source,Le=ve.sources;typeof _e=="string"&&Array.isArray(Le)&&Le.length>0&&(me[_e]=Le)}return me},[x.breakdowns.sources?.data]),V=ct.useMemo(()=>{let O=(_e,Le)=>{let nt=x.breakdowns[_e]?.data;return!nt||nt.status!=="ok"?[]:[...new Set(nt.data.map(Oe=>Oe[Le]).filter(Oe=>typeof Oe=="string"&&Oe!==""))]};return{channel:x.channels.data?.status==="ok"?[...new Set(x.channels.data.data.map(_e=>_e.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]),[fe,Ke]=ct.useState({}),vt=JSON.stringify(V),[Ee,Fe]=ct.useState(new Map),Ze=JSON.stringify(M);ct.useEffect(()=>{let{suggestions:O,folds:me}=tc($.current,{api:m,period:c},JSON.parse(vt),JSON.parse(Ze));Ke(O),Fe(me)},[vt,Ze,m,c]);let Te=ct.useCallback((O,me)=>O!=="source"?me:[...new Set(me.flatMap(ve=>{let _e=[...Ee.get(ve)??[],...M[ve]??[]];return _e.length>0?_e:[ve]}))],[Ee,M]),kt=ct.useMemo(()=>{let O=x.conversions.error;return O instanceof St&&O.details?.code==="goals_exceed_report_budget"?O.message:null},[x.conversions.error]),E=ct.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]),B=(O,me,ve,_e,Le,nt,Oe,ut,oe)=>()=>{let Re=x.breakdowns[O];return xe(bn,{sourced:Re?.data??null,error:Re?.error,isLoading:Re?.isLoading,what:me,collecting:P?.collecting,onRetry:x.refetch,children:st=>{let da=Lt=>ut?Te(ut,[Lt]):Lt;return xe(Bi,{rows:st,dimension:ve,metric:_e,metricLabel:Le,secondary:nt,emptyCopy:h.length>0?"No data for this filter":Oe,canFilter:ut?(Lt,Yt)=>y(ut,da(Lt),oe?{dimension:oe,value:Yt}:void 0):()=>!1,onFilter:ut?(Lt,Yt)=>N(ut,da(Lt),oe?{dimension:oe,value:Yt}:void 0):void 0})}})};if(Fr({status:P,holdingForFirstData:Q,refetchStatus:x.refetchStatus,refetch:x.refetch}),K){let O=!!d&&String(d).slice(0,10)<Bm;return xe(_t,{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:[xe("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),xe("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:ne?"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 F?xe(_t,{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:[xe("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),xe("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."})]})}):X?qt(_t,{title:"Analytics",onBackToWebsite:s,className:r,children:[xe("div",{className:"af-mb-3 af-flex af-justify-end",children:xe(Li,{value:_,chosen:i,onChange:O=>{Yr(O),g(O)}})}),qt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[xe("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."]}),xe("div",{className:"af-mt-4 af-flex af-justify-center",children:xe(Ui,{currentVisitors:te.currentVisitors,asOf:te.asOf,isStale:te.isStale,isUnreachable:te.isUnreachable||te.error!==null,isInitialLoad:te.isInitialLoad})})]})]}):xe(_t,{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:[xe("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Fm.map(O=>xe("button",{type:"button","aria-pressed":O.value===c,onClick:()=>u(O.value),className:O.value===c?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:O.label},O.value))}),xe(Li,{value:_,chosen:i,onChange:O=>{Yr(O),g(O)}}),xe(Ui,{currentVisitors:te.currentVisitors,asOf:te.asOf,isStale:te.isStale,isUnreachable:te.isUnreachable||te.error!==null,isInitialLoad:te.isInitialLoad,scopeIsSiteWide:h.length>0})]}),xe(ac,{filters:h,onChange:w,suggestions:fe,expandValues:Te,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:[xe("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),xe("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:E}),xe("button",{type:"button",onClick:()=>w([]),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?xe("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(Vi,{children:[xe(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(Vi,{children:[xe(nc,{summary:O,selected:R,onSelect:A}),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]})}),xe("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:xe(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 xe(zr,{rows:O,window:me,metric:R,timeZone:T??"UTC"})}})}),qt("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[xe(Ds,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>xe(bn,{sourced:x.channels.data,error:x.channels.error,isLoading:x.channels.isLoading,what:"Channels",collecting:P?.collecting,onRetry:x.refetch,children:O=>xe(Bi,{rows:O,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:h.length>0?"No data for this filter":"No data for this period",canFilter:me=>y("channel",me),onFilter:me=>N("channel",me)})})},{id:"sources",label:"Sources",render:B("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:B("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),xe(Ds,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:B("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:B("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:B("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),xe(Ds,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:B("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:B("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:B("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),xe(Ds,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:B("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:B("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:B("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:[xe("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:xe("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:[xe("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),xe("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:kt})]}):xe(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 xe(Vi,{children:xe(Vr,{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 pc from"react";import{Phone as dc,Mail as zi,ShoppingBag as zm,ExternalLink as qm,MessageCircle as jm,Download as Gm,Target as gc}from"lucide-react";import*as Ea from"react";import{Check as Hi,ChevronLeft as $m,Loader2 as ic}from"lucide-react";import{jsx as Ge,jsxs as Dt}from"react/jsx-runtime";var oc=90,lc=100;function Vm(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function cc(e){return!!e.label&&e.label!==e.target}function Hm(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 Bs(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function uc({current:e,onChange:t,onClose:n}){let{api:s}=ee(),[a,r]=Ea.useState(null),[o,d]=Ea.useState(!1),[c,u]=Ea.useState({at:"goals"}),[i,g]=Ea.useState(null),[v,f]=Ea.useState(null),[l,m]=Ea.useState(!1),[p,b]=Ea.useState(null),h=Ea.useRef(0);Ea.useEffect(()=>{let N=!0;return r(null),d(!1),u({at:"goals"}),g(null),f(null),m(!1),b(null),h.current+=1,s.getAnalyticsConversions(oc).then(R=>{if(N){if(R.status!=="ok"){d(!0);return}r(R.data)}}).catch(()=>{N&&d(!0)}),()=>{N=!1}},[s]);let w=N=>{u({at:"targets",row:N}),g(null),f(null),m(!1),b(null);let R=++h.current;s.getAnalyticsGoalTargets(N.goal,oc,lc).then(A=>{if(R===h.current){if(A.status!=="ok"){f("failed");return}g(A.data),m(A.truncated===!0),b(A.coverage??null)}}).catch(A=>{if(R!==h.current)return;let x=A instanceof St?A.details?.code:void 0;f(x==="goal_has_no_targets"?"no-values":"failed")})},k=N=>{t(N),n()};if(o)return Ge("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:[Ge(ic,{className:"af-h-4 af-w-4 af-animate-spin"}),Ge("span",{children:"Loading your conversions\u2026"})]});if(c.at==="targets"){let N=c.row,R=new Map;for(let A of i??[])R.set(A.label,(R.get(A.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:[Ge("header",{className:"af-flex af-items-center af-gap-1",children:Dt(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({at:"goals"}),children:[Ge($m,{className:"af-h-4 af-w-4"}),Ge("span",{children:"All conversions"})]})}),Dt("button",{type:"button","aria-current":e&&Bs(N,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>k({goal:N.goal,implicit:N.implicit}),children:[e&&Bs(N,e)&&!e.target&&Ge(Hi,{className:"af-h-4 af-w-4 af-shrink-0"}),Dt("span",{children:["Any ",N.goal.toLowerCase()]})]}),v==="no-values"&&Ge("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"&&Dt("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[Ge("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),Ge(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>w(N),children:"Try again"})]}),!i&&v===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:[Ge(ic,{className:"af-h-4 af-w-4 af-animate-spin"}),Ge("span",{children:"Loading\u2026"})]}),i&&Ge("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Hm(i.length,p,l)}),l&&Dt("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",lc,". If what you want isn\u2019t here, pick the conversion itself instead."]}),i?.some(cc)&&Ge("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(A=>{let x=!!(e&&Bs(N,e)&&e.target===A.target),P=R.get(A.label)>1;return cc(A)?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:[Ge("span",{className:"af-block af-truncate",children:A.label}),P&&Ge("span",{className:"af-block af-truncate af-text-xs",children:A.target})]}),Ge("span",{className:"af-shrink-0 af-text-xs",children:A.visitors.toLocaleString()})]},A.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:()=>k({goal:N.goal,implicit:N.implicit,target:A.target,...A.label&&A.label!==A.target?{label:A.label}:{}}),children:[Dt("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[x&&Ge(Hi,{className:"af-h-4 af-w-4 af-shrink-0"}),Dt("span",{className:"af-min-w-0",children:[Ge("span",{className:"af-block af-truncate",children:A.label}),P&&Ge("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:A.target})]})]}),Ge("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:A.visitors.toLocaleString()})]},A.target)})]})}let y=e?.goal&&!a.some(N=>Bs(N,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:[y&&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&&Ge("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(N=>{let R=e?Bs(N,e):!1;return Dt("div",{className:"af-flex af-items-center af-gap-1",children:[Dt("button",{type:"button","aria-current":R?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>k({goal:N.goal,implicit:N.implicit}),children:[Dt("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[R&&Ge(Hi,{className:"af-h-4 af-w-4 af-shrink-0"}),Ge("span",{className:"af-truncate",children:N.goal})]}),Ge("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:N.visitors.toLocaleString()})]}),Vm(N)&&Ge(S,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${N.goal}`,onClick:()=>w(N),children:"Narrow"})]},N.goal)}),e?.goal&&Ge("button",{type:"button",className:"af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm af-text-muted-foreground hover:af-bg-accent",onClick:()=>k(null),children:"No main conversion"})]})}import{Fragment as Jm,jsx as jn,jsxs as mc}from"react/jsx-runtime";function Wm(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let n of t)try{let{hostname:s}=new URL(n);if(s)return s.toLowerCase().replace(/^www\./,"")}catch{}return null}function Km(e){if(qi(e,"whatsapp"))return!0;let t=Wm(e);return t===null?!1:["wa.me","whatsapp.com"].some(n=>t===n||t.endsWith(`.${n}`))}function qi(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var fc=[{goal:"Contact",target:e=>qi(e,"tel"),icon:dc,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>qi(e,"mailto"),icon:zi,line:"This site is set up to get you emails."},{goal:"Contact",icon:dc,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Km(e),icon:jm,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:qm,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:zi,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:zi,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:Gm,line:"This site is set up to get your file downloaded."}];function vc(e){let{goal:t,target:n}=e;return e.implicit!==!0?null:(n?fc.find(a=>a.goal===t&&a.target?.(n)):void 0)??fc.find(a=>a.goal===t&&!a.target)??null}function Zm(e){return vc(e)?.icon??gc}function bc({primaryConversion:e,onChange:t}){let[n,s]=pc.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?vc(e):null,o=e?.label?.trim(),d=e?Zm(e):gc,c=e?.goal?o?`Your main conversion is ${o}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",u=mc(Jm,{children:[jn(d,{className:"af-h-4 af-w-4 af-shrink-0"}),jn("span",{children:c})]});return t?mc(or,{open:n,onOpenChange:s,children:[jn(lr,{asChild:!0,children:jn("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:u})}),jn(Ns,{align:"start",className:"af-w-80 af-p-1",children:n&&jn(uc,{current:e,onChange:t,onClose:()=>s(!1)})})]}):jn("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:u})}import{Fragment as Ym,jsx as An,jsxs as qr}from"react/jsx-runtime";function yc({refreshKey:e,onViewAll:t,primaryConversion:n}){let s=us(7,{refreshKey:e,breakdowns:[]}),a=s.status.data??void 0,{nothingToReport:r,notCollecting:o,holdingForFirstData:d}=Br(a);return Fr({status:a,holdingForFirstData:d,refetchStatus:s.refetchStatus,refetch:s.refetch}),qr("section",{className:"af-rounded-md af-border af-p-3",children:[qr("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(S,{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."}):qr(Ym,{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:c=>{let u=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return An(zr,{rows:c,window:u?.window??{from:"",to:""},metric:"visitors",timeZone:u?.timezone,height:140})}}),qr("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:c=>{let u=s.conversions.data?.status==="ok"?s.conversions.data:null;return An(Vr,{rows:c,primaryConversion:n,denominator:u?.denominator??0,windowPrecedesCollection:u?.window_precedes_collection??!1,coverageUnknown:u?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as Ga,jsxs as Fs}from"react/jsx-runtime";var ji=5;function Gi({title:e,viewAllLabel:t,onViewAll:n}){return Fs("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Ga("h3",{className:"af-text-sm af-font-medium",children:e}),n&&Ga(S,{type:"button",variant:"ghost",size:"sm",onClick:n,children:t})]})}function Xm({refreshKey:e,onBackToWebsite:t,primaryConversion:n,onChangePrimaryConversion:s,onOpenSurface:a,needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:d}){let c=ss({refreshKey:e}),u=(c.summary?.products.count??0)>0||(c.summary?.commerce?.storefront_orders??!1),i=u||(c.summary?.commerce?.invoicing??!1);return Ga(_t,{title:"Dashboard",onBackToWebsite:t,children:Fs("div",{className:"af-flex af-flex-col af-gap-4",children:[Ga(bc,{primaryConversion:n,onChange:s}),Ga(yc,{refreshKey:e,onViewAll:a&&(()=>a("analytics")),primaryConversion:n}),Fs("section",{className:"af-rounded-md af-border af-p-3",children:[Ga(Gi,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:a&&(()=>a("leads"))}),Ga(kr,{refreshKey:e,maxRows:ji,onViewAll:a&&(()=>a("leads"))})]}),u&&Fs("section",{className:"af-rounded-md af-border af-p-3",children:[Ga(Gi,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:a&&(()=>a("orders"))}),Ga(_n,{refreshKey:e,maxRows:ji,onViewAll:a&&(()=>a("orders"))})]}),i&&Fs("section",{className:"af-rounded-md af-border af-p-3",children:[Ga(Gi,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:a&&(()=>a("invoices"))}),Ga(Pn,{refreshKey:e,maxRows:ji,onViewAll:a&&(()=>a("invoices")),needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:d})]})]})})}export{St as AifeaturesApiError,wc as AifeaturesProvider,Mm as AnalyticsView,vr as CustomerDetail,br as CustomersList,Xm as DashboardView,$t as ExportCsvButton,er as FormSettings,Js as FormSubmissions,bo as FormsDashboard,Hs as FormsList,vi as InvoiceDetail,_s as InvoiceLabelBadge,Lr as InvoiceSettingsPanel,Pn as InvoicesList,Hl as InvoicesView,kr as LeadsView,fs as MAX_ANALYTICS_FILTERS,ms as MAX_ANALYTICS_FILTER_VALUES,$l as NotificationRecipientsSettings,fr as OrderDetail,Fn as OrderStatusBadge,_n as OrdersList,Yo as OrdersView,Ko as PaymentsDashboard,es as PaymentsSetup,rr as ProductSettings,nr as ProductsList,rl as ProductsView,Wn as PromosPanel,Ai as REALTIME_FAILURES_BEFORE_ERROR,Ii as REALTIME_POLL_MS,bi as RetainerStatusBadge,Qn as RetainersPanel,Fl as StoreSettings,Gs as SubmissionDetail,hl as SubscriptionsView,sr as VariantsEditor,_t as ViewShell,Xs as WebhookDeliveries,Qs as WebhookSettings,pn as chargedTotal,Xr as createApiClient,j as formatPrice,Na as isZeroDecimalCurrency,it as toMajorUnits,Ot as toMinorUnits,ee as useAifeatures,ee as useAifeaturesContext,us as useAnalytics,ss as useBusinessSummary,Zs as useCsvExport,gr as useCustomers,Ys as useEventDestinations,Gn as useForms,Yn as useInvoices,ir as useOrders,Sn as usePaymentsStatus,Cr as usePeople,Tr as usePerson,ts as useProducts,Or as useRealtimeVisitors,as as useRetainers,kn as useSiteSettings,js as useSubmissions,Er as useSubscriptions};
|
|
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};
|